Close order by sequence

MQL5 Indicadores Asesores Expertos

Trabajo finalizado

Plazo de ejecución 3 días
Comentario del Cliente
Super genius and super fast
Comentario del Ejecutor
5 star client! Happy to have worked with Naresh.

Tarea técnica

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


Han respondido

1
Desarrollador 1
Evaluación
(21)
Proyectos
23
0%
Arbitraje
6
17% / 83%
Caducado
2
9%
Libre
2
Desarrollador 2
Evaluación
(49)
Proyectos
62
40%
Arbitraje
1
0% / 100%
Caducado
7
11%
Trabaja
3
Desarrollador 3
Evaluación
(181)
Proyectos
242
45%
Arbitraje
18
78% / 17%
Caducado
35
14%
Trabaja
4
Desarrollador 4
Evaluación
(139)
Proyectos
181
24%
Arbitraje
23
22% / 39%
Caducado
13
7%
Libre
5
Desarrollador 5
Evaluación
(93)
Proyectos
133
35%
Arbitraje
13
38% / 31%
Caducado
32
24%
Libre
6
Desarrollador 6
Evaluación
(1)
Proyectos
1
0%
Arbitraje
2
0% / 100%
Caducado
0
Libre
7
Desarrollador 7
Evaluación
(564)
Proyectos
777
46%
Arbitraje
23
39% / 13%
Caducado
63
8%
Trabaja
8
Desarrollador 8
Evaluación
(24)
Proyectos
28
32%
Arbitraje
1
0% / 0%
Caducado
0
Libre
9
Desarrollador 9
Evaluación
(155)
Proyectos
239
70%
Arbitraje
3
67% / 33%
Caducado
20
8%
Libre
Solicitudes similares
BUY AND SELL 30+ USD
Create an Expert Advisor that collaborates between these indicators ETR, MEv2 and STLv3 with these features 1. SL and TP 2. TIME FILTER 3. ETR, MEv2 and STLv3 PARAMETERS BUY ENTRY STEP 1. FIRST candle OPEN above Symphonie Trend Line STEP 2. Check Symphonie Extreme must indicate color BLUE STEP 3. Check Symphonie Emotion must indicate color BLUE STEP 4. Open trade with money management STEP 5. Trade open MUST BE 1
Hello, I have a protected Ninja trader Order Flow indicator and I was wondering if you can reverse engineer it to replicate the functionality. H ere are the specifications and indicator: https://docs.google.com/document/d/1KyYwQ7iTL2KWGhnZzxS1gObccu9LPMrGuMc9Mdk_3KY/edit?usp=sharing
I have an EA that need some changes including integrating the indicator code directly into the Expert Advisor. I will give the detailed doc once we settle on the candidate for the job . Please bid if you can work with the stated amount. Thanks
Hello, Need to convert Tradingview Indicator to MQL4 indicator. or if you have this one converted already, let me buy a copy please. If we're good, then will definitely buy it and ask to convert into EA on new order. Supertrend by KivancOzbilgic
Fix bug or modify an existing Trading view indicator to display correct. The indicator is working but not displaying/plotting all the information i want. So i want it adjusted to plot all the info
Here's a brief requirement you can use: **Description:** I am seeking an experienced MQL5 developer to create a (EA). The EA should include features for placing pending orders (Buy Stop and Sell Stop) based on market spread, managing trades effectively at the opening of new candlesticks, and implementing take profit and stop loss strategies. Additionally, I would like the option to adjust parameters based on market
I have an EA which i need to do below modifications. Variable Inputs to be added Order Type : Market , Pending Trade Type : Buy, Sell , Buy & Sell Pending Pips Step : ( Pips Value can be negative or positive to decide on what type of Pending Order ) // If trade type Buy is selected Close Type : Close All ( Bulk Close Option in MT5 ) , Close Individually Close Option : %of Equity , %of Balance , Amount $ , %of No
Add multiplier to grid recovery system. For example: Grid Trade 2-3 Spacing; 1.0 Multiplier Grid Trade 4-6 Spacing; 2.0 Multiplier Grid Trade 7+ Spacing; 1.6 Multiplier Need quick turn around. Need it done ASAP
Objects reader PIN 70 - 100 USD
Hi I have an indicator that create objects in the chart and using those following some rules the new indicator will create external global variables with value = 0 ( NONE ), = 1 ( BUY ) or = 2 ( SELL ). The global variable will use PIN external integer number . PINS are by now global variables (GV) whose name indicates the pair name and the PIN belonging and their value indicates it direction/action. PINS GV names
I want an indicator and its source code that returns the value of: - two moving averages in different selectable timeframes, with method Exponential and price calculation price_open; - Opening, closing, maximum and minimum of the candle in different timeframes And that returns the values ​​regardless in a chart of one minute. The input parameters: * select timeframe media1 = {1,2,3,4,5,...} * select timeframe media2

Información sobre el proyecto

Presupuesto
30+ USD
Para el ejecutor
27 USD
Plazo límite de ejecución
a 2 día(s)