Bridge Server
Relevant source files
The following files were used as context for generating this wiki page:
The Bridge Server is a standalone gRPC-based component designed to run within a Windows or Wine environment. Its primary purpose is to expose the official MetaTrader5 Python module—which is natively limited to Windows—to Linux-based clients. By acting as a high-performance intermediary, it allows developers to execute trading operations and fetch market data from Linux systems using both synchronous and asynchronous clients.
Sources: mt5linux/bridge.py:1-40, mt5linux/main.py:1-15
Architecture and Core Components
The server is implemented as a MT5GRPCServicer, which inherits from the gRPC-generated service definition. It uses a ThreadPoolExecutor to handle concurrent requests and incorporates robust signal handling for graceful shutdowns.
Server Lifecycle and Execution
The bridge is designed to be self-sufficient, requiring only the generated protobuf files and basic dependencies like grpcio, orjson, and numpy. It is typically invoked via the mt5linux module with the --server flag, which lazily loads the bridge machinery to avoid import errors on Linux hosts where the MetaTrader5 module is absent.
Key Classes and Logic
MT5GRPCServicer: The central logic hub that maps gRPC RPC calls to nativeMetaTrader5function calls. It manages an internal RLock to synchronize access to the MT5 module.- Timeout Protection: Blocking MT5 calls are wrapped in
_call_mt5_with_timeout(default 30s) to prevent the server from hanging indefinitely. - Data Materialization: Since MT5 returns specialized namedtuples (structseq), the bridge uses introspection to convert these into JSON-serializable dictionaries or raw bytes for Numpy arrays.
Sources: mt5linux/bridge.py:84-110, mt5linux/bridge.py:133-146, mt5linux/bridge.py:155-165
API Endpoints and Data Flow
The bridge implements a wide array of service methods defined in mt5.proto. These include terminal operations, account management, and market data retrieval.
Endpoint Summary Table
| Category | Method | Request Type | Response Type | Description |
|---|---|---|---|---|
| Terminal | HealthCheck | Empty | HealthStatus | Returns terminal connection and trade availability status. |
| Terminal | Initialize | InitRequest | BoolResponse | Establishes connection to the MT5 terminal. |
| Market Data | CopyRatesFrom | CopyRatesRequest | NumpyArray | Fetches OHLCV data as serialized bytes. |
| Trading | OrderSend | OrderRequest | DictData | Submits a trading order via JSON-serialized payload. |
| Provisioning | CreateDemoAccount | CreateDemoRequest | ProvisionedAccount | Drives a GUI-based wizard to create a new demo account. |
Sources: mt5linux/mt5.proto:210-280, mt5linux/bridge.py:246-300, mt5linux/bridge.py:530-550
Market Data Flow
When a client requests market data (e.g., CopyRates), the bridge fetches the data from the MT5 module, which returns a Numpy structured array. The bridge then serializes the raw bytes, dtype, and shape into a NumpyArray protobuf message to minimize overhead.
Server Configuration
The Bridge Server behavior is controlled through command-line arguments and centralized settings defined in mt5linux/settings.py.
Configuration Options
| Variable | CLI Argument | Default | Description |
|---|---|---|---|
MT5_HOST | --host | 0.0.0.0 | Bind address for the gRPC server. |
MT5_GRPC_PORT | -p, --port | 50051 | Port to listen for gRPC connections. |
MT5_WORKERS | --workers | 10 | Number of threads in the ThreadPoolExecutor. |
MT5_TIMEOUT | --mt5-timeout | 30.0 | Timeout in seconds for MT5 function calls. |
Sources: mt5linux/bridge.py:925-950, mt5linux/settings.py:120-135, mt5linux/main.py:30-45
Introspection and Protocol Validation
One unique feature of the Bridge Server is its ability to introspect the MetaTrader5 module at runtime. This ensures that the protocol remains compatible with the official API versions.
GetMethods: Parses the docstrings of MT5 functions to extract parameter signatures and default values.GetModels: Inspects MT5 tuple subclasses to determine the correct positional order of fields, which is crucial for reconstruction on the client side.
Sources: mt5linux/bridge.py:415-450, mt5linux/bridge.py:490-520
Implementation Details: JSON and Serialization
To maintain high performance, the bridge uses orjson for JSON serialization of dictionary data, which is approximately 3-10x faster than the standard library.
def _json_serialize(data: dict[str, JSONValue]) -> str:
"""Serialize dict to JSON string using orjson for high performance."""
return orjson.dumps(data, default=str).decode()
Sources: mt5linux/bridge.py:116-125
Conclusion
The Bridge Server serves as the critical backbone for mt5linux, effectively neutralizing the Windows-only limitation of MetaTrader 5. By leveraging gRPC and high-speed serialization, it provides a robust, thread-safe environment for Linux-based algorithmic trading.
Sources: mt5linux/bridge.py:1-20, tests/integration/test_bridge_behavior.py:35-50