MetaTrader API
Documentation

MetaTrader 5 Python SDK

Connect directly to any MT5 broker server from Python. Stream real-time quotes, execute trades, and manage positions without installing MetaTrader.

Installation

pip
1pip install metatrader5

Quick Start

example.py
1from metatrader5 import MT5Client, OrderType, UpdateType, Position, TradeStatus, Quote
2
3# Initialize client with your broker credentials
4client = MT5Client(52557472, "JtT7!DeEzhXOPW", "ICMarketsSC-Demo")
5print(f"Balance: {client.balance}")
6
7# Subscribe to market data
8client.subscribe_all_symbols()
9
10# Place a trade
11result = client.order_send("EURUSD", OrderType.BUY, 0.1)
12print(f"Success: {result.success}, Ticket: {result.ticket}, Status: {result.status}")
13
14# Handle real-time tick data
15def on_tick(quote: Quote):
16 print(f"{quote.symbol}: {quote.bid}/{quote.ask}")
17
18client.on_tick(on_tick)
19
20# Keep the connection alive
21input()

Client

MT5Client

Creates a new connection to a MetaTrader 5 broker server. The client handles authentication, connection management, and provides methods for trading and market data.

Signature
1MT5Client(account: int, password: str, server: str) -> MT5Client

Parameters

accountintYour MT5 account number
passwordstrYour MT5 account password
serverstrBroker server name (e.g., 'ICMarketsSC-Demo')

Returns

MT5ClientConnected client instance

Example

1client = MT5Client(52557472, "JtT7!DeEzhXOPW", "ICMarketsSC-Demo")
2print(f"Balance: {client.balance}")

Properties

balancefloatCurrent account balance
equityfloatCurrent account equity
marginfloatUsed margin
free_marginfloatAvailable margin for new positions
positionslist[Position]List of open positions

Methods

order_send

Places a synchronous trade order. Blocks until the order is confirmed by the broker. Returns an OrderResult with the trade status.

Signature
1client.order_send(symbol: str, order_type: OrderType, volume: float, price: float = None, sl: float = None, tp: float = None) -> OrderResult

Parameters

symbolstrTrading symbol (e.g., 'EURUSD')
order_typeOrderTypeType of order (BUY, SELL, etc.)
volumefloatLot size
pricefloat | NonePrice for pending orders (optional)
slfloat | NoneStop loss price (optional)
tpfloat | NoneTake profit price (optional)

Returns

OrderResultResult containing success status, ticket, and TradeStatus

Example

1result = client.order_send("EURUSD", OrderType.BUY, 0.1)
2print(f"Success: {result.success}, Ticket: {result.ticket}")

order_send_async

Places an asynchronous trade order. Returns immediately with a request ID. Use on_trade callback to receive the result.

Signature
1client.order_send_async(symbol: str, order_type: OrderType, volume: float, price: float = None, sl: float = None, tp: float = None) -> int

Parameters

symbolstrTrading symbol (e.g., 'EURUSD')
order_typeOrderTypeType of order (BUY, SELL, etc.)
volumefloatLot size
pricefloat | NonePrice for pending orders (optional)
slfloat | NoneStop loss price (optional)
tpfloat | NoneTake profit price (optional)

Returns

intRequest ID to track the order in on_trade callback

Example

1request_id = client.order_send_async("EURUSD", OrderType.BUY, 0.1)
2print(f"Order sent with request ID: {request_id}")

subscribe_all_symbols

Subscribes to real-time market data for all available symbols. Tick data will be delivered via the on_tick callback as Quote objects.

Signature
1client.subscribe_all_symbols() -> None

Example

1client.subscribe_all_symbols()
2# Now on_tick will receive updates for all symbols

on_tick

Registers a callback function to receive real-time tick data. Called whenever a new Quote is received. Use subscribe_all_symbols to start receiving data.

Signature
1client.on_tick(callback: Callable[[Quote], None]) -> None

Parameters

callback(Quote) -> NoneFunction called with each new Quote

Example

1def on_tick(quote: Quote):
2 print(f"{quote.symbol}: {quote.bid}/{quote.ask}")
3
4client.on_tick(on_tick)

on_trade

Registers a callback function to receive trade execution results. Used with order_send_async to track order status. Receives the request_id, ticket, and TradeStatus.

Signature
1client.on_trade(callback: Callable[[int, int, TradeStatus], None]) -> None

Parameters

callback(int, int, TradeStatus) -> NoneFunction called with request_id, ticket, and TradeStatus

Example

1def on_trade(request_id: int, ticket: int, status: TradeStatus):
2 print(f"Trade result: request_id={request_id}, ticket={ticket}, status={status}")
3
4client.on_trade(on_trade)

on_order

Registers a callback function to receive order update notifications. Called when Positions are opened, closed, or modified. Receives UpdateType and Position details.

Signature
1client.on_order(callback: Callable[[UpdateType, Position], None]) -> None

Parameters

callback(UpdateType, Position) -> NoneFunction called with UpdateType and Position details

Example

1def on_order(update_type: UpdateType, position: Position):
2 print(f"Order updated: {update_type}, {position.symbol}, {position.direction}, {position.lots}")
3
4client.on_order(on_order)

Types

OrderType
1class OrderType(Enum):
2 BUY = "buy" # Market buy order
3 SELL = "sell" # Market sell order
4 BUY_LIMIT = "buy_limit" # Buy limit pending order
5 SELL_LIMIT = "sell_limit" # Sell limit pending order
6 BUY_STOP = "buy_stop" # Buy stop pending order
7 SELL_STOP = "sell_stop" # Sell stop pending order
UpdateType
1class UpdateType(Enum):
2 OPENED = "opened" # New position opened
3 CLOSED = "closed" # Position closed
4 MODIFIED = "modified" # Position modified (SL/TP changed)
TradeStatus
1class TradeStatus(Enum):
2 SUCCESS = "success" # Order executed successfully
3 REJECTED = "rejected" # Order rejected by broker
4 TIMEOUT = "timeout" # Order timed out
5 INVALID_VOLUME = "invalid_volume" # Invalid lot size
6 INVALID_PRICE = "invalid_price" # Invalid price
7 NO_MONEY = "no_money" # Insufficient funds
8 MARKET_CLOSED = "market_closed" # Market is closed
Quote
1class Quote:
2 symbol: str # Trading symbol (e.g., "EURUSD")
3 bid: float # Current bid price
4 ask: float # Current ask price
5 last: float # Last traded price
6 volume: float # Current volume
7 time: datetime # Quote timestamp
Position
1class Position:
2 ticket: int # Unique position identifier
3 symbol: str # Trading symbol
4 direction: str # "buy" or "sell"
5 lots: float # Position volume
6 open_price: float # Entry price
7 current_price: float # Current market price
8 sl: float | None # Stop loss price
9 tp: float | None # Take profit price
10 profit: float # Current P&L
11 open_time: datetime # When position was opened
OrderResult
1class OrderResult:
2 success: bool # Whether order was successful
3 ticket: int | None # Position ticket (if successful)
4 status: TradeStatus # Detailed status
5 message: str # Human-readable message

Full Example

complete_example.py
1from metatrader5 import MT5Client, OrderType, UpdateType, Position, TradeStatus, Quote
2
3# Initialize client
4client = MT5Client(52557472, "JtT7!DeEzhXOPW", "ICMarketsSC-Demo")
5print(f"Balance: {client.balance}")
6
7# Subscribe to all market data
8client.subscribe_all_symbols()
9
10# Handle real-time tick data
11def on_tick(quote: Quote):
12 print(f"{quote.symbol}: {quote.bid}/{quote.ask}")
13
14# Handle trade execution results (for async orders)
15def on_trade(request_id: int, ticket: int, status: TradeStatus):
16 print(f"Trade result: request_id={request_id}, ticket={ticket}, status={status}")
17
18# Handle position updates
19def on_order(update_type: UpdateType, position: Position):
20 print(f"Order updated: {update_type}, {position.symbol}, {position.direction}, {position.lots}")
21
22# Register callbacks
23client.on_tick(on_tick)
24client.on_trade(on_trade)
25client.on_order(on_order)
26
27# Place a synchronous order
28result = client.order_send("EURUSD", OrderType.BUY, 0.1)
29print(f"Sync order - Success: {result.success}, Ticket: {result.ticket}")
30
31# Place an asynchronous order
32request_id = client.order_send_async("GBPUSD", OrderType.SELL, 0.05)
33print(f"Async order sent with request ID: {request_id}")
34
35# Keep connection alive
36input("Press Enter to exit...")