Reference
This page lists the classes and methods of the SDK with their Python names. The other languages have the same methods, written in the style of each language:
| Python, C++ and Rust | C# | Java |
|---|---|---|
open_market_order(...) |
OpenMarketOrderAsync(...) |
openMarketOrder(...) |
candles_history(...) |
CandlesHistoryAsync(...) |
candlesHistory(...) |
on_tick |
OnTick |
onTick |
license_key |
LicenseKey |
licenseKey(...) |
mode=ConnectionMode.BROWSER |
Mode = ConnectionMode.Browser |
mode(ConnectionMode.BROWSER) |
The models (Account, Position, Candle, TradeResult...) are typed in every language, so your editor
completes their fields.
MT5WebClient and MT4WebClient
One client is one connection to one trading account:
- MetaTrader 5:
MT5WebClient(url, options), with the address of the web terminal (wss://...). - MetaTrader 4:
MT4WebClient(server, options), with the name of the trade server ("MetaQuotes-Demo").
Both have the methods below, which come from their common base class, MTWebClient: use it for code that works with
both platforms. MetaTrader 5 adds market depth, the filling type and stop-limit orders; the differences of
MetaTrader 4 are listed in MetaTrader 4.
Options
MT5WebClientOptions:
| Option | Default | Description |
|---|---|---|
license_key |
None |
License key (the same license works for MetaTrader 5 and 4). Without it: demo mode (demo accounts only, 1 lot, 5 symbols, 30 days of history). |
origin |
None |
Origin header of the handshake. Default: https:// + host of the URL. "" sends none. |
user_agent |
None |
User-Agent header. Default: desktop Chrome. "" sends none. |
request_timeout |
30.0 |
Timeout of regular commands, in seconds (history and candles use at least 60). |
trade_timeout |
20.0 |
Maximum time a trading method waits for the final result, in seconds. |
deal_wait_timeout |
3.0 |
Time to wait for the actual deal of a market order or close, in seconds. |
mode |
ConnectionMode.DIRECT |
How the client talks to the server. With BROWSER the calls do not change, but they are slower (they go through the interface of the web terminal, one at a time) and a few parameters the web terminal does not offer (filling type, the price and the comment of a close, the comment of an order modification, market depth of more than one symbol) raise ValueError. |
browser_path |
None |
Browser mode: path of the browser executable. Default: the installed Edge, Chrome or Chromium. |
headless |
True |
Browser mode: run the browser without a window. False shows it (to watch or to debug a selector). |
selectors_file |
None |
Browser mode: JSON file whose entries replace the built-in selectors of the web terminal interface (see selectors.default.json). Use it when MetaQuotes changes the web terminal, until a new version of the library. |
MT4WebClientOptions (MetaTrader 4 always connects in Direct mode):
| Option | Default | Description |
|---|---|---|
license_key |
None |
License key (the same license works for MetaTrader 5 and 4). Without it: demo mode (demo accounts only, 1 lot, 5 symbols, 30 days of history). |
user_agent |
None |
User-Agent header. Default: desktop Chrome. "" sends none. |
request_timeout |
30.0 |
Timeout of regular commands, in seconds (history and candles use at least 60). |
trade_timeout |
20.0 |
Maximum time a trading method waits for the final result, in seconds. |
Connection
connect()-
Loads the license and connects. A missing or invalid license does not make it fail (demo mode). Raises a license error for the Unlimited activation limit or an expired version. MetaTrader 5 opens the WebSocket here; MetaTrader 4 only loads the license and login() opens the connection.
login(login: int, password: str, otp: str='', page_url: str='')-
Logs in. Demo accounts always work (demo mode without license); live accounts need a license that includes them, otherwise the connection is closed and a license error is raised.
otpandpage_urlare only used by MetaTrader 5. disconnect()-
Closes the connection.
logout()-
Logs out of the account.
is_connected→bool-
Whether the connection is open.
options→dict-
Settings with every default resolved.
close()-
Disconnects and releases the native object.
License
license→LicenseInfo-
State of the license and of the session (plan, access, accounts, limits).
refresh_license()→LicenseInfo-
Checks the license with the license server now (also done automatically every hour).
Account
account_info()→Account-
Account data: balance, equity, margin, currency, leverage and server time offset.
positions→List[Position]-
Open positions (a snapshot; no network).
orders→List[Order]-
Pending orders (a snapshot; no network).
history(from_: TimeArg, to: Optional[TimeArg]=None)→HistoryData-
Deals, orders and positions rebuilt from the deals between two broker times (only the last 30 days without a Professional license).
Market data
load_symbols()→List[SymbolEntry]-
List of the symbols of the account.
full_symbols(symbols: Iterable[SymbolEntry])→List[FullSymbol]-
Full specification of the given symbols.
subscribe(symbols: Iterable[SymbolEntry])-
Real-time quotes (on_tick). Replaces the previous set. More than 5 symbols need a Professional license.
subscribe_depth(symbols: Iterable[SymbolEntry])-
Order book (on_book). Replaces the previous set.
unsubscribe_depth()-
Stops the order book subscription.
candles_history(symbol: SymbolEntry, timeframe: Timeframe, from_: TimeArg, to: TimeArg)→List[Candle]-
OHLC candles between two broker times (only the last 30 days without a Professional license). MetaTrader 4 only has M1, M5, M15, M30, H1, H4, D1, W1 and MN1.
Trading
open_market_order(symbol: SymbolEntry, side: Side, lots: float, sl: Optional[float]=None, tp: Optional[float]=None, comment: str='', filling: Optional[Filling]=None)→TradeResult-
Market order. A rejection is not an exception: check result.ok and result.retcode.
close_position(position_id: int, lots: Optional[float]=None, comment: str='', filling: Optional[Filling]=None, price: Optional[float]=None)→TradeResult-
Closes a position (lots=None: all of it; a value: partial close).
modify_position(position_id: int, sl: Optional[float]=None, tp: Optional[float]=None)→TradeResult-
Modifies the stop loss and/or take profit of a position (None keeps it, 0 removes it).
open_pending_order(symbol: SymbolEntry, order_type: PendingType, lots: float, price: float, sl: Optional[float]=None, tp: Optional[float]=None, stop_limit: Optional[float]=None, expiration: Optional[TimeArg]=None, comment: str='')→TradeResult-
Pending order (limit, stop or stop-limit); expiration in broker time, None = Good-Till-Cancelled.
modify_order(order_id: int, price: Optional[float]=None, sl: Optional[float]=None, tp: Optional[float]=None, stop_limit: Optional[float]=None, expiration: Optional[TimeArg]=None, comment: Optional[str]=None)→TradeResult-
Modifies a pending order (None keeps a value; NO_EXPIRATION makes it Good-Till-Cancelled).
cancel_order(order_id: int)→TradeResult-
Cancels a pending order.
MetaTrader 4
MT4WebClient has every method above except subscribe_depth and unsubscribe_depth (MT4 has no market depth).
Its trading methods have no filling and no stop_limit parameters:
open_market_order(symbol: SymbolEntry, side: Side, lots: float, sl: Optional[float]=None, tp: Optional[float]=None, comment: str='')→TradeResult-
Market order with the execution mode of the symbol (instant, request or market). A rejection is not an exception: check result.ok and result.retcode (the MT4 code is in result.comment).
close_position(position_id: int, lots: Optional[float]=None, comment: str='', price: Optional[float]=None)→TradeResult-
Closes a position (lots=None: all of it; a value: partial close, and the rest gets a new ticket, returned in result.position). price: instant and request execution, None = the current quote.
open_pending_order(symbol: SymbolEntry, order_type: PendingType, lots: float, price: float, sl: Optional[float]=None, tp: Optional[float]=None, expiration: Optional[TimeArg]=None, comment: str='')→TradeResult-
Pending order: buy/sell limit or buy/sell stop (no stop-limit in MT4); expiration in broker time, None = Good-Till-Cancelled.
modify_order(order_id: int, price: Optional[float]=None, sl: Optional[float]=None, tp: Optional[float]=None, expiration: Optional[TimeArg]=None)→TradeResult-
Modifies a pending order (MT4 cannot change its comment; None keeps a value; NO_EXPIRATION makes it Good-Till-Cancelled).
How MetaTrader 4 appears with the common types:
- An open market order is a
Position(its ticket is the position id) and a pending order is anOrder. - The history is made of closed orders: each one gives an entry deal and an exit deal, so that
HistoryData.positionsis rebuilt as with MetaTrader 5. Balance and credit operations are deals of type balance or credit. - The MT4 return codes are translated to the MT5 codes (
10009= done); the original MT4 code and its text are inTradeResult.comment. - A partial close leaves the rest of the volume with a new ticket, returned in
TradeResult.position. - Timeframes:
M1,M5,M15,M30,H1,H4,D1,W1andMN1.
Events
Assign a function to receive them. Event handlers run on a background thread of the library.
| Event | Receives | When |
|---|---|---|
on_tick |
Tick |
A new price of a symbol subscribed with subscribe |
on_book |
BookSnapshot |
A new order book of a symbol subscribed with subscribe_depth (MetaTrader 5) |
on_trade_event |
OrderEvent, DealEvent or AccountEvent |
An order, a deal or the account changed |
on_disconnected |
DisconnectInfo |
The connection was closed |
on_warning |
text | A non-fatal issue, for example a limit applied by the license |
Values
| Type | Values |
|---|---|
Side |
BUY, SELL |
PendingType |
BUY_LIMIT, SELL_LIMIT, BUY_STOP, SELL_STOP, BUY_STOP_LIMIT, SELL_STOP_LIMIT |
Filling |
FOK, IOC, RETURN |
Timeframe |
M1, M5, M15, M30, H1, H4, D1, W1, MN1 |
ConnectionMode |
DIRECT (default), BROWSER, HYBRID (MetaTrader 5): see Connection modes |
Errors
| Error | Meaning |
|---|---|
MT5Error / MT4Error |
Protocol or operation error: server result code, connection failure, invalid state |
MT5LicenseError / MT4LicenseError |
The license does not allow the operation: live account not authorized, more than 1 lot or 5 symbols without a Professional license, activation limit of an Unlimited license, or an expired version of the library |
MT5TimeoutError / MT4TimeoutError |
No response from the server in time |
ValueError |
Invalid argument; in Browser mode, also a parameter the web terminal does not offer (see Connection modes) |
MTError, MTLicenseError and MTTimeoutError are the bases of both platforms: catch them in code that works with
MetaTrader 4 and 5. In the other languages: MT5Exception / MT4Exception, MT5LicenseException /
MT4LicenseException and the base MTException (with IsLicenseError) in C#, Java and C++; Error::Mt5,
Error::Mt4, Error::License, Error::Timeout and Error::Argument in Rust.
A rejected order is not an error: the trading methods return a TradeResult; check ok, retcode and
retcode_text.
CalendarWebClient
The MQL5 economic calendar. It needs no trading account: CalendarWebClient(options).
| Option | Default | Description |
|---|---|---|
license_key |
None |
License key (the same as MT5WebClient). Without a license: only the last 30 days, no future events. |
origin |
None |
Origin header. Default: none. |
user_agent |
None |
User-Agent header. Default: desktop Chrome. |
connect()-
Opens the connection.
disconnect()-
Closes the connection.
license→LicenseInfo-
License loaded by connect(); only calendar_days applies to the calendar.
get_values(from_utc: TimeArg, to_utc: TimeArg)→List[CalendarValue]-
Calendar values (actual, forecast, previous) of a UTC range.
get_event_info(country: int, lang: CalendarLanguage=CalendarLanguage.EN)→List[CalendarEventInfo]-
Description of the calendar events of a country.
get_events(from_utc: TimeArg, to_utc: TimeArg, countries: Optional[Iterable[int]]=None, lang: CalendarLanguage=CalendarLanguage.EN)→List[CalendarEvent]-
Values of a UTC range joined with the description of their events (countries: CalendarCountry; None = all). Without a license: only the last 30 days and no future events (on_warning is called).
Times
Trading times (history, candles, positions) are in broker time, which is Account.server_offset seconds ahead
of UTC. Calendar times are UTC. BrokerTime converts between them.