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
(67)
Projects
83
40%
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%
Free
6
Developer 6
Rating
(96)
Projects
143
76%
Arbitration
0
Overdue
2
1%
Free
Similar orders
Hello I have my own candlestick pattern that I manually trade looking for someone who could automate it its based off visual seeing the candle and not math hopefully we could chat with each other and testing it rigorously to ensure its exactly like my system willing to pay 1k to 5k even 10 depending on how hard the job is... Thank You, Victor
Starting from scratch, I need a solution to develop my own crypto trading and exchange platform. This platform should compare prices across various exchanges like Coinbase, Binance, KuCoin, and Unocoin, as well as different cryptocurrencies. The solution must identify opportunities to buy on one platform and sell on another for a profit, transferring funds to my personal wallet instantly for security. The bot should
3 indicators to entry and exit Displays indicator state. Alerts and grid trades control, lots and hedge Trade management modules that will work across pairs and time frames. Make breaking news in vertical lines and e-mail alert
Hello please my budget 50$ and I will not choose any developer until you complete the work with a full trial version as I want I am ready for any discussion or clarification. I need new EA Range breakout EA and fix my RsiMA EA Range breakout new EA The orders must be pending stop orders, BUY STOP, SELL STOP Input menu Comment Magic number Lot = Fixed TP in points 0 = OFF SL in points 0 = OFF
Can someone please send me an offer of an MT4 EA based on this indicator: https://www.mql5.com/en/code/50636?utm_campaign=codebase.list&amp ;utm_medium=special&utm_source=mt4terminal Open and close position on "change Color" Settings in settings window needed: 1)Dropdown for decision of Lot Size: fix or variable 1a)Variable risk in % of cash: Value in % combine with the difference between entry an SL 1b)Lot-Size as
Range breakout 30+ USD
I need a 1st 3hour candle range breakout ea. With take profit and Stop loss levels in points. That Range clearly shown in colour shades. I need that ea ASAP
I am looking for a programmer to do EA trader. If you can understand what I want from the video i do and you can do it, contact me because you will be able to do what I want. https://drive.google.com/file/d/1wbHxbUQQqCkdpr0-pHfIh2b288LzYTV2/view?usp=sharing
Hi, I am looking for someone who can code a auto lot size calculator for cTrader - where I can drag stop loss line and the algo automatically calculates the lot size I need to place a trade with a fixed % risk of account. It also needs to show the lot size and est. margin on screen before entering and needs to execute market and limit orders. It must work on FX, Commodities, Indices, Stocks and Crypto. With options
Auria2.0 30+ USD
I would like to get your help with compiling my EA ihave my code written in MQL5 when I compile it shows that my strategy have errors bit ican only identify few as I'm not familiar with MQL5 what's in it for you?well after compiling Auria you will get to keep her if you find her interesting
Am looking for a programmer who will convert 2 mt5 indicators into an expert adviser. The buy and sell order will be placed after certain conditions are met which i will specify later to the applicant that i will choose

Project information

Budget
30+ USD
For the developer
27 USD