Observability Module

mt5cli.observability

Observability snapshot orchestration for account, position, order, terminal state.

This module owns when and what to snapshot, using the canonical :class:~mt5cli.contract.ObservabilityClient contract rather than raw pdmt5 method names, and the SQLite snapshot tables the results are persisted into.

__all__ module-attribute

__all__ = [
    "ObservabilitySnapshot",
    "capture_observability_snapshot",
    "create_snapshot_tables",
    "insert_account_snapshot",
    "insert_order_snapshots",
    "insert_position_snapshots",
    "insert_terminal_snapshot",
    "persist_observability_snapshot",
    "record_snapshot_run",
    "start_snapshot_run",
    "update_observability",
    "update_observability_with_config",
]

logger module-attribute

logger = logging.getLogger(__name__)

ObservabilitySnapshot dataclass

ObservabilitySnapshot(
    observed_at: int,
    account: DataFrame | None,
    positions: DataFrame | None,
    orders: DataFrame | None,
    terminal: DataFrame | None,
    symbols: tuple[str, ...] | None,
)

MT5-independent captured account/position/order/terminal state.

Produced by :func:capture_observability_snapshot on the MT5 connection thread; consumed by :func:persist_observability_snapshot, which never touches MT5 or any connection-scoped MT5 state and may run on a different thread. A field is None when its include_* flag was False at capture time, distinct from an empty DataFrame returned by MT5 itself.

account instance-attribute

account: DataFrame | None

observed_at instance-attribute

observed_at: int

orders instance-attribute

orders: DataFrame | None

positions instance-attribute

positions: DataFrame | None

symbols instance-attribute

symbols: tuple[str, ...] | None

terminal instance-attribute

terminal: DataFrame | None

capture_observability_snapshot

capture_observability_snapshot(
    *,
    client: ObservabilityClient,
    symbols: Sequence[str] | None = None,
    include_account: bool = True,
    include_positions: bool = True,
    include_orders: bool = True,
    include_terminal: bool = True,
) -> ObservabilitySnapshot

Capture current account/position/order/terminal state as plain data.

Reads MT5 state via client and returns it as a serialization-safe, MT5-independent snapshot. Performs no SQLite access. Never places orders or modifies trading state. Pass the result to :func:persist_observability_snapshot -- from any thread, without MT5 access -- to write it.

Parameters:

Name Type Description Default
client ObservabilityClient

Connected MT5 client implementation.

required
symbols Sequence[str] | None

Optional symbol filter for positions and orders. When None, all positions and orders are captured.

None
include_account bool

Capture account info.

True
include_positions bool

Capture open positions.

True
include_orders bool

Capture active orders.

True
include_terminal bool

Capture terminal info.

True

Returns:

Type Description
ObservabilitySnapshot

The captured snapshot.

Source code in mt5cli/observability.py
def capture_observability_snapshot(
    *,
    client: ObservabilityClient,
    symbols: Sequence[str] | None = None,
    include_account: bool = True,
    include_positions: bool = True,
    include_orders: bool = True,
    include_terminal: bool = True,
) -> ObservabilitySnapshot:
    """Capture current account/position/order/terminal state as plain data.

    Reads MT5 state via ``client`` and returns it as a serialization-safe,
    MT5-independent snapshot. Performs no SQLite access. Never places orders
    or modifies trading state. Pass the result to
    :func:`persist_observability_snapshot` -- from any thread, without MT5
    access -- to write it.

    Args:
        client: Connected MT5 client implementation.
        symbols: Optional symbol filter for positions and orders. When None,
            all positions and orders are captured.
        include_account: Capture account info.
        include_positions: Capture open positions.
        include_orders: Capture active orders.
        include_terminal: Capture terminal info.

    Returns:
        The captured snapshot.
    """
    return ObservabilitySnapshot(
        observed_at=int(datetime.now(UTC).timestamp()),
        account=client.account_info() if include_account else None,
        positions=client.positions() if include_positions else None,
        orders=client.orders() if include_orders else None,
        terminal=client.terminal_info() if include_terminal else None,
        symbols=tuple(symbols) if symbols is not None else None,
    )

create_snapshot_tables

