mt5.order_calc_margin() in MetaTrader5 Python: work out the margin for an order

Works out the margin a buy or sell of a given volume and price would need, in the account currency, without placing anything. Returns a float or None.

Signature

mt5.order_calc_margin(action, symbol, volume, price)

What it does

Use order_calc_margin() to size a trade before you send it, or to check that free margin covers it.

Parameters

ParameterWhat it is
actionmt5.ORDER_TYPE_BUY or mt5.ORDER_TYPE_SELL.
symbolThe symbol name.
volumeThe size in lots.
priceThe open price to work the margin out at.

What it returns

  • A float: the margin in the account currency.
  • None when it can't be worked out. Check mt5.last_error().

Example

import MetaTrader5 as mt5

if not mt5.initialize():
    raise SystemExit(mt5.last_error())

ask = mt5.symbol_info_tick("EURUSD").ask
need = mt5.order_calc_margin(mt5.ORDER_TYPE_BUY, "EURUSD", 0.10, ask)
free = mt5.account_info().margin_free
if need is None:
    print("cannot calculate:", mt5.last_error())
elif need > free:
    print(f"needs {need:.2f}, only {free:.2f} free")
mt5.shutdown()

Common mistakes

  • Margin depends on the account's leverage and the symbol's settings, and both can change. Work it out just before you trade.
  • A calculation that fails shows as 4758 in the terminal's codes.

The same with Tickwire on Linux

The package needs a Windows terminal on the same machine. Tickwire runs the terminal for you and gives you a REST API, so the code below runs on Linux, macOS or a server.

Tickwire's calculate-margin route takes symbol, type (ORDER_TYPE_BUY or ORDER_TYPE_SELL), volume and openPrice, and returns {"margin": ...}. It returns {} when the terminal cannot work it out. Nothing is placed.

import os, requests

API = "https://api.tickwire.io"
h = {"auth-token": os.environ["TW_KEY"]}      # your Tickwire key
base = f"{API}/users/current/accounts/{os.environ['TW_ACCOUNT']}"

r = requests.post(f"{base}/calculate-margin", headers=h, json={
    "symbol": "EURUSD", "type": "ORDER_TYPE_BUY", "volume": 0.10, "openPrice": 1.0850,
})
print(r.json().get("margin"))

Related error codes

All MetaTrader5 Python functions

MT5 from Python, on any machine

One REST API for MT4 and MT5, with idempotent orders and an audit log. Read the MT5 Python API page or the quickstart.