how to convert MarketInfo(Symbol(), MODE_MARGINREQUIRED) to mt5 version

 

how to convert MarketInfo(Symbol(), MODE_MARGINREQUIRED) to mt5 version

 
Chao Wu: how to convert MarketInfo(Symbol(), MODE_MARGINREQUIRED) to mt5 version

It is a little more complicate in MT5 because it can operate on several different markets, not just Forex, where the calculation of Margin can be different on each one.

Instead, you can use the OrderCalcMargin() function!

OrderCalcMargin

The function calculates the margin required for the specified order type, on the current account, in the current market environment not taking into account current pending orders and open positions. It allows the evaluation of margin for the trade operation planned. The value is returned in the account currency.

bool  OrderCalcMargin(
   ENUM_ORDER_TYPE       action,           // type of order
   string                symbol,           // symbol name
   double                volume,           // volume
   double                price,            // open price
   double&               margin            // variable for obtaining the margin value
   );
 
Fernando Carreiro:

It is a little more complicate in MT5 because it can operate on several different markets, not just Forex, where the calculation of Margin can be different on each one.

Instead, you can use the OrderCalcMargin() function!


thanks for your reply. but OrderCalcMargin return a bool, I need a double 

 
Chao Wu: thanks for your reply. but OrderCalcMargin return a bool, I need a double 

Read the documentation again!

bool  OrderCalcMargin(
   ENUM_ORDER_TYPE       action,           // type of order
   string                symbol,           // symbol name
   double                volume,           // volume
   double                price,            // open price
   double&               margin            // variable for obtaining the margin value
   );

margin

[out]  The variable, to which the value of the required margin will be written in case the function is successfully executed. The calculation is performed as if there were no pending orders and open positions on the current account. The margin value depends on many factors, and can differ in different market environments.

 

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

Особенности языка mql5, тонкости и приёмы работы

fxsaber, 2017.02.27 18:40

// Размер свободных средств, необходимых для открытия 1 лота на покупку
double GetMarginRequired( const string Symb )
{
  MqlTick Tick;
  double MarginInit, MarginMain;

  return((SymbolInfoTick(Symb, Tick) && SymbolInfoMarginRate(Symb, ORDER_TYPE_BUY, MarginInit, MarginMain)) ? MarginInit * Tick.ask *
          SymbolInfoDouble(Symb, SYMBOL_TRADE_TICK_VALUE) / (SymbolInfoDouble(Symb, SYMBOL_TRADE_TICK_SIZE) * AccountInfoInteger(ACCOUNT_LEVERAGE)) : 0);
}

// Альтернатива OrderCalcMargin
bool MyOrderCalcMargin( const ENUM_ORDER_TYPE action, const string symbol, const double volume, const double price, double &margin )
{
  double MarginInit, MarginMain;

  const bool Res = SymbolInfoMarginRate(symbol, action, MarginInit, MarginMain);
  
  margin = Res ? MarginInit * price * volume * SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE) /
                 (SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE) * AccountInfoInteger(ACCOUNT_LEVERAGE)) : 0;
  
  return(Res);  
}
 
fxsaber:

According to ENUM_SYMBOL_CALC_MODE documentation, I'm not sure that margin can be calculated via current price unconditionally as in the presented code - there are cases when formulae differ.

 
Stanislav Korotky:

According to ENUM_SYMBOL_CALC_MODE documentation, I'm not sure that margin can be calculated via current price unconditionally as in the presented code - there are cases when formulae differ.

It is necessary that someone checked.

 
Stanislav Korotky:

According to ENUM_SYMBOL_CALC_MODE documentation, I'm not sure that margin can be calculated via current price unconditionally as in the presented code - there are cases when formulae differ.

It can't be. Depends of the symbol : Forex (yes), Futures (No)...
 
To convert MarketInfo(Symbol(), MODE_MARGINREQUIRED) to mt5 version is order_calc_margin

Retourne la marge dans la devise du compte pour effectuer une opération de trading spécifiée. It's double

