Code for risk per trade?

 

Hello,


I have coded my first EA and I am looking for the code that will open lot sizes at a percentage of my account. Can anyone help please?

 
Lots=NormalizeDouble((AccountEquity()*Profit_F),2);
 
Thanks, where do I place that code and do I need to add anything else anywhere in the code or just that line. Please help me I am new to this and have been code bashing flat out for days.
 

I'm kinda new programmer too. There's no easy way. There are advanced versions of what we'll call Money Management. That code is my simple version I used since I started programming.

1st, You define Lots.

double Lots=0.1;

2nd, You define Risk or Percentage

double Profit_F=0.00002;

3rd, Insert Lots in OrderSend()

OrderSend(NULL,OP_BUY,Lots,Price,Slip,Stop_Loss,Take_Profit,
Comments,Magic#,Exp,Color);

For additional detail understanding try the book

https://book.mql4.com//

 

gangsta1 I'd recommend, based upon your response to ubzen, that you should take some time away from "code bashing", read the book and get things straight in your head. You'll find yourself a lot more productive that way. And more relaxed.

CB

 
Thanks guys.
 
ubzen:
Lots=NormalizeDouble((AccountEquity()*Profit_F),2);
I disagree. Actual risk is the point value per lot * lot size * maximum point risk (open price minus initial stop loss). Here's my code:
//+------------------------------------------------------------------+
//| Lot size computation.                                            |
//+------------------------------------------------------------------+
double  LotSize(double SLpoints){
/*double    TSSF.value, TEF.value;          // Import from ComputeTSSF
//double    at.risk;                        // Export to init/start/OpenNew */
    /* This function computes the lot size for a trade.
     * Explicit inputs are SL relative to bid/ask (E.G. SL=30*points,)
     * Implicit inputs are the MM mode, the MM multiplier, count currently
     * filled orders by all EA's vs this EA/pair/period count and history.
     * Implicit inputs are all used to reduce available balance the maximum
     * dollar risk allowed. StopLoss determines the maximum dollar risk possible
     * per lot. Lots=maxRisk/maxRiskPerLot
     **************************************************************************/

    /*++++ Compute lot size based on account balance and MM mode*/{
    double  ab  = AccountBalance();
    switch(Money.Management.F0M1G2){
    case MMMODE_FIXED:
        at.risk = Money.Management.Multiplier;
        break;
    case MMMODE_MODERATE:
        // See https://www.mql5.com/en/articles/1526 Fallacies, Part 1: Money
        // Management is Secondary and Not Very Important.       // %used/trade=
        at.risk = MathSqrt(Money.Management.Multiplier * ab)/ab; // ~const rate.
        at.risk = MathSqrt(Money.Management.Multiplier * ab
                            * MathPow( 1 - at.risk, OrdersTotal() ));
        break;
    case MMMODE_GEOMETRICAL:
        at.risk = Money.Management.Multiplier * ab *
                MathPow(1 - Money.Management.Multiplier, OrdersTotal());
        break;
    }
    double  maxLossPerLot   = SLpoints * PointValuePerLot(),
    /* Number of lots wanted = at.risk / maxLossPerLot rounded/truncated to
    /* nearest lotStep size.
    /*
    /* However, the broker doesn't care about the at.risk/account balance. They
    /* care about margin. Margin used=lots used*marginPerLot and that must be
    /* less than free margin available. */
            marginFree      = AccountFreeMargin()*0.95, // Allow some slack
            marginPerLot    = MarketInfo( Symbol(), MODE_MARGINREQUIRED ),
    // So I use, the lesser of either.
            size = MathMin(marginFree / marginPerLot, at.risk / maxLossPerLot);
    /*---- Compute lot size based on account balance and MM mode*/}
    /*++++ Combine TSSF and trade size*/{
    double  minLot  = MarketInfo(Symbol(), MODE_MINLOT);
    if (size < minLot){ // Multiple orders -> no free margin
            // [risk=9.48USD/40.80, margin=10.62/1334.48, MMM=1x1, ExtraOO=0]
            //       0.23                  0.007
        Print(
            "LotSize(SL=", DoubleToStr(SLpoints/pips2dbl, Digits.pips), ")=",
            size, " [risk=", at.risk, AccountCurrency(),    "/", maxLossPerLot,
                    ", margin=",    marginFree,             "/", marginPerLot,
                    ", MMM=",       Money.Management.F0M1G2,"x",
                    Money.Management.Multiplier,
                    ", ExtraOO=",   OrdersTotal(),
                "]" );
        return(0.0);    // Risk limit.
    }
    if (!TSSF.Enable01) double  adjFactTSSF = 1;
    else                        adjFactTSSF = MathMin(1,(TSSF.value-1)/(TSSF.Max-1));
    if (!TEF.Enable01)  double  adjFactTEF  = 1;
    else                        adjFactTEF  = MathMin(1,MathMax(0,TEF.value));
    double  LotStep     = MarketInfo(Symbol(), MODE_LOTSTEP);
    size =  MathMax( minLot
                   , MathFloor(size*adjFactTSSF*adjFactTEF/ LotStep)*LotStep
                   );
    /*---- Combine TSSF and trade size*/}
    at.risk = size * maxLossPerLot; // Export for Comment
    return(size);
}   // LotSize
double PointValuePerLot() { // Value in the account currency of a Point of Symbol.
    /* 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/mini       EURUSD TICKVALUE=0.1 MAXLOT=50 LOTSIZE=10,000
     * IBFX demo/standard   EURUSD TICKVALUE=1.0 MAXLOT=50 LOTSIZE=100,000
     *                                  $1.00/point or $10.00/pip.
     *
     * https://www.mql5.com/en/forum/127584 CB: MODE_TICKSIZE will usually return the
     * same value as MODE_POINT (or Point for the current symbol), however, an
     * example of where to use MODE_TICKSIZE would be as part of a ratio with
     * MODE_TICKVALUE when performing money management calculations which need
     * to take account of the pair and the account currency. The reason I use
     * this ratio is that although TV and TS may constantly be returned as
     * something like 7.00 and 0.00001 respectively, I've seen this
     * (intermittently) change to 14.00 and 0.00002 respectively (just example
     * tick values to illustrate). */
    return(  MarketInfo(Symbol(), MODE_TICKVALUE)
           / MarketInfo(Symbol(), MODE_TICKSIZE) ); // Not Point.
}

 

He.he.he, I knew it was coming. Well there's the Advanced Version of what we'll call Money Management. IMO such a code is not easy for a Newbie programmer to figure out/nor use. Does my code not accomplish the same thing?

extern double Profit_F=0.00002;
extern double Lots=0.1;

Lots=NormalizeDouble((AccountEquity()*Profit_F),2);
if(Lots<0.1) Lots=0.1;

If I want to bet no more than 2% of capital. I know that 1/pip = .0001 = $1. If my initial stop_loss is 100/pips. And my account equity is $10,000. Then AccountEquity()*Profit_F = 0.2 Lots. 0.2*100/pips = $200. $200 is 2% of 10,000. Goal achieved :)

