Adding direction to reversal opening

MQL5 Эксперты

Работа завершена

Время выполнения 4 минуты
Отзыв от заказчика
Experienced coder of our generation, flexible and understanding each and every details. He is fast, faster than Japanese bullet train.
Отзыв от исполнителя
Excellent client I will help him again thank you

Техническое задание

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;
}

Файлы:

Откликнулись

1
Разработчик 1
Оценка
(8)
Проекты
11
18%
Арбитраж
7
43% / 29%
Просрочено
1
9%
Свободен
2
Разработчик 2
Оценка
(67)
Проекты
83
40%
Арбитраж
4
50% / 50%
Просрочено
2
2%
Свободен
3
Разработчик 3
Оценка
(10)
Проекты
15
27%
Арбитраж
3
67% / 33%
Просрочено
0
Свободен
4
Разработчик 4
Оценка
(37)
Проекты
59
27%
Арбитраж
25
20% / 52%
Просрочено
10
17%
Работает
5
Разработчик 5
Оценка
(126)
Проекты
160
36%
Арбитраж
4
25% / 50%
Просрочено
13
8%
Свободен
6
Разработчик 6
Оценка
(96)
Проекты
143
76%
Арбитраж
0
Просрочено
2
1%
Свободен
Похожие заказы
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
ROBO EA(MQL CODING) 50 - 200 USD
i have required EA(auto Bot) i will give some ideas in that way i need EA please study and understand my view what exact i want first order buy and sell of 0.01 lot Example Conditions 1) if market movies 100 pips(selection of button 100 or 200 or 300 pips my choice) upward direction then place order i.e 0.02 (buy) if it will give profit 5 dollars then close all trades at time. like same SELL also. 2) first order

Информация о проекте

Бюджет
30+ USD
Исполнителю
27 USD