Analytics¶
mt5cli.analytics ¶
Canonical trading analytics views and static-dashboard Parquet publication.
create_analytics_views ¶
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 |
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 |
bool
|
columns required for position reconstruction. |
Source code in mt5cli/analytics.py
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 |
MANIFEST_NAME
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The manifest as a dictionary. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the source database is invalid, |
Source code in mt5cli/analytics.py
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.
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'sdeal_portionsview, the same source aspositions_reconstructed). A leg is the stretch of aposition_idbetween reversals: aDEAL_ENTRY_INOUTdeal 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 reportsDEAL_SWAPfor 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 matchespositions_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'snet_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'smagic. 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: perdate,symbol,magic(the deal-level magic) from the realized events:event_count,profit,commission,swap,fee,net_profit.analytics_strategy_stats: persymbol,magicfrom the trade legs (trade count, wins, losses, win rate, gross profit/loss, profit factor), plusavg_holding_seconds,first_open_time,last_close_time. A leg'smagicis its entry magic; legs whose entry deals mix magics have a NULLmagicwithmagic_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 withcumulative_net_profit(realized P&L only).
Net P/L is:
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.