Now on the other hand, if my initial stop_loss was 200/pips. If I want to bet no more than 2% of capital, I just make the Profit_F=0.00001;....And for 50/pip SL, Profit_F=0.00004;

Yeah I know it assumes some responsibility on the user. Your version is more correct but I don't believe would get a noob to start coding if they had to understand that first. Can anyone Advanced point out a major flaw in my approach. Ps: I don't believe we can get the Risk % to be exact with any method because of factors like minimum workable broker lot sizes. So the rounding off works for me, and when it doesn't I just decrease the Profit_F variable.

 

I think an advanced money management code is a "one-size-fits-all" solution, its good and nice but do you really need it? If you are a trader, you will know the SL & TP levels your EA will use. I doubt if there are any EAs that trade with a 1000 pip SL on one trade and 10 pips on another. This would be ridiculous. I would prefer the simpler code if two codes do nearly the same thing.

 
savastekin:

I think an advanced money management code is a "one-size-fits-all" solution, its good and nice but do you really need it? If you are a trader, you will know the SL & TP levels your EA will use. I doubt if there are any EAs that trade with a 1000 pip SL on one trade and 10 pips on another. This would be ridiculous. I would prefer the simpler code if two codes do nearly the same thing.

Right, but it would not be uncommon for an EA to have variable SL based on indicators. Although not to your extremes, my own EA will trades variable SL. I therefore prefer a more encompassing method that also acounts for pips at risk when defining lot size.
 
Viffer:
Right, but it would not be uncommon for an EA to have variable SL based on indicators. Although not to your extremes, my own EA will trades variable SL. I therefore prefer a more encompassing method that also acounts for pips at risk when defining lot size.


Viffer I have such a code, it is designed to work with any currency-pair, any broker.

You input the stoploss in pips (which would come from your indicator, like fractal or ATR) and the maximum dollar-amount you are willing to lose on the trade should the stops be hit (i.e. the VaR) and it returns the lotsize of the position you can open. It can normalize the lotsize to your broker's specific granularity as well.

If you are interested in the code give me till this evening and I'll post it to the thread.

Reason: