Close order by sequence

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

Время выполнения 3 дня
Отзыв от заказчика
Super genius and super fast
Отзыв от исполнителя
5 star client! Happy to have worked with Naresh.

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

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


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

1
Разработчик 1
Оценка
(21)
Проекты
23
0%
Арбитраж
6
17% / 83%
Просрочено
2
9%
Свободен
2
Разработчик 2
Оценка
(49)
Проекты
62
40%
Арбитраж
1
0% / 100%
Просрочено
7
11%
Работает
3
Разработчик 3
Оценка
(181)
Проекты
242
45%
Арбитраж
18
78% / 17%
Просрочено
35
14%
Работает
4
Разработчик 4
Оценка
(139)
Проекты
181
24%
Арбитраж
23
22% / 39%
Просрочено
13
7%
Свободен
5
Разработчик 5
Оценка
(93)
Проекты
133
35%
Арбитраж
13
38% / 31%
Просрочено
32
24%
Свободен
6
Разработчик 6
Оценка
(1)
Проекты
1
0%
Арбитраж
2
0% / 100%
Просрочено
0
Свободен
7
Разработчик 7
Оценка
(564)
Проекты
777
46%
Арбитраж
23
39% / 13%
Просрочено
63
8%
Работает
8
Разработчик 8
Оценка
(24)
Проекты
28
32%
Арбитраж
1
0% / 0%
Просрочено
0
Свободен
9
Разработчик 9
Оценка
(155)
Проекты
239
70%
Арбитраж
3
67% / 33%
Просрочено
20
8%
Свободен
Похожие заказы
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

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

Бюджет
30+ USD
Исполнителю
27 USD
Сроки выполнения
до 2 дн.