[Help - fixed] Leverage is disturbing my Size calculation. Using TV.

 

Hi all.

My function SetSize is working on my own trading conditions, but not working on high leverage or low account balances as I extecpted.

I expected on a smaller account the size to be smaller since I am making it a function of the balance.

I expected on a large leverage account the size to also be smaller to get to the same dollar value risk.

What am I doing wrong?

float SetSize(string par) {
//   DeltaValuePerLot(par);
   double point=SymbolInfoDouble(par,SYMBOL_POINT);

   DeltaValuePerLot(par);

   int stopLossDistance=350; // dist em points
   


   double PositionRisk=AccountInfoDouble(ACCOUNT_EQUITY)*0.01;    // Static Risk to 1% account Equity

// Calculate lotSize
   float lotSize=point*PositionRisk/(stopLossDistance*DeltaValuePerLot(par));
printf("-----------------");
printf("LotSize pre digits: "+lotSize);
printf("Money Risk: "+DoubleToString(PositionRisk));
printf("TS: "+SymbolInfoDouble(par,SYMBOL_TRADE_TICK_SIZE));
printf("TV: "+SymbolInfoDouble(par,SYMBOL_TRADE_TICK_VALUE));
// DIGITS
   if(SymbolInfoInteger(par,SYMBOL_DIGITS)==2) lotSize=lotSize/SymbolInfoDouble(par,SYMBOL_POINT);  // XAU & XAG

// Cap lotSize by Free Margin & Leverage
   lotSize=floor(lotSize/SymbolInfoDouble(par,SYMBOL_VOLUME_MIN))*SymbolInfoDouble(par,SYMBOL_VOLUME_MIN);

   if(lotSize<SymbolInfoDouble(par,SYMBOL_VOLUME_MIN)) lotSize=SymbolInfoDouble(par,SYMBOL_VOLUME_MIN);
   double margin=0;


Print("Returned Size:"+lotSize);
   return lotSize;
}

double  DeltaValuePerLot(string pair){
//printf("Entering DeltaValuePerLot: "+SymbolInfoDouble(pair,SYMBOL_TRADE_TICK_VALUE) / SymbolInfoDouble(pair,SYMBOL_TRADE_TICK_SIZE));
    if (pair == "") pair = Symbol();
    return(SymbolInfoDouble(pair,SYMBOL_TRADE_TICK_VALUE)
           / SymbolInfoDouble(pair,SYMBOL_TRADE_TICK_SIZE)); // Not Point.
}



Case 1)

10k account, 1:33 leverage, risks $100 as expected


2023.06.22 23:14:30.445 2020.05.01 01:37:20   -----------------

2023.06.22 23:14:30.445 2020.05.01 01:37:20   LotSize pre digits: 0.0028571428265422583

2023.06.22 23:14:30.445 2020.05.01 01:37:20   Money Risk: 100.00000000

2023.06.22 23:14:30.445 2020.05.01 01:37:20   TS: 0.01

2023.06.22 23:14:30.445 2020.05.01 01:37:20   TV: 0.01

2023.06.22 23:14:30.445 2020.05.01 01:37:20   Returned Size:0.2800000011920929


Case 2)

10k account, 1:100 leverage, risks $100 as expected



2023.06.22 23:19:25.060 2020.05.01 02:44:40   -----------------

2023.06.22 23:19:25.060 2020.05.01 02:44:40   LotSize pre digits: 0.0028571428265422583

2023.06.22 23:19:25.060 2020.05.01 02:44:40   Money Risk: 100.00000000

2023.06.22 23:19:25.060 2020.05.01 02:44:40   TS: 0.01

2023.06.22 23:19:25.060 2020.05.01 02:44:40   TV: 0.01

2023.06.22 23:19:25.060 2020.05.01 02:44:40   Returned Size:0.2800000011920929


I expected a 3 times smaller Size since the leverage is 3x

Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Account Properties
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Account Properties
  • www.mql5.com
Account Properties - Environment State - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
Nuno Madeira Amaro Pire Costa: My function SetSize is working on my own trading conditions, but not working on high leverage or low account balances as I extecpted.

Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

  1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support. Then you compute your lot size.

  2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)

  3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
              MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
              Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
              Lot value calculation off by a factor of 100 - MQL5 programming forum (2019)

  4. You must normalize lots properly and check against min and max.

  5. You must also check Free Margin to avoid stop out

  6. For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)

Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

 

Risk depends on the size of the stop-loss, which then has to be adjusted depending on the % margin you want to apply.

Here are a few of some of my related posts:

Forum on trading, automated trading systems and testing trading strategies

Confused about tickvalue

Fernando Carreiro, 2023.04.26 13:27

