Order Management
Relevant source files
The following files were used as context for generating this wiki page:
Order Management in mt5linux is a comprehensive system designed to facilitate trading operations between Linux-based Python environments and the MetaTrader 5 (MT5) platform via gRPC. It encompasses the entire lifecycle of a trade, including pre-trade validation (order checking), execution (order sending), and post-trade tracking of positions, orders, and deals.
The system uses Pydantic models to ensure type safety and schema validation for all trading requests and results. By leveraging gRPC, it provides both synchronous and asynchronous execution paths, allowing for high-performance trading strategies. The module also integrates a resilience layer that classifies MT5 return codes to handle transient errors and maintain consistency across network boundaries.
Sources: mt5linux/client.py:1-25, mt5linux/models.py:1-20, mt5linux/mt5.proto:1-15
Architecture and Data Flow
The order management process follows a structured flow from the client application through a gRPC service to the MT5 terminal.
The diagram shows the lifecycle of a trading request from model instantiation to final result classification.
Sources: mt5linux/client.py:470-550, mt5linux/constants.py:80-120, mt5linux/models.py:75-115
Key Components
| Component | Description | Source File |
|---|---|---|
OrderRequest | Pydantic model for validating and formatting trade requests for MT5. | mt5linux/models.py:75 |
OrderResult | Model representing the outcome of a trade execution, including retcodes and deal IDs. | mt5linux/models.py:127 |
TransactionOutcome | Public API enum for classifying trade results (Success, Retry, Verify Required). | mt5linux/constants.py:165 |
OrderCheckResult | Model for the order_check result, containing margin and feasibility data. | mt5linux/models.py:173 |
Trade Execution Lifecycle
1. Order Validation (order_check)
Before committing capital, the system allows for order validation. The order_check method sends a request to MT5 to verify if the account has sufficient margin and if the order parameters are valid according to broker rules.
This sequence illustrates the non-binding validation of a trade request.
Sources: mt5linux/client.py:461-471, mt5linux/models.py:173-205, tests/integration/test_trading.py:38-80
2. Order Execution (order_send)
Actual trade execution is performed via order_send. This method supports various trade actions defined in c.Order.TradeAction, such as DEAL (instant execution), PENDING (limit/stop orders), and MODIFY.
Supported Order Types:
- Market:
BUY,SELL - Pending:
BUY_LIMIT,SELL_LIMIT,BUY_STOP,SELL_STOP,BUY_STOP_LIMIT,SELL_STOP_LIMIT - Closing:
CLOSE_BY
Sources: mt5linux/constants.py:270-300, mt5linux/client.py:473-483
3. Asynchronous and Batch Operations
mt5linux extends the standard MT5 API with asynchronous capabilities.
order_send_async: Returns arequest_idimmediately and executes the trade in the background with callbacks.order_send_batch: Executes multiple orders simultaneously, utilizing a request queue to manage concurrency.
Sources: mt5linux/client.py:497-550, mt5linux/constants.py:590-600
Resilience and Error Classification
The system categorizes MT5 return codes (retcodes) into specific sets to determine the next logical action. This is critical for maintaining state consistency in distributed environments.
Return Code Categories
| Category | Retcodes (Examples) | Action |
|---|---|---|
| Success | 10008 (Placed), 10009 (Done) | Operation complete. |
| Retryable | 10004 (Requote), 10020 (Price Changed), 10024 (Too Many Requests) | Safe to retry; order was NOT executed. |
| Verify Required | 0 (Empty), 10012 (Timeout), 10031 (Connection) | Critical: Order may have executed; must verify state before retry. |
| Permanent | 10013 (Invalid), 10019 (No Money), 10017 (Trade Disabled) | Do not retry; fix underlying issue. |
Sources: mt5linux/constants.py:195-255
The decision tree used to handle trade results based on MT5 retcodes.
Sources: mt5linux/constants.py:140-190
Data Models for Management
Order Request Model
The OrderRequest model enforces strict constraints:
volume: Must be between 0 and 1000.comment: Max length of 31 characters.price,sl,tp,deviation,magic: Must be non-negative.
Sources: mt5linux/models.py:75-125
Tracking State (Positions vs. Orders)
- Positions: Represent active market exposure (
positions_get). - Orders: Represent pending requests or historical requests that haven't become deals yet (
orders_get). - Deals: Represent the actual execution record of an order in history (
history_deals_get).
Sources: mt5linux/models.py:355-410, mt5linux/client.py:567-680
Conclusion
Order Management in mt5linux provides a robust, type-safe wrapper around the MT5 trading protocol. By implementing complex retcode classification and supporting asynchronous batch operations, it enables reliable algorithmic trading on Linux systems. The integration of Write-Ahead Logs (WAL) and health monitoring further ensures that state-changing financial operations are handled with the necessary durability and transparency required for professional trading.
Sources: mt5linux/client.py:1-40, mt5linux/constants.py:603-620