Simple risk percentage lot size calculation > Not working (yet)

 

Hi All,

I'm trying to have my EA set the lot size based on a risk percentage. Here is some key element of my setup:

Currency of account EUR

Trading pair EURJPY

Leverage 1/100

Fixed SL at 50 pips

Target risk per trade for example 5%

 

I'm also trying to keep that as simple as possible and looking around I found this formula:

Lot Size = Amount Risked / Number of Pips x Pip Value

 

Trying to turn into EA code I created the below. But as you will see from the screenshot below the calculation of "Pips" is really wrong and I'm not sure how to adjust it.

Can anyone help ? 

input int      StopLoss=50;               // Stop Loss
input double   RiskPercentage=5;          // Lots to Trade

int STP, TKP; 
double LotSize;
double Pips;



//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==3)
     {
      STP = STP*10;
      TKP = TKP*10;
     }
   return(0);
  }


 My Buying Script

   if(Buy_Condition_1 && Buy_Condition_2)
     {
         // any opened position?
         if((Buy_opened)||(Sell_opened))
           {
            //Alert("We already have an open Position. Oportuinity passed.");
            return;    // Don't open a new Buy Position
           }
           
         // Calculating Lot size based on SL and Risk Percentage
         
         MqlTick latest_price;
         SymbolInfoTick(_Symbol,latest_price);
         
         Pips = (latest_price.bid - STP)/_Point;          
         
         double AccountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
         double TickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
         LotSize = (AccountBalance * (RiskPercentage/100))/(Pips * TickValue);  
         
         Print("Pips ", Pips, " Acc Bal: ", AccountBalance," Tick Val ", TickValue," Lot Size ", LotSize);      
         
         //Executing the Trade 
         ZeroMemory(mrequest);
         mrequest.action = TRADE_ACTION_DEAL;                                    // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);             // latest ask price
         mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits);   // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits);   // Take Profit
         mrequest.symbol = _Symbol;                                              // currency pair
         mrequest.volume = LotSize;                                                  // number of lots to trade
         mrequest.magic = EA_Magic;                                              // Order Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                         // Buy Order
         mrequest.type_filling = ORDER_FILLING_FOK;                              // Order execution type
         mrequest.deviation=100;                                                 // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
            SendNotification("BBWP added a new Buy order!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();           
            return;
           }
        
     }

 Print Outcome

 

 
wiptheman:

Hi All,

I'm trying to have my EA set the lot size based on a risk percentage. Here is some key element of my setup:

Currency of account EUR

Trading pair EURJPY

Leverage 1/100

Fixed SL at 50 pips

Target risk per trade for example 5%

 

I'm also trying to keep that as simple as possible and looking around I found this formula:

Lot Size = Amount Risked / Number of Pips x Pip Value

 

Trying to turn into EA code I created the below. But as you will see from the screenshot below the calculation of "Pips" is really wrong and I'm not sure how to adjust it.

Can anyone help ? 

 My Buying Script

 

 

  

a couple of points jump to mind....

 

1.  The size of a tick is often not the same as the size of a pip  on a 5 digit broker for instance EURUSD 1 pip is likely equal to 10 ticks, I believe that you can query the symbol for this information and therefore you can work out that your 50 pip SL = XXX ticks so now you can do the calculation and get the right answer.

2. You need to make sure that the trade volume is adjusted to:

a) a minimum of the minimum volume allowed 

b)  a maximum of the maximum volume allowed

c) is in increments of the step value

so if min = 0.1  max =50.0 step = 0.1 you could have volumes of  0.1,  0.2, 0.3  1.5, etc   but not  0.01  0.15 1.35 51.0

 

 

 
this a considering strategy. thanks share
 

Hi Max,

 Thanks a lot for the additional information !!

1. I'm not sure at this point how I can retrieve the tick value and apply it to my risk of 50 pips.

2.a.  And the Max and a Min is a very good advise! 

2.c. Increment values is also a very good advise to avoid Lot with many decimals.   

 

But at this point I'm not sure how to code this. Would someone know how to code that?

 Thanks a lot!

W. 

 

 

 

 

I will look into your code later.

In the mean time please read here https://www.mql5.com/en/forum/7418#comment_295486 and here https://www.mql5.com/en/forum/7417#comment_291743

(bug?) SYMBOL_MARGIN_INITIAL = 0.0
(bug?) SYMBOL_MARGIN_INITIAL = 0.0
  • www.mql5.com
"SYMBOL_MARGIN_INITIAL Initial margin means the amount in the margin currency required for opening a position with the volume of one lot.
 

Hi Phi.nuts,

 Always a pleasure to hear from you!

I read your articles and I realized I should have specified that the EA I'm building only trades one pair and one deal at a time. If a deal is open it will not open a new one. 
I guess this simplifies the margin calculation part of your first article.

The second article GetLotForOpeningPos is very interesting! Seem to be doing the necessaring math for the Min, Max and "steps"

What I can't figure out is how you set the percentage of risk. I would expect an Input Variable where you can set for example the risk to a given percentage?
Or is it based on lot_margin ? Not really sure what that means?

W. 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Environment State / Symbol Properties
Documentation on MQL5: Standard Constants, Enumerations and Structures / Environment State / Symbol Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Environment State / Symbol Properties - Documentation on MQL5
 

seem wrong code here
Pips = (latest_price.bid - STP)/_Point;   

try change it to:

Pips = (latest_price.bid - STP*_Point)/_Point;   
 
tuoitrecuoi:

seem wrong code here

 Hey thank you for helping me with this :) 

 Here are the "printed values" when applying your change. Pips value seem super high no ? What I also find very of is how Lot size goes from 14,383 to 0,00501723 

 

 

 

The account leverage should also take into account.

         Pips = (latest_price.bid - STP*_Point)/_Point;          
         double AccountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
         double TickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
         double Leverage = AccountInfoDouble(AccountLeverage);
         LotSize = (AccountBalance * (RiskPercentage/100))*Leverage/(Pips * TickValue);  

 I don't think "risk percentage" means the money you open your position with but the loss which you are willing to take each time. :)

AccountBalance * (RiskPercentage/100) = STP * TickValue

Documentation on MQL5: Standard Constants, Enumerations and Structures / Environment State / Account Properties
Documentation on MQL5: Standard Constants, Enumerations and Structures / Environment State / Account Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Environment State / Account Properties - Documentation on MQL5
 

Hey Luenbo !!

Thanks for the additional information.  You are right by "risk percentage" I mean the money I'm ready to lose for each deal. 

 I tried your code but "AccountLeverage" is not recongnized : (

W. 

 
wiptheman:

Hey Luenbo !!

Thanks for the additional information.  You are right by "risk percentage" I mean the money I'm ready to lose for each deal. 

 I tried your code but "AccountLeverage" is not recongnized : (

W. 

Sorry, it is AccountInfoInteger(ACCOUNT_LEVERAGE) in MT5.
double Leverage = AccountInfoInteger(ACCOUNT_LEVERAGE);