create_snapshot_tables(conn: Connection) -> None

Create snapshot tables idempotently.

Source code in mt5cli/observability.py
def create_snapshot_tables(conn: sqlite3.Connection) -> None:
    """Create snapshot tables idempotently."""
    for ddl in _SNAPSHOT_TABLE_DDLS:
        conn.execute(ddl)

insert_account_snapshot

insert_account_snapshot(
    conn: Connection, run_id: int, row: dict[str, object]
) -> None

Append one account state row to account_snapshots.

Source code in mt5cli/observability.py
def insert_account_snapshot(
    conn: sqlite3.Connection,
    run_id: int,
    row: dict[str, object],
) -> None:
    """Append one account state row to account_snapshots."""
    conn.execute(
        "INSERT INTO account_snapshots"
        " (run_id, login, currency, balance, equity,"
        "  margin, margin_free, margin_level, profit, leverage)"
        " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        (
            run_id,
            row.get("login"),
            row.get("currency"),
            row.get("balance"),
            row.get("equity"),
            row.get("margin"),
            row.get("margin_free"),
            row.get("margin_level"),
            row.get("profit"),
            row.get("leverage"),
        ),
    )

insert_order_snapshots

insert_order_snapshots(
    conn: Connection,
    run_id: int,
    login: int | None,
    rows: list[dict[str, object]],
) -> None

Append order rows to order_snapshots; no-op when rows is empty.

Source code in mt5cli/observability.py
def insert_order_snapshots(
    conn: sqlite3.Connection,
    run_id: int,
    login: int | None,
    rows: list[dict[str, object]],
) -> None:
    """Append order rows to order_snapshots; no-op when rows is empty."""
    if not rows:
        return
    conn.executemany(
        "INSERT INTO order_snapshots"
        " (run_id, login, ticket, symbol, type, volume_current,"
        "  price_open, price_current, state, comment, magic, time_setup)"
        " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        [
            (
                run_id,
                login,
                r.get("ticket"),
                r.get("symbol"),
                r.get("type"),
                r.get("volume_current"),
                r.get("price_open"),
                r.get("price_current"),
                r.get("state"),
                r.get("comment"),
                r.get("magic"),
                _to_epoch_int(r.get("time_setup")),
            )
            for r in rows
        ],
    )

insert_position_snapshots

insert_position_snapshots(
    conn: Connection,
    run_id: int,
    login: int | None,
    rows: list[dict[str, object]],
) -> None

Append position rows to position_snapshots; no-op when rows is empty.

Source code in mt5cli/observability.py
def insert_position_snapshots(
    conn: sqlite3.Connection,
    run_id: int,
    login: int | None,
    rows: list[dict[str, object]],
) -> None:
    """Append position rows to position_snapshots; no-op when rows is empty."""
    if not rows:
        return
    conn.executemany(
        "INSERT INTO position_snapshots"
        " (run_id, login, ticket, position_id, symbol, type, volume,"
        "  price_open, price_current, profit, swap, comment, magic)"
        " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        [
            (
                run_id,
                login,
                r.get("ticket"),
                # MT5 positions expose the position ID as ``identifier``.
                r.get("position_id", r.get("identifier")),
                r.get("symbol"),
                r.get("type"),
                r.get("volume"),
                r.get("price_open"),
                r.get("price_current"),
                r.get("profit"),
                r.get("swap"),
                r.get("comment"),
                r.get("magic"),
            )
            for r in rows
        ],
    )

insert_terminal_snapshot

insert_terminal_snapshot(
    conn: Connection, run_id: int, row: dict[str, object]
) -> None

Append one terminal state row to terminal_snapshots.

Source code in mt5cli/observability.py
def insert_terminal_snapshot(
    conn: sqlite3.Connection,
    run_id: int,
    row: dict[str, object],
) -> None:
    """Append one terminal state row to terminal_snapshots."""
    conn.execute(
        "INSERT INTO terminal_snapshots"
        " (run_id, name, connected, community_account,"
        "  trade_allowed, trade_expert, path, company, language)"
        " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
        (
            run_id,
            row.get("name"),
            row.get("connected"),
            row.get("community_account"),
            row.get("trade_allowed"),
            row.get("trade_expert"),
            row.get("path"),
            row.get("company"),
            row.get("language"),
        ),
    )

persist_observability_snapshot

persist_observability_snapshot(
    snapshot: ObservabilitySnapshot, *, output: Path | str
) -> None

Persist a :func:capture_observability_snapshot result into SQLite.

Opens and owns its own SQLite connection (WAL journal mode, synchronous=NORMAL). Never accesses MT5 or any connection-scoped MT5 state, so it is safe to call from a dedicated persistence-writer thread that holds no MT5 client.

Parameters:

Name Type Description Default
snapshot ObservabilitySnapshot

A snapshot from :func:capture_observability_snapshot.

required
output Path | str

SQLite database path.

required
Source code in mt5cli/observability.py
def persist_observability_snapshot(
    snapshot: ObservabilitySnapshot,
    *,
    output: Path | str,
) -> None:
    """Persist a :func:`capture_observability_snapshot` result into SQLite.

    Opens and owns its own SQLite connection (WAL journal mode,
    ``synchronous=NORMAL``). Never accesses MT5 or any connection-scoped MT5
    state, so it is safe to call from a dedicated persistence-writer thread
    that holds no MT5 client.

    Args:
        snapshot: A snapshot from :func:`capture_observability_snapshot`.
        output: SQLite database path.
    """
    with closing(sqlite3.connect(Path(output))) as conn, conn:
        conn.execute("PRAGMA journal_mode=WAL")
        conn.execute("PRAGMA synchronous=NORMAL")
        create_snapshot_tables(conn)
        with get_metrics().record_snapshot_update():
            run_id = start_snapshot_run(conn, snapshot.observed_at)
            try:
                login = _persist_account(conn, snapshot.account, run_id)
                _persist_positions(
                    conn,
                    snapshot.positions,
                    run_id,
                    login,
                    snapshot.symbols,
                )
                _persist_orders(conn, snapshot.orders, run_id, login, snapshot.symbols)
                _persist_terminal(conn, snapshot.terminal, run_id)
                record_snapshot_run(conn, run_id, "ok")
            except Exception:
                record_snapshot_run(conn, run_id, "error")
                conn.commit()
                raise

record_snapshot_run

record_snapshot_run(
    conn: Connection,
    run_id: int,
    status: str,
    detail: str | None = None,
) -> None

Finalize a snapshot run by setting its status.

Source code in mt5cli/observability.py
def record_snapshot_run(
    conn: sqlite3.Connection,
    run_id: int,
    status: str,
    detail: str | None = None,
) -> None:
    """Finalize a snapshot run by setting its status."""
    conn.execute(
        "UPDATE snapshot_runs SET status = ?, detail = ? WHERE run_id = ?",
        (status, detail, run_id),
    )

start_snapshot_run

start_snapshot_run(
    conn: Connection, observed_at: int
) -> int

Insert a snapshot_runs row with status 'running' and return its run_id.

Returns:

Type Description
int

The auto-assigned run_id for the new row.

Source code in mt5cli/observability.py
def start_snapshot_run(conn: sqlite3.Connection, observed_at: int) -> int:
    """Insert a snapshot_runs row with status 'running' and return its run_id.

    Returns:
        The auto-assigned run_id for the new row.
    """
    cursor = conn.execute(
        "INSERT INTO snapshot_runs (observed_at, status) VALUES (?, 'running')",
        (observed_at,),
    )
    return cast("int", cursor.lastrowid)

update_observability

update_observability(
    *,
    client: ObservabilityClient,
    output: Path | str,
    symbols: Sequence[str] | None = None,
    include_account: bool = True,
    include_positions: bool = True,
    include_orders: bool = True,
    include_terminal: bool = True,
) -> None

Snapshot current account/position/order/terminal state into SQLite.

Reads the current MT5 state and appends timestamped snapshot rows. Never places orders or modifies trading state.

Parameters:

Name Type Description Default
client ObservabilityClient

Connected MT5 client implementation.

required
output Path | str

SQLite database path.

required
symbols Sequence[str] | None

Optional symbol filter for positions and orders. When None, all positions and orders are snapshotted.

None
include_account bool

Snapshot account info into account_snapshots.

True
include_positions bool

Snapshot open positions into position_snapshots.

True
include_orders bool

Snapshot active orders into order_snapshots.

True
include_terminal bool

Snapshot terminal info into terminal_snapshots.

True
Source code in mt5cli/observability.py
def update_observability(
    *,
    client: ObservabilityClient,
    output: Path | str,
    symbols: Sequence[str] | None = None,
    include_account: bool = True,
    include_positions: bool = True,
    include_orders: bool = True,
    include_terminal: bool = True,
) -> None:
    """Snapshot current account/position/order/terminal state into SQLite.

    Reads the current MT5 state and appends timestamped snapshot rows. Never
    places orders or modifies trading state.

    Args:
        client: Connected MT5 client implementation.
        output: SQLite database path.
        symbols: Optional symbol filter for positions and orders. When None,
            all positions and orders are snapshotted.
        include_account: Snapshot account info into ``account_snapshots``.
        include_positions: Snapshot open positions into ``position_snapshots``.
        include_orders: Snapshot active orders into ``order_snapshots``.
        include_terminal: Snapshot terminal info into ``terminal_snapshots``.
    """
    snapshot = capture_observability_snapshot(
        client=client,
        symbols=symbols,
        include_account=include_account,
        include_positions=include_positions,
        include_orders=include_orders,
        include_terminal=include_terminal,
    )
    persist_observability_snapshot(snapshot, output=output)

update_observability_with_config

update_observability_with_config(
    *,
    output: Path | str,
    config: Mt5Config | None = None,
    symbols: Sequence[str] | None = None,
    include_account: bool = True,
    include_positions: bool = True,
    include_orders: bool = True,
    include_terminal: bool = True,
) -> None

Snapshot current MT5 state, opening and closing the MT5 connection.

Convenience wrapper around :func:update_observability for standalone use.

Parameters:

Name Type Description Default
output Path | str

SQLite database path.

required
config Mt5Config | None

MT5 connection configuration. Defaults to an empty config that attaches to a running terminal.

None
symbols Sequence[str] | None

Optional symbol filter for positions and orders.

None
include_account bool

Snapshot account info.

True
include_positions bool

Snapshot open positions.

True
include_orders bool

Snapshot active orders.

True
include_terminal bool

Snapshot terminal info.

True
Source code in mt5cli/observability.py
def update_observability_with_config(
    *,
    output: Path | str,
    config: Mt5Config | None = None,
    symbols: Sequence[str] | None = None,
    include_account: bool = True,
    include_positions: bool = True,
    include_orders: bool = True,
    include_terminal: bool = True,
) -> None:
    """Snapshot current MT5 state, opening and closing the MT5 connection.

    Convenience wrapper around :func:`update_observability` for standalone use.

    Args:
        output: SQLite database path.
        config: MT5 connection configuration. Defaults to an empty config that
            attaches to a running terminal.
        symbols: Optional symbol filter for positions and orders.
        include_account: Snapshot account info.
        include_positions: Snapshot open positions.
        include_orders: Snapshot active orders.
        include_terminal: Snapshot terminal info.
    """
    with mt5_session(config) as client:
        update_observability(
            client=client,
            output=output,
            symbols=symbols,
            include_account=include_account,
            include_positions=include_positions,
            include_orders=include_orders,
            include_terminal=include_terminal,
        )

Snapshot persistence (SQLite)

These helpers append timestamped account/position/order/terminal snapshot rows into 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

Both functions write to the SQLite path given by output=. The optional symbols parameter filters positions / orders by symbol.

Pass the MT5Client yielded by mt5_session() directly to update_observability(client=...). This workflow calls the facade's canonical data methods (account_info, positions, orders, terminal_info); callers never need a pdmt5 client, and no raw pdmt5 method-name fallback logic is involved.

from mt5cli import mt5_session, update_observability

with mt5_session() as client:
    update_observability(client=client, output="observability.db")

The snapshot table DDL and row inserts (create_snapshot_tables, start_snapshot_run, insert_*_snapshot(s), record_snapshot_run) live in this module alongside the orchestration that decides when and what to snapshot.