Pydantic Models
Relevant source files
The following files were used as context for generating this wiki page:
Pydantic models in mt5linux provide a type-safe, validated layer for interacting with MetaTrader 5 (MT5) data structures. These models bridge the gap between raw MT5 objects (often returned as namedtuples or dictionaries) and a structured Pythonic interface, ensuring data integrity across the gRPC bridge. The implementation utilizes Pydantic v2 to enforce constraints, handle serialization, and provide clear error messages when data does not conform to the expected MT5 schema.
Sources: mt5linux/models.py:1-18, tests/unit/test_model_schema_validation.py:1-15
Architecture and Base Implementation
The models are organized within a central container class, MT5Models. All data models inherit from a common Base class which configures default Pydantic behavior and provides factory methods for cross-compatibility with native MT5 objects.
Model Configuration
The MT5Models.Base class enforces two critical configurations:
- Immutability: Models are
frozen=True, preventing accidental modification of trading data after instantiation. - Attribute Compatibility:
from_attributes=Trueallows models to be populated from objects that expose data via attributes, such as native MT5 objects or namedtuples.
Sources: mt5linux/models.py:46-55, tests/unit/test_model_schema_validation.py:169-215
The from_mt5 Factory
The from_mt5() method serves as the primary ingestion point for data. It identifies the input type and converts it into a validated model instance. It specifically handles raw dictionaries, objects with _asdict methods (standard namedtuples), and objects with direct attribute access.
The diagram above shows the logic flow of the from_mt5 factory method.
Sources: mt5linux/models.py:57-81, tests/unit/test_model_schema_validation.py:118-164
Core Trading Models
The library defines specific models for every major MT5 data structure. These are designed to be 1:1 compatible with the official MetaTrader 5 Python API structures.
Account and Terminal Information
These models capture the state of the trading environment and the current user's financial status.
| Model | Purpose | Key Fields |
|---|---|---|
AccountInfo | Financial and permission state of the account. | login, balance, equity, margin, leverage |
TerminalInfo | State of the MT5 Terminal instance. | connected, trade_allowed, build, path |
CurrentAccount | Extension view combining connection health with live account data. | host, port, connected, login, server |
Sources: mt5linux/models.py:206-258, tests/unit/test_model_schema_validation.py:50-113
Market Data Models
Models for price data and symbol metadata ensure that calculations (like margin and profit) are based on valid inputs.
SymbolInfo: A comprehensive model containing 96 fields including identification (name, ISIN), pricing (bid, ask, digits), and volume constraints (volume_min, volume_max).Tick: Represents a single price update with millisecond precision (time_msc) and volume data.BookEntry: Represents a single level in the Market Depth (DOM), tracking price and volume for bid/ask levels.
Sources: mt5linux/models.py:288-412, mt5linux/models.py:431-441, mt5linux/models.py:488-500
Trade Execution and Validation
A major feature of the Pydantic implementation is the validation of OrderRequest and the parsing of OrderResult.
Order Request Validation
The OrderRequest model enforces strict constraints on trading parameters before they are sent to the gRPC bridge. It includes a to_mt5_request() method that filters out default or zero values to conform to the MT5 API's expectations.
| Field | Constraints | Description |
|---|---|---|
volume | gt=0, le=1000 | Lot size of the order. |
price | ge=0 | Execution price (0 for market). |
comment | max_length=31 | String comment sent with order. |
magic | ge=0 | Expert Advisor identifier. |
Sources: mt5linux/models.py:99-145, tests/unit/test_model_schema_validation.py:270-305
Result Interpretation
The OrderResult and OrderCheckResult models provide computed properties to simplify logic for the developer.
Class relationship showing the structure of trading results.
Sources: mt5linux/models.py:155-204, tests/unit/test_model_schema_validation.py:217-259
Type Consistency and Protocol Alignment
The Pydantic models are validated against both internal TypedDict definitions and the real MetaTrader 5 module via introspection.
Protocol Compatibility
The MT5Protocol defines that methods such as account_info() and symbol_info() must return their respective Pydantic model types rather than raw tuples. This ensures a consistent interface for both the synchronous MetaTrader5 client and the AsyncMetaTrader5 client.
Sources: mt5linux/protocols.py:145-210, mt5linux/client.py:255-300
Structural Validation
Integration tests verify that field order and types match the real MT5 namedtuples. For example, AccountInfo must maintain exactly 28 fields in a specific positional order to ensure compatibility with data serialized over the bridge.
Sources: tests/integration/test_types_consistency.py:28-60, tests/integration/test_real_mt5_validation.py:139-245
Summary
The Pydantic models in mt5linux provide a robust, immutable, and validated data layer. By implementing strict field constraints and factory methods that handle various MT5 data formats, the library minimizes runtime errors and provides developers with a type-safe environment for developing algorithmic trading systems on Linux. Reaching full compatibility with the official API, these models serve as the "source of truth" for data flowing through the gRPC bridge.
Sources: mt5linux/models.py:1-40, tests/unit/test_model_schema_validation.py:326-340