This site has something called "search" ... https://www.mql5.com/en/search#!keyword=OrderCalcProfit%20calculate%20volume&module=mql5_module_forum

To calculate the correct volume for your trade, you should ...

  1. Use the OrderCalcProfit to first obtain the correct volume based on your stop-loss size and percentage risk.
  2. Adjust the volume, based on the contract specifications
  3. Use the OrderCalcMargin to verify that the volume is within the margin limits and requirements, and if not, then either reduce the volume or abort the trade.
  4. And finally, before placing the order, use OrderCheck to make sure everything is in valid.

Forum on trading, automated trading systems and testing trading strategies

P&L calculation formula for different traded assets

Fernando Carreiro, 2023.05.04 14:53

I suggest reading up on the following two MQL5 trade functions ...

OrderCalcMargin

Calculates the margin required for the specified order type, in the deposit currency

OrderCalcProfit

Calculates the profit based on the parameters passed, in the deposit currency

They calculate the margin and the profit/loss respectively, adjusting automatically for the asset type, making it unnecessary to calculate it manually using the methods you have described.

They do however, not include Commission or Swaps. Those are only provided after the fact and are accessible via other functionality — Documentation on MQL5: Trade Functions

Forum on trading, automated trading systems and testing trading strategies

How to calculate take profit from currency

Fernando Carreiro, 2022.09.05 17:00

These are all the same equation written in different ways ...

[Volume]      = [Money Value] * [Tick Size] / ( [Tick Value] * [Stop Size] )
[Stop Size]   = [Money Value] * [Tick Size] / ( [Tick Value] * [Volume]    )
[Money Value] = [Volume]      * [Stop Size] * [Tick Value]   / [Tick Size]

[Volume] in lots
[Stop Size] in quote price change
[Money Value] in account currency

Forum on trading, automated trading systems and testing trading strategies

SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) sometimes zero

Fernando Carreiro, 2022.08.23 17:41

You can! These are the steps I take. I supply the function with a lot size equal to the “Max Lot Size” allowed for the symbol in question, then calculate the ratio needed to achieve the fractional risk that I wish to apply, to get the correct volume for the order. I then align that with the “Lot Step” and finally check it against both the maximum and minimum allowed lots for the symbol.

The reason I use the “maximum” lots instead of just “1.0” lots as a reference value is because there is no guarantee that the value of 1.0 is within the minimum and maximum values allowed. Given that using 1.0, or the maximum, gives equivalent results anyway (by using the ratio method), I choose to use the “max lots” as the reference point which also offers the most precision for the calculation.

Something like this ...

// This code will not compile. It is only a example reference

if( OrderCalcProfit( eOrderType, _Symbol, dbLotsMax, dbPriceOpen, dbPriceStopLoss, dbProfit ) )
{
   dbOrderLots = fmin( fmax( round( dbRiskMax * dbLotsMax / ( -dbProfit * dbLotsStep ) )
               * dbLotsStep, dbLotsMin ), dbLotsMax ); 
      
   // the rest of the code ...
};

Forum on trading, automated trading systems and testing trading strategies

Market Registration of EA Unable to Validate

Fernando Carreiro, 2022.08.30 14:20

For your screenshot with an Error 131 and it also has a link on "How to fix it". So follow up on it and fix your EA accordingly.

In regards to volume, you have to check the contract specification of the symbol and limit your volume to the minimum, maximum and step that is allowed for the symbol.

// Variables for symbol volume conditions
   double
      dbLotsMinimum = SymbolInfoDouble( _Symbol, SYMBOL_VOLUME_MIN  ),
      dbLotsMaximum = SymbolInfoDouble( _Symbol, SYMBOL_VOLUME_MAX  ),
      dbLotsStep    = SymbolInfoDouble( _Symbol, SYMBOL_VOLUME_STEP );
       
// Adjust volume for allowable conditions
   dbLots = fmin(  dbLotsMaximum,                           // Prevent too greater volume
            fmax(  dbLotsMinimum,                           // Prevent too smaller volume
            round( dbLots / dbLotsStep ) * dbLotsStep ) );  // Align to step value
 
Nuno Madeira Amaro Pire Costa:...

I expected a 3 times smaller Size since the leverage is 3x

Why are you expecting that ?

Your lot size is calculated from risk (SL) and an amount of money to risk. Nothing to do with the leverage which will change the margin, not the risk.

If you want your lot size to take into account the leverage then include the leverage somehow in your calculations.

 

I was already using the DeltaValuePerLot, but it was my understanding of the code that was not correct.

My expectation was wrong so when I exposed my code to a higher leverage, I had a result I was not expecting.

I have read the info and link provided and I want to thank you all for your contributions. Was very helpful!

Reason: