Adding direction to reversal opening

MQL5 Experts

Trabalho concluído

Tempo de execução 4 minutos
Comentário do cliente
Experienced coder of our generation, flexible and understanding each and every details. He is fast, faster than Japanese bullet train.
Comentário do desenvolvedor
Excellent client I will help him again thank you

Termos de Referência

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

Arquivos anexados:

Respondido

1
Desenvolvedor 1
Classificação
(8)
Projetos
11
18%
Arbitragem
7
43% / 29%
Expirado
1
9%
Livre
2
Desenvolvedor 2
Classificação
(77)
Projetos
94
43%
Arbitragem
4
50% / 50%
Expirado
2
2%
Livre
3
Desenvolvedor 3
Classificação
(10)
Projetos
15
27%
Arbitragem
3
67% / 33%
Expirado
0
Trabalhando
4
Desenvolvedor 4
Classificação
(37)
Projetos
59
27%
Arbitragem
25
20% / 52%
Expirado
10
17%
Trabalhando
5
Desenvolvedor 5
Classificação
(130)
Projetos
165
36%
Arbitragem
4
25% / 50%
Expirado
13
8%
Carregado
6
Desenvolvedor 6
Classificação
(96)
Projetos
143
76%
Arbitragem
0
Expirado
2
1%
Livre
Pedidos semelhantes
I have an indicator that give signals. I would like an EA to automate the strategy. the Indicator gives an arrow in the direction the trade needs to open. Attached is a picture of the indicator. I have also attached the Indicator as well as a word document of what I would like be able to select on the EA
Hello, I am seeking an experienced expert who can assist me in converting a trading indicator or strategy written in Vbox Thinkscript into a compatible format for use with Sierra Chart
My idea _Anna. 50+ USD
I'm looking for a strategy where I can specify two points, such as Point A and Point B, which could be based on today's high/low or yesterday’s high/low, etc. I should have the option to define these points. The system should execute a buy order when the price goes above Point A, with the ability to set a target in percentage or points, as well as a stop-loss. Similarly, when the price drops below Point B, it should
RackemupEA is based on an indicator which was made freely available to all. The mql4 file is attached. The requirements doc spells out easy to understand entry/exit conditions as well as some trade management functions to control the size of successive entries in the series. Series (or sequence) is a set of trades that open in the same direction, either long or short. The EA will and must be FIFO compliant. Hedging
I have one expert advisor. I optimized it and generated 3 optimized set files. As each EA can run only single set file, I need my EA to run with the parametrization from 3 set files at the same time because trade conditions those are defined by the set files are not same
Buy - 2 or 3 (option) moving average (simple or exponential) alignment, with the shortest above the longest and if 3, with the second in the middle of the others 2. Wait a candle close above the one or two (option) previous maximums Stop loss: in the minimum of previous candle or minimum of the enter candle (option) with option to add 5, 10, 15, 20, 25, 30, 35, 40, 45 or 50 points below (options to set) Trailing stop
Project Overview Develop a custom automated trading bot (Expert Advisor) for MetaTrader 4 (MT4) that executes trades on the S&P 500 index CFDs via CMC Markets. The bot will implement a momentum-based trading strategy that utilizes technical indicators for market entry and exit signals, incorporates dynamic stop-loss orders, adjusts position sizes based on market momentum, and adheres to strict risk management
Hello, I want to make simple EA for MT5 where I can set main pair and correlated pair and if main pair open trade it will open opposite trade on correlated pair and when main pair close trade it will close trade on correlated pair also. For example if I set US30 as main and NAS100 as correlated and open buy on US30 it will open sell on NAS100. When I close buy on US30 it also close sell on NAS100. Additional options
no order will be given until you prove that you are capable to code , so at least make a basic demo first to take the final order from me. and i can not afford to pay more than 30 usd. so its final offer EA should work with any pair like jpy , oil and Gold pairs along with EURUSD , GBPUSD etc and GBPJPY and too Lot size … its fixed for all. So which ever size client set . it will set for all the trades Gap between
My Goal: I want to make an EA that makes money using AI.. with zero losses and 100% winning chances and we will continue to upgrade and design the EA until we reach our goal. this could be a long term project

Informações sobre o projeto

Orçamento
30+ USD
Desenvolvedor
27 USD