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
1pip install metatrader5Quick Start
1from metatrader5 import MT5Client, OrderType, UpdateType, Position, TradeStatus, Quote23# Initialize client with your broker credentials4client = MT5Client(52557472, "JtT7!DeEzhXOPW", "ICMarketsSC-Demo")5print(f"Balance: {client.balance}")67# Subscribe to market data8client.subscribe_all_symbols()910# Place a trade11result = client.order_send("EURUSD", OrderType.BUY, 0.1)12print(f"Success: {result.success}, Ticket: {result.ticket}, Status: {result.status}")1314# Handle real-time tick data15def on_tick(quote: Quote):16 print(f"{quote.symbol}: {quote.bid}/{quote.ask}")1718client.on_tick(on_tick)1920# Keep the connection alive21input()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.
1MT5Client(account: int, password: str, server: str) -> MT5ClientParameters
accountintYour MT5 account numberpasswordstrYour MT5 account passwordserverstrBroker server name (e.g., 'ICMarketsSC-Demo')Returns
MT5ClientConnected client instanceExample
1client = MT5Client(52557472, "JtT7!DeEzhXOPW", "ICMarketsSC-Demo")2print(f"Balance: {client.balance}")Properties
balancefloatCurrent account balanceequityfloatCurrent account equitymarginfloatUsed marginfree_marginfloatAvailable margin for new positionsMethods
order_send
Places a synchronous trade order. Blocks until the order is confirmed by the broker. Returns an OrderResult with the trade status.
1client.order_send(symbol: str, order_type: OrderType, volume: float, price: float = None, sl: float = None, tp: float = None) -> OrderResultParameters
symbolstrTrading symbol (e.g., 'EURUSD')volumefloatLot sizepricefloat | NonePrice for pending orders (optional)slfloat | NoneStop loss price (optional)tpfloat | NoneTake profit price (optional)Returns
OrderResultResult containing success status, ticket, and TradeStatusExample
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.
1client.order_send_async(symbol: str, order_type: OrderType, volume: float, price: float = None, sl: float = None, tp: float = None) -> intParameters
symbolstrTrading symbol (e.g., 'EURUSD')volumefloatLot sizepricefloat | 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 callbackExample
1request_id = client.order_send_async("EURUSD", OrderType.BUY, 0.1)2print(f"Order sent with request ID: {request_id}")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.
1client.on_tick(callback: Callable[[Quote], None]) -> NoneExample
1def on_tick(quote: Quote):2 print(f"{quote.symbol}: {quote.bid}/{quote.ask}")34client.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.
1client.on_trade(callback: Callable[[int, int, TradeStatus], None]) -> NoneParameters
Example
1def on_trade(request_id: int, ticket: int, status: TradeStatus):2 print(f"Trade result: request_id={request_id}, ticket={ticket}, status={status}")34client.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.
1client.on_order(callback: Callable[[UpdateType, Position], None]) -> NoneParameters
Example
1def on_order(update_type: UpdateType, position: Position):2 print(f"Order updated: {update_type}, {position.symbol}, {position.direction}, {position.lots}")34client.on_order(on_order)Types
1class OrderType(Enum):2 BUY = "buy" # Market buy order3 SELL = "sell" # Market sell order4 BUY_LIMIT = "buy_limit" # Buy limit pending order5 SELL_LIMIT = "sell_limit" # Sell limit pending order6 BUY_STOP = "buy_stop" # Buy stop pending order7 SELL_STOP = "sell_stop" # Sell stop pending order1class UpdateType(Enum):2 OPENED = "opened" # New position opened3 CLOSED = "closed" # Position closed4 MODIFIED = "modified" # Position modified (SL/TP changed)1class TradeStatus(Enum):2 SUCCESS = "success" # Order executed successfully3 REJECTED = "rejected" # Order rejected by broker4 TIMEOUT = "timeout" # Order timed out5 INVALID_VOLUME = "invalid_volume" # Invalid lot size6 INVALID_PRICE = "invalid_price" # Invalid price7 NO_MONEY = "no_money" # Insufficient funds8 MARKET_CLOSED = "market_closed" # Market is closed1class Quote:2 symbol: str # Trading symbol (e.g., "EURUSD")3 bid: float # Current bid price4 ask: float # Current ask price5 last: float # Last traded price6 volume: float # Current volume7 time: datetime # Quote timestamp1class Position:2 ticket: int # Unique position identifier3 symbol: str # Trading symbol4 direction: str # "buy" or "sell"5 lots: float # Position volume6 open_price: float # Entry price7 current_price: float # Current market price8 sl: float | None # Stop loss price9 tp: float | None # Take profit price10 profit: float # Current P&L11 open_time: datetime # When position was opened1class OrderResult:2 success: bool # Whether order was successful3 ticket: int | None # Position ticket (if successful)4 status: TradeStatus # Detailed status5 message: str # Human-readable messageFull Example
1from metatrader5 import MT5Client, OrderType, UpdateType, Position, TradeStatus, Quote23# Initialize client4client = MT5Client(52557472, "JtT7!DeEzhXOPW", "ICMarketsSC-Demo")5print(f"Balance: {client.balance}")67# Subscribe to all market data8client.subscribe_all_symbols()910# Handle real-time tick data11def on_tick(quote: Quote):12 print(f"{quote.symbol}: {quote.bid}/{quote.ask}")1314# 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}")1718# Handle position updates19def on_order(update_type: UpdateType, position: Position):20 print(f"Order updated: {update_type}, {position.symbol}, {position.direction}, {position.lots}")2122# Register callbacks23client.on_tick(on_tick)24client.on_trade(on_trade)25client.on_order(on_order)2627# Place a synchronous order28result = client.order_send("EURUSD", OrderType.BUY, 0.1)29print(f"Sync order - Success: {result.success}, Ticket: {result.ticket}")3031# Place an asynchronous order32request_id = client.order_send_async("GBPUSD", OrderType.SELL, 0.05)33print(f"Async order sent with request ID: {request_id}")3435# Keep connection alive36input("Press Enter to exit...")