User defined function, help

 

Hi, My EA is opening a grid of sell orders when the price goes down, and a grid of buy orders when the price goes up. I need to calculate the last ( current) order so that if pair goes to an input price, the whole cycle will achieve break even.

I wrote a function for that but it seems not working correct. 

double CalculateSubsequent(int MAGIC, int type, double BEPrice)
  {
   double minLot = MarketInfo(Symbol(),MODE_MINLOT);
   double maxLot = MarketInfo(Symbol(),MODE_MAXLOT);
   double c_price = Ask;
   double prices = 0;
   double lots = 0;
   double lot = 0;
   if(type == 1)
      c_price = Bid;
   for(int i = 0 ; i < OrdersTotal() ; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol() != Symbol())
            continue;
         if(OrderMagicNumber() != MAGIC || OrderType() != type)
            continue;
         prices += OrderOpenPrice();
         lots += OrderLots();
        }
     }
   lot = ((prices + c_price)/BEPrice) - lots; // this equation is not correct I believe
   if(lot >= maxLot)
      lot = maxLot;
   if(lot < minLot)
      lot = minLot;
   return (NormalizeDouble(lot,2));
  }

I used excel to prove if it is working correct or not. It seems it is wrong. 

Example:

I have 4 sell orders opened on a grid every 10 pips: 

1- 0.1 lot at 1.1200

2-0.2 lot at 1.1190

3-0.3 lot at 1.1180 

4-0.4 lot at 1.1170

Now the EA wants to open the 5th order at 1.1160 and needs to calculate the sizing of the fifth so that if price goes to 1.1180, the whole cycle profit = 0

Please help


 

 

I think the answer is highly related to this post but I amnot sure how to incorporate these equations ( especially they are in the picture format and include special characters) and I am not a mathematician.

https://www.mql5.com/en/forum/279448/page10#comment_8704870

Any great idea about HEDGING positions welcome here
Any great idea about HEDGING positions welcome here
  • 2018.09.17
  • www.mql5.com
i am a professional trader that have been in the marketplace since 9 years ago...