I think what you want is a calculation to determine the lot size based on a percentage of equity.
It is actually not that easy to do because of rounding in the calculation will not give you an even number of lots. You need to take into account the minimum lot size as well. Use the Marketinfo() function to get this info using MODE_LOTSTEP. Then figure out the nearest lot size from the result of the calculation.
MarketInfo(Symbol(), MODE_TICKVALUE); is what you’ll probably need to make conversions easiest. Then using CodeMeister’s suggestion to make it round down to the nearest lot-step.
You could try something like this with double RiskPerTrade in the input parameters.
Probably not the absolute best way, but it seems to work ok for me.
//entryprice is the calculated entry level,StopLoss is calculated stop level
double Step = MarketInfo(Symbol(), MODE_LOTSTEP);
double LossLot = MathAbs( entryprice- StopLoss)/ MarketInfo(Symbol(), MODE_TICKSIZE)*MarketInfo(Symbol(), MODE_TICKVALUE) ;
int Lot = AccountEquity( )*RiskPerTrade/100 / LossLot/ Step ;
LotSize = Lot * Step;
if(LotSize < MarketInfo(Symbol(), MODE_MINLOT))
{
//code to do something if calculated lot size is less than the minimum allowed
}
The exact code you want is in a book “Expert Advisor Programming” by Andrew R Young and is available from Amazon.
You need to add two extra variables.
extern bool DynamicLotSize = true;
extern double EquityPercent = 2; // Percentage of account to risk.
extern double FixedLotSize = 0.1; to replace your extern double Lots = 0.01;
The first variable DynamicLotSize allows you to turn on or off the dynamic lot size based on a percentage of your account size or default to a fixed lot size.
Which I think is what you want. It then goes on to calculate the lot size and then verify it for your broker type. I don’t want to infringe any copyright laws so have only shown a small part of the code. If you plan to modify EA’s or write your own, then you will find this book very helpful.
ClarkFX,
Sorry, But I make no apologies for recommending this book again.
Maybe not the best approach, but if you just want to get the job done, it should be as easy as:
Comment the declaration for Lots. (just put two bars before) This is because you don’t want it to be an external variable, but instead you want to give it a value at runtime.
// extern double Lots = 0.01;
Put this code after the int init() { and after the int start() {