Forum on trading, automated trading systems and testing trading strategies
Margin requirements calculation
gordon, 2010.04.08 04:42
Margin requirement for 1 lot is given by MarketInfo(symbol,MODE_MARGINREQUIRED). Calculating this value seems to be different among some brokers (specifically ones that use a bridge).
The majority of brokers use this calculation (taken from the article 'Forex Trading ABC' -> https://www.mql5.com/en/articles/1453):
double MarginCalculate(string symbol, double volume) { string first = StringSubstr(symbol,0,3); // the first symbol, for example, EUR string second = StringSubstr(symbol,3,3); // the second symbol, for example, USD string currency = AccountCurrency(); // deposit currency, for example, USD double leverage = AccountLeverage(); // leverage, for example, 100 // contract size, for example, 100000 double contract = MarketInfo(symbol, MODE_LOTSIZE); double bid = MarketInfo(symbol, MODE_BID); // Bid price //---- allow only standard forex symbols like XXXYYY if(StringLen(symbol) != 6) { Print("MarginCalculate: '",symbol,"' must be standard forex symbol XXXYYY"); return(0.0); } //---- check for data availability if(bid <= 0 || contract <= 0) { Print("MarginCalculate: no market information for '",symbol,"'"); return(0.0); } //---- check the simplest variations - without cross currencies if(first == currency) return(contract*volume / leverage); // USDxxx if(second == currency) return(contract*bid*volume / leverage); // xxxUSD //---- check normal cross currencies, search for direct conversion through deposit currency string base = currency + first; // USDxxx if(MarketInfo(base, MODE_BID) > 0) return(contract / MarketInfo(base, MODE_BID)*volume / leverage); //---- try vice versa base = first + currency; // xxxUSD if(MarketInfo(base, MODE_BID) > 0) return(contract*MarketInfo(base, MODE_BID)*volume / leverage); //---- direct conversion is impossible Print("MarginCalculate: can not convert '",symbol,"'"); return(0.0); }
But some brokers do not factor 'bid' price when calculating (regardless of symbol):
double MarginCalculate(string symbol, double volume) { double leverage = AccountLeverage(); double contract = MarketInfo(symbol, MODE_LOTSIZE); return(contract*volume / leverage); }
Note that MODE_MARGINREQUIRED is 'static' in Tester and that both methods of calculation cannot be used in Tester (they rely on MarketInfo() of other symbols...).
Forum on trading, automated trading systems and testing trading strategies
Fernando Carreiro, 2022.05.19 06:20
Reference: How to calculate Margin & Margin Level on MT4?
Some other reference material:
- What is Margin?
- What is Margin Trading?
- Forex Leverage and Margin Explained
- How to Calculate Margin for Forex Trades
- Leverage, Margin, Balance, Equity, Free Margin, Margin Call And Stop Out Level In Forex Trading
All this found with a simple Google search.
My apologies. I misunderstood your question. I thought you were requesting an alternative to the MODE_MARGINREQUIRED functionality.
Here is an old post where I use the MODE_MARGINREQUIRED:
Forum on trading, automated trading systems and testing trading strategies
Need moneymanagement LOT size formula based on SL and Account Risk!
Fernando Carreiro, 2014.01.09 02:37
OK guys! This code was written by me and it is what I use in my own EA's. It is quite complex because, besides the Risk% and StopLoss, it also takes into account the Margin Risk% as well as correct the Lot Size based on Minimum, Maximum and Step Size. It also always uses the minimum value of Current Balance and Equity instead of just using one of them. I feel it is safer that way.
Please note, however, that it does not use the spread in the calculation, because I calculate that separately when calculating the StopLoss to be used. The below function, thus uses a relative stop loss size. In my EA's the argument dblStopLossPips is calculated beforehand depending on various factors such as the strategy, spread, ATR, etc.; so the final value passed on to the dblLotsRisk() function is already a final value in order to calculate the Lot size to be used.
// Function to Determine Tick Point Value in Account Currency double dblTickValue( string strSymbol ) { return( MarketInfo( strSymbol, MODE_TICKVALUE ) ); } // Function to Determine Pip Point Value in Account Currency double dblPipValue( string strSymbol ) { double dblCalcPipValue = dblTickValue( strSymbol ); switch ( MarketInfo( strSymbol, MODE_DIGITS ) ) { case 3: case 5: dblCalcPipValue *= 10; break; } return( dblCalcPipValue ); } // Calculate Lot Size based on Maximum Risk & Margin double dblLotsRisk( string strSymbol, double dblStopLossPips, double dblRiskMaxPercent, double dblMarginMaxPercent, double dblLotsMin, double dblLotsMax, double dblLotsStep ) { double dblValueAccount = MathMin( AccountEquity(), AccountBalance() ) , dblValueRisk = dblValueAccount * dblRiskMaxPercent / 100.0 , dblValueMargin = AccountFreeMargin() * dblMarginMaxPercent / 100.0 , dblLossOrder = dblStopLossPips * dblPipValue( strSymbol ) , dblMarginOrder = MarketInfo( strSymbol, MODE_MARGINREQUIRED ) , dblCalcLotMin = MathMax( dblLotsMin, MarketInfo( strSymbol, MODE_MINLOT ) ) , dblCalcLotMax = MathMin( dblLotsMax, MarketInfo( strSymbol, MODE_MAXLOT ) ) , dblModeLotStep = MarketInfo( strSymbol, MODE_LOTSTEP ) , dblCalcLotStep = MathCeil( dblLotsStep / dblModeLotStep ) * dblModeLotStep , dblCalcLotLoss = MathFloor( dblValueRisk / dblLossOrder / dblCalcLotStep ) * dblCalcLotStep , dblCalcLotMargin = MathFloor( dblValueMargin / dblMarginOrder / dblCalcLotStep ) * dblCalcLotStep , dblCalcLot = MathMin( dblCalcLotLoss, dblCalcLotMargin ) ; if ( dblCalcLot < dblCalcLotMin ) dblCalcLot = dblCalcLotMin; if ( dblCalcLot > dblCalcLotMax ) dblCalcLot = dblCalcLotMax; return ( dblCalcLot ); }
Please note that the above example code is old and only works for Forex Currency pairs.
You will have to adapt the calculations for other symbols based on the MODE_MARGINCALCMODE.
Also the following may be of interest.
Forum on trading, automated trading systems and testing trading strategies
Fernando Carreiro, 2022.04.05 01:03
In MQL4, I use these:
MODE_MARGINCALCMODE
28
Margin calculation mode. 0 - Forex; 1 - CFD; 2 - Futures; 3 - CFD for indices
MODE_MARGININIT
29
Initial margin requirements for 1 lot
MODE_MARGINMAINTENANCE
30
Margin to maintain open orders calculated for 1 lot
MODE_MARGINHEDGED
31
Hedged margin calculated for 1 lot
MODE_MARGINREQUIRED
32
Free margin required to open 1 lot for buying
The following information is from MQL5 but the information about the different modes of calculating margin (in the "Formula" column) is useful for MQL4 too ...
The ENUM_SYMBOL_CALC_MODE enumeration is used for obtaining information about how the margin requirements for a symbol are calculated.
ENUM_SYMBOL_CALC_MODE
Identifier
Description
Formula
SYMBOL_CALC_MODE_FOREX
Forex mode - calculation of profit and margin for Forex
Margin: Lots * Contract_Size / Leverage * Margin_Rate
Profit: (close_price - open_price) * Contract_Size*Lots
SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE
Forex No Leverage mode – calculation of profit and margin for Forex symbols without taking into account the leverage
Margin: Lots * Contract_Size * Margin_Rate
Profit: (close_price - open_price) * Contract_Size * Lots
SYMBOL_CALC_MODE_FUTURES
Futures mode - calculation of margin and profit for futures
Margin: Lots * InitialMargin * Margin_Rate
Profit: (close_price - open_price) * TickPrice / TickSize*Lots
SYMBOL_CALC_MODE_CFD
CFD mode - calculation of margin and profit for CFD
Margin: Lots * ContractSize * MarketPrice * Margin_Rate
Profit: (close_price - open_price) * Contract_Size * Lots
SYMBOL_CALC_MODE_CFDINDEX
CFD index mode - calculation of margin and profit for CFD by indexes
Margin: (Lots * ContractSize * MarketPrice) * TickPrice / TickSize * Margin_Rate
Profit: (close_price - open_price) * Contract_Size * Lots
SYMBOL_CALC_MODE_CFDLEVERAGE
CFD Leverage mode - calculation of margin and profit for CFD at leverage trading
Margin: (Lots * ContractSize * MarketPrice) / Leverage * Margin_Rate
Profit: (close_price-open_price) * Contract_Size * Lots
SYMBOL_CALC_MODE_EXCH_STOCKS
Exchange mode – calculation of margin and profit for trading securities on a stock exchange
Margin: Lots * ContractSize * LastPrice * Margin_Rate
Profit: (close_price - open_price) * Contract_Size * Lots
SYMBOL_CALC_MODE_EXCH_FUTURES
Futures mode – calculation of margin and profit for trading futures contracts on a stock exchange
Margin: Lots * InitialMargin * Margin_Rate or Lots * MaintenanceMargin * Margin_Rate
Profit: (close_price - open_price) * Lots * TickPrice / TickSize
SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS
FORTS Futures mode – calculation of margin and profit for trading futures contracts on FORTS. The margin may be reduced by the amount of MarginDiscount deviation according to the following rules:
1. If the price of a long position (buy order) is less than the estimated price, MarginDiscount = Lots*((PriceSettle-PriceOrder)*TickPrice/TickSize)
2. If the price of a short position (sell order) exceeds the estimated price, MarginDiscount = Lots*((PriceOrder-PriceSettle)*TickPrice/TickSize)
where:
- PriceSettle – estimated (clearing) price of the previous session;
- PriceOrder – average weighted position price or open price set in the order (request);
- TickPrice – tick price (cost of the price change by one point)
- TickSize – tick size (minimum price change step)
Margin: Lots * InitialMargin * Margin_Rate or Lots * MaintenanceMargin * Margin_Rate * Margin_Rate
Profit: (close_price - open_price) * Lots * TickPrice / TickSize
SYMBOL_CALC_MODE_EXCH_BONDS
Exchange Bonds mode – calculation of margin and profit for trading bonds on a stock exchange
Margin: Lots * ContractSize * FaceValue * open_price * /100
Profit: Lots * close_price * FaceValue * Contract_Size + AccruedInterest * Lots * ContractSize
SYMBOL_CALC_MODE_EXCH_STOCKS_MOEX
Exchange MOEX Stocks mode – calculation of margin and profit for trading securities on MOEX
Margin: Lots * ContractSize * LastPrice * Margin_Rate
Profit: (close_price - open_price) * Contract_Size * Lots
SYMBOL_CALC_MODE_EXCH_BONDS_MOEX
Exchange MOEX Bonds mode – calculation of margin and profit for trading bonds on MOEX
Margin: Lots * ContractSize * FaceValue * open_price * /100
Profit: Lots * close_price * FaceValue * Contract_Size + AccruedInterest * Lots * ContractSize
- www.mql5.com
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Hello,
can I use MarketInfo (Symbol(), MODE_MARGINREQUIRED) to calculate the amount in account currency spend for the invested lots in the trade? Are there any restrictions or why some coders do complex calculations based on conversions from base currency to the account currency?