max money at risk per trade

 
Hi,
I want to write a script to limit the money at risk per trade. I want to limit my risk at n% of my equity. I found some scripts in the forum but still have some questions..
I found:
lot = NormalizeDouble(AccountFreeMargin() * Risk * 0.01 * MarketInfo(Symbol(), MODE_TICKSIZE), 2);//last 2 changes to 1 depending on account type
also
lotsize = NormalizeDouble(AccountFreeMargin()*(MaximumPercentageatRisk/100)/1000.0,2); //last 2 changes to 1 depending on account type

Why the difference between those two? why people don't take into account the leverage ?
Shouldn't it be something like freemargin * % risk * leverage = max to invest and then obtain the lot size... (How? I don't know)

can someone please help? I am really confused.
 
emforex:
why people don't take into account the leverage ?

You are confusing max leverage with actual leverage. If your broker says u can have 1:100 leverage it means up to 1:100 leverage. True leverage depends on your balance and your position's total lot size.

 
True risk is the initial stop loss times $ amount of a point. Choose your opening price. Choose your SL per the market. Control risk by limiting the lot size.
//+------------------------------------------------------------------+
//| Lot size computation.                                            |
//+------------------------------------------------------------------+
//double        atRisk;                                                 // Export to Comment and Init.
double  LotSize(double SL_points, bool modifying = false) {
    /* This function computes the lot size for a trade.
     * Explicit inputs are SL relative to bid/ask (E.G. SL=30*points,) and if
     * returned lot size will be used in a new order or be used to modify an
     * pending order (trade count-1.) Implicit inputs are the MM mode, the MM
     * multiplier and currently filled or pending trade count (used to reduce
     * available balance.) Mode, multiplier, adjusted account balance determined
     * the maximum dollar risk allowed. StopLoss determines the maximum dollar
     * risk possible per lot. Lots=maxRisk/maxRiskPerLot
     **************************************************************************/
    double  ab  = AccountBalance();
    switch(MMMode_F0M1G2) {
    case MMMODE_FIXED:
        atRisk  = MMMultplier;
        break;
    case MMMODE_MODERATE:
        // See https://www.mql5.com/en/articles/1526 Fallacies, Part 1: Money
        // Management is Secondary and Not Very Important.
        atRisk  = MathSqrt(MMMultplier * ab)/ab;    // % used/trade ~const.
        atRisk  = MathSqrt(MMMultplier * ab
                            * MathPow( 1 - atRisk, OrdersTotal()-modifying ));
        break;
    case MMMODE_GEOMETRICAL:
        atRisk  = MMMultplier * ab
                            * MathPow(1 - MMMultplier, OrdersTotal()-modifying);
        break;
    }
    double  maxLossPerLot   = SL_points/Point
                            * MarketInfo( Symbol(), MODE_TICKVALUE );
    // IBFX demo/mini       EURUSD TICKVALUE=0.1 MAXLOT=50 LOTSIZE=10,000
    // In tester I had a sale: open=1.35883 close=1.35736 (0.00147)
    // gain$=97.32/6.62 lots/147 points=$0.10/point or $1.00/pip.
    // IBFX demo/standard   EURUSD TICKVALUE=1.0 MAXLOT=50 LOTSIZE=100,000
    //                                  $1.00/point or $10.00/pip.
    double  LotStep = MarketInfo( Symbol(), MODE_LOTSTEP ),
    // atRisk / maxLossPerLot = number of lots wanted. Must be rounded/truncated
    // to nearest lotStep size.
    //
    // However, the broker doesn't care about the atRisk/account balance. They
    // care about margin. margin used=lots used*marginPerLot and that must be
    // less than free margin available.
    marginFree   = AccountFreeMargin() * 0.90,  // Allow some slack for PAIRS
    marginPerLot = MarketInfo( Symbol(), MODE_MARGINREQUIRED ),
    // So I use, the lesser of either.

    // I don't use MODE_MAXLOT as OpenNow handles that.
    size =  MathFloor(  MathMin ( marginFree / marginPerLot
                                , atRisk     / maxLossPerLot )
                        / LotStep )*LotStep;        // truncate
    if (size < MarketInfo( Symbol(), MODE_MINLOT )) {
        // Multiple orders -> no free margin -> LotSize(SL=4.1)=0
        // [risk=9.48USD/40.80, margin=10.62/1334.48, MMM=1x1, coat=0]
        //       0.23                  0.007
        Print(
            "LotSize(SL=", DoubleToStr(SL_points/pips2dbl, Digits.pips), ")=",
            size, " [risk=",    atRisk, AccountCurrency(),  "/", maxLossPerLot,
                    ", margin=",    marginFree,             "/", marginPerLot,
                    ", MMM=",       MMMode_F0M1G2,          "x", MMMultplier,
                    ", coat=",      OrdersTotal(),  // Count Of active trades
                "]" );
        return(0.0);    // Risk limit.
    }
    atRisk  = size * maxLossPerLot; // Export for Comment
    return(size);
}   // LotSize

 
whroeder1:
True risk is the initial stop loss times $ amount of a point. Choose your opening price. Choose your SL per the market. Control risk by limiting the lot size.

Hello Whroeder1, is this for MQL5? I have been looking for a code for my robots on MQL5. I'm not sure how to include it on my code.

I need to use size as the lot size for the order.

And, SL_points as the stop loss? In my case the stop loss is calculated on each trade based on ATR and a factor.


Thanks!

Reason: