Public API Contract

mt5cli is the canonical operational trading SDK and CLI/batch layer over pdmt5. The intended dependency direction is:

downstream app -> mt5cli -> pdmt5 -> MetaTrader 5

Responsibility boundary

Layer Owns
pdmt5 MT5 core wrapper; DataFrame/dict conversion; canonical MT5 constants and parsers; direct low-level order primitives
mt5cli CLI/batch workflows; SQLite history collection; normalized datasets; closed-bar helpers; small downstream operational SDK; generic broker-facing margin/volume/order orchestration
downstream Strategy logic; signals; risk policy; backtesting; optimization; YAML/application semantics

pdmt5 is an implementation detail for downstream applications. Applications use MT5Client and mt5_session() for all data, calculations, history, and execution helpers; no mt5cli public API returns or requires a raw pdmt5 client.

Note: the former mt5cli re-export TICK_FLAG_MAP corresponds to COPY_TICKS_MAP in pdmt5 — the name changed, it was not simply moved.

Downstream packages should import from the package root (from mt5cli import ...). The authoritative SDK declaration in mt5cli.sdk enumerates every package-root symbol. Helpers promoted for downstream use, including selected configuration and parsing utilities, history timeframe resolution, and dashboard publication, are part of that root contract. Other low-level schema, export, conversion, and implementation helpers remain available only from their owning modules.

Module responsibility map

mt5cli.sdk is the internal source of truth for the stable package-root exports. Downstream code should import stable names from mt5cli; each operational capability still has exactly one owning module:

Module Owns
mt5cli.client Connection lifecycle (build_config, mt5_session, MT5Client); the sole session factory
mt5cli.lifecycle Account selection within an already-active persistent MT5 session (switch_account)
mt5cli.marketdata Stateless one-off market-data reads and multi-account rate collection (AccountSpec, collect_latest_rates_for_accounts, etc.)
mt5cli.history Legacy history collection, incremental updates, and SQLite storage (collect_history, update_history, write_*_dataset)
mt5cli.rates Canonical rate persistence/loading and stable update wrappers (load_rate_series_from_sqlite, update_history, ThrottledHistoryUpdater)
mt5cli.observability Observability snapshot orchestration and SQLite snapshot tables (update_observability, update_observability_with_config)
mt5cli.analytics Canonical analytics_* views and static-dashboard Parquet publication (publish_dashboard)
mt5cli.trading Order preparation, broker-facing calculations, and normalized execution receipts
mt5cli.contract The internal HistoryClient / ObservabilityClient protocols
mt5cli.sdk Authoritative stable package-root export declaration; no separate connection lifecycle
mt5cli.cli Typer/Click adapters; no MT5 operational logic of its own
mt5cli.utils Generic conversion, parsing, and file/SQLite export helpers, independent of the MT5 connection lifecycle

No module combines connection lifecycle, history collection, observability, telemetry, SQLite orchestration, and CLI-adjacent concerns.

Stable downstream SDK API

These names are exported from mt5cli and enumerated in mt5cli.STABLE_SDK_EXPORTS (defined by mt5cli.sdk).

Session lifecycle and configuration

Symbol Role
MT5Client The single connected client for data, history, calculations, order checking, and order sending
build_config Build the underlying MT5 connection config from connection fields; login accepts int \| str \| None — numeric strings are coerced to int, blank strings are treated as unset, and ${ENV_VAR} / $ENV_NAME placeholders in string parameters are expanded when allow_whole_dollar_env=True
substitute_mapping_values Generic selected-key environment substitution for downstream configuration adapters
mt5_session Canonical context manager: initialize/login once, yield MT5Client, shut down once; a supplied client= remains caller-owned.
switch_account Change the account selected by an already-active persistent MT5Client with MT5 login() only; verifies the requested login/server and does not reinitialize or shut down the terminal
Mt5Config Canonical pdmt5 connection configuration type returned by build_config and accepted by managed-session wrappers
AccountSpec Generic account group: symbols plus optional credentials
resolve_account_spec, resolve_account_specs Merge overrides and expand ${ENV_VAR} placeholders; opt-in allow_whole_dollar_env for bare $NAME

Closed-bar rate helpers

MetaTrader 5 returns the still-forming bar as the last row when start_pos=0. Use these helpers instead of reimplementing bar trimming or timestamp normalization in downstream apps.

Symbol Role
drop_forming_rate_bar Remove the last row from chronologically ordered rate data
fetch_latest_closed_rates Single connected client: fetch count + 1, drop forming bar
fetch_latest_closed_rates_indexed Same as above but returns a UTC DatetimeIndex named "time" (no time column)
collect_latest_closed_rates_for_accounts Multi-account closed bars with optional retry wrapper
collect_latest_closed_rates_by_granularity Same data keyed by (symbol, granularity_name)
collect_latest_rates_for_accounts_with_retries Bounded exponential backoff for transient MT5 errors

SQLite history collection and rate loading

Symbol Role
collect_history One-shot date-range export into SQLite
report_rate_gaps SQLite-only one-row-per-gap report for the canonical rates table or an explicit custom table
update_history, update_history_with_config Incremental append from MAX(time) cursors; explicit naive trade-server date_to required
ThrottledHistoryUpdater Minimum interval between successful incremental updates; explicit date_to; optional update_backend injection
capture_history_datasets MT5-bound half of update_history: resolves cursors and fetches MT5 data, returns a HistoryCapture, writes nothing
persist_history_datasets MT5-free half of update_history: writes a HistoryCapture to SQLite (append/dedup/index/views); owns its own connection
HistoryCapture Frozen, MT5-independent bundle returned by capture_history_datasets and consumed by persist_history_datasets
RateTarget, build_rate_targets Neutral (symbol, timeframe) series descriptors
load_rate_series_from_sqlite, load_rate_series_by_granularity Load normalized rates series or explicit custom tables; reject invalid targets clearly

See History Collection (SQLite) for the canonical schema, loading contract, and ER diagrams.

update_history(client=...) is exactly capture_history_datasets(client=...) followed by persist_history_datasets(...) on the returned capture (skipped when it is None, i.e. no datasets selected). Downstream applications that must keep SQLite writes off an MT5-bound thread — for example a live trading loop that cannot block on database I/O — call capture_history_datasets on the thread holding the connected client, hand the returned HistoryCapture to a separate persistence worker, and call persist_history_datasets there; persist_history_datasets never accesses MT5 or any connection-scoped MT5 state. Capturing again for the same output before a prior capture has been persisted re-reads the same not-yet-advanced incremental cursor and may re-fetch an overlapping range (safe under deduplicate=True, but wasteful); callers that queue persistence work should avoid capturing a new batch for a target while one is still pending.

Shared package-root helpers used by downstream adapters include Dataset, parse_timeframe, and resolve_history_timeframes. These are stable exports; downstream applications should not import them from mt5cli.utils or mt5cli.history.

Trading and sizing primitives (generic)

These helpers implement broker-facing calculations only. They do not encode strategy entries, exits, Kelly sizing, or signal logic.

Symbol Role
get_account_snapshot, get_symbol_snapshot, get_tick_snapshot, get_positions_frame Normalized account/symbol/tick/position views
extract_tick_price Positive finite bid/ask extraction from tick mappings
TickClockNormalizer Connection-scoped, host-clock-validated UTC tick normalization
TickClockCalibration Server-clock calibration diagnostics (offset, evidence, status)
NormalizedTickSnapshot Typed latest-tick contract with raw vs validated UTC timestamps
CalibrationStatus, ClockStatus Literal status types for clock calibration and normalization
detect_position_side Net long / short / flat from open positions
calculate_spread_ratio Relative bid-ask spread
calculate_margin_and_volume, calculate_volume_by_margin, calculate_account_projected_margin_ratio Margin budget and volume sizing
normalize_order_volume, estimate_order_margin, calculate_positions_margin Broker volume normalization and margin totals
calculate_positions_margin_by_symbol Per-symbol margin map (resilient, first-seen order)
calculate_positions_margin_safe Summed total margin across symbols (failed symbols skipped)
calculate_projected_margin_ratio Estimated symbol-scoped margin/equity after optional new exposure
calculate_account_projected_margin_ratio Account snapshot margin/equity after optional new exposure
calculate_symbol_group_margin_ratio Estimated symbol-group margin/equity with optional exposure
determine_order_limits SL/TP price levels from ratios
calculate_trailing_stop_updates Per-ticket generic trailing stop-loss update plan
resolve_broker_filling_mode Broker-supported filling-mode selection helper
ensure_symbol_selected Select/verify Market Watch visibility
place_market_order, close_open_positions, update_sltp_for_open_positions, update_trailing_stop_loss_for_open_positions Order execution helpers (dry_run supported)
MarginVolume, OrderLimits, OrderExecutionResult Typed return contracts for order helpers
OrderSide, OrderFillingMode, OrderTimeMode, PositionSide, ExecutionStatus Typed enums for order helpers
ProjectionMode Literal type for calculate_symbol_group_margin_ratio projection

calculate_positions_margin_safe intentionally omits symbols whose margin estimates fail. The returned sum is not a verified upper bound on exposure and must not be used to approve risk-limited entries or enforce exposure caps. For risk guards, use the strict calculate_positions_margin helper with errors propagated, or reject the entry when any required estimate is unavailable. Similarly, call calculate_symbol_group_margin_ratio(..., suppress_errors=False) for exposure-limit decisions; its default suppress_errors=True can omit failed per-symbol estimates.

calculate_symbol_group_margin_ratio accepts an optional projection_mode parameter ("add" by default). Pass projection_mode="replace_symbol" to subtract current exposure for new_symbol before adding the candidate margin — useful for reversal-style projections. mt5cli only calculates broker-facing exposure; downstream applications own thresholds, risk guard actions, and strategy policy.

MT5Client.order_send() and CLI order-send --yes are live execution paths.

Order helpers validate broker stop-level distance in determine_order_limits() and raise Mt5OperationError when computed SL/TP prices are too close to the entry quote. Validation uses trade_stops_level * point from the current quote and symbol metadata as a pre-check only; it does not guarantee live order acceptance after price movement and does not inspect trade_freeze_level. Live place_market_order() and SL/TP updates call ensure_symbol_selected() so hidden symbols are added to Market Watch before sending requests. OrderExecutionResult is a frozen, JSON-compatible receipt. Its direct fields are status, symbol, order_side, requested_volume, filled_volume, request_price, filled_price, order_ticket, deal_ticket, position_id, magic, retcode, comment, dry_run, request, and response. Fill values are null unless the broker supplies them. Statuses are filled, partial_fill, placed, dry_run, skipped, rejected, malformed, and failed; unknown retcodes are rejected, missing retcodes are malformed, and runtime failures are failed. A dry-run market order reads the current quote into request["price"] (so request_price is populated) but has no fills, identifiers, or response and never selects a symbol or sends. Broker sentinel identifiers (0 or negative order/deal/position values) are normalized to None.

Breaking migration

create_trading_client() and mt5_trading_session() are removed from the package-root API. Replace either with with mt5_session(config) as client: and retrieve deal history through client.history_deals() or client.recent_history_deals(). Consume execution receipt attributes instead of parsing a raw broker response or assuming requested volume was filled.

mt5cli.sdk is an internal source-of-truth module for the stable package-root exports. It does not provide a second connection lifecycle or alternate public client type; from mt5cli import MT5Client, mt5_session remains the supported way to obtain a connected client. Downstream code should import stable names from the package root and capability-specific helpers from their owning modules.

Observability snapshots (SQLite)

These helpers append timestamped account/position/order/terminal snapshot rows to a SQLite database. The snapshot tables are created on demand with idempotent DDL (CREATE TABLE IF NOT EXISTS).

Symbol Role
update_observability Append one timestamped snapshot row per data type from a connected client implementation
update_observability_with_config Standalone wrapper: opens/closes MT5 connection automatically around update_observability
capture_observability_snapshot MT5-bound half of update_observability: reads account/position/order/terminal state, returns an ObservabilitySnapshot, writes nothing
persist_observability_snapshot MT5-free half of update_observability: writes an ObservabilitySnapshot to SQLite; owns its own connection
ObservabilitySnapshot Frozen, MT5-independent bundle returned by capture_observability_snapshot and consumed by persist_observability_snapshot

update_observability and persist_observability_snapshot write to the SQLite path given by output=. The optional symbols parameter filters positions_get / orders_get by symbol.

update_observability(client=...) is exactly capture_observability_snapshot(client=...) followed by persist_observability_snapshot(...). As with history, a downstream application that must keep SQLite writes off an MT5-bound thread calls capture_observability_snapshot on the thread holding the connected client and hands the returned ObservabilitySnapshot to a separate persistence worker; persist_observability_snapshot never accesses MT5 or any connection-scoped MT5 state.

Pass the MT5Client yielded by mt5_session() directly to both update_history(client=...) and update_observability(client=...). These workflows call the facade's canonical data methods (account_info, positions, orders, terminal_info, copy_rates_range, copy_ticks_range, history_orders, and history_deals); callers never need a pdmt5 client.

Snapshot tables (created by create_snapshot_tables in mt5cli.observability):

Table Content
account_snapshots Balance, equity, margin, free-margin, P&L
position_snapshots Open positions: symbol, volume, profit, …
order_snapshots Active orders: symbol, type, price, …
terminal_snapshots Terminal connectivity and build info
snapshot_runs Per-run status (ok / error) timestamp

publish_dashboard(source, output_dir) is a stable package-root helper that publishes Parquet analytics datasets and manifest.json from an offline SQLite history database without connecting to MT5 or modifying the source; see Analytics.

Lower-level snapshot helpers (create_snapshot_tables, start_snapshot_run, insert_account_snapshot, insert_position_snapshots, insert_order_snapshots, insert_terminal_snapshot, record_snapshot_run) are available directly from mt5cli.observability and are not part of the package-root stable surface.

Errors

Symbol Role
Mt5CliError, Mt5ConnectionError, Mt5OperationError, Mt5SchemaError Stable mt5cli exception types

Only pdmt5.Mt5RuntimeError raised by MT5 operations is normalized (to Mt5ConnectionError). Exceptions raised by application callbacks, input validation, SQLite, or the filesystem propagate unchanged, after owned sessions have shut down exactly once. This normalization is identical for every MT5Client call path: a transient client created without a session (MT5Client().account_info()), a persistent client entered as a context manager (with MT5Client() as client: ...), and a caller-owned client bound with MT5Client.from_connected_client(...). Exceptions raised by code inside the body of with mt5_session(...) as client: are never normalized — only exceptions raised by an MT5Client method call itself are. MT5Client.__enter__() and mt5_session() share the same initialization-error contract: an Mt5RuntimeError raised during initialize_and_login_mt5() is normalized to Mt5ConnectionError before the session is yielded, and the terminal is shut down exactly once on both normal and exceptional exit.

History and observability client contracts

update_history() and update_observability() type their client parameter against internal structural protocols defined in mt5cli.contract — HistoryClient (copy_rates_range, copy_ticks_range, history_orders, history_deals, symbol_info_as_dict) and ObservabilityClient (account_info, terminal_info, positions, orders) — instead of object or pdmt5.Mt5DataClient. MT5Client satisfies both protocols, so the MT5Client yielded by mt5_session() can be passed directly to update_history(client=...) and update_observability(client=...) without any adaptation. Raw pdmt5 method-name fallback logic (for example probing for copy_rates_range_as_df when copy_rates_range is absent) has been removed; callers must supply a client that implements the canonical mt5cli method names.

Module-scoped helpers

Lower-level helpers are available from their owning modules and are not part of the package-root stable surface. Import them directly when needed:

Module Examples
mt5cli.analytics create_analytics_views
mt5cli.marketdata copy_rates_from, copy_ticks_from, account_info, symbols, mt5_summary, latest_rates
mt5cli.schemas DataKind, normalize_dataframe, validate_schema, DEDUP_KEYS
mt5cli.utils Dataset, IfExists, detect_format, export_dataframe, export_dataframe_to_sqlite
mt5cli.converters normalize_symbol, ensure_utc, ensure_trade_server_time, parse_date_range, granularity_name
mt5cli.exceptions normalize_mt5_exception, call_with_normalized_errors, is_recoverable_mt5_error

CLI commands

The Typer application in mt5cli.cli exposes file-export commands documented in CLI Module and the project README. CLI commands:

  • Require -o/--output and write CSV, JSON, Parquet, or SQLite.
  • Accept global MT5 connection options (--login, --password, --server, --path, --timeout).
  • Resolve unset CLI connection options from MT5_LOGIN, MT5_PASSWORD, MT5_SERVER, and MT5_PATH, and expand ${ENV_VAR} placeholders in CLI string fields before building the MT5 config.
  • Delegate to the same Python APIs described here; they are not duplicated business logic.

snapshot appends one timestamped row per enabled data type (--with-account, --with-positions, --with-orders, --with-terminal) and never places orders or modifies trading state. It requires -o/--output to point at a .db / SQLite file.

order-send is the expert raw-request path; it requires --yes and a fully constructed request payload. close-positions is the safer high-level helper that closes open positions by --symbol or --ticket using close_open_positions(). Both order-send --yes and close-positions --yes are live execution paths. close-positions --dry-run previews close orders without placing them and does not require --yes. close-positions also accepts optional --filling-mode, --deviation, --comment, and --magic; --magic scopes the selected open positions fail-closed when position magic metadata is absent. When --filling-mode (or the order_filling_mode parameter of close_open_positions()) is omitted, the filling mode is resolved per symbol with resolve_broker_filling_mode() so closes are not rejected on brokers whose symbols do not support IOC.

history-gaps reads an existing SQLite history database and exports one row per detected gap from the canonical rates table or an explicitly named custom table. It never initializes MT5. Pass --granularity-seconds for custom tables whose bar spacing cannot be inferred from timeframe metadata.

Internal helpers (not stable)

Do not import these for downstream contracts; they may change without a semver notice:

Module Examples
mt5cli.client _connected_client, _run_with_client, private coercion helpers
mt5cli.history write_*_dataset, deduplicate_history_tables, parse_sqlite_timestamp
mt5cli.retry retry_with_backoff
mt5cli.cli Typer command handlers and Click parameter types
Leading-underscore names Any _-prefixed function or method

Use the package-root stable exports instead of reaching into submodule internals.

Explicitly out of scope

mt5cli must not implement downstream strategy or research responsibilities. The following belong in consuming applications, not in mt5cli:

  • Signal detection (for example AR-GARCH or other model-specific triggers)
  • Backtesting, walk-forward analysis, or parameter optimization
  • Strategy-specific risk policy, position sizing systems, or Kelly fractions
  • Entry/exit decision logic or YAML strategy semantics
  • Entry-deal classification, Kelly fractions, or betting-specific deal transformations (retrieve canonical deal data through MT5Client.history_deals() or MT5Client.recent_history_deals(), then apply downstream transformations in your own adapter layer)
  • Application-specific credential schema keys wired into mt5cli internals

mt5cli provides connection lifecycle, normalized data access, SQLite history machinery, closed-bar helpers, generic margin/volume/spread/SL/TP utilities, and optional order primitives so downstream apps can focus on strategy code behind their own adapter layer.

Contract verification

tests/contracts/test_public_api.py asserts that every name in STABLE_SDK_EXPORTS is importable from mt5cli, that all package-root exports are covered by the stable set, and that the package-root API exposes only the canonical public surface. Module-specific unit tests cover closed-bar, SQLite loading, account-resolution, and trading-session behaviors.