Adding direction to reversal opening

MQL5 Experts

Job finished

Execution time 4 minutes
Feedback from customer
Experienced coder of our generation, flexible and understanding each and every details. He is fast, faster than Japanese bullet train.
Feedback from employee
Excellent client I will help him again thank you

Specification

Anyone who can add opening direction base on moving average if its above MA must take buy trades only if below then take sell trades only.

#property copyright "Copyright 2022, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.20"



input bool inputOpenOppositeTradeAfterClose = true; // Open Opposite Trade After Close

input ENUM_ORDER_TYPE_FILLING typeFilling = ORDER_FILLING_FOK; //Order Filling Type

input int inputMaxOppositeTradePerSymbol = 3; //Max Opposite Trade Per Symbol
input int slippage = 100; //Slippage In Points

long MagicNumber = 163818213;


bool timerCreated = false;
int TIMER_FREQUENCY = 1; 

struct FLOATING_TRADES 
{
  ulong ticket;
  int tradeType;
  string symbol;
  double tradeLots;
  double stoploss;
  double takeprofit;
  bool oppositeAllowed;
 
};

FLOATING_TRADES FloatingTradesArray[];


bool inititalized = false;

int OnInit()
{   
  if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
  {
    Alert("Please Allow Auto Trading");
    return(INIT_FAILED);
  }

  if(!inititalized)
  { 
    ArrayResize(FloatingTradesArray, 0);
    timerCreated = EventSetTimer(TIMER_FREQUENCY);
    inititalized = true;
  }

  return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
  switch (reason) 
  {
    case REASON_CHARTCHANGE: break;
    case REASON_PARAMETERS: break;

    default:

    inititalized = false; 
    EventKillTimer();
    timerCreated = false;

    break;
  }
}

void OnTick()
{
  if (!timerCreated) timerCreated = EventSetTimer(TIMER_FREQUENCY);
}

void OnTimer()
{
  FindClosedPositions();
  FindNewPositions();
} 

void FindNewPositions()
{
  for(int i=PositionsTotal()-1; i>=0; i--)
  {
    ulong position_ticket=PositionGetTicket(i);
    ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
    string symbol = PositionGetString(POSITION_SYMBOL);

    if(position_ticket != 0 && (type==POSITION_TYPE_BUY || type==POSITION_TYPE_SELL) && PositionGetInteger(POSITION_MAGIC) != MagicNumber)
    { 
      if(CheckNewPosition(position_ticket))
      {
        Print("position "+(string)position_ticket+" opened");

        bool oppositeAllowed = CountOfTradeWithSameSymbolInArray(symbol) < inputMaxOppositeTradePerSymbol;

        FLOATING_TRADES newTrade;

        newTrade.ticket = position_ticket;
        newTrade.tradeType = (int)PositionGetInteger(POSITION_TYPE);
        newTrade.symbol = symbol;
        newTrade.tradeLots = PositionGetDouble(POSITION_VOLUME); 
        newTrade.stoploss = PositionGetDouble(POSITION_SL);
        newTrade.takeprofit = PositionGetDouble(POSITION_TP);   
        newTrade.oppositeAllowed = oppositeAllowed;

        int size = ArraySize(FloatingTradesArray);
        ArrayResize(FloatingTradesArray, size + 1);
        FloatingTradesArray[size] = newTrade;
      }
    }
  }
}

bool CheckNewPosition(ulong positionTicket)
{
  bool result = true;

  for(int i=0; i<ArraySize(FloatingTradesArray); i++)
  {
    if(FloatingTradesArray[i].ticket == positionTicket)
    {
      result = false;
      break;
    }  
  }

  return result;
}

void FindClosedPositions()
{
  for(int i=0; i<ArraySize(FloatingTradesArray); i++)
  {
    ulong PositionTicket = FloatingTradesArray[i].ticket;
    ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)FloatingTradesArray[i].tradeType;
    string symbol = FloatingTradesArray[i].symbol;
    double lot = FloatingTradesArray[i].tradeLots;
    double stoploss = FloatingTradesArray[i].stoploss;
    double takeprofit = FloatingTradesArray[i].takeprofit;
    bool oppositeAllowed = FloatingTradesArray[i].oppositeAllowed;

    if(PositionTicket != 0 && (type==POSITION_TYPE_BUY || type==POSITION_TYPE_SELL))
    {
      if(!CheckIfPositionIsFloating(PositionTicket) && CheckPositionFromHistory(PositionTicket))
      {
        Print("position "+(string)PositionTicket+" closed");

        if(oppositeAllowed)
        {
          if(OpenOppsitePositionOpened(PositionTicket, symbol, type, lot, stoploss, takeprofit))
          {      
            Print("oppsite of position "+(string)PositionTicket+" opened");
            int size = ArraySize(FloatingTradesArray);
            for (int j = i + 1; j < size; j++) 
            {
              FloatingTradesArray[j - 1] = FloatingTradesArray[j];
            }
            size--;
            ArrayResize(FloatingTradesArray, size);
          }  
        }
        else
        {
          int size = ArraySize(FloatingTradesArray);
          for (int j = i + 1; j < size; j++) 
          {
            FloatingTradesArray[j - 1] = FloatingTradesArray[j];
          }
          size--;
          ArrayResize(FloatingTradesArray, size);
        }
      }
    }
  }
}

bool CheckIfPositionIsFloating(ulong PositionTicket) 
{ 
  bool result = false;

  for(int i=PositionsTotal()-1; i>=0; i--)
  {     
    ulong position_ticket = PositionGetTicket(i);  
    if(position_ticket == PositionTicket)
    {
      result = true;    
      break;   
    }                                      
  }
  return result;
}

bool CheckPositionFromHistory(ulong positionTicket) 
{
  bool result = false;

  if(HistorySelectByPosition(positionTicket))
  {  
    ulong dealTicket = 0;
    int DealEntry;
 
    for(uint j = 0; j<2; j++)
    {   
      if((dealTicket=HistoryDealGetTicket(j))>0)
      {  
        DealEntry = (int)HistoryDealGetInteger(dealTicket,DEAL_ENTRY);
        if(DealEntry==DEAL_ENTRY_OUT) result = true;
      }
    }
  } 

  return result;
}

bool OpenOppsitePositionOpened(long ticket, string symbol, ENUM_POSITION_TYPE positionType, double lot, double sl,double tp)
{
  if(!inputOpenOppositeTradeAfterClose) return true;

  string tradeComment = "opp:"+(string)ticket;  

  if(CheckIfPositionIsOpened(tradeComment)) return true;
  if(CheckIfOrderIsOpened(tradeComment)) return true;

  ENUM_POSITION_TYPE OppPositionType = ReversePosition(positionType); 

  double temp = sl;
  sl = tp;
  tp = temp;

  if(OppPositionType == POSITION_TYPE_BUY) return OpenBuyPosition(symbol, lot, sl, tp, tradeComment);
  else if(OppPositionType == POSITION_TYPE_SELL) return  OpenSellPosition(symbol, lot, sl, tp, tradeComment);
  
  return false;
}

ENUM_POSITION_TYPE ReversePosition(ENUM_POSITION_TYPE positionType)
{
  if(positionType == POSITION_TYPE_BUY) return POSITION_TYPE_SELL; //buy reverse to sell
  else if(positionType == POSITION_TYPE_SELL) return POSITION_TYPE_BUY; //sell reverse to buy
  
  return positionType;
}

bool OpenBuyPosition(string symbol,double lot,double sl,double tp, string comment)
{
  bool res = false;

  MqlTradeRequest request={};
  MqlTradeResult  result={};

  request.action = TRADE_ACTION_DEAL;                    
  request.symbol = symbol;                             
  request.volume = lot;                                
  request.type = ORDER_TYPE_BUY;                        
  request.price = SymbolInfoDouble(symbol,SYMBOL_ASK); 
  request.sl = sl;                    
  request.tp = tp; 
  request.deviation = slippage;                                     
  request.type_filling = typeFilling;   
  request.comment = comment;
  request.magic = MagicNumber;               
  
  if(!OrderSend(request,result))
  {
    PrintFormat("OrderSend error %d",GetLastError());
    res = false;
  }
  else res = true;

  return res;
}

bool OpenSellPosition(string symbol,double lot,double sl,double tp, string comment)
{
  bool res = false;

  MqlTradeRequest request={};
  MqlTradeResult  result={};

  request.action = TRADE_ACTION_DEAL;                  
  request.symbol = symbol;                              
  request.volume = lot;                                  
  request.type = ORDER_TYPE_SELL;                       
  request.price = SymbolInfoDouble(symbol,SYMBOL_BID); 
  request.sl = sl;                    
  request.tp = tp; 
  request.deviation = slippage;                                     
  request.type_filling = typeFilling;   
  request.comment = comment;   
  request.magic = MagicNumber;         

  if(!OrderSend(request,result))
  {
    PrintFormat("OrderSend error %d",GetLastError()); 
    res = false;
  }
  else res = true;

  return res;
}

bool CheckIfPositionIsOpened(string positionComment) 
{
  bool result = false;
  for(int i=PositionsTotal()-1; i >= 0; i--)
  {   
    ulong position_ticket=PositionGetTicket(i);   
    string position_comment = PositionGetString(POSITION_COMMENT);          
    if(position_comment==positionComment)
    {
      result = true;
      break;
    }                                              
  }
  return result;
}

bool CheckIfOrderIsOpened(string orderComment) 
{
  bool result = false;
  for(int i=OrdersTotal()-1; i >= 0; i--)
  {   
    ulong orderticket=OrderGetTicket(i);   
    string order_comment = OrderGetString(ORDER_COMMENT);          
    if(order_comment==orderComment)
    {
      result = true;
      break;
    }                                              
  }
  return result;
}
 
int CountOfTradeWithSameSymbolInArray(string symbol)
{
  int count = 0;

  for(int i=0; i<ArraySize(FloatingTradesArray); i++)
  {
    if(FloatingTradesArray[i].symbol == symbol) count++;
  }

  return count;
}

Responded

1
Developer 1
Rating
(8)
Projects
11
18%
Arbitration
7
43% / 29%
Overdue
1
9%
Free
2
Developer 2
Rating
(73)
Projects
90
41%
Arbitration
4
50% / 50%
Overdue
2
2%
Free
3
Developer 3
Rating
(10)
Projects
15
27%
Arbitration
3
67% / 33%
Overdue
0
Free
4
Developer 4
Rating
(37)
Projects
59
27%
Arbitration
25
20% / 52%
Overdue
10
17%
Working
5
Developer 5
Rating
(126)
Projects
160
36%
Arbitration
4
25% / 50%
Overdue
13
8%
Working
6
Developer 6
Rating
(96)
Projects
143
76%
Arbitration
0
Overdue
2
1%
Free
Similar orders
Telegram To MT5 EA 40 - 50 USD
I'm in need of Telegram to MT5 EA copier. The copier should be able to open telesignals directly on MT5 terminal. Message me if you can create the EA as described. Regards
Tiazo chrino 30 - 200 USD
Donc pour moi ça constite à faire de l'argent en ligne et faire aussi quelques pub en passant c'est toujours comme ça on y peut rien mais faire de l'argent c'est plus mieux je trouve
Hey I am looking for someone to help with the testing of my 1000+ robots, you will be asked to always run testing for 30 expert advisors within 24/7 and you will have to provide results from the testing of each EA, let me know if you can help thanks
I need an expert to test robots 24/7 and the best ones come to real servers to work with real money. If we have good success, I increase the risk to 10-20% and the capital. a) 30x Forex robot installation. b) 30x Forex robot settings adjustment. c) 30x Forex robot is tested 24/7 for success. d) 30x Forex robot is provided by the client. e) 30x Forex robot is tested for functions to see if it works on MT4 or MT5. f)
Hello, how are you? I would like to create a robot (another version of a robot I already have) I currently have the source code but would like to have another robot that belongs to me but with different settings, if I provide you with the source code with all the settings are you able to remake me another robot with modifications? and if so what would be your price
EA indicador Velas 30 - 50 USD
Necesito crear un EA basado en un indicador que da señal de entrada y que tenga los siguientes parametros 1. Entrar Buy o Sell en la siguiente vela de la señal dependiendo la Flecha 2. El TP para BUY sera apenas cierre en vela verde sin importar los pips que saque de ganancias puede ser que sea 1 pip o 10 o incluso salir en perdida, no importa 2. El TP para Sell sera apenas cierre en vela roja sin importar los pips
Hello, i haven an idea for a bot i had becktested it for 1year and it is really easy, it is a range of 30 min where you take the high and low, now price need to cross that zone and also close, then i want an entre with SL not the same candle but the candle after. and just aim for 1;1 , i really think this should not be expensive to make? is this right? is yes, please tell me who i can contact and discuss the price to
hello there, first thing first, I worked hard to develop this EA, I have 8 years of trading experience, and I come to conclusion that an EA is a must. now this EA have some (unseen) TP taking and trade management. I a Entry On cross only, if True m looking for someone that is 1- serious to make this work 2- knowlagble and having extensive trading experience 3- great experience in optimiation AFTER OPTIMIZATION this
So the below format is what I am currently using from a 3rd party EA. 🪖 COMMANDO TRADE 🪖 < Whenever an order is opened (OpenText1) ==================== 🚫 WE DO NOT ADVICE TRADING SIGNALS FROM DIFFERENT TRADERS ON THE SAME ACCOUNT 🚫 ==================== ⚠️ LOT SIZE ⚠️ < Whenever an order is opened (OpenText2) 💰 $100,000 - 1.00 💰 💰 $200,000 - 2.00 💰 💰 $300,000 - 3.00 💰 💰 $400,000 - 4.00 💰 💰
Request to improve performance in back test of a custom indicator SMC_OSC (Smart market concept + Market sentiment oscillator). It works fine but it has a hard problem, it is extremely slow in tick-mode and I cannot use it in EA due the infinite range times it gets to back-testing. About the first section in Chart price (Smart market concept), it uses candle close pivots (on bar, no ticks) and so I think that this

Project information

Budget
30+ USD
For the developer
27 USD