Analytics

mt5cli.analytics

Canonical trading analytics views and static-dashboard Parquet publication.

MANIFEST_NAME module-attribute

MANIFEST_NAME = 'manifest.json'

SCHEMA_VERSION module-attribute

SCHEMA_VERSION = 1

logger module-attribute

logger = logging.getLogger(__name__)

create_analytics_views

create_analytics_views(
    conn: Connection, *, temporary: bool = False
) -> bool

Create the canonical analytics_* views idempotently.

analytics_trades has one row per completed trade leg. A leg is the stretch of a position_id between reversals: a DEAL_ENTRY_INOUT deal closes the current leg and opens the next (leg_index); its volume, commission and fee are split pro rata and its swap goes to the closing leg. A leg is complete once its closing volume covers its opening volume, so partially closed legs are excluded. For positions without reversals, leg 0 matches positions_reconstructed. net_profit is profit + commission + swap + fee with NULL treated as zero, and magic/commission/swap/fee come from history_deals. A leg needs a visible opening volume, and its position must start inside the captured history (its first visible deal is an entry-in), to count as a trade. A leg's magic is the entry magic, or NULL when its entry deals mix magics (see magic_count). analytics_realized_events lists every deal portion, including portions of partially closed, still-open and not fully captured legs, at its own timestamp with its own deal's magic (cash basis) and feeds analytics_daily_pnl and analytics_equity; events of a completed leg sum to its net_profit. analytics_strategy_stats aggregates the legs by symbol and magic. Stored trade-server wall-clock timestamps are preserved without implicit UTC conversion. A trade is a win when net_profit > 0 and a loss when net_profit < 0; break-even trades count as neither.

Parameters:

Name Type Description Default
conn Connection

SQLite connection holding history_deals.

required
temporary bool

Create connection-local TEMP views so a read-only database is never modified.

False

Returns:

Type Description
bool

True if the views were created, False if history_deals lacks the

bool

columns required for position reconstruction.

Source code in mt5cli/analytics.py
def create_analytics_views(
    conn: sqlite3.Connection,
    *,
    temporary: bool = False,
) -> bool:
    """Create the canonical ``analytics_*`` views idempotently.

    ``analytics_trades`` has one row per completed trade leg. A leg is the
    stretch of a ``position_id`` between reversals: a ``DEAL_ENTRY_INOUT`` deal
    closes the current leg and opens the next (``leg_index``); its volume,
    commission and fee are split pro rata and its swap goes to the closing leg.
    A leg is complete once its closing volume covers
    its opening volume, so partially closed legs are excluded. For positions
    without reversals, leg 0 matches ``positions_reconstructed``. ``net_profit``
    is ``profit + commission + swap + fee`` with NULL treated as zero, and
    ``magic``/``commission``/``swap``/``fee`` come from ``history_deals``.
    A leg needs a visible opening volume, and its position must start inside the
    captured history (its first visible deal is an entry-in), to count as a
    trade. A leg's ``magic`` is the entry magic, or NULL when its entry deals mix
    magics (see ``magic_count``). ``analytics_realized_events`` lists every deal
    portion, including portions of partially closed, still-open and not fully
    captured legs, at its own timestamp with its own deal's ``magic`` (cash
    basis) and feeds
    ``analytics_daily_pnl`` and ``analytics_equity``; events of a completed leg
    sum to its ``net_profit``. ``analytics_strategy_stats`` aggregates the legs by
    ``symbol`` and ``magic``. Stored trade-server wall-clock timestamps are
    preserved without implicit UTC conversion. A trade is a win when
    ``net_profit > 0`` and a loss when ``net_profit < 0``; break-even trades
    count as neither.

    Args:
        conn: SQLite connection holding ``history_deals``.
        temporary: Create connection-local TEMP views so a read-only database
            is never modified.

    Returns:
        True if the views were created, False if ``history_deals`` lacks the
        columns required for position reconstruction.
    """
    deal_columns = get_table_columns(conn, "history_deals")
    if not create_deal_portions_view(conn, deal_columns, temporary=temporary):
        return False
    for name, sql in (
        ("analytics_trades", _TRADES_SQL),
        ("analytics_realized_events", _REALIZED_EVENTS_SQL),
        ("analytics_daily_pnl", _DAILY_PNL_SQL),
        ("analytics_strategy_stats", _STRATEGY_STATS_SQL),
        ("analytics_equity", _EQUITY_SQL),
    ):
        _create_view(conn, name, sql, temporary=temporary)
    return True

publish_dashboard

publish_dashboard(
    source: str | Path,
    output_dir: str | Path,
    *,
    manifest_name: str = MANIFEST_NAME,
) -> dict[str, Any]

Publish Parquet datasets and a manifest for static dashboards.

Reads an existing SQLite history database without modifying it or connecting to MetaTrader 5, and writes trades, daily_pnl, strategy_stats, equity and account_snapshots Parquet files plus a manifest into output_dir. Datasets whose source tables are missing are skipped and omitted from the manifest. The manifest is written last so readers never see it before the datasets it lists.

Parameters:

Name Type Description Default
source str | Path

Path to the SQLite history database.

required
output_dir str | Path

Directory receiving the Parquet files and manifest.

required
manifest_name str

File name (no directory components, and not the name of a dataset file) of the manifest inside output_dir.

MANIFEST_NAME

Returns:

Type Description
dict[str, Any]

The manifest as a dictionary.

Raises:

Type Description
ValueError

If the source database is invalid, manifest_name is not a plain file name or collides with a dataset file, or no dataset can be built.

Source code in mt5cli/analytics.py
def publish_dashboard(
    source: str | Path,
    output_dir: str | Path,
    *,
    manifest_name: str = MANIFEST_NAME,
) -> dict[str, Any]:
    """Publish Parquet datasets and a manifest for static dashboards.

    Reads an existing SQLite history database without modifying it or
    connecting to MetaTrader 5, and writes ``trades``, ``daily_pnl``,
    ``strategy_stats``, ``equity`` and ``account_snapshots`` Parquet files plus
    a manifest into ``output_dir``. Datasets whose source tables are missing
    are skipped and omitted from the manifest. The manifest is written last
    so readers never see it before the datasets it lists.

    Args:
        source: Path to the SQLite history database.
        output_dir: Directory receiving the Parquet files and manifest.
        manifest_name: File name (no directory components, and not the name of a
            dataset file) of the manifest inside ``output_dir``.

    Returns:
        The manifest as a dictionary.

    Raises:
        ValueError: If the source database is invalid, ``manifest_name`` is not a
            plain file name or collides with a dataset file, or no dataset can be
            built.
    """
    manifest_name = _validate_manifest_name(manifest_name)
    conn, _ = open_existing_sqlite_database(source)
    with closing(conn):
        frames = _collect_dataset_frames(conn)
    if not frames:
        msg = f"No analytics datasets could be built from {source}"
        raise ValueError(msg)
    dataset_files = {f"{name}.parquet" for name in frames}
    if manifest_name in dataset_files:
        msg = f"Manifest name collides with dashboard dataset: {manifest_name}"
        raise ValueError(msg)
    out_dir = Path(output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    manifest: dict[str, Any] = {
        "schema_version": SCHEMA_VERSION,
        "generated_at": datetime.now(UTC).isoformat(timespec="seconds"),
        "mt5cli_version": _mt5cli_version(),
        "datasets": [
            {
                "name": name,
                "file": f"{name}.parquet",
                "rows": len(frame),
                "columns": [str(column) for column in frame.columns],
            }
            for name, frame in frames.items()
        ],
    }
    with tempfile.TemporaryDirectory(dir=out_dir) as tmp:
        staged = Path(tmp)
        for name, frame in frames.items():
            export_dataframe(frame, staged / f"{name}.parquet", "parquet")
        (staged / manifest_name).write_text(
            json.dumps(manifest, indent=2) + "\n",
            encoding="utf-8",
        )
        for name in [f"{name}.parquet" for name in frames] + [manifest_name]:
            (staged / name).replace(out_dir / name)
    logger.info("Published %d dashboard datasets to %s", len(frames), out_dir)
    return manifest

Static dashboard workflow

mt5cli keeps SQLite as the canonical local store and publishes browser-facing Parquet datasets from it, so a static site (for example DuckDB-Wasm) can query the data without a live API or direct SQLite access. Visualization stays outside mt5cli.

mt5cli -o dist/data/manifest.json publish-dashboard --sqlite3 history.db
from mt5cli import publish_dashboard

manifest = publish_dashboard("history.db", "dist/data")

Publication never connects to MetaTrader 5 and never modifies the source database (analytics views are created as connection-local TEMP views). It requires the parquet extra (pip install "mt5cli[parquet]").

File Source view
trades.parquet analytics_trades
daily_pnl.parquet analytics_daily_pnl
strategy_stats.parquet analytics_strategy_stats
equity.parquet analytics_equity
account_snapshots.parquet account_snapshots joined to successful runs
manifest.json schema_version, generated_at, mt5cli_version, and per dataset name, file, rows, columns

Datasets whose source tables are missing are skipped and omitted from the manifest. The manifest is written last. manifest_name must be a plain file name (no /, \\, drive prefix or ..) that is not the name of a dataset file; otherwise ValueError is raised before anything is written (the CLI reports it as a usage error).

Analytics views

create_analytics_views(conn) creates the views idempotently in an existing history database (temporary=True creates TEMP views for read-only databases).

  • analytics_trades: one row per completed trade leg (built on the history layer's deal_portions view, the same source as positions_reconstructed). A leg is the stretch of a position_id between reversals: a DEAL_ENTRY_INOUT deal closes the current leg and opens the next one (leg_index). Its volume, commission and fee are split pro rata between the two legs; its swap goes wholly to the closing leg (MT5 reports DEAL_SWAP for the position being closed), and profit is realized on the closed part only. A leg is complete once its closing volume covers its opening volume (1e-9 lot tolerance), so partially closed legs and the still-open leg after a reversal are excluded. For positions without reversals, leg 0 matches positions_reconstructed. Columns: position_id, symbol, leg_index, magic, magic_count, side, open_time, close_time, close_date, holding_seconds, volume, entry_price, exit_price (volume-weighted), reversal_count, deals_count, profit, commission, swap, fee, net_profit. Numeric timestamps stay numeric epoch values; textual timestamps remain timezone-naive MT5 trade-server wall-clock values. No implicit UTC conversion is performed.
  • analytics_realized_events: every deal portion, each at its own timestamp (cash basis: an entry's commission lands on the entry date and a partial close's profit on the day it is realized), including partially closed and still-open legs. Events of a completed leg sum to that leg's net_profit, so cumulative equity also reflects entry costs and partial-close profit of legs that have not completed yet. Each event carries its own deal's magic. A leg needs a visible opening volume to count as a trade, and its position must start inside the captured history (its first visible deal is an entry-in, since the reversal split cannot be reconstructed otherwise), so positions opened before the captured history appear only in the events, daily P/L and equity. This check is best-effort: a scale-in cut by the capture window looks like a position start and cannot be told apart from one using the deals alone, so collect history from before the oldest open position when exact trade legs matter.
  • analytics_daily_pnl: per date, symbol, magic (the deal-level magic) from the realized events: event_count, profit, commission, swap, fee, net_profit.
  • analytics_strategy_stats: per symbol, magic from the trade legs (trade count, wins, losses, win rate, gross profit/loss, profit factor), plus avg_holding_seconds, first_open_time, last_close_time. A leg's magic is its entry magic; legs whose entry deals mix magics have a NULL magic with magic_count > 1, so for such legs daily P/L by magic and the strategy stats by magic can differ.
  • analytics_equity: one row per realized event in time order with cumulative_net_profit (realized P&L only).

Net P/L is:

net_profit = COALESCE(profit, 0) + COALESCE(commission, 0)
           + COALESCE(swap, 0) + COALESCE(fee, 0)

Missing optional deal columns are treated as zero (or NULL for magic). A trade is a win when net_profit > 0 and a loss when net_profit < 0; break-even trades count as neither. gross_profit and gross_loss sum positive and negative trade net_profit, and profit_factor = gross_profit / ABS(gross_loss) is NULL without losses. Metrics needing unavailable state (such as MAE/MFE) are out of scope.

Parquet columns with a fixed meaning are written with stable types (Int64, float64, string) even for empty tables; time columns keep the stored representation.