Fail-Fast Error Handling
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The mt5linux library implements a comprehensive "Fail-Fast" error handling architecture designed to ensure financial safety and system reliability when interfacing with MetaTrader 5 (MT5). This system prioritizes immediate detection of critical failures and strictly categorizes errors to prevent dangerous side effects, such as double-execution of trades during ambiguous network conditions.
At its core, the system utilizes a centralized ErrorClassifier and TransactionOrchestrator to distinguish between transient network issues, which are safe to retry, and ambiguous states (like timeouts) that require explicit state verification before proceeding. This approach ensures that the client application is always aware of the exact state of an operation, raising permanent exceptions when recovery is unsafe.
Sources: README.md:154-162, mt5linux/utilities.py:382-402
Error Classification Architecture
The system employs a multi-tiered classification strategy for MT5 return codes and gRPC exceptions. This ensures that every failure is handled according to its specific risk profile.
Error Categories
Errors are classified into seven fine-grained internal categories, which are then mapped to simplified outcomes for the public API.
| Category | Description | Risk Level |
|---|---|---|
| SUCCESS | Operation completed successfully. | None |
| PARTIAL | Partially completed; may need follow-up. | Low |
| RETRYABLE | Transient error (e.g., price changed); safe to retry immediately. | Low |
| VERIFY_REQUIRED | Ambiguous state (e.g., Timeout); MUST verify terminal state before retrying. | Critical |
| CONDITIONAL | May be retryable depending on user context or market hours. | Medium |
| PERMANENT | Logical or terminal error; do not retry. | High |
| UNKNOWN | Unrecognized code; treated conservatively as PERMANENT for safety. | High |
Sources: mt5linux/constants.py:84-118, mt5linux/utilities.py:461-487
Classification Logic Flow
The following diagram illustrates how the ErrorClassifier determines the next step in the execution lifecycle based on the received return code.
Transaction Safety and Idempotency
To prevent the double execution of orders—a critical requirement in financial software—mt5linux implements a specialized TransactionHandler and a Write-Ahead Log (WAL).
Idempotency Tracking
Since MT5 does not provide native idempotency keys, the library utilizes the 31-character comment field to embed unique request identifiers.
- Request ID Generation: A unique 18-character string (prefix "RQ" + 16 hex characters) is generated for every
order_sendrequest. - Comment Marking: The request ID is prepended to the user's comment, ensuring it can be recovered even if the response is lost.
- Verification: If a timeout occurs, the system queries the order history and scans the
commentfields for the specific Request ID to determine if the order was actually executed.
Sources: mt5linux/utilities.py:726-805, tests/unit/test_transaction_safety.py:27-77
Write-Ahead Log (WAL)
The WAL provides persistence for trade intents, enabling recovery even after a complete application crash.
Resilience Components
The fail-fast strategy is supported by several resilience patterns implemented in mt5linux/utilities.py.
Circuit Breaker
Prevents cascading failures by blocking requests to the MT5 terminal if a failure threshold is reached.
- States:
CLOSED(Normal),OPEN(Blocking),HALF_OPEN(Testing Recovery). - Threshold: Configurable via
cb_threshold(Default: 5). - Recovery: Transitions after
cb_recoveryseconds (Default: 30.0).
Sources: mt5linux/utilities.py:612-645, mt5linux/constants.py:53-65
Priority Request Queue
Managed by MT5Utilities.RequestQueue, this system provides parallel execution with backpressure. If the queue_max_depth is reached, it raises a QueueFullError, allowing the application to fail fast rather than accumulating unbounded latency.
Sources: mt5linux/utilities.py:975-1020, mt5linux/constants.py:347-353
Summary of Exception Types
The library consolidates all errors into the MT5Utilities.Exceptions container for unified handling.
| Exception Class | Usage Scenario |
|---|---|
RetryableError | Transient issues where it is safe to try again. |
PermanentError | Critical failures (e.g., Invalid Volume, Insufficient Funds). |
MaxRetriesError | Raised when the retry limit is reached without success. |
CircuitBreakerOpenError | Raised when the system is in a failed state and refusing new requests. |
EmptyResponseError | Specific to gRPC cases where a response was expected but not received. |
Sources: mt5linux/utilities.py:134-215
Conclusion
The Fail-Fast error handling in mt5linux provides a rigorous framework for financial trading on Linux. By combining detailed error classification, idempotency tracking via Request IDs, and a persistent Write-Ahead Log, the system ensures that trade execution is either confirmed or safely failed, never left in an ambiguous state that could lead to financial loss.