Asynchronous Client (AsyncMetaTrader5)
Relevant source files
The following files were used as context for generating this wiki page:
The AsyncMetaTrader5 client is a non-blocking gRPC-based implementation designed to connect Linux systems to MetaTrader 5 (MT5) terminals, typically running within Docker or Wine environments. It provides an asynchronous API that mirrors the official MetaTrader 5 Python library while introducing modern features like parallel data fetching, automated resilience, and type-safe Pydantic models.
This client serves as the core engine for the mt5linux library, handling all low-level gRPC communication, connection lifecycle management, and transaction persistence. The synchronous MetaTrader5 class is a thin wrapper around this asynchronous implementation, delegating all business logic to it.
Sources: mt5linux/async_client.py, mt5linux/client.py:16-24, README.md
Architecture and Connection Lifecycle
The AsyncMetaTrader5 client utilizes grpc.aio for high-performance, non-blocking RPC calls. It manages an underlying asynchronous channel and a service stub generated from the mt5.proto definition.
Connection Management Flow
The client handles connection established via connect() or automatically during initialize(). It includes idempotent logic to ensure that multiple connection attempts do not disrupt existing channels.
The _connect method is responsible for creating the insecure_channel, initializing the MT5ServiceStub, fetching terminal constants, and starting background tasks like the Request Queue and Write-Ahead Log (WAL).
Sources: mt5linux/async_client.py, tests/unit/test_async_client_unit.py:186-215, mt5linux/mt5.proto:200-264
Resilience Features
The asynchronous client implements several resilience layers to handle transient network failures and terminal disconnects:
- Circuit Breaker: Monitors failure rates of RPC calls. If a threshold is met, the circuit opens to prevent further calls until a recovery timeout expires.
- Auto-Reconnect: Automatically attempts to restore the gRPC channel if the connection is lost during an operation.
- Health Monitor: A background task that periodically executes
HealthCheckRPCs to ensure the remote terminal is responsive and logged into a broker.
Sources: mt5linux/async_client.py, tests/unit/test_async_client_unit.py:440-470, tests/integration/test_async_client.py:65-75
Core API Methods
The client implements the full suite of MT5 operations, categorized into terminal management, symbol operations, market data, and trading.
API Summary Table
| Category | Key Methods | Description |
|---|---|---|
| Connection | initialize, login, shutdown | Manages terminal lifecycle and account authentication. |
| Information | terminal_info, account_info, version | Returns metadata about the MT5 environment and trading account. |
| Symbols | symbol_info, symbol_info_tick, symbol_select | Retrieves instrument properties and current prices. |
| Market Data | copy_rates_from, copy_ticks_range | Fetches historical bars (OHLCV) and tick data as NumPy arrays. |
| Trading | order_send, order_check, order_calc_margin | Validates and executes trading transactions. |
Sources: mt5linux/async_client.py, tests/integration/test_async_client.py:110-180, mt5linux/mt5.proto:200-264
Market Data Handling
Historical data requests return NumPy structured arrays. The gRPC layer transfers these as raw bytes with explicit dtypes to ensure compatibility between the Linux host (often Python 3.13+) and the Wine/Windows bridge (often Python 3.10/3.11).
# Parallel fetching example from AsyncMetaTrader5
account, symbol, tick = await asyncio.gather(
mt5.account_info(),
mt5.symbol_info("EURUSD"),
mt5.symbol_info_tick("EURUSD"),
)
Sources: mt5linux/async_client.py, README.md, pyproject.toml:23-28
Asynchronous Trading Extensions
Beyond the standard MT5 API, AsyncMetaTrader5 introduces specialized methods for high-concurrency trading environments.
Parallel Order Execution
The client features a RequestQueue that limits concurrent operations to match server capacity (default 10 workers). This prevents overloading the MT5 terminal while allowing the Python application to dispatch multiple orders simultaneously.
order_send_async: Dispatches an order and returns a uniquerequest_idimmediately. It acceptson_completeandon_errorcallbacks.order_send_batch: Executes a list of order requests in parallel, providing individual and aggregate completion callbacks.
Sources: mt5linux/async_client.py, tests/unit/test_async_client_unit.py:530-580, mt5linux/constants.py:690-698
Transaction Integrity (WAL and Verification)
To prevent "ghost orders" (orders sent but not confirmed due to connection loss), the client uses a Write-Ahead Log (WAL).
If a transaction returns an ambiguous status (e.g., Timeout or Connection error), the client enters a verification phase, checking pending orders and trade history to confirm if the order was actually placed on the server.
Sources: mt5linux/async_client.py, tests/unit/test_async_client_unit.py:690-750, mt5linux/constants.py:702-718
Data Models and Validation
The client uses Pydantic v2 models defined in MT5Models to provide type safety and runtime validation for all MT5 data structures.
Model Hierarchy
All models inherit from MT5Models.Base, which provides a unified from_mt5() factory. This factory allows models to be instantiated from raw dictionaries, gRPC messages, or C-style namedtuples returned by the underlying MT5 API.
| Model | Purpose | Key Constraints |
|---|---|---|
OrderRequest | Validates orders before sending | volume must be between 0 and 1000. comment max 31 chars. |
OrderResult | Parses execution results | Implements is_success property. |
AccountInfo | Represents account state | Maps 28 fields in positional order from MT5. |
SymbolInfo | Instrument metadata | Maps 96 specific symbol properties. |
Sources: mt5linux/models.py:58-200, tests/unit/test_async_client_unit.py:340-360
Summary
The AsyncMetaTrader5 client provides a robust, asynchronous bridge for MetaTrader 5 on Linux. By combining gRPC performance with a parallelized request queue and a persistence-focused Write-Ahead Log, it enables reliable algorithmic trading in containerized environments. Its architecture ensures that even when the network or the underlying MT5 terminal is unstable, transactions are tracked and verified, maintaining the integrity of the trading state.
Sources: mt5linux/async_client.py, mt5linux/client.py, README.md