MQL5 ATR Based Position Size Calculator

OMID  

GREETINGS

So should the price hit our Stoploss, we lose 2% of our equity

The formula to calculating the proper lot size is Equity*Risk/Stoploss

Now our Stoploss is going to be 2*ATR Value

I've been trying to turn all this into an MQL5 code

PROBLEM: When I set the SL to a number (e.g. 50), the EA works perfectly fine; however when I try setting the ATR value as the SL, it doesn't work (no issue with compiling the file).


ANY IDEAS?

   #include <Trade\Trade.mqh>

   CTrade trade;
  
 
void OnTick()
  {

      double Bid=NormalizeDouble(SymbolInfoDouble(_Symbol ,SYMBOL_BID),_Digits);
      
      double ATRArray [];
      int ATRDefinition = iATR(_Symbol,_Period,14);
      ArraySetAsSeries(ATRArray,true);
      CopyBuffer(ATRDefinition,0,0,3,ATRArray);
      double ATRValue=NormalizeDouble(ATRArray[0],_Digits);
      
      double Stoploss=NormalizeDouble(ATRValue*10000,_Digits);
      double Equity=AccountInfoDouble(ACCOUNT_EQUITY);
      double Risk=NormalizeDouble(0.02,2);
      double LotSize= NormalizeDouble(Equity*Risk/Stoploss,2);      
     
      if (PositionsTotal()<1)
      
      trade.Sell(LotSize,NULL,Bid, (Bid + Stoploss*_Point), (Bid- 3 * Stoploss * _Point), NULL);
      }
Vladimir Karputov  

First, correct your main mistake: you create an indicator handle at every tick.

Remember: in MQL5, the indicator handle is created ONCE! And this is done in OnInit !!!

Reason: