Close order by sequence

MQL5 Indicadores Experts

Trabalho concluído

Tempo de execução 3 dias
Comentário do cliente
Super genius and super fast
Comentário do desenvolvedor
5 star client! Happy to have worked with Naresh.

Termos de Referência

I need to modify my script to create a loop to check the buy and sell orders profit separately. close when 1st buy order and last buy order's average is profit. 

Currently, my code closes all the buy/sell order's  average is in profit. I would like to modify that for buy and sell orders. 

//+------------------------------------------------------------------+
//|                                               CloseOnAverage.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern int Choose_stragegy=1; // 1-hedging 2-trend
input int             InpMaxTrades = 10;         // Max number of trades
input double          InpTradeGap = 0.005;       // Distance between trades
//input ENUM_ORDER_TYPE InpType = ORDER_TYPE_BUY;  // Order type;//
input double          InpMinProfit = 1.00;       // Profit point
input int             InpMagicNumber = 1111;     // Magic number
input double          Multiplier = 2;       
input string          InpTradeComment = __FILE__; // Trade comment
input double          InpVolume = 0.01;          // Volume per order
double pips;

//double multi= (InpVolume*Multiplier);

struct STradeSum {
   int buycount;
   int sellcount;
   double buyprofit;
   double sellprofit;
   double buytrailPrice;
   double selltrailPrice;
};

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+

void OnTick() 
{
 
   STradeSum  sum;
   GetSum(sum);
    
   if (sum.buyprofit>InpMinProfit) 
   { // target reached
      CloseAll(ORDER_TYPE_BUY);
   } 
   if (OrdersTotal()>=3)
   {
      drawdownreduction();
   }
   
   else if (sum.sellprofit>InpMinProfit) 
   { // target reached
      CloseAll(ORDER_TYPE_SELL);
   }
   
   else if (sum.buycount==0) 
   {  // no buy trades
      OpenTrade(ORDER_TYPE_BUY);
   } 
   
   else if (sum.sellcount==0)
   {  // no sell trades
      OpenTrade(ORDER_TYPE_SELL);
   } 
   
   else if ((sum.buycount<InpMaxTrades))
   {
      
      if ( OrderType()==ORDER_TYPE_BUY && SymbolInfoDouble(Symbol(), SYMBOL_ASK)<=(sum.buytrailPrice-InpTradeGap)) 
      {   // Far enough below
         OpenmultiTrade(ORDER_TYPE_BUY);
      } 
      else if ((sum.sellcount<InpMaxTrades))
      {
         if ( OrderType() ==ORDER_TYPE_SELL && SymbolInfoDouble(Symbol(), SYMBOL_BID)>=(sum.selltrailPrice+InpTradeGap)) 
            {   // Far enough above
              OpenmultiTrade(ORDER_TYPE_SELL);
             }
      }
    }
    
   //else  if (sum.sellcount<InpMaxTrades)     
}

//+------------------------------------------------------------------+

void  OpenTrade(ENUM_ORDER_TYPE InpType) {
 
   double   price =  (InpType==ORDER_TYPE_BUY) ?
                        SymbolInfoDouble(Symbol(), SYMBOL_ASK) :
                        SymbolInfoDouble(Symbol(), SYMBOL_BID);
   OrderSend(Symbol(), InpType, InpVolume, price, 0, 0, 0, InpTradeComment, InpMagicNumber);
    
}

//+------------------------------------------------------------------+

void  OpenmultiTrade(ENUM_ORDER_TYPE InppType) {
 
   double   price =  (InppType==ORDER_TYPE_BUY) ?
                        SymbolInfoDouble(Symbol(), SYMBOL_ASK) :
                        SymbolInfoDouble(Symbol(), SYMBOL_BID);
   double multi = (InpVolume*Multiplier);
   OrderSend(Symbol(), InppType, multi, price, 0, 0, 0, InpTradeComment, InpMagicNumber);
}

//+------------------------------------------------------------------+

void  CloseAll(ENUM_ORDER_TYPE orderType) {
 
   int   count    =  OrdersTotal();
 
   for (int i = count-1; i>=0; i--) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if (  OrderSymbol()==Symbol()
               && OrderMagicNumber()==InpMagicNumber
               && OrderType()==orderType
               ) {
            OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);
         }
      }
   }
 
}
//+------------------------------------------------------------------+

void  GetSum(STradeSum &sum) {
 
   sum.buycount      =  0;
   sum.buyprofit     =  0.0;
   sum.buytrailPrice =  0.0;
   sum.sellcount      =  0;
   sum.sellprofit     =  0.0;
   sum.selltrailPrice =  0.0;
    
   int   count    =  OrdersTotal();
 
   for (int i = count-1; i>=0; i--) 
   {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
      {
      //Buy orders
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==InpMagicNumber && OrderType()== ORDER_TYPE_BUY)
                {
                  sum.buycount++;
                  sum.buyprofit  += OrderProfit()+OrderSwap()+OrderCommission();
                  if (sum.buytrailPrice==0 || OrderOpenPrice()<sum.buytrailPrice)
                     {
                        sum.buytrailPrice =  OrderOpenPrice();
                     }
                 }
          //sellorders
          if (OrderSymbol()==Symbol()&& OrderMagicNumber()==InpMagicNumber && OrderType()==ORDER_TYPE_SELL)
                { 
                  sum.sellcount++;
                  sum.sellprofit  += OrderProfit()+OrderSwap()+OrderCommission();
                  if (sum.selltrailPrice==0 || OrderOpenPrice()>sum.selltrailPrice)
                     {
                        sum.selltrailPrice =  OrderOpenPrice();
                     }
                }
            
        } 
     }
          
   return;
    
}

//+------------------------------------------------------------------+
//found this code online. The below code compares and closes the last two orders
void drawdownreduction()
{
  int slippage=10;
  double minimum_profit=InpMinProfit;
  int x;
  double trades[][4];
  int total=OrdersTotal();
  if(total>1)
  {
  ArrayResize(trades,total);
  for(x=total-1;x>=0;x--)
     {
     if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES))
        {
        trades[x][0]=OrderTicket();
        trades[x][1]=OrderProfit()+OrderCommission()+OrderSwap();
        trades[x][2]=OrderLots();
        trades[x][3]=OrderType();
        }
     }
  
  ArraySort(trades,WHOLE_ARRAY,0,MODE_ASCEND);
  x=0;
  
  while(x<total-1)
     {
     double profit=trades[x][1]+trades[total-1][1];
     if(profit>=minimum_profit)
        {
        RefreshRates();
        double close_price=Ask;
        if(trades[x][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x][0],trades[x][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        RefreshRates();
        close_price=Ask;
        if(trades[x+1][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x+1][0],trades[x+1][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        }
        x+=2;
     }
     }
 }   
  


Respondido

1
Desenvolvedor 1
Classificação
(21)
Projetos
23
0%
Arbitragem
6
17% / 83%
Expirado
2
9%
Livre
2
Desenvolvedor 2
Classificação
(49)
Projetos
62
40%
Arbitragem
1
0% / 100%
Expirado
7
11%
Trabalhando
3
Desenvolvedor 3
Classificação
(182)
Projetos
243
46%
Arbitragem
18
78% / 17%
Expirado
35
14%
Carregado
4
Desenvolvedor 4
Classificação
(139)
Projetos
181
24%
Arbitragem
23
22% / 39%
Expirado
13
7%
Livre
5
Desenvolvedor 5
Classificação
(93)
Projetos
133
35%
Arbitragem
13
38% / 31%
Expirado
32
24%
Livre
6
Desenvolvedor 6
Classificação
(1)
Projetos
1
0%
Arbitragem
2
0% / 100%
Expirado
0
Livre
7
Desenvolvedor 7
Classificação
(570)
Projetos
784
47%
Arbitragem
23
39% / 13%
Expirado
63
8%
Carregado
8
Desenvolvedor 8
Classificação
(24)
Projetos
28
32%
Arbitragem
1
0% / 0%
Expirado
0
Livre
9
Desenvolvedor 9
Classificação
(155)
Projetos
239
70%
Arbitragem
3
67% / 33%
Expirado
20
8%
Livre
Pedidos semelhantes
Trade Manger EA 30+ USD
Hello Programmer! I am looking to build an EA that will place my trade and manage it. Once i have manually found my setup, I will want an EA to open the trade, set the R:R and manage it according to my specifications. please take a look at the attached to get an Idea of what I would like. I will require the source code once completed
Hello there i need someone who will create a robot that will calculate the movement between buy/sell and show where to take profit the robot should work with all currency and indices including stock
EA to send account history to web request. It should send every 5 mins or when there is an update. It then sends the json to a web request where gain, drawdown, balance, equity will be displayed
I have a full strategy based on indicator and candle based on . i would like to make it into a robot which will trade for me on a specific time and specific rules. i need a person who can do this project for me. If you have done this type of job . you are most welcome for this. Apply only if you know binary trading option and binomo trading platform well and how it works
Preciso de um EA, que faça o fecho automático de operações abertas no final da sessão e nas notícias de alto impacto. Um EA simples com apenas 1 função. Fecho das operações abertas
Enter buy trade at close of candle when bar closes above the 3 emas. Emas are 34 ema, 64 ema and 128 ema. For a buy trade the 34 ema must be above the other two emas. The 64 ema should be in the middle. The 128 ema should be below the other two emas. For a buy trade the Awesome Oscillator should be above the middle line and colored green. Exit a buy trade when price touches 64 ema. Sell trade same conditions as buy
I want to make AI based on Attached Picture Swing High low. If you have experience can share demo first. Stop loss, take profit, trailing , break even ,DD etc. also amiable
Hello, I’m looking for a TradingView indicator that fits my forex trading needs. If you can create or customize one for me, please reach out. I'd appreciate your help! Thanks in advance."
I need someone who can code a new EA from scratch and also know how to integrate AI into the EA and use AI and market sentiments along with news to then open positions. I have the description of the job ready. Need someone serious, with experience and who will help optimize the current strategy with their expertise. Thanks
I’m looking for an experienced MQL5 developer to create a custom Break of Structure (BoS) Indicator for MetaTrader 5. This indicator should automatically detect and mark key market structure breakpoints in real-time, offering traders clear visual signals when the market experiences a structural shift. The indicator should include the following features: Automatic detection of Break of Structure (BoS) and Change of

Informações sobre o projeto

Orçamento
30+ USD
Desenvolvedor
27 USD
Prazo
para 2 dias