order_calc_margin(
   action,      // type de l'ordre (ORDER_TYPE_BUY ou ORDER_TYPE_SELL)
   symbol,      // nom du symbole
   volume,      // volume
   price        // prix d'ouverture
   )

Paramètres

action

[in]  Type de l'ordre dont les valeurs proviennent de l'énumération ORDER_TYPE. Paramètre sans nom requis.

symbol

[in] Nom de l'instrument financier. Paramètre non nommé requis.

volume

[in] Volume de l'opération de trading. Paramètre non nommé requis.

price

[in]  Prix d'ouverture. Paramètre non nommé requis.

Valeur de Retour

Valeur réelle en cas de succès, sinon None. Les informations sur l'erreur peuvent être obtenues en utilisant last_error().

 

EXEMPLE:

import
 MetaTrader5 as mt5
# affiche les données du package MetaTrader 5
print("Auteur du package MetaTrader5 : ",mt5.__author__)
print("Version du package MetaTrader5 : ",mt5.__version__)
 
# établit une connexion au terminal MetaTrader 5
if not mt5.initialize():
 print("initialize() a échoué, code d'erreur=",mt5.last_error())
    quit()
 
# récupère la devise du compte
account_currency=mt5.account_info().currency
print("Devise du compte :",account_currency)
 
# arrange la liste des symboles
symbols=("EURUSD","GBPUSD","USDJPY""USDCHF","EURJPY","GBPJPY")
print("Symboles pour vérifier la marge :", symbols)
action=mt5.ORDER_TYPE_BUY
lot=0.1
for symbol in symbols:
    symbol_info=mt5.symbol_info(symbol)
    if symbol_info is None:
        print(symbol,"non trouvé, ignoré")
        continue
    if not symbol_info.visible:
        print(symbol, "n'est pas visible, tente de l'afficher")
        if not mt5.symbol_select(symbol,True):
            print("symbol_select({}}) a échoué, ignoré",symbol)
            continue
    ask=mt5.symbol_info_tick(symbol).ask
    margin=mt5.order_calc_margin(action,symbol,lot,ask)
    if margin != None:
        print("   {} buy {} lots marge : {} {}".format(symbol,lot,margin,account_currency));
    else:
        print("order_calc_margin a échoué : , code d'erreur="mt5.last_error())
 
# ferme la connexion au terminal MetaTrader 5
mt5.shutdown()
 
 
Résultat :
Auteur du package MetaTrader5 :  MetaQuotes Software Corp.
Version du package MetaTrader5 :  5.0.29
 
Devise du compte : USD
 
Symboles pour vérifier la marge : ('EURUSD', 'GBPUSD', 'USDJPY', 'USDCHF', 'EURJPY', 'GBPJPY')
  EURUSD buy 0.1 lots marge : 109.91 USD
  GBPUSD buy 0.1 lots marge : 122.73 USD
  USDJPY buy 0.1 lots marge : 100.0 USD
  USDCHF buy 0.1 lots marge : 100.0 USD
  EURJPY buy 0.1 lots marge : 109.91 USD
  GBPJPY buy 0.1 lots marge : 122.73 USD

 
Another way is using Class CAccountInfo in : 

mt5-include/Trade/AccountInfo.mqh


//+------------------------------------------------------------------+
//| Access functions OrderCalcMargin(...). |
//| INPUT: name - symbol name, |
//| trade_operation - trade operation, |
//| volume - volume of the opening position, |
//| price - price of the opening position. |
//+------------------------------------------------------------------+
double CAccountInfo::MarginCheck(const string symbol,const ENUM_ORDER_TYPE trade_operation,
const double volume,const double price) const
{
double margin=EMPTY_VALUE;
//---
if(!OrderCalcMargin(trade_operation,symbol,volume,price,margin))
return(EMPTY_VALUE);
//---
return(margin);
}



GitHub - gsemet/mt5-include
GitHub - gsemet/mt5-include
  • gsemet
  • github.com
Contribute to gsemet/mt5-include development by creating an account on GitHub.
Reason: