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",
]

ClockStatus module-attribute

ClockStatus = Literal['calibrated', 'uncalibrated']

ExecutionStatus module-attribute

ExecutionStatus = Literal[
    "filled",
    "partial_fill",
    "placed",
    "dry_run",
    "skipped",
    "rejected",
    "malformed",
    "failed",
]

OrderFillingMode module-attribute

OrderFillingMode = Literal['IOC', 'FOK', 'RETURN']

OrderSide module-attribute

OrderSide = Literal['BUY', 'SELL']

OrderTimeMode module-attribute

OrderTimeMode = Literal[
    "GTC", "DAY", "SPECIFIED", "SPECIFIED_DAY"
]

POSITION_COLUMNS module-attribute

POSITION_COLUMNS = (
    "ticket",
    "time",
    "symbol",
    "type",
    "volume",
    "price_open",
    "sl",
    "tp",
    "price_current",
    "profit",
    "swap",
    "comment",
    "magic",
)

PositionSide module-attribute

PositionSide = Literal['long', 'short']

ProjectionMode module-attribute

ProjectionMode = Literal['add', 'replace_symbol']

__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.

available_margin instance-attribute

available_margin: float

buy_volume instance-attribute

buy_volume: float

margin_free instance-attribute

margin_free: float

sell_volume instance-attribute

sell_volume: float

trade_margin instance-attribute

trade_margin: float

volume_max instance-attribute

volume_max: float

volume_min instance-attribute

volume_min: float

volume_step instance-attribute

volume_step: float

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.

ask instance-attribute

ask: float | int | None

bid instance-attribute

bid: float | int | None

clock_status instance-attribute

clock_status: ClockStatus

last instance-attribute

last: float | int | None

raw_time instance-attribute

raw_time: float | int | None

server_clock_offset_seconds instance-attribute

server_clock_offset_seconds: float | None

symbol instance-attribute

symbol: str

time_utc instance-attribute

time_utc: datetime | None

volume instance-attribute

volume: float | int | None

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.

comment instance-attribute

comment: str | None

deal_ticket instance-attribute

deal_ticket: int | None

dry_run instance-attribute

dry_run: bool

filled_price instance-attribute

filled_price: float | None

filled_volume instance-attribute

filled_volume: float | None

magic instance-attribute

magic: int | None

order_side instance-attribute

order_side: OrderSide

order_ticket instance-attribute

order_ticket: int | None

position_id instance-attribute

position_id: int | None

request instance-attribute

request: dict[str, object]

request_price instance-attribute

request_price: float | None

requested_volume instance-attribute

requested_volume: float

response instance-attribute

response: dict[str, object] | None

retcode instance-attribute

retcode: int | None

status instance-attribute

symbol instance-attribute

symbol: str

to_dict

to_dict() -> dict[str, object]

Return a JSON-compatible representation of this receipt.

Source code in mt5cli/trading.py
def to_dict(self) -> dict[str, object]:
    """Return a JSON-compatible representation of this receipt."""
    return cast("dict[str, object]", asdict(self))

OrderLimits

Bases: TypedDict

Protective order prices derived from current quotes and ratio parameters.

entry instance-attribute

entry: float

stop_loss instance-attribute

stop_loss: float | None

take_profit instance-attribute

take_profit: float | None

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).

calibrated property

calibrated: bool

Whether this calibration produced a usable offset.

calibrated_at instance-attribute

calibrated_at: float | None

evidence_symbols instance-attribute

evidence_symbols: tuple[str, ...]

last_sample_host_time class-attribute instance-attribute

last_sample_host_time: float | None = None

last_sample_raw_offset_seconds class-attribute instance-attribute

last_sample_raw_offset_seconds: float | None = None

last_sample_raw_time class-attribute instance-attribute

last_sample_raw_time: float | None = None

last_sample_symbol class-attribute instance-attribute

last_sample_symbol: str | None = None

offset_seconds instance-attribute

offset_seconds: float | None

sample_count instance-attribute

sample_count: int

status instance-attribute

to_dict

to_dict() -> dict[str, object]

Return a JSON-compatible representation of this calibration.

Source code in mt5cli/trading.py
def to_dict(self) -> dict[str, object]:
    """Return a JSON-compatible representation of this calibration."""
    return cast("dict[str, object]", asdict(self))

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 symbol_info_tick.

required
symbols Sequence[str] | None

Optional default calibration symbols. Prefer several actively updating symbols; when omitted, calibration uses the symbol passed to :meth:get_normalized_tick_snapshot.

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 (unstable_offset / implausible_offset) and not otherwise explained by the cached offset given the real elapsed time since that symbol's prior observation and that observation's own inferred delay, invalidates the cache and forces full recalibration, even when another symbol in the same round still confirms the cache (contradictory evidence for a connection-scoped offset must fail closed, not be averaged away). This catches an offset decrease (for example a UTC+3 to UTC+2 transition) well before max_calibration_age_seconds would, while a confirming or inconclusive symbol cannot cancel another symbol's refuting evidence. A disagreement one bucket away that is only explained by the elapsed time since the last observation and that observation's own inferred delay is forgiven once per symbol; if it recurs on that symbol's very next round instead of resolving back to the cached offset, it invalidates the cache on that second round instead.

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
def __init__(
    self,
    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,
) -> None:
    """Initialize a normalizer bound to one connected MT5 client.

    Args:
        client: Connected MT5 client exposing ``symbol_info_tick``.
        symbols: Optional default calibration symbols. Prefer several
            actively updating symbols; when omitted, calibration uses the
            symbol passed to :meth:`get_normalized_tick_snapshot`.
        samples_per_symbol: 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.
        min_agreeing_samples: 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.
        sample_interval_seconds: Pause between consecutive polls of one
            symbol so an actively updating symbol can produce distinct
            tick events.
        max_calibration_age_seconds: Age after which a cached calibration
            is recomputed unconditionally (bounds DST-transition
            staleness).
        revalidation_interval_seconds: 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 (``unstable_offset`` / ``implausible_offset``) and
            not otherwise explained by the cached offset given the real
            elapsed time since that symbol's prior observation and that
            observation's own inferred delay, invalidates the cache and
            forces full recalibration, even when another symbol in the
            same round still confirms the cache (contradictory evidence
            for a connection-scoped offset must fail closed, not be
            averaged away). This catches an offset decrease (for example
            a UTC+3 to UTC+2 transition) well before
            ``max_calibration_age_seconds`` would, while a confirming or
            inconclusive symbol cannot cancel another symbol's refuting
            evidence. A disagreement one bucket away that is only
            explained by the elapsed time since the last observation and
            that observation's own inferred delay is forgiven once per
            symbol; if it recurs on that symbol's very next round instead
            of resolving back to the cached offset, it invalidates the
            cache on that second round instead.
        failed_calibration_retry_seconds: Minimum time between full
            recalibration attempts after a failed calibration, so a
            closed or illiquid market does not retry on every call.

    Raises:
        ValueError: If a numeric tuning parameter is not positive.
    """
    if samples_per_symbol < _MIN_SAMPLES_PER_SYMBOL:
        msg = f"samples_per_symbol must be >= {_MIN_SAMPLES_PER_SYMBOL}."
        raise ValueError(msg)
    if min_agreeing_samples < _MIN_AGREEING_SAMPLES:
        msg = f"min_agreeing_samples must be >= {_MIN_AGREEING_SAMPLES}."
        raise ValueError(msg)
    if sample_interval_seconds < 0:
        msg = "sample_interval_seconds must not be negative."
        raise ValueError(msg)
    if (
        max_calibration_age_seconds <= 0
        or revalidation_interval_seconds <= 0
        or failed_calibration_retry_seconds <= 0
    ):
        msg = (
            "max_calibration_age_seconds, revalidation_interval_seconds,"
            " and failed_calibration_retry_seconds must be positive."
        )
        raise ValueError(msg)
    self._client = client
    self._symbols = tuple(symbols) if symbols else ()
    self._samples_per_symbol = samples_per_symbol
    self._min_agreeing_samples = min_agreeing_samples
    self._sample_interval_seconds = sample_interval_seconds
    self._max_calibration_age_seconds = max_calibration_age_seconds
    self._revalidation_interval_seconds = revalidation_interval_seconds
    self._failed_calibration_retry_seconds = failed_calibration_retry_seconds
    self._calibration: TickClockCalibration | None = None
    self._last_attempt_at: float | None = None
    self._last_observations: dict[str, _LiveObservation] = {}
    self._pending_disagreement: dict[str, _OffsetSample] = {}

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
def calibrate(
    self,
    symbols: Sequence[str] | None = None,
) -> TickClockCalibration:
    """Measure the server clock offset from advancing live tick evidence.

    Args:
        symbols: Symbols to sample; defaults to the constructor symbols.

    Returns:
        The calibration result, also cached on this normalizer. Failed
        calibrations are recorded for diagnostics but never reused.

    Raises:
        ValueError: If no calibration symbol is available.
    """
    resolved = tuple(symbols) if symbols is not None else self._symbols
    if not resolved:
        msg = "At least one symbol is required for tick clock calibration."
        raise ValueError(msg)
    # A full calibration must never compare against an observation left
    # over from an earlier attempt (for example one made hours ago,
    # before `invalidate()` or a `max_calibration_age_seconds` expiry):
    # such a stale baseline would let this attempt's very first poll be
    # scored as a fresh event merely because it differs from that old
    # observation, even though it may itself be an equally stale closing
    # tick. Dropping any prior baseline forces every symbol's first poll
    # in this attempt to establish a fresh one instead. Any pending,
    # not-yet-repeated disagreement recorded against the old cached
    # offset is equally stale once that offset is replaced.
    for resolved_symbol in resolved:
        self._last_observations.pop(resolved_symbol, None)
        self._pending_disagreement.pop(resolved_symbol, None)
    matched, failures, last_sample = self._collect_offset_samples(resolved)
    calibration = self._build_calibration(matched, failures, last_sample)
    self._calibration = calibration
    self._last_attempt_at = datetime.now(UTC).timestamp()
    if calibration.calibrated:
        _logger.info(
            "Calibrated MT5 server clock offset: %.0f seconds"
            " (%d samples from %s).",
            calibration.offset_seconds,
            calibration.sample_count,
            ", ".join(calibration.evidence_symbols),
        )
    else:
        _logger.warning(
            "MT5 server clock calibration failed for %s: %s"
            " (accepted_samples=%d evidence=%s last_symbol=%s"
            " last_raw_time=%s last_host_time=%s last_raw_offset=%s).",
            ", ".join(resolved),
            calibration.status,
            calibration.sample_count,
            ", ".join(calibration.evidence_symbols) or "none",
            calibration.last_sample_symbol,
            calibration.last_sample_raw_time,
            calibration.last_sample_host_time,
            calibration.last_sample_raw_offset_seconds,
        )
    return calibration

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; on any calibration failure the

NormalizedTickSnapshot

snapshot carries clock_status="uncalibrated", a None

NormalizedTickSnapshot

time_utc, and a None offset while preserving raw fields.

Source code in mt5cli/trading.py
def get_normalized_tick_snapshot(self, 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.

    Args:
        symbol: Symbol whose latest tick is normalized.

    Returns:
        A :class:`NormalizedTickSnapshot`; on any calibration failure the
        snapshot carries ``clock_status="uncalibrated"``, a ``None``
        ``time_utc``, and a ``None`` offset while preserving raw fields.
    """
    now_epoch = datetime.now(UTC).timestamp()
    calibration = self._current_calibration(symbol, now_epoch=now_epoch)
    snapshot = get_tick_snapshot(self._client, symbol)
    raw_time = snapshot.get("time")
    normalized_epoch = _normalized_epoch(raw_time, calibration)
    if (
        normalized_epoch is not None
        and normalized_epoch - now_epoch > _MAX_FUTURE_SKEW_SECONDS
    ):
        _logger.warning(
            "Normalized tick time for %s is %.0f seconds in the future;"
            " recalibrating the MT5 server clock offset.",
            symbol,
            normalized_epoch - now_epoch,
        )
        calibration = self.calibrate(self._symbols or (symbol,))
        snapshot = get_tick_snapshot(self._client, symbol)
        raw_time = snapshot.get("time")
        now_epoch = datetime.now(UTC).timestamp()
        normalized_epoch = _normalized_epoch(raw_time, calibration)
        if (
            normalized_epoch is not None
            and normalized_epoch - now_epoch > _MAX_FUTURE_SKEW_SECONDS
        ):
            normalized_epoch = None
    if normalized_epoch is None:
        time_utc = None
        offset_seconds = None
    else:
        time_utc = datetime.fromtimestamp(normalized_epoch, tz=UTC)
        offset_seconds = calibration.offset_seconds
    return NormalizedTickSnapshot(
        symbol=str(snapshot.get("symbol") or symbol),
        bid=snapshot.get("bid"),
        ask=snapshot.get("ask"),
        last=snapshot.get("last"),
        volume=snapshot.get("volume"),
        raw_time=raw_time,
        time_utc=time_utc,
        server_clock_offset_seconds=offset_seconds,
        clock_status="calibrated" if time_utc is not None else "uncalibrated",
    )

invalidate

invalidate() -> None

Drop the cached calibration so the next call recalibrates.

Source code in mt5cli/trading.py
def invalidate(self) -> None:
    """Drop the cached calibration so the next call recalibrates."""
    self._calibration = None

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
def 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.

    """
    account = get_account_snapshot(client)
    equity = _required_account_number(account, "equity", allow_zero=False)
    margin = _required_account_number(account, "margin", allow_zero=True)
    if symbol is not None and new_position_side is not None and new_position_volume > 0:
        margin += estimate_order_margin(
            client,
            symbol,
            new_position_side,
            new_position_volume,
        )
    return margin / equity

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 margin_free, available_margin, trade_margin,

MarginVolume

buy_volume, and sell_volume. Negative margin_free values are

MarginVolume

clamped to 0.0 before sizing.

Source code in mt5cli/trading.py
def 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.

    Args:
        client: Connected MT5 client instance.
        symbol: Symbol used for minimum-lot margin and volume calculations.
        unit_margin_ratio: Fraction of free margin to allocate per unit.

    Returns:
        Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``,
        ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are
        clamped to ``0.0`` before sizing.
    """
    _require_unit_ratio(unit_margin_ratio, "unit_margin_ratio")

    account = client.account_info_as_dict()
    margin_free = max(0.0, float(account.get("margin_free") or 0.0))
    available_margin = margin_free
    trade_margin = available_margin * unit_margin_ratio
    if unit_margin_ratio == 0:
        buy_volume = _calculate_min_volume_if_affordable(
            client,
            symbol,
            available_margin,
            "BUY",
        )
        sell_volume = _calculate_min_volume_if_affordable(
            client,
            symbol,
            available_margin,
            "SELL",
        )
    else:
        buy_volume = calculate_volume_by_margin(client, symbol, trade_margin, "BUY")
        sell_volume = calculate_volume_by_margin(client, symbol, trade_margin, "SELL")
    try:
        symbol_info = get_symbol_snapshot(client, symbol)
        volume_min = float(symbol_info.get("volume_min") or 0.0)
        volume_max = float(symbol_info.get("volume_max") or 0.0)
        volume_step = float(symbol_info.get("volume_step") or 0.0)
    except AttributeError:
        volume_min = volume_max = volume_step = 0.0
    return {
        "margin_free": margin_free,
        "available_margin": available_margin,
        "trade_margin": trade_margin,
        "buy_volume": float(buy_volume),
        "sell_volume": float(sell_volume),
        "volume_min": volume_min,
        "volume_max": volume_max,
        "volume_step": volume_step,
    }

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 0.0 when no matching positions exist.

Source code in mt5cli/trading.py
def calculate_positions_margin(
    client: _Mt5ClientProtocol,
    *,
    symbols: Sequence[str] | None = None,
) -> float:
    """Return the sum of estimated current margin for open positions.

    Args:
        client: Connected MT5 client instance.
        symbols: Optional symbol filter. When omitted, all open positions are
            included.

    Returns:
        Total estimated margin, or ``0.0`` when no matching positions exist.
    """
    frame = get_positions_frame(client)
    if frame.empty or "symbol" not in frame.columns:
        return 0.0
    if symbols is not None:
        frame = frame[frame["symbol"].isin(list(symbols))]
    if frame.empty:
        return 0.0
    grouped_volumes: dict[tuple[str, OrderSide], float] = {}
    for _, row in frame.iterrows():
        symbol = row.get("symbol")
        if not isinstance(symbol, str) or not symbol:
            continue
        volume = row.get("volume")
        if not _is_positive_finite_number(volume):
            continue
        order_side = _order_side_from_position_type(client, row.get("type"))
        if order_side is None:
            continue
        key = (symbol, order_side)
        finite_volume = float(cast("float | int", volume))
        grouped_volumes[key] = grouped_volumes.get(key, 0.0) + finite_volume
    total = 0.0
    for (symbol, order_side), volume in grouped_volumes.items():
        total += estimate_order_margin(client, symbol, order_side, volume)
    return total

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, log and skip symbols that raise Mt5OperationError, Mt5RuntimeError, or AttributeError. When False, re-raise the first failure.

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 symbols is empty or all symbols fail

dict[str, float]

with suppress_errors=True.

Raises:

Type Description
Mt5OperationError

When a symbol raises Mt5OperationError and suppress_errors=False.

Mt5RuntimeError

When a symbol raises Mt5RuntimeError and suppress_errors=False.

AttributeError

When a symbol raises AttributeError and suppress_errors=False.

Source code in mt5cli/trading.py
def 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.

    Args:
        client: Connected MT5 client instance.
        symbols: Symbols to compute margin for.
        suppress_errors: When ``True``, log and skip symbols that raise
            ``Mt5OperationError``, ``Mt5RuntimeError``, or ``AttributeError``.
            When ``False``, re-raise the first failure.

    Returns:
        Mapping of symbol to margin total in first-seen unique-symbol order.
        Returns an empty dict when ``symbols`` is empty or all symbols fail
        with ``suppress_errors=True``.

    Raises:
        Mt5OperationError: When a symbol raises ``Mt5OperationError`` and
            ``suppress_errors=False``.
        Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and
            ``suppress_errors=False``.
        AttributeError: When a symbol raises ``AttributeError`` and
            ``suppress_errors=False``.
    """
    result: dict[str, float] = {}
    for symbol in dict.fromkeys(symbols):
        try:
            result[symbol] = calculate_positions_margin(client, symbols=[symbol])
        except (Mt5OperationError, Mt5RuntimeError, AttributeError) as exc:
            if not suppress_errors:
                raise
            _logger.warning("Skipping margin for %r: %s", symbol, exc)
    return result

calculate_positions_margin_safe

calculate_positions_margin_safe(
    client: _Mt5ClientProtocol, *, symbols: Sequence[str]
) -> float

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; 0.0 when no symbols or all fail.

Source code in mt5cli/trading.py
def calculate_positions_margin_safe(
    client: _Mt5ClientProtocol,
    *,
    symbols: Sequence[str],
) -> float:
    """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.

    Args:
        client: Connected MT5 client instance.
        symbols: Symbols to include.

    Returns:
        Sum of per-symbol margins; ``0.0`` when no symbols or all fail.
    """
    return sum(
        calculate_positions_margin_by_symbol(client, symbols=symbols).values(),
        0.0,
    )

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
def 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.
    """
    equity = _account_equity(client)
    margin = calculate_positions_margin(client, symbols=[symbol])
    if new_position_side is not None and new_position_volume > 0:
        margin += estimate_order_margin(
            client,
            symbol,
            new_position_side,
            new_position_volume,
        )
    return margin / equity

calculate_spread_ratio

calculate_spread_ratio(
    client: _Mt5ClientProtocol, symbol: str
) -> float

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
def calculate_spread_ratio(client: _Mt5ClientProtocol, symbol: str) -> float:
    """Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick.

    Raises:
        Mt5OperationError: If bid or ask is unavailable.
    """
    tick = get_tick_snapshot(client, symbol)
    bid = extract_tick_price(tick, "bid")
    ask = extract_tick_price(tick, "ask")
    if bid is None or ask is None:
        msg = f"Tick bid/ask is unavailable for {symbol!r}."
        raise Mt5OperationError(msg)
    return (ask - bid) / ((ask + bid) / 2.0)

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 for new_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 suppress_errors is False.

Mt5RuntimeError

When symbol margin lookup or projected margin lookup fails and suppress_errors is False.

Mt5OperationError

When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and suppress_errors is False.

Source code in mt5cli/trading.py
def 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 for ``new_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:
        AttributeError: When symbol margin lookup or projected margin lookup
            fails and ``suppress_errors`` is ``False``.
        Mt5RuntimeError: When symbol margin lookup or projected margin lookup
            fails and ``suppress_errors`` is ``False``.
        Mt5OperationError: When account equity is invalid, or when symbol margin
            lookup or projected margin lookup fails and ``suppress_errors`` is
            ``False``.
    """
    projection_mode = _validate_projection_mode(projection_mode)
    equity = _account_equity(client)
    unique_symbols = list(dict.fromkeys(symbols))
    per_symbol = calculate_positions_margin_by_symbol(
        client,
        symbols=unique_symbols,
        suppress_errors=suppress_errors,
    )
    margin = sum(per_symbol.values(), 0.0)
    if (
        new_symbol in unique_symbols
        and new_position_side is not None
        and new_position_volume > 0
    ):
        try:
            candidate_margin = estimate_order_margin(
                client,
                new_symbol,
                new_position_side,
                new_position_volume,
            )
        except (Mt5OperationError, Mt5RuntimeError, AttributeError):
            if not suppress_errors:
                raise
            _logger.warning("Skipping projected margin for %r.", new_symbol)
        else:
            if projection_mode == "replace_symbol":
                margin = max(0.0, margin - per_symbol.get(new_symbol, 0.0))
            margin += candidate_margin
    return margin / equity

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
def 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.
    """
    _require_protective_ratio(trailing_stop_ratio, "trailing_stop_ratio")
    positions = _filter_positions(
        get_positions_frame(client, symbol=symbol), magic=magic
    )
    if positions.empty:
        return {}
    tick = get_tick_snapshot(client, symbol)
    bid = extract_tick_price(tick, "bid")
    ask = extract_tick_price(tick, "ask")
    digits = _symbol_digits(client, symbol)
    if digits is None:
        return {}

    updates: dict[int, float] = {}
    for row in positions.to_dict("records"):
        ticket = _position_ticket(row.get("ticket"))
        if ticket is None:
            continue
        next_sl = _trailing_stop_loss(
            client,
            position_type=row.get("type"),
            current_sl=_current_stop_loss(row.get("sl")),
            bid=bid,
            ask=ask,
            digits=digits,
            trailing_stop_ratio=trailing_stop_ratio,
        )
        if next_sl is None:
            continue
        updates[ticket] = next_sl
    return updates

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 order_calc_margin)

float

fits within available_margin, rounded down to symbol volume

float

constraints; 0.0 when no affordable step exists.

Raises:

Type Description
Mt5OperationError

If symbol volume constraints or tick data are invalid.

Source code in mt5cli/trading.py
def calculate_volume_by_margin(
    client: _Mt5ClientProtocol,
    symbol: str,
    available_margin: float,
    order_side: OrderSide,
) -> float:
    """Calculate max normalized volume affordable for one side.

    Returns:
        Largest stepped volume whose actual margin (from ``order_calc_margin``)
        fits within ``available_margin``, rounded down to symbol volume
        constraints; ``0.0`` when no affordable step exists.

    Raises:
        Mt5OperationError: If symbol volume constraints or tick data are invalid.
    """
    if available_margin <= 0:
        return 0.0
    symbol_info = get_symbol_snapshot(client, symbol)
    volume_min = float(symbol_info.get("volume_min") or 0.0)
    volume_max = float(symbol_info.get("volume_max") or 0.0)
    volume_step = float(symbol_info.get("volume_step") or volume_min or 0.0)
    if volume_min <= 0 or volume_step <= 0:
        msg = f"Invalid volume constraints for {symbol!r}."
        raise Mt5OperationError(msg)
    side = _normalize_order_side(order_side)
    price = extract_tick_price(
        get_tick_snapshot(client, symbol), "ask" if side == "BUY" else "bid"
    )
    if price is None:
        msg = f"Tick price is unavailable for {symbol!r}."
        raise Mt5OperationError(msg)
    order_type = (
        client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    )
    min_margin = float(client.order_calc_margin(order_type, symbol, volume_min, price))
    if min_margin <= 0 or min_margin > available_margin:
        return 0.0
    lo = 0
    hi = int(
        max(
            0,
            floor(
                (
                    (
                        min(available_margin / min_margin * volume_min, volume_max)
                        if volume_max > 0
                        else available_margin / min_margin * volume_min
                    )
                    - volume_min
                )
                / volume_step
                + 1e-12
            ),
        )
    )
    best = -1

    while lo <= hi:
        mid = (lo + hi) // 2
        normalized = round(volume_min + mid * volume_step, 10)
        actual = float(client.order_calc_margin(order_type, symbol, normalized, price))

        if actual > 0 and actual <= available_margin:
            best = mid
            lo = mid + 1
        else:
            hi = mid - 1

    return round(volume_min + best * volume_step, 10) if best >= 0 else 0.0

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
def 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:
        Normalized execution results for matching positions.
    """
    positions = _filter_positions(
        get_positions_frame(client),
        symbols=symbols,
        tickets=tickets,
        magic=magic,
    )
    results: list[OrderExecutionResult] = []
    resolved_filling_modes: dict[str, OrderFillingMode] = {}
    for row in positions.to_dict("records"):
        pos_type = row["type"]
        symbol = str(row["symbol"])
        side: OrderSide = "BUY"
        mt5: Any = object()
        try:
            mt5 = client.mt5
            side = "SELL" if pos_type == mt5.POSITION_TYPE_BUY else "BUY"
            filling_mode = _cached_close_filling_mode(
                client,
                symbol,
                order_filling_mode,
                resolved_filling_modes,
            )
        except Exception as exc:  # ruff: ignore[blind-except] - receipt is the execution contract
            results.append(
                _execution_receipt(
                    mt5=mt5,
                    symbol=symbol,
                    order_side=side,
                    request={
                        "symbol": symbol,
                        "volume": float(row["volume"]),
                        "position": int(row["ticket"]),
                        **({"magic": magic} if magic is not None else {}),
                    },
                    dry_run=dry_run,
                    error=exc,
                )
            )
            continue
        result = place_market_order(
            client,
            symbol=symbol,
            volume=float(row["volume"]),
            order_side=side,
            order_filling_mode=filling_mode,
            position=int(row["ticket"]),
            deviation=deviation,
            comment=comment,
            magic=magic,
            dry_run=dry_run,
        )
        results.append(result)
    return results

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

"long" when there are buy positions and no sell positions,

PositionSide | None

"short" when there are sell positions and no buy positions, or

PositionSide | None

None when no positions or mixed exposure exists.

Source code in mt5cli/trading.py
def detect_position_side(
    client: _Mt5ClientProtocol,
    symbol: str,
    *,
    magic: int | None = None,
) -> PositionSide | None:
    """Detect the net open position side for a symbol.

    Args:
        client: Connected MT5 client instance.
        symbol: Symbol to inspect.
        magic: Optional magic number filter applied fail-closed.

    Returns:
        ``"long"`` when there are buy positions and no sell positions,
        ``"short"`` when there are sell positions and no buy positions, or
        ``None`` when no positions or mixed exposure exists.
    """
    positions = _filter_positions(
        get_positions_frame(client, symbol=symbol), magic=magic
    )
    if positions.empty:
        return None

    buy_type = client.mt5.POSITION_TYPE_BUY
    sell_type = client.mt5.POSITION_TYPE_SELL
    buy_volume = _sum_position_volume(positions, buy_type)
    sell_volume = _sum_position_volume(positions, sell_type)
    if buy_volume > 0 and sell_volume == 0:
        return "long"
    if sell_volume > 0 and buy_volume == 0:
        return "short"
    return None

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 "long"/"short" ("buy"/"sell" aliases are accepted).

required
stop_loss_limit_ratio float | None

Relative distance from entry for stop loss in [0, 1). A value of 0 omits the stop loss.

None
take_profit_limit_ratio float | None

Relative distance from entry for take profit in [0, 1). A value of 0 omits the take profit.

None

Returns:

Type Description
OrderLimits

Dictionary with entry, stop_loss, and take_profit keys.

OrderLimits

Omitted protective levels are returned as None.

Raises:

Type Description
Mt5OperationError

If required tick data is invalid or computed SL/TP prices violate available trade_stops_level pre-validation.

Source code in mt5cli/trading.py
def 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.

    Args:
        client: Connected MT5 client instance.
        symbol: Symbol used for the quote lookup.
        side: Position side as ``"long"``/``"short"`` (``"buy"``/``"sell"``
            aliases are accepted).
        stop_loss_limit_ratio: Relative distance from entry for stop loss in
            ``[0, 1)``. A value of ``0`` omits the stop loss.
        take_profit_limit_ratio: Relative distance from entry for take profit in
            ``[0, 1)``. A value of ``0`` omits the take profit.

    Returns:
        Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys.
        Omitted protective levels are returned as ``None``.

    Raises:
        Mt5OperationError: If required tick data is invalid or computed SL/TP
            prices violate available ``trade_stops_level`` pre-validation.
    """
    stop_loss_ratio = stop_loss_limit_ratio or 0.0
    take_profit_ratio = take_profit_limit_ratio or 0.0
    _require_protective_ratio(stop_loss_ratio, "stop_loss_limit_ratio")
    _require_protective_ratio(take_profit_ratio, "take_profit_limit_ratio")
    normalized_side = _position_side_from_order_side(side)
    tick = get_tick_snapshot(client, symbol)
    entry_key = "ask" if normalized_side == "long" else "bid"
    entry = extract_tick_price(tick, entry_key)
    if entry is None:
        msg = f"Tick price is unavailable for {symbol!r}."
        raise Mt5OperationError(msg)
    try:
        symbol_info = get_symbol_snapshot(client, symbol)
    except (AttributeError, KeyError, TypeError, ValueError):
        symbol_info = {}
    try:
        raw_digits = symbol_info.get("digits")
        # ``0`` is a valid precision (integer-priced symbols), not "unknown".
        digits = 8 if raw_digits is None else int(raw_digits)
    except (TypeError, ValueError):
        digits = 8
    if digits < 0:
        digits = 8
    min_distance = _minimum_stop_distance(symbol_info)

    stop_loss: float | None = None
    if stop_loss_ratio > 0:
        if normalized_side == "long":
            stop_loss = entry * (1.0 - stop_loss_ratio)
        else:
            stop_loss = entry * (1.0 + stop_loss_ratio)
        stop_loss = round(stop_loss, digits)

    take_profit: float | None = None
    if take_profit_ratio > 0:
        if normalized_side == "long":
            take_profit = entry * (1.0 + take_profit_ratio)
        else:
            take_profit = entry * (1.0 - take_profit_ratio)
        take_profit = round(take_profit, digits)

    _validate_protective_prices(
        symbol=symbol,
        side=normalized_side,
        entry=entry,
        stop_loss=stop_loss,
        take_profit=take_profit,
        min_distance=min_distance,
    )

    return {
        "entry": entry,
        "stop_loss": stop_loss,
        "take_profit": take_profit,
    }

ensure_symbol_selected

ensure_symbol_selected(
    client: _Mt5ClientProtocol, symbol: str
) -> None

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 symbol_select is unavailable on the client.

Source code in mt5cli/trading.py
def ensure_symbol_selected(client: _Mt5ClientProtocol, symbol: str) -> None:
    """Ensure a symbol is visible in Market Watch before sending orders.

    Args:
        client: Connected MT5 client instance.
        symbol: Symbol to select.

    Raises:
        Mt5OperationError: If the symbol cannot be selected in Market Watch or
            ``symbol_select`` is unavailable on the client.
    """
    snapshot = get_symbol_snapshot(client, symbol)
    if snapshot.get("visible"):
        return
    select = getattr(client, "symbol_select", None)
    if not callable(select):
        msg = "MT5 client is missing required method: symbol_select"
        raise Mt5OperationError(msg)
    if select(symbol, enable=True):
        return
    last_error = getattr(client, "last_error", None)
    detail = f" ({last_error()})" if callable(last_error) else ""
    msg = f"Failed to select symbol {symbol!r} in Market Watch{detail}."
    raise Mt5OperationError(msg)

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
def 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:
        Positive finite margin required for the order at the current quote.

    Raises:
        Mt5OperationError: If volume, tick data, or margin estimation is invalid.
    """
    if not _is_positive_finite_number(volume):
        msg = "Volume must be a positive finite number to estimate order margin."
        raise Mt5OperationError(msg)
    side = _normalize_order_side(order_side)
    tick = get_tick_snapshot(client, symbol)
    price = extract_tick_price(tick, "ask" if side == "BUY" else "bid")
    if price is None:
        msg = f"Tick price is unavailable for {symbol!r}."
        raise Mt5OperationError(msg)
    order_type = (
        client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    )
    raw_margin = client.order_calc_margin(order_type, symbol, volume, price)
    try:
        margin = float(raw_margin)
    except (TypeError, ValueError) as exc:
        msg = f"Margin estimate is invalid for {symbol!r}."
        raise Mt5OperationError(msg) from exc
    if margin <= 0 or not isfinite(margin):
        msg = f"Margin estimate is invalid for {symbol!r}."
        raise Mt5OperationError(msg)
    return margin

extract_tick_price

extract_tick_price(
    tick: Mapping[str, object], key: str
) -> float | None

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
def extract_tick_price(tick: Mapping[str, object], key: str) -> float | None:
    """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.
    """
    value = tick.get(key)
    if value is None or isinstance(value, bool):
        return None
    if isinstance(value, int | float):
        price = float(value)
    elif isinstance(value, str):
        try:
            price = float(value)
        except ValueError:
            return None
    else:
        return None
    if not isfinite(price) or price <= 0:
        return None
    return price

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 "M1", "H1").

required
count int

Maximum number of closed bars to return.

required

Returns:

Type Description
DataFrame

Up to count closed bars ordered oldest to newest, with a

DataFrame

UTC-aware DatetimeIndex named "time". The original time

DataFrame

column is dropped.

Raises:

Type Description
ValueError

If count is not positive, rate data is empty or malformed, the time column is missing, or timestamp data is invalid or unparseable.

Mt5OperationError

If the client cannot fetch rate data.

TypeError

If the client returns a non-DataFrame payload.

Source code in mt5cli/trading.py
def fetch_latest_closed_rates_indexed(
    client: _Mt5ClientProtocol,
    *,
    symbol: str,
    granularity: str,
    count: int,
) -> pd.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.

    Args:
        client: Connected public client with rate-fetch capability.
        symbol: Symbol name.
        granularity: Timeframe string (for example ``"M1"``, ``"H1"``).
        count: Maximum number of closed bars to return.

    Returns:
        Up to ``count`` closed bars ordered oldest to newest, with a
        UTC-aware ``DatetimeIndex`` named ``"time"``. The original ``time``
        column is dropped.

    Raises:
        ValueError: If ``count`` is not positive, rate data is empty or
            malformed, the ``time`` column is missing, or timestamp data
            is invalid or unparseable.
        Mt5OperationError: If the client cannot fetch rate data.
        TypeError: If the client returns a non-DataFrame payload.
    """
    if count <= 0:
        msg = "count must be positive."
        raise ValueError(msg)
    copy_rates = getattr(client, "copy_rates_from_pos", None)
    if not callable(copy_rates):
        msg = "MT5 client cannot fetch rate data."
        raise Mt5OperationError(msg)
    frame = copy_rates(symbol, granularity, 0, count + 1)
    if not isinstance(frame, pd.DataFrame):
        msg = "MT5 client returned malformed rate data."
        raise TypeError(msg)
    frame = drop_forming_rate_bar(_ensure_rate_time_column(frame))
    if frame.empty:
        msg = f"Rate data is empty for {symbol!r} at granularity {granularity!r}."
        raise ValueError(msg)
    frame = frame.tail(count).reset_index(drop=True)
    if "time" not in frame.columns:
        msg = f"Rate data is missing a time column for {symbol!r}."
        raise ValueError(msg)
    idx = _rate_time_to_utc(frame["time"], symbol)
    idx.name = "time"
    result = frame.drop(columns=["time"])
    result.index = idx
    return result

get_account_snapshot

get_account_snapshot(
    client: _Mt5ClientProtocol,
) -> dict[str, float | int | str | None]

Return normalized account state with stable keys.

Source code in mt5cli/trading.py
def get_account_snapshot(
    client: _Mt5ClientProtocol,
) -> dict[str, float | int | str | None]:
    """Return normalized account state with stable keys."""
    value = _call_snapshot_method(client, "account_info_as_dict", "account_info")
    return cast(
        "dict[str, float | int | str | None]",
        _snapshot_from_value(value, _ACCOUNT_SNAPSHOT_FIELDS),
    )

get_positions_frame

get_positions_frame(
    client: _Mt5ClientProtocol, symbol: str | None = None
) -> DataFrame

Return open positions as a DataFrame with stable baseline columns.

Source code in mt5cli/trading.py
def get_positions_frame(
    client: _Mt5ClientProtocol,
    symbol: str | None = None,
) -> pd.DataFrame:
    """Return open positions as a DataFrame with stable baseline columns."""
    frame = client.positions_get_as_df(symbol=symbol)
    for column in POSITION_COLUMNS:
        if column not in frame.columns:
            frame[column] = pd.Series(dtype="object")
    return frame

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
def get_symbol_snapshot(
    client: _Mt5ClientProtocol,
    symbol: str,
) -> dict[str, float | int | str | bool | None]:
    """Return normalized symbol metadata required for trading decisions."""
    method = getattr(client, "symbol_info_as_dict", None)
    value = method(symbol=symbol) if callable(method) else client.symbol_info(symbol)
    snapshot = _snapshot_from_value(value, _SYMBOL_SNAPSHOT_FIELDS)
    snapshot["symbol"] = snapshot.get("symbol") or symbol
    return cast("dict[str, float | int | str | bool | None]", snapshot)

get_tick_snapshot

get_tick_snapshot(
    client: _Mt5ClientProtocol, symbol: str
) -> dict[str, float | int | None]

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
def get_tick_snapshot(
    client: _Mt5ClientProtocol,
    symbol: str,
) -> dict[str, float | int | None]:
    """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.
    """
    snapshot = _snapshot_from_value(
        _raw_tick_value(client, symbol),
        _TICK_SNAPSHOT_FIELDS,
    )
    snapshot["symbol"] = snapshot.get("symbol") or symbol
    snapshot["time"] = _numeric_tick_time(snapshot.get("time"))
    return cast("dict[str, float | int | None]", snapshot)

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 volume_min,

float

capped at volume_max when finite and positive, and rounded

float

deterministically. The result never exceeds the capped request except

float

by floating-point noise (a relative tolerance of 1e-12), which

float

keeps on-step requests on their step. Returns 0.0 when inputs or

float

constraints are invalid, non-finite, or the capped request is below

float

volume_min.

Source code in mt5cli/trading.py
def 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:
        Volume floored to the nearest valid broker step from ``volume_min``,
        capped at ``volume_max`` when finite and positive, and rounded
        deterministically. The result never exceeds the capped request except
        by floating-point noise (a relative tolerance of ``1e-12``), which
        keeps on-step requests on their step. Returns ``0.0`` when inputs or
        constraints are invalid, non-finite, or the capped request is below
        ``volume_min``.
    """
    if not _is_finite_number(volume):
        return 0.0
    if not _is_positive_finite_number(volume_min):
        return 0.0
    if not _is_positive_finite_number(volume_step):
        return 0.0
    has_volume_cap = _is_positive_finite_number(volume_max)
    capped = min(volume, volume_max) if has_volume_cap else volume
    if capped < volume_min:
        return 0.0
    steps = max(0, floor((capped - volume_min) / volume_step))
    # Float division can land just below an on-step request and floor it one
    # step short. Take the next step only when it does not exceed the request
    # beyond float noise, so genuinely sub-step requests are still floored.
    next_step = round(volume_min + (steps + 1) * volume_step, 10)
    if next_step <= capped or isclose(
        next_step, capped, rel_tol=_VOLUME_STEP_REL_TOLERANCE, abs_tol=0.0
    ):
        steps += 1
    normalized = volume_min + steps * volume_step
    if has_volume_cap:
        normalized = min(normalized, volume_max)
    return round(normalized, 10)

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
def place_market_order(  # ruff: ignore[complex-structure, too-many-arguments]
    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:
        Normalized execution result containing request and response details.

    Raises:
        Mt5OperationError: If volume is invalid.
        ValueError: If an order mode is unsupported.
    """
    if volume <= 0:
        msg = "volume must be positive."
        raise Mt5OperationError(msg)
    side = _normalize_order_side(order_side)
    if order_filling_mode not in _ORDER_FILLING_MODES:
        msg = f"Unsupported order_filling mode: {order_filling_mode!r}."
        raise ValueError(msg)
    if order_time_mode not in _ORDER_TIME_MODES:
        msg = f"Unsupported order_time mode: {order_time_mode!r}."
        raise ValueError(msg)
    request: dict[str, object] = {
        "symbol": symbol,
        "volume": volume,
    }
    if sl is not None:
        request["sl"] = sl
    if tp is not None:
        request["tp"] = tp
    if position is not None:
        request["position"] = position
    if deviation is not None:
        request["deviation"] = deviation
    if comment is not None:
        request["comment"] = comment
    if magic is not None:
        request["magic"] = magic
    mt5: Any = object()
    try:
        mt5 = client.mt5
        request.update(
            _market_order_constants(mt5, side, order_filling_mode, order_time_mode),
        )
        if dry_run:
            request["price"] = _market_order_price(client, symbol, side)
            return _execution_receipt(
                mt5=mt5,
                symbol=symbol,
                order_side=side,
                request=request,
                dry_run=True,
            )
        response = _send_market_order_request(client, request, symbol, side)
    except Exception as exc:  # ruff: ignore[blind-except] - receipt is the execution contract
        return _execution_receipt(
            mt5=mt5,
            symbol=symbol,
            order_side=side,
            request=request,
            dry_run=dry_run,
            error=exc,
        )
    return _execution_receipt(
        mt5=mt5,
        symbol=symbol,
        order_side=side,
        request=request,
        response=response,
    )

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
def 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:
        ValueError: If any preferred or default mode name is unsupported.
    """
    preferred = [mode.upper() for mode in preferred_modes]
    for mode in [*preferred, default_mode]:
        if mode not in _ORDER_FILLING_MODES:
            msg = f"Unsupported order_filling mode: {mode!r}."
            raise ValueError(msg)

    preferred_default = cast(
        "OrderFillingMode", preferred[0] if preferred else default_mode
    )
    supported = _supported_filling_modes(
        client,
        symbol=symbol,
        preferred_default=preferred_default,
    )
    if supported is None:
        return preferred_default

    for mode in preferred:
        if mode in supported:
            return cast("OrderFillingMode", mode)
    fallback_mode = next(
        mode for mode in (default_mode, "IOC", "FOK", "RETURN") if mode in supported
    )
    return cast("OrderFillingMode", fallback_mode)

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
def 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:
        Normalized execution results for matching positions.
    """
    positions = _filter_positions(
        get_positions_frame(client),
        symbols=symbol,
        tickets=tickets,
        magic=magic,
    )
    results: list[OrderExecutionResult] = []
    for row in positions.to_dict("records"):
        symbol = str(row["symbol"])
        side: OrderSide = "BUY"
        mt5: Any = object()
        request: dict[str, object] = {}
        try:
            mt5 = client.mt5
            side = _populate_sltp_request(
                request,
                mt5,
                row,
                stop_loss=stop_loss,
                take_profit=take_profit,
            )
        except Exception as exc:  # ruff: ignore[blind-except] - receipt is the execution contract
            results.append(
                _execution_receipt(
                    mt5=mt5,
                    symbol=symbol,
                    order_side=side,
                    request=request,
                    dry_run=dry_run,
                    error=exc,
                )
            )
            continue
        if dry_run:
            results.append(
                _execution_receipt(
                    mt5=mt5,
                    symbol=symbol,
                    order_side=side,
                    request=request,
                    dry_run=True,
                )
            )
            continue
        try:
            ensure_symbol_selected(client, symbol)
            response = client.order_send(request)
        except Exception as exc:  # ruff: ignore[blind-except] - receipt is the execution contract
            results.append(
                _execution_receipt(
                    mt5=mt5,
                    symbol=symbol,
                    order_side=side,
                    request=request,
                    error=exc,
                )
            )
            continue
        results.append(
            _execution_receipt(
                mt5=mt5,
                symbol=symbol,
                order_side=side,
                request=request,
                response=response,
            )
        )
    return results

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
def 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:
        Normalized execution results for positions that need an SL update.
    """
    updates = calculate_trailing_stop_updates(
        client,
        symbol=symbol,
        trailing_stop_ratio=trailing_stop_ratio,
        magic=magic,
    )
    results: list[OrderExecutionResult] = []
    for ticket, stop_loss in updates.items():
        results.extend(
            update_sltp_for_open_positions(
                client,
                symbol=symbol,
                tickets=[ticket],
                stop_loss=stop_loss,
                magic=magic,
                dry_run=dry_run,
            ),
        )
    return results

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_offset or implausible_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.