Trading Module¶
mt5cli.trading ¶
Trading-capable MetaTrader 5 session helpers and operational utilities.
CalibrationStatus
module-attribute
¶
CalibrationStatus = Literal[
"calibrated",
"no_live_tick",
"not_advancing",
"unstable_offset",
"insufficient_agreement",
"offset_disagreement",
"implausible_offset",
]
ExecutionStatus
module-attribute
¶
ExecutionStatus = Literal[
"filled",
"partial_fill",
"placed",
"dry_run",
"skipped",
"rejected",
"malformed",
"failed",
]
OrderTimeMode
module-attribute
¶
POSITION_COLUMNS
module-attribute
¶
POSITION_COLUMNS = (
"ticket",
"time",
"symbol",
"type",
"volume",
"price_open",
"sl",
"tp",
"price_current",
"profit",
"swap",
"comment",
"magic",
)
__all__
module-attribute
¶
__all__ = [
"POSITION_COLUMNS",
"CalibrationStatus",
"ClockStatus",
"ExecutionStatus",
"MarginVolume",
"NormalizedTickSnapshot",
"OrderExecutionResult",
"OrderFillingMode",
"OrderLimits",
"OrderSide",
"OrderTimeMode",
"PositionSide",
"ProjectionMode",
"TickClockCalibration",
"TickClockNormalizer",
"calculate_account_projected_margin_ratio",
"calculate_margin_and_volume",
"calculate_positions_margin",
"calculate_positions_margin_by_symbol",
"calculate_positions_margin_safe",
"calculate_projected_margin_ratio",
"calculate_spread_ratio",
"calculate_symbol_group_margin_ratio",
"calculate_trailing_stop_updates",
"calculate_volume_by_margin",
"close_open_positions",
"detect_position_side",
"determine_order_limits",
"ensure_symbol_selected",
"estimate_order_margin",
"extract_tick_price",
"fetch_latest_closed_rates_indexed",
"get_account_snapshot",
"get_positions_frame",
"get_symbol_snapshot",
"get_tick_snapshot",
"normalize_order_volume",
"place_market_order",
"resolve_broker_filling_mode",
"update_sltp_for_open_positions",
"update_trailing_stop_loss_for_open_positions",
]
MarginVolume ¶
Bases: TypedDict
Affordable volume bounds derived from account margin and symbol constraints.
NormalizedTickSnapshot ¶
Bases: TypedDict
Latest tick with an explicit raw-vs-UTC timestamp distinction.
raw_time preserves the numeric MT5 epoch exactly as labeled by the
broker server. time_utc is populated only when a validated server
clock offset could be applied (clock_status == "calibrated");
otherwise time_utc and server_clock_offset_seconds are None
and callers must not treat raw_time as UTC.
OrderExecutionResult
dataclass
¶
OrderExecutionResult(
status: ExecutionStatus,
symbol: str,
order_side: OrderSide,
requested_volume: float,
filled_volume: float | None,
request_price: float | None,
filled_price: float | None,
order_ticket: int | None,
deal_ticket: int | None,
position_id: int | None,
magic: int | None,
retcode: int | None,
comment: str | None,
dry_run: bool,
request: dict[str, object],
response: dict[str, object] | None,
)
Serialization-safe normalized receipt for an execution request.
filled_volume and filled_price are only populated when returned by
the broker; a successful retcode never implies that the requested values
were filled. response is diagnostic data, not the primary contract.
OrderLimits ¶
TickClockCalibration
dataclass
¶
TickClockCalibration(
status: CalibrationStatus,
offset_seconds: float | None,
sample_count: int,
evidence_symbols: tuple[str, ...],
calibrated_at: float | None,
last_sample_symbol: str | None = None,
last_sample_raw_time: float | None = None,
last_sample_host_time: float | None = None,
last_sample_raw_offset_seconds: float | None = None,
)
Diagnostic record of one server-clock calibration attempt.
offset_seconds is server labeled time - true UTC (10800.0 for
a UTC+3 server wall clock), rounded to 30-minute increments, and is only
set when status == "calibrated". sample_count counts distinct
advancing live tick events that agreed on the offset (each event's
server-labeled epoch compared against the host clock's own time at the
moment it was observed), and evidence_symbols names the symbols that
provided that evidence. calibrated_at is the UTC epoch when the
calibration was accepted.
last_sample_* fields describe the most recent live tick observation
considered (accepted or rejected), regardless of outcome, so a failed
calibration still carries enough evidence to diagnose it in production:
the symbol, its raw (server-labeled) timestamp, the host clock's time
when it was observed, and the resulting raw offset before rounding. They
are None only when no symbol ever produced a comparable advancing
tick (for example every configured symbol had a cold start with no prior
observation, or none of them were trading).
TickClockNormalizer ¶
TickClockNormalizer(
client: _Mt5ClientProtocol,
symbols: Sequence[str] | None = None,
*,
samples_per_symbol: int = 3,
min_agreeing_samples: int = 2,
sample_interval_seconds: float = 1.0,
max_calibration_age_seconds: float = 6 * 3600.0,
revalidation_interval_seconds: float = 300.0,
failed_calibration_retry_seconds: float = 30.0,
)
Connection-scoped UTC normalization for live MT5 tick timestamps.
symbol_info_tick() timestamps may carry a broker server wall-clock
label (for example UTC+2/UTC+3 on OANDA-style servers) instead of true
UTC. MetaQuotes documents copy_ticks_range() as UTC, but that
contract is broker/terminal-dependent and not independently verified
here, so this normalizer never relies on it as an out-of-band UTC
reference for the live tick clock (a prior design that did so failed
every calibration sample with no_matching_event because a query
window built from the host clock could not match the live event, off by
roughly the broker's offset; whether copied rows carry the same non-UTC
label was never isolated, and calibration no longer depends on it).
This normalizer instead calibrates the offset from live ticks alone,
using this process's own clock as the independent reference: each poll of
symbol_info_tick() is stamped with datetime.now(UTC) at the moment
it is received, and comparing that host receipt time against the tick's
own server-labeled epoch yields one candidate offset. A single poll is
never trusted on its own — a closed, stale, or illiquid symbol keeps
returning the exact same last-traded tick, so its epoch never changes
between polls; only a different epoch than the previous poll proves
the broker produced a fresh event (a broker offset decrease can relabel
the next fresh event with a numerically smaller epoch, so freshness is
inequality, not a "must increase" ordering), and only repeated agreement
across distinct fresh events (one symbol polled several times, and/or
several symbols) is accepted. Accepted offsets are rounded to 30-minute
increments within a plausible UTC offset range and cached per client
connection.
A cached calibration is revalidated after max_calibration_age_seconds
(covering DST transitions on the broker side), immediately when a
normalized timestamp lands implausibly far in the future (evidence the
broker offset grew), and periodically through one full revalidation round
over every configured symbol well before the cache would otherwise
expire (evidence the broker offset shrank, which a future-skew check
alone cannot catch since it looks like ordinary staleness rather than an
anomaly). The whole round is evaluated before deciding: any advancing
sample that refutes the cached offset — a clean disagreement, or an
advancing tick whose raw offset is unusable (unstable_offset /
implausible_offset) and not otherwise explained by the cached offset
given the real elapsed time since it was last observed and that prior
observation's own inferred delay — invalidates the cache and forces
full recalibration, while confirming or inconclusive symbols never
cancel that evidence. Failed calibrations are retried at
most once per failed_calibration_retry_seconds rather than on every
call. When no
offset can be established safely, normalized snapshots fail closed with
clock_status="uncalibrated" and time_utc=None instead of
treating the raw timestamp as UTC, and a cached offset that advancing
evidence has just refuted is never applied to another tick.
Keep one instance per MT5 connection/account; the calibration is a property of the broker server, not of an individual symbol.
Initialize a normalizer bound to one connected MT5 client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client exposing |
required |
symbols
|
Sequence[str] | None
|
Optional default calibration symbols. Prefer several
actively updating symbols; when omitted, calibration uses the
symbol passed to :meth: |
None
|
samples_per_symbol
|
int
|
Live polls attempted per symbol during one calibration. Every full calibration clears each resolved symbol's prior observation first, so a symbol's first poll in the attempt only establishes a baseline; each subsequent poll whose epoch differs from its predecessor yields one candidate offset. Must be at least 2, or no attempt could ever produce evidence. |
3
|
min_agreeing_samples
|
int
|
Distinct fresh (changed-epoch) tick events that must agree on the same rounded offset before it is accepted. Must be at least 2: a single agreeing event is one delayed or anomalous tick away from selecting the wrong 30-minute bucket, which would contradict the repeated- agreement safety this class is meant to provide. |
2
|
sample_interval_seconds
|
float
|
Pause between consecutive polls of one symbol so an actively updating symbol can produce distinct tick events. |
1.0
|
max_calibration_age_seconds
|
float
|
Age after which a cached calibration is recomputed unconditionally (bounds DST-transition staleness). |
6 * 3600.0
|
revalidation_interval_seconds
|
float
|
Minimum time between opportunistic
checks of an otherwise still-fresh cached calibration. Every
configured symbol is polled once and the whole round is
collected before deciding; any accepted sample that disagrees
with the cached offset, and any advancing sample whose offset
is unusable ( |
300.0
|
failed_calibration_retry_seconds
|
float
|
Minimum time between full recalibration attempts after a failed calibration, so a closed or illiquid market does not retry on every call. |
30.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a numeric tuning parameter is not positive. |
Source code in mt5cli/trading.py
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 | |
calibration
property
¶
calibration: TickClockCalibration | None
The most recent calibration attempt, or None before the first.
calibrate ¶
calibrate(
symbols: Sequence[str] | None = None,
) -> TickClockCalibration
Measure the server clock offset from advancing live tick evidence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
Sequence[str] | None
|
Symbols to sample; defaults to the constructor symbols. |
None
|
Returns:
| Type | Description |
|---|---|
TickClockCalibration
|
The calibration result, also cached on this normalizer. Failed |
TickClockCalibration
|
calibrations are recorded for diagnostics but never reused. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no calibration symbol is available. |
Source code in mt5cli/trading.py
get_normalized_tick_snapshot ¶
get_normalized_tick_snapshot(
symbol: str,
) -> NormalizedTickSnapshot
Return the latest tick with a validated UTC timestamp when possible.
The raw fields mirror :func:get_tick_snapshot, fetched only after
calibration is confirmed or refreshed; an initial or expired
calibration takes multiple paced samples, and fetching the reported
tick beforehand would report a snapshot that was already stale by the
time calibration finished. time_utc is set only under a currently
valid calibration; when the normalized time would land implausibly
far in the future (evidence that the broker offset changed, e.g. a
DST transition) the offset is recalibrated once, the tick is
refetched, and the snapshot fails closed if it still cannot be
validated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol whose latest tick is normalized. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
NormalizedTickSnapshot
|
class: |
NormalizedTickSnapshot
|
snapshot carries |
|
NormalizedTickSnapshot
|
|
Source code in mt5cli/trading.py
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 | |
calculate_account_projected_margin_ratio ¶
calculate_account_projected_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbol: str | None = None,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
) -> float
Return account-wide current plus optional new-position margin over equity.
Current exposure comes from the broker account snapshot margin field so
unrelated open positions remain in the baseline. Optional projected
exposure is added via :func:estimate_order_margin only when a symbol, side,
and positive volume are all supplied.
Source code in mt5cli/trading.py
calculate_margin_and_volume ¶
calculate_margin_and_volume(
client: _Mt5ClientProtocol,
symbol: str,
unit_margin_ratio: float,
) -> MarginVolume
Calculate tradable margin and volumes from account free margin.
Allocates unit_margin_ratio of nonnegative margin_free as the
margin budget for proportional volume sizing on both buy and sell sides.
A unit_margin_ratio of 0 requests exactly one minimum valid unit per
side when free margin can afford it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol used for minimum-lot margin and volume calculations. |
required |
unit_margin_ratio
|
float
|
Fraction of free margin to allocate per unit. |
required |
Returns:
| Type | Description |
|---|---|
MarginVolume
|
Dictionary with |
MarginVolume
|
|
MarginVolume
|
clamped to |
Source code in mt5cli/trading.py
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 | |
calculate_positions_margin ¶
calculate_positions_margin(
client: _Mt5ClientProtocol,
*,
symbols: Sequence[str] | None = None,
) -> float
Return the sum of estimated current margin for open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbols
|
Sequence[str] | None
|
Optional symbol filter. When omitted, all open positions are included. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Total estimated margin, or |
Source code in mt5cli/trading.py
calculate_positions_margin_by_symbol ¶
calculate_positions_margin_by_symbol(
client: _Mt5ClientProtocol,
*,
symbols: Sequence[str],
suppress_errors: bool = True,
) -> dict[str, float]
Return per-symbol estimated margin for open positions.
Computes margin for each unique input symbol independently using the strict
:func:calculate_positions_margin helper. Duplicates are deduplicated in
first-seen order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbols
|
Sequence[str]
|
Symbols to compute margin for. |
required |
suppress_errors
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Mapping of symbol to margin total in first-seen unique-symbol order. |
dict[str, float]
|
Returns an empty dict when |
dict[str, float]
|
with |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
When a symbol raises |
Mt5RuntimeError
|
When a symbol raises |
AttributeError
|
When a symbol raises |
Source code in mt5cli/trading.py
calculate_positions_margin_safe ¶
Return the total estimated margin for open positions across symbols.
Internally calls :func:calculate_positions_margin_by_symbol with
suppress_errors=True. Failed symbols are silently skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbols
|
Sequence[str]
|
Symbols to include. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Sum of per-symbol margins; |
Source code in mt5cli/trading.py
calculate_projected_margin_ratio ¶
calculate_projected_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbol: str,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
) -> float
Return estimated current plus optional new-position margin over equity.
Current exposure is estimated from open positions with
:func:calculate_positions_margin. Optional projected exposure is added via
:func:estimate_order_margin. Thresholds and guard actions are intentionally
left to downstream applications.
Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller.
Source code in mt5cli/trading.py
calculate_spread_ratio ¶
Return (ask - bid) / ((ask + bid) / 2) for the latest tick.
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If bid or ask is unavailable. |
Source code in mt5cli/trading.py
calculate_symbol_group_margin_ratio ¶
calculate_symbol_group_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbols: Sequence[str],
new_symbol: str | None = None,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
suppress_errors: bool = True,
projection_mode: ProjectionMode = "add",
) -> float
Return estimated symbol-group margin over account equity.
Per-symbol current exposure is summed with
:func:calculate_positions_margin_by_symbol. When new_symbol is inside
the input symbol group and candidate side/volume are provided, projected order
margin is applied according to projection_mode:
"add"(default): adds candidate margin to the group total."replace_symbol": subtracts current margin fornew_symbol, then adds candidate margin. Useful for reversal-style projections where the new order is intended to replace existing exposure for that symbol.
If the candidate margin estimation fails, the subtraction is also skipped so the operation is atomic. Invalid equity always raises to fail closed.
Raises:
| Type | Description |
|---|---|
AttributeError
|
When symbol margin lookup or projected margin lookup
fails and |
Mt5RuntimeError
|
When symbol margin lookup or projected margin lookup
fails and |
Mt5OperationError
|
When account equity is invalid, or when symbol margin
lookup or projected margin lookup fails and |
Source code in mt5cli/trading.py
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 | |
calculate_trailing_stop_updates ¶
calculate_trailing_stop_updates(
client: _Mt5ClientProtocol,
*,
symbol: str,
trailing_stop_ratio: float,
magic: int | None = None,
) -> dict[int, float]
Return per-ticket trailing stop-loss updates for open symbol positions.
Buy positions trail from bid using bid * (1 - trailing_stop_ratio).
Sell positions trail from ask using ask * (1 + trailing_stop_ratio).
Existing stop losses are preserved when they are already more favorable.
Missing symbol metadata returns an empty update map. Positions with a
missing side-specific tick price are skipped.
Source code in mt5cli/trading.py
calculate_volume_by_margin ¶
calculate_volume_by_margin(
client: _Mt5ClientProtocol,
symbol: str,
available_margin: float,
order_side: OrderSide,
) -> float
Calculate max normalized volume affordable for one side.
Returns:
| Type | Description |
|---|---|
float
|
Largest stepped volume whose actual margin (from |
float
|
fits within |
float
|
constraints; |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If symbol volume constraints or tick data are invalid. |
Source code in mt5cli/trading.py
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 | |
close_open_positions ¶
close_open_positions(
client: _Mt5ClientProtocol,
*,
symbols: str | list[str] | None = None,
tickets: list[int] | None = None,
order_filling_mode: OrderFillingMode | None = None,
deviation: int | None = None,
comment: str | None = None,
magic: int | None = None,
dry_run: bool = False,
) -> list[OrderExecutionResult]
Close matching open positions.
When order_filling_mode is None, the filling mode is resolved per
symbol with :func:resolve_broker_filling_mode so closes are not rejected
on brokers whose symbols do not support IOC.
Returns:
| Type | Description |
|---|---|
list[OrderExecutionResult]
|
Normalized execution results for matching positions. |
Source code in mt5cli/trading.py
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 | |
detect_position_side ¶
detect_position_side(
client: _Mt5ClientProtocol,
symbol: str,
*,
magic: int | None = None,
) -> PositionSide | None
Detect the net open position side for a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol to inspect. |
required |
magic
|
int | None
|
Optional magic number filter applied fail-closed. |
None
|
Returns:
| Type | Description |
|---|---|
PositionSide | None
|
|
PositionSide | None
|
|
PositionSide | None
|
|
Source code in mt5cli/trading.py
determine_order_limits ¶
determine_order_limits(
client: _Mt5ClientProtocol,
symbol: str,
side: PositionSide | str,
stop_loss_limit_ratio: float | None = None,
take_profit_limit_ratio: float | None = None,
) -> OrderLimits
Derive entry and protective order prices from current market quotes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol used for the quote lookup. |
required |
side
|
PositionSide | str
|
Position side as |
required |
stop_loss_limit_ratio
|
float | None
|
Relative distance from entry for stop loss in
|
None
|
take_profit_limit_ratio
|
float | None
|
Relative distance from entry for take profit in
|
None
|
Returns:
| Type | Description |
|---|---|
OrderLimits
|
Dictionary with |
OrderLimits
|
Omitted protective levels are returned as |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If required tick data is invalid or computed SL/TP
prices violate available |
Source code in mt5cli/trading.py
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 | |
ensure_symbol_selected ¶
Ensure a symbol is visible in Market Watch before sending orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol to select. |
required |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If the symbol cannot be selected in Market Watch or
|
Source code in mt5cli/trading.py
estimate_order_margin ¶
estimate_order_margin(
client: _Mt5ClientProtocol,
symbol: str,
order_side: OrderSide | str,
volume: float,
) -> float
Estimate required margin for one order at the current market price.
Returns:
| Type | Description |
|---|---|
float
|
Positive finite margin required for the order at the current quote. |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If volume, tick data, or margin estimation is invalid. |
Source code in mt5cli/trading.py
extract_tick_price ¶
Return a positive finite float from tick[key], or None if invalid.
Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None.
Source code in mt5cli/trading.py
fetch_latest_closed_rates_indexed ¶
fetch_latest_closed_rates_indexed(
client: _Mt5ClientProtocol,
*,
symbol: str,
granularity: str,
count: int,
) -> DataFrame
Fetch the latest closed bars with a UTC DatetimeIndex from a client.
Fetches one additional current bar, removes it, then converts the time
column to a UTC-aware :class:~pandas.DatetimeIndex named "time" and
drops the original column. Intended for downstream time-series consumers
that require a datetime index rather than a time column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected public client with rate-fetch capability. |
required |
symbol
|
str
|
Symbol name. |
required |
granularity
|
str
|
Timeframe string (for example |
required |
count
|
int
|
Maximum number of closed bars to return. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Up to |
DataFrame
|
UTC-aware |
DataFrame
|
column is dropped. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Mt5OperationError
|
If the client cannot fetch rate data. |
TypeError
|
If the client returns a non-DataFrame payload. |
Source code in mt5cli/trading.py
get_account_snapshot ¶
Return normalized account state with stable keys.
Source code in mt5cli/trading.py
get_positions_frame ¶
Return open positions as a DataFrame with stable baseline columns.
Source code in mt5cli/trading.py
get_symbol_snapshot ¶
get_symbol_snapshot(
client: _Mt5ClientProtocol, symbol: str
) -> dict[str, float | int | str | bool | None]
Return normalized symbol metadata required for trading decisions.
Source code in mt5cli/trading.py
get_tick_snapshot ¶
Return normalized latest tick data with a numeric MT5 timestamp.
The numeric time preserves the original value returned by MT5 without
applying timezone or server-offset correction. Use
:class:TickClockNormalizer when a validated UTC timestamp is required.
Source code in mt5cli/trading.py
normalize_order_volume ¶
normalize_order_volume(
volume: float,
*,
volume_min: float,
volume_max: float,
volume_step: float,
) -> float
Normalize a requested order volume to broker volume constraints.
Returns:
| Type | Description |
|---|---|
float
|
Volume floored to the nearest valid broker step from |
float
|
capped at |
float
|
deterministically. The result never exceeds the capped request except |
float
|
by floating-point noise (a relative tolerance of |
float
|
keeps on-step requests on their step. Returns |
float
|
constraints are invalid, non-finite, or the capped request is below |
float
|
|
Source code in mt5cli/trading.py
place_market_order ¶
place_market_order(
client: _Mt5ClientProtocol,
*,
symbol: str,
volume: float,
order_side: OrderSide,
order_filling_mode: OrderFillingMode = "IOC",
order_time_mode: OrderTimeMode = "GTC",
sl: float | None = None,
tp: float | None = None,
position: int | None = None,
deviation: int | None = None,
comment: str | None = None,
magic: int | None = None,
dry_run: bool = False,
) -> OrderExecutionResult
Place one normalized market order or return a dry-run result.
A dry run reads the current side-appropriate quote into
request["price"] and returns a status="dry_run" receipt without
selecting the symbol or sending an order. Live orders return
status="rejected" for a valid non-success retcode,
status="malformed" when the broker response has no valid retcode, and
status="failed" when preparation or submission raises; the normalized
request and response stay available for inspection.
Returns:
| Type | Description |
|---|---|
OrderExecutionResult
|
Normalized execution result containing request and response details. |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If volume is invalid. |
ValueError
|
If an order mode is unsupported. |
Source code in mt5cli/trading.py
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 | |
resolve_broker_filling_mode ¶
resolve_broker_filling_mode(
client: _Mt5ClientProtocol,
*,
symbol: str,
preferred_modes: Sequence[OrderFillingMode] = (
"IOC",
"FOK",
"RETURN",
),
default_mode: OrderFillingMode = "IOC",
) -> OrderFillingMode
Return the first broker-supported filling mode from a preferred order.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any preferred or default mode name is unsupported. |
Source code in mt5cli/trading.py
update_sltp_for_open_positions ¶
update_sltp_for_open_positions(
client: _Mt5ClientProtocol,
*,
symbol: str | None = None,
tickets: list[int] | None = None,
magic: int | None = None,
stop_loss: float | None = None,
take_profit: float | None = None,
dry_run: bool = False,
) -> list[OrderExecutionResult]
Update SL/TP for matching open positions.
Returns:
| Type | Description |
|---|---|
list[OrderExecutionResult]
|
Normalized execution results for matching positions. |
Source code in mt5cli/trading.py
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 | |
update_trailing_stop_loss_for_open_positions ¶
update_trailing_stop_loss_for_open_positions(
client: _Mt5ClientProtocol,
*,
symbol: str,
trailing_stop_ratio: float,
magic: int | None = None,
dry_run: bool = False,
) -> list[OrderExecutionResult]
Update open positions whose trailing stop loss should move favorably.
Returns:
| Type | Description |
|---|---|
list[OrderExecutionResult]
|
Normalized execution results for positions that need an SL update. |
Source code in mt5cli/trading.py
Trading-capable MT5 sessions¶
mt5_session() is the single lifecycle API. It yields MT5Client, which
supports both market data and generic operational execution. It initializes and
logs in once, then shuts down once; passing client= yields a caller-owned
client without changing its lifecycle.
from mt5cli import mt5_session
with mt5_session() as client:
positions = client.positions(symbol="EURUSD")
account = client.account_info()
login accepts int, numeric str, or an empty string; empty strings are
treated as unset. path, password, server, and timeout are forwarded to
pdmt5.Mt5Config, and omitted timeout values keep the lower-level default.
The same client also retrieves canonical deal history with
client.history_deals() and client.recent_history_deals().
State and order helpers¶
These helpers are strategy-agnostic and do not depend on signal detection, betting logic, or scheduling code in downstream applications.
from mt5cli import (
calculate_positions_margin,
calculate_spread_ratio,
calculate_margin_and_volume,
close_open_positions,
detect_position_side,
determine_order_limits,
estimate_order_margin,
fetch_latest_closed_rates_indexed,
get_account_snapshot,
get_positions_frame,
get_symbol_snapshot,
get_tick_snapshot,
normalize_order_volume,
place_market_order,
)
account = get_account_snapshot(client)
symbol = get_symbol_snapshot(client, "EURUSD")
tick = get_tick_snapshot(client, "EURUSD")
positions = get_positions_frame(client, "EURUSD")
side = detect_position_side(client, "EURUSD")
spread_ratio = calculate_spread_ratio(client, "EURUSD")
volume = normalize_order_volume(
0.15,
volume_min=symbol["volume_min"],
volume_max=symbol["volume_max"],
volume_step=symbol["volume_step"],
)
buy_margin = (
estimate_order_margin(client, "EURUSD", "BUY", volume) if volume > 0 else 0.0
)
open_margin = calculate_positions_margin(client, symbols=["EURUSD"])
# Fetch closed bars with a UTC DatetimeIndex instead of a "time" column:
indexed_bars = fetch_latest_closed_rates_indexed(
client,
symbol="EURUSD",
granularity="M1",
count=100,
)
# indexed_bars.index is a UTC-aware DatetimeIndex named "time"
sizing = calculate_margin_and_volume(
client,
"EURUSD",
unit_margin_ratio=0.5,
)
limits = determine_order_limits(
client,
"EURUSD",
side="long",
stop_loss_limit_ratio=0.01,
take_profit_limit_ratio=0.02,
)
preview = place_market_order(
client,
symbol="EURUSD",
volume=sizing["buy_volume"],
order_side="BUY",
sl=limits["stop_loss"],
tp=limits["take_profit"],
dry_run=True,
)
closed = close_open_positions(client, symbols="EURUSD", dry_run=True)
detect_position_side() returns long for buy-only exposure, short for
sell-only exposure, and None for no positions or mixed long/short exposure.
calculate_spread_ratio() uses (ask - bid) / ((ask + bid) / 2) and raises
Mt5OperationError when bid or ask is missing or non-positive.
normalize_order_volume() returns 0.0 for invalid constraints or
sub-minimum requests; check the result before calling estimate_order_margin(),
which requires a positive finite volume. calculate_positions_margin() silently
skips rows with missing symbols, non-positive volumes, non-finite volumes, or
unsupported position types, but propagates Mt5OperationError from estimate_order_margin() when a valid row
encounters invalid tick data or margin results from the broker.
SL/TP ratios for determine_order_limits() must satisfy 0 <= ratio < 1; 0
omits that level. SL/TP prices are rounded with symbol digits metadata when
available. determine_order_limits() pre-validates computed SL/TP prices against
available trade_stops_level * point metadata when present; violations raise
Mt5OperationError. This is a planning helper only: it does not guarantee broker
acceptance because live validation can still depend on price movement, bid/ask
side, freeze levels, and server-side rules, and it does not validate
trade_freeze_level. When symbol metadata cannot be loaded, protective prices
still round with digits=8 and stop-level validation is skipped.
unit_margin_ratio for calculate_margin_and_volume() accepts
0 <= ratio <= 1; a value of 0 requests one minimum valid unit when free
margin can afford it. Negative margin_free is clamped to 0.0 before
sizing. Execution helpers return frozen, typed
OrderExecutionResult receipts. Access fields directly and call to_dict()
only when serializing; dry_run=True never sends an order or mutates Market
Watch visibility.
A dry-run market order still reads the current side-appropriate quote into
request["price"], so request_price is populated on the preview receipt,
while response and filled_price stay None.
ensure_symbol_selected() adds hidden symbols to Market Watch before live order
placement and SL/TP updates; dry runs never call it. Receipt statuses follow
the public contract: filled, partial_fill, and placed map to broker
success retcodes; unknown but valid integer retcodes are rejected; a broker
response with a missing or unparsable retcode is malformed; exceptions during
MT5 constant access, symbol preparation, tick retrieval, or order submission
are failed; skipped means no execution was attempted for a defined
operational reason; dry_run is a preview only. The raw request and
response mappings remain diagnostic fields — use the normalized direct fields
(request_price, filled_price, order_ticket, deal_ticket,
position_id, retcode, ...) for standard execution metadata. Broker sentinel
identifiers (0 or negative order/deal/position values) are normalized to
None; close and SL/TP receipts keep the known positive position ticket from
the request when the broker response omits it.
Order planning return contracts¶
from mt5cli import MarginVolume, OrderLimits, OrderExecutionResult
sizing: MarginVolume = calculate_margin_and_volume(
client,
"EURUSD",
unit_margin_ratio=0.5,
)
limits: OrderLimits = determine_order_limits(
client,
"EURUSD",
side="long",
stop_loss_limit_ratio=0.01,
take_profit_limit_ratio=0.02,
)
preview: OrderExecutionResult = place_market_order(
client,
symbol="EURUSD",
volume=sizing["buy_volume"],
order_side="BUY",
sl=limits["stop_loss"],
tp=limits["take_profit"],
dry_run=True,
)
updates: list[OrderExecutionResult] = update_sltp_for_open_positions(
client,
symbol="EURUSD",
stop_loss=limits["stop_loss"],
dry_run=True,
)
Closes issue #33: strategy-neutral order planning and execution helpers exposed through the stable package root without embedding entry/exit policy.
Retrieving recent history deals¶
MT5Client.recent_history_deals() fetches canonical history deals from the
single connected client over a trailing time window.
The helper returns a chronologically sorted DataFrame with a RangeIndex and
all columns from the underlying client (time, symbol, type, entry,
volume, profit, position_id, etc.). It does not apply any
strategy-specific transformations — entry/exit classification, Kelly fractions,
and betting semantics belong in downstream applications.
from mt5cli import mt5_session
with mt5_session() as client:
deals_df = client.recent_history_deals(
symbol="JP225",
hours=24,
date_to="2024-02-01",
)
hours must be positive and date_to must be an explicit naive MT5
trade-server wall-clock end time. mt5cli cannot determine the current server
time, so omitted date_to values are rejected. Offset-bearing strings and
aware datetime objects are rejected because mt5cli has no validated
UTC-to-server-time converter. An empty or None result from the underlying
client is normalized to an empty DataFrame.
Downstream packages own all strategy-specific transformations. mt5cli does not provide entry-deal classification, Kelly sizing, or any betting-specific helpers.
Timestamp sources and broker clock offsets¶
pdmt5's copied-history APIs accept timezone-naive trade-server wall-clock
query bounds. mt5cli rejects offset-bearing strings and timezone-aware
datetime objects at that boundary; it does not infer a broker offset or
strip tzinfo to simulate a conversion. Copied-history timestamps remain
broker/terminal-dependent for downstream interpretation.
mt5cli does not call copy_ticks_range() or copy_rates_range() to calibrate
the live tick clock. Some brokers label symbol_info_tick() epochs with the
trade-server wall clock (for example, UTC+3), not true UTC. Treating copied
history as an independent UTC reference can therefore cause calibration to
fail when the server clock has an offset.
get_tick_snapshot() preserves the numeric MT5 epoch value in time; it does
not expose pdmt5's timezone-naive Timestamp conversion or alter the instant,
and it never applies any offset correction. Any broker-specific offset
handling requires independent evidence — see TickClockNormalizer below —
and must be applied separately. Do not subtract a presumed UTC+2 or UTC+3
offset from a raw timestamp without that evidence.
No offset is applied automatically by history retrieval helpers.
UTC normalization for live ticks¶
TickClockNormalizer provides the stable API for obtaining a latest tick with
a validated UTC timestamp, so strategy applications never compare a raw
server-labeled tick time against datetime.now(UTC) themselves.
from mt5cli import TickClockNormalizer, mt5_session
with mt5_session() as client:
normalizer = TickClockNormalizer(client, ["SING30", "EURUSD"])
snapshot = normalizer.get_normalized_tick_snapshot("SING30")
if snapshot["clock_status"] == "calibrated":
freshness = now_utc - snapshot["time_utc"] # safe wall-clock compare
A normalized snapshot keeps the raw/UTC distinction explicit:
{
"symbol": "SING30",
"bid": ...,
"ask": ...,
"last": ...,
"volume": ...,
"raw_time": 1717243200, # numeric MT5 epoch, as labeled by broker
"time_utc": datetime(..., tzinfo=UTC), # None unless calibrated
"server_clock_offset_seconds": 10800.0, # None unless calibrated
"clock_status": "calibrated", # or "uncalibrated"
}
Calibration evidence¶
copy_ticks_range() is not used for calibration: its documented UTC contract
is broker/terminal-dependent and not independently verified here (see
above), so neither the query timestamps nor the returned historical tick
timestamps can serve as an out-of-band UTC reference, and historical copied
rows are never used to infer the server offset. Instead, the only
independent reference available is this process's own clock: every
calibration poll
fetches one live symbol_info_tick() value and stamps it with
datetime.now(UTC) at the moment it is received. Comparing that host receipt
time against the tick's own server-labeled epoch yields one candidate offset,
which must align to a 30-minute increment within the realistic UTC-14..UTC+14
range. time_msc is preferred over second-resolution time when available.
A single poll is never trusted on its own. A closed, stale, or illiquid symbol keeps returning the exact same last-traded tick, so its epoch never changes between polls — that ordinary tick age is not calibration evidence. Only a poll whose epoch differs from the previous poll (comparison is inequality, not "must increase": a genuine broker offset decrease, e.g. a UTC+3 to UTC+2 DST fallback, relabels the next fresh event with a numerically smaller epoch than the last one observed under the old, larger offset) proves the broker produced a new event, and only then is its offset computed.
An offset is accepted only after min_agreeing_samples (default 2)
distinct fresh tick events agree on the same rounded offset — repeated
polls of one unchanged tick never count as evidence, so an illiquid symbol
cannot self-confirm. Evidence can come from multiple samples of one actively
updating symbol (paced by sample_interval_seconds) or across several
symbols passed to the constructor; a closed symbol among several configured
symbols simply contributes no evidence rather than blocking the others. Any
two fresh events that disagree on the rounded offset abort the calibration
(offset_disagreement) instead of being averaged or resolved by recency.
Failure modes and fail-closed behavior¶
When calibration cannot be established safely — no symbol ever produced a
fresh (changed-epoch) tick, e.g. every configured symbol is closed or
illiquid (not_advancing), a fresh event's raw offset does not round cleanly
to a plausible bucket (unstable_offset), an unrealistic rounded delta
(implausible_offset), too few distinct agreeing events
(insufficient_agreement), disagreeing events (offset_disagreement), or
missing live data (no_live_tick) — snapshots fail closed: clock_status is
"uncalibrated", time_utc and server_clock_offset_seconds are None,
and the raw fields remain available. A raw timestamp is never silently
treated as UTC. The same fail-closed rule applies after a successful
calibration: once periodic revalidation invalidates the cached offset (see
below), subsequent snapshots are normalized only by a successful full
recalibration — never by the refuted cache. normalizer.calibration
exposes the full
TickClockCalibration diagnostics: status, offset, distinct sample count,
evidence symbols, last calibration time, and (for troubleshooting a failed
attempt) the most recently considered sample's symbol, raw server-labeled
time, host observation time, and raw (pre-rounding) offset —
to_dict() for serialization, and all of it is included in the one
concise warning logged per failed calibration attempt.
Caching and revalidation¶
Calibration is a property of the broker server clock, so it is cached on the normalizer (keep one instance per MT5 connection/account) and reused across symbols and calls. A cached offset is recomputed in three cases:
- After
max_calibration_age_seconds(default 6 hours, bounding DST-transition staleness), unconditionally. - Immediately when a normalized timestamp lands more than two minutes in the future — evidence that the broker offset grew, e.g. a UTC+2 to UTC+3 transition.
- Periodically, at most once per
revalidation_interval_seconds(default 5 minutes), through one full revalidation round over every configured symbol. This is what catches a broker offset decrease (e.g. UTC+3 to UTC+2): the resulting normalized time looks stale rather than future, which a future-skew check alone cannot distinguish from ordinary quiet-market staleness.
In a revalidation round each configured symbol is polled once and compared against that symbol's last known observation (from the initial calibration or a prior revalidation), and the whole round is evaluated before any decision is made — revalidation never stops at the first confirming symbol. A symbol is inconclusive — skipped, neither confirming nor refuting the cache — when its fetch is unusable, when it has no prior observation to compare against, or when its tick epoch is unchanged since that observation (ordinary tick age, e.g. a closed or illiquid symbol). Every other advancing sample is evidence the cache must be able to explain:
- an accepted offset equal to the cached one confirms the cache, but never cancels another symbol's refuting evidence from the same round;
- an accepted offset that differs from the cached one refutes the cache (a clean broker offset change) — unless the cached offset, widened by the elapsed time since that symbol's prior observation plus that prior observation's own inferred delay under the cached offset, still explains the disagreeing raw offset. That case is forgiven once per symbol and held as a pending disagreement instead of refuting immediately, since it cannot yet be told apart from a maximally delayed tick under the cached offset. A pending disagreement escalates to a refutation only if that same symbol's next conclusive round rounds to the identical bucket again; any inconclusive, differently-bucketed, or unusable round in between clears it instead of letting unrelated samples accumulate into false corroboration;
- an advancing sample with no usable offset (
unstable_offsetorimplausible_offset) also refutes the cache, subject to the same once-per-symbol forgiveness above — but an unusable sample can never itself be held as, or match, a pending disagreement, since it carries no specific offset to corroborate. A fresh market event whose raw offset is neither reconciled with any plausible 30-minute bucket nor forgiven this way is contradictory evidence the cached calibration cannot explain.
Any refuting evidence invalidates the cached calibration and forces full
recalibration; when several symbols refute the cache in one round, the
reported evidence is deterministic (implausible_offset first, then
unstable_offset, then a clean disagreement). The recalibration either
re-establishes a validated offset or fails closed — a raw tick is never
normalized with a cached offset that advancing evidence has just refuted. A
wholly inconclusive round keeps the cache, and a round in which no symbol
had a comparable baseline does not consume the interval, so the next call
retries immediately instead of waiting a full
revalidation_interval_seconds.
If recalibration still cannot validate the timestamp, the snapshot fails
closed. Failed calibrations are recorded for diagnostics but never reused;
retries are bounded to at most once per failed_calibration_retry_seconds
(default 30 seconds) rather than on every call, so a closed or illiquid
market does not trigger a full resample on every snapshot request.
A genuinely stale tick (weekend, illiquid symbol) under a valid calibration normalizes to its true past UTC instant — staleness is preserved, never corrected to the present.
mt5cli owns MT5 timestamp normalization only. Freshness thresholds, entry-blocking rules, and other strategy policy belong in downstream applications.
Migration from application-local helpers¶
| Application-local concern | mt5cli replacement |
|---|---|
| Manual terminal spawn/kill around trading code | with mt5_session(config) as client: |
| Local position-side detection | detect_position_side() |
| Local margin/volume sizing | calculate_margin_and_volume() |
| Local broker volume step normalization | normalize_order_volume() |
| Local order or position margin estimation | estimate_order_margin(), calculate_positions_margin() |
| Local closed-bar fetch from a session | fetch_latest_closed_rates() or fetch_latest_closed_rates_indexed() |
| Local recent deal history fetch from a session | client.recent_history_deals() |
| Local broker server clock offset measurement | TickClockNormalizer |
| Local SL/TP price derivation | determine_order_limits() |
| Throttled SQLite history loop with ad-hoc error handling | ThrottledHistoryUpdater(suppress_errors=True) |
Use mt5_session() / MT5Client for both data collection and generic
execution helpers.