Calculating maximum Lots

 
Hi Guys, good day to you all,

I have a question, tough I think it has been answered many times - yet I don't seem to be able to find straight answer anywhere. For many people I'm sure this problem is just a thumb excercise, but unfortunately I'm not one of those lucky souls.. .

I'm new to MQL4, and I would need some code example of how to calculate the following: You have X account balance on symbol/pair Y. (For example, balance USD 500 and you want to trade EURGBP.) How do you calculate, what formula do you use to get what is the maximum lot you can open a trade with (0.3, 0,6, 1, etc)?

Thanks if anyone answers. And I'm sorry if I'm redundant with this...

Levente
 

MarketInfo(Symbol(),MODE_MARGINREQUIRED) gives you money needed to open 1 lot of Symbol(), for example with leverage 1:100 it will take about $1465 to open 1 lot of EURUSD.

so maximum number of lots could be AccountBalance()/MarketInfo(Symbol(),MODE_MARGINREQUIRED).

To be safe so you don't exceed margin maintenance use 80% of account balance if you maint margin is 100%.

 
irusoh1:

MarketInfo(Symbol(),MODE_MARGINREQUIRED) gives you money needed to open 1 lot of Symbol(), for example with leverage 1:100 it will take about $1465 to open 1 lot of EURUSD.

so maximum number of lots could be AccountBalance()/MarketInfo(Symbol(),MODE_MARGINREQUIRED).

To be safe so you don't exceed margin maintenance use 80% of account balance if you maint margin is 100%.

Thank you! This helped me a "LOT" :-)
 
In case I want to invole an SL in it.
For example I risked 10% of my equity in my 30 pips stoploss, so if my SL get hit, I lose 10% of my equity. How to code that?

Thanks
 
int    stoploss = 30;
double allowed_risk = 0.1*AccountEquity();  // 10% of equity
double allowed_cost_per_tick = allowed_risk/stoploss;
double cost_per_tick = MarketInfo(Symbol(),MODE_TICKVALUE);  // cost per tick of one lot size
double your_lot = allowed_cost_per_tick/cost_per_tick;
 
// you should normalize that lot based on MarketInfo(Symbol(),MODE_LOTSTEP) specified by your broker, i.e if the lotstep is 0.1 then the lot is as below
// your_lot = NormalizeDouble(allowed_cost_per_tick/cost_per_tick,1);
 
Thank you Riyo
Reason: