History Collection (SQLite)

mt5cli.history

History collection, incremental updates, and SQLite storage for MT5 data.

DEFAULT_HISTORY_DATASETS module-attribute

DEFAULT_HISTORY_DATASETS: frozenset[Dataset] = frozenset({
    Dataset.rates,
    Dataset.history_orders,
    Dataset.history_deals,
})

DEFAULT_HISTORY_TIMEFRAMES module-attribute

DEFAULT_HISTORY_TIMEFRAMES: tuple[str, ...] = (
    TIMEFRAME_NAMES
)

SqliteConnOrPath module-attribute

SqliteConnOrPath = sqlite3.Connection | Path | str

UpdateHistoryBackend module-attribute

UpdateHistoryBackend = Callable[..., None]

VOLUME_EPSILON module-attribute

VOLUME_EPSILON = 1e-09

logger module-attribute

logger = logging.getLogger(__name__)

DedupScope dataclass

DedupScope(
    where: str,
    params: tuple[object, ...],
    required_columns: frozenset[str],
)

Scoped deduplication predicate and the columns it references.

Attributes:

Name Type Description
where str

SQL predicate appended to the duplicate-removal query.

params tuple[object, ...]

Parameters bound to the scope predicate.

required_columns frozenset[str]

Columns that must be present in the written table for the scope to run.

params instance-attribute

params: tuple[object, ...]

required_columns instance-attribute

required_columns: frozenset[str]

where instance-attribute

where: str

HistoryCapture dataclass

HistoryCapture(
    output: Path,
    selected_datasets: frozenset[Dataset],
    groups: tuple[_CapturedDatasetGroup, ...],
    deduplicate: bool,
    with_views: bool,
    captured_at: datetime,
)

MT5-independent captured history data, ready for later SQLite persistence.

Produced by :func:capture_history_datasets on the MT5 connection thread; consumed by :func:persist_history_datasets, which never touches MT5 or any connection-scoped MT5 state and may run on a different thread.

captured_at instance-attribute

captured_at: datetime

deduplicate instance-attribute

deduplicate: bool

groups instance-attribute

groups: tuple[_CapturedDatasetGroup, ...]

output instance-attribute

output: Path

selected_datasets instance-attribute

selected_datasets: frozenset[Dataset]

with_views instance-attribute

with_views: bool

RateTarget dataclass

RateTarget(symbol: str | None, timeframe: int | str)

A single rate series identified by symbol and timeframe.

Attributes:

Name Type Description
symbol str | None

MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view).

timeframe int | str

MT5 timeframe as an integer or name (for example M1).

symbol instance-attribute

symbol: str | None

timeframe instance-attribute

timeframe: int | str

timeframe_int property

timeframe_int: int

Integer MT5 timeframe value.

__post_init__

__post_init__() -> None

Normalize accepted timeframe aliases to the stored integer value.

Source code in mt5cli/history.py
def __post_init__(self) -> None:
    """Normalize accepted timeframe aliases to the stored integer value."""
    if not isinstance(self.timeframe, int):
        object.__setattr__(self, "timeframe", parse_timeframe(self.timeframe))

ThrottledHistoryUpdater

ThrottledHistoryUpdater(
    *,
    output: Path | str,
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    with_views: bool = False,
    include_account_events: bool = True,
    interval_seconds: float = 0.0,
    suppress_errors: bool = False,
    update_backend: UpdateHistoryBackend | None = None,
)

Throttled incremental SQLite history updater for long-running apps.

Wraps :func:update_history (or a custom update_backend) with a minimum interval between successful updates, so a tight application loop can call :meth:update every iteration without re-fetching MT5 history more often than desired. Timing uses a monotonic clock, so it is unaffected by wall-clock changes.

Downstream applications may pass update_backend to substitute the default :func:update_history implementation—for example to add application-specific logging, metrics, or test doubles—without monkey- patching :func:update_history.

Initialize the throttled updater.

Parameters:

Name Type Description Default
output Path | str

SQLite database path.

required
datasets set[Dataset] | None

Datasets to include (defaults to rates, history-orders, history-deals; pass {Dataset.ticks} to opt in to ticks, or {Dataset.symbols} to opt in to symbol metadata snapshots).

None
timeframes Sequence[int | str] | None

Rate timeframes to update (defaults to all fixed MT5 timeframes).

None
flags int | str

Tick copy flags as integer or name (e.g. ALL).

'ALL'
lookback_hours float

First-run lookback when a table has no prior rows.

24.0
with_views bool

Create cash_events and positions_reconstructed views.

False
include_account_events bool

Include account-level cash events.

True
interval_seconds float

Minimum seconds between successful updates. Values <= 0 update on every call.

0.0
suppress_errors bool

When True, recoverable errors (Mt5RuntimeError, Mt5ConnectionError, sqlite3.Error, ValueError, and OSError) raised during an update are swallowed and :meth:update returns False without advancing the throttle. When False (default), recoverable errors propagate so callers control logging.

False
update_backend UpdateHistoryBackend | None

Callable invoked instead of :func:update_history when :meth:update runs. Receives the same keyword arguments as :func:update_history (client, output, symbols, datasets, timeframes, flags, lookback_hours, date_to, with_views, include_account_events). Defaults to :func:update_history.

None
Source code in mt5cli/history.py
def __init__(
    self,
    *,
    output: Path | str,
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    with_views: bool = False,
    include_account_events: bool = True,
    interval_seconds: float = 0.0,
    suppress_errors: bool = False,
    update_backend: UpdateHistoryBackend | None = None,
) -> None:
    """Initialize the throttled updater.

    Args:
        output: SQLite database path.
        datasets: Datasets to include (defaults to rates, history-orders,
            history-deals; pass ``{Dataset.ticks}`` to opt in to ticks,
            or ``{Dataset.symbols}`` to opt in to symbol metadata
            snapshots).
        timeframes: Rate timeframes to update (defaults to all fixed MT5
            timeframes).
        flags: Tick copy flags as integer or name (e.g. ``ALL``).
        lookback_hours: First-run lookback when a table has no prior rows.
        with_views: Create ``cash_events`` and ``positions_reconstructed``
            views.
        include_account_events: Include account-level cash events.
        interval_seconds: Minimum seconds between successful updates. Values
            ``<= 0`` update on every call.
        suppress_errors: When True, recoverable errors (``Mt5RuntimeError``,
            ``Mt5ConnectionError``, ``sqlite3.Error``, ``ValueError``, and
            ``OSError``) raised
            during an update are swallowed and :meth:`update` returns False
            without advancing the throttle. When False (default),
            recoverable errors propagate so callers control logging.
        update_backend: Callable invoked instead of :func:`update_history`
            when :meth:`update` runs. Receives the same keyword arguments as
            :func:`update_history` (``client``, ``output``, ``symbols``,
            ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``,
            ``date_to``, ``with_views``, ``include_account_events``).
            Defaults to
            :func:`update_history`.
    """
    self.output = output
    self.datasets = datasets
    self.timeframes = timeframes
    self.flags = flags
    self.lookback_hours = lookback_hours
    self.with_views = with_views
    self.include_account_events = include_account_events
    self.interval_seconds = interval_seconds
    self.suppress_errors = suppress_errors
    self.update_backend = (
        update_history if update_backend is None else update_backend
    )
    self._last_update_monotonic: float | None = None

datasets instance-attribute

datasets = datasets

flags instance-attribute

flags = flags

include_account_events instance-attribute

include_account_events = include_account_events

interval_seconds instance-attribute

interval_seconds = interval_seconds

last_update_monotonic property

last_update_monotonic: float | None

Monotonic timestamp of the last successful update.

lookback_hours instance-attribute

lookback_hours = lookback_hours

output instance-attribute

output = output

suppress_errors instance-attribute

suppress_errors = suppress_errors

timeframes instance-attribute

timeframes = timeframes

update_backend instance-attribute

update_backend = (
    update_history
    if update_backend is None
    else update_backend
)

with_views instance-attribute

with_views = with_views

should_update

should_update() -> bool

Return whether enough time has elapsed to run another update.

Returns:

Type Description
bool

True when interval_seconds <= 0, when no update has succeeded

bool

yet, or when at least interval_seconds have elapsed since the

bool

last successful update.

Source code in mt5cli/history.py
def should_update(self) -> bool:
    """Return whether enough time has elapsed to run another update.

    Returns:
        True when ``interval_seconds <= 0``, when no update has succeeded
        yet, or when at least ``interval_seconds`` have elapsed since the
        last successful update.
    """
    if self.interval_seconds <= 0 or self._last_update_monotonic is None:
        return True
    return (time.monotonic() - self._last_update_monotonic) >= self.interval_seconds

update

update(
    client: HistoryClient,
    symbols: Sequence[str],
    *,
    date_to: datetime | str | None = None,
) -> bool

Run a throttled incremental history update.

Parameters:

Name Type Description Default
client HistoryClient

Connected MT5 data client.

required
symbols Sequence[str]

Symbols to update.

required
date_to datetime | str | None

Explicit naive MT5 trade-server end datetime. Required when datasets are selected; mt5cli cannot determine the current server time.

None

Returns:

Type Description
bool

True if an update ran successfully, False if it was throttled or

bool

(when suppress_errors is True) failed with a recoverable error.

bool

When suppress_errors is False, recoverable update failures

bool

propagate to the caller.

Source code in mt5cli/history.py
def update(
    self,
    client: HistoryClient,
    symbols: Sequence[str],
    *,
    date_to: datetime | str | None = None,
) -> bool:
    """Run a throttled incremental history update.

    Args:
        client: Connected MT5 data client.
        symbols: Symbols to update.
        date_to: Explicit naive MT5 trade-server end datetime. Required
            when datasets are selected; mt5cli cannot determine the
            current server time.

    Returns:
        True if an update ran successfully, False if it was throttled or
        (when ``suppress_errors`` is True) failed with a recoverable error.
        When ``suppress_errors`` is False, recoverable update failures
        propagate to the caller.

    """
    if not self.should_update():
        return False
    try:
        _resolve_update_history_request(
            output=self.output,
            symbols=symbols,
            datasets=self.datasets,
            timeframes=self.timeframes,
            flags=self.flags,
            lookback_hours=self.lookback_hours,
            date_to=date_to,
        )
        self.update_backend(
            client=client,
            output=self.output,
            symbols=symbols,
            datasets=self.datasets,
            timeframes=self.timeframes,
            flags=self.flags,
            lookback_hours=self.lookback_hours,
            date_to=date_to,
            with_views=self.with_views,
            include_account_events=self.include_account_events,
        )
    except _RECOVERABLE_HISTORY_UPDATE_ERRORS:
        if self.suppress_errors:
            logger.warning("Suppressed history update error", exc_info=True)
            return False
        raise
    self._last_update_monotonic = time.monotonic()
    return True

append_dataframe

append_dataframe(
    conn: Connection,
    frame: DataFrame,
    table_name: str,
    if_exists: IfExists,
    *,
    empty_log_level: int = WARNING,
) -> bool

Append a DataFrame to SQLite when it has a schema.

Returns:

Type Description
bool

True if a table was written, False if the frame had no columns.

Source code in mt5cli/history.py
def append_dataframe(
    conn: sqlite3.Connection,
    frame: pd.DataFrame,
    table_name: str,
    if_exists: IfExists,
    *,
    empty_log_level: int = logging.WARNING,
) -> bool:
    """Append a DataFrame to SQLite when it has a schema.

    Returns:
        True if a table was written, False if the frame had no columns.
    """
    if len(frame.columns) == 0:
        logger.log(
            empty_log_level,
            "Skipping %s: dataset returned no columns",
            table_name,
        )
        return False
    writable = _canonicalize_sqlite_time_columns(frame)
    writable.to_sql(  # type: ignore[reportUnknownMemberType]
        table_name,
        conn,
        if_exists=if_exists.value,
        index=False,
        chunksize=50_000,
    )
    return True

augment_written_columns_from_sqlite

augment_written_columns_from_sqlite(
    conn: Connection,
    datasets: set[Dataset],
    written_columns: dict[Dataset, set[str]],
) -> None

Add existing table columns to the written column map.

Source code in mt5cli/history.py
def augment_written_columns_from_sqlite(
    conn: sqlite3.Connection,
    datasets: set[Dataset],
    written_columns: dict[Dataset, set[str]],
) -> None:
    """Add existing table columns to the written column map."""
    for dataset in datasets:
        columns = get_table_columns(conn, dataset.table_name)
        if not columns:
            continue
        if dataset in written_columns:
            written_columns[dataset].update(columns)
        else:
            written_columns[dataset] = columns

build_rate_targets

build_rate_targets(
    symbols: Sequence[str],
    timeframes: Sequence[int | str],
    *,
    allow_missing_symbol: bool = False,
) -> list[RateTarget]

Build rate targets for every symbol and timeframe combination.

Parameters:

Name Type Description Default
symbols Sequence[str]

MT5 symbol names. May be empty when allow_missing_symbol.

required
timeframes Sequence[int | str]

MT5 timeframes as integers or names (for example M1).

required
allow_missing_symbol bool

When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising.

False

Returns:

Type Description
list[RateTarget]

Targets in row-major order: every timeframe for the first symbol, then

list[RateTarget]

every timeframe for the next symbol, and so on.

Raises:

Type Description
ValueError

If timeframes is empty, or symbols is empty and allow_missing_symbol is False.

Source code in mt5cli/history.py
def build_rate_targets(
    symbols: Sequence[str],
    timeframes: Sequence[int | str],
    *,
    allow_missing_symbol: bool = False,
) -> list[RateTarget]:
    """Build rate targets for every symbol and timeframe combination.

    Args:
        symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``.
        timeframes: MT5 timeframes as integers or names (for example ``M1``).
        allow_missing_symbol: When True and ``symbols`` is empty, build targets
            with ``symbol=None`` for each timeframe instead of raising.

    Returns:
        Targets in row-major order: every timeframe for the first symbol, then
        every timeframe for the next symbol, and so on.

    Raises:
        ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and
            ``allow_missing_symbol`` is False.
    """
    if not timeframes:
        msg = "At least one timeframe is required."
        raise ValueError(msg)
    if not symbols:
        if not allow_missing_symbol:
            msg = "At least one symbol is required."
            raise ValueError(msg)
        return [RateTarget(symbol=None, timeframe=tf) for tf in timeframes]
    return [
        RateTarget(symbol=symbol, timeframe=tf)
        for symbol in symbols
        for tf in timeframes
    ]

capture_history_datasets

capture_history_datasets(
    *,
    client: HistoryClient,
    output: Path | str,
    symbols: Sequence[str],
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    date_to: datetime | str | None = None,
    deduplicate: bool = True,
    with_views: bool = False,
    include_account_events: bool = True,
) -> HistoryCapture | None

Capture incremental MT5 history as plain data, without writing SQLite.

Reads the existing output database (if any), read-only, only to resolve each dataset's incremental cursor, then fetches MT5 data for the resolved range using client. Performs no SQLite writes. Pass the result to :func:persist_history_datasets -- from any thread, without MT5 access -- to append it.

Capturing again before a prior capture for the same output has been persisted re-reads the same not-yet-advanced cursor and may re-fetch an overlapping range (safe under deduplication, but wasteful); callers that queue persistence work should avoid capturing a new batch while one for the same target is still pending.

Returns:

Type Description
HistoryCapture | None

A capture bundle, or None when no datasets are selected.

Source code in mt5cli/history.py
def capture_history_datasets(  # ruff: ignore[too-many-arguments]
    *,
    client: HistoryClient,
    output: Path | str,
    symbols: Sequence[str],
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    date_to: datetime | str | None = None,
    deduplicate: bool = True,
    with_views: bool = False,
    include_account_events: bool = True,
) -> HistoryCapture | None:
    """Capture incremental MT5 history as plain data, without writing SQLite.

    Reads the existing ``output`` database (if any), read-only, only to
    resolve each dataset's incremental cursor, then fetches MT5 data for the
    resolved range using ``client``. Performs no SQLite writes. Pass the
    result to :func:`persist_history_datasets` -- from any thread, without MT5
    access -- to append it.

    Capturing again before a prior capture for the same ``output`` has been
    persisted re-reads the same not-yet-advanced cursor and may re-fetch an
    overlapping range (safe under deduplication, but wasteful); callers that
    queue persistence work should avoid capturing a new batch while one for
    the same target is still pending.

    Returns:
        A capture bundle, or None when no datasets are selected.
    """
    request = _resolve_update_history_request(
        output=output,
        symbols=symbols,
        datasets=datasets,
        timeframes=timeframes,
        flags=flags,
        lookback_hours=lookback_hours,
        date_to=date_to,
    )
    if request is None:
        return None
    ref_conn = _open_history_cursor_reference(request.output_path)
    try:
        groups = _capture_incremental_groups(
            ref_conn,
            client,
            symbols,
            request.selected,
            request.resolved_timeframes,
            request.resolved_tick_flags,
            request.fallback_start,
            request.end,
            include_account_events=include_account_events,
        )
    finally:
        ref_conn.close()
    return HistoryCapture(
        output=request.output_path,
        selected_datasets=frozenset(request.selected),
        groups=tuple(groups),
        deduplicate=deduplicate,
        with_views=with_views,
        captured_at=datetime.now(UTC),
    )

collect_history

collect_history(
    output: Path,
    symbols: list[str],
    date_from: datetime | str,
    date_to: datetime | str,
    *,
    datasets: set[Dataset] | None = None,
    timeframe: int | str = 1,
    flags: int | str = "ALL",
    if_exists: IfExists = FAIL,
    with_views: bool = False,
    config: Mt5Config | None = None,
) -> None

Collect historical datasets into a single SQLite database.

Parameters:

Name Type Description Default
output Path

SQLite database path.

required
symbols list[str]

Symbols to collect.

required
date_from datetime | str

Naive trade-server wall-clock start date.

required
date_to datetime | str

Naive trade-server wall-clock end date.

required
datasets set[Dataset] | None

Datasets to include (defaults to rates, history-orders, history-deals; pass {Dataset.ticks} to opt in to ticks, or {Dataset.symbols} to opt in to symbol metadata snapshots).

None
timeframe int | str

Rates timeframe as integer or name (e.g. M1).

1
flags int | str

Tick copy flags as integer or name (e.g. ALL).

'ALL'
if_exists IfExists

Behavior when a target table already exists.

FAIL
with_views bool

Create cash_events and positions_reconstructed views.

False
config Mt5Config | None

MT5 connection configuration.

None
Source code in mt5cli/history.py
def collect_history(
    output: Path,
    symbols: list[str],
    date_from: datetime | str,
    date_to: datetime | str,
    *,
    datasets: set[Dataset] | None = None,
    timeframe: int | str = 1,
    flags: int | str = "ALL",
    if_exists: IfExists = IfExists.FAIL,
    with_views: bool = False,
    config: Mt5Config | None = None,
) -> None:
    """Collect historical datasets into a single SQLite database.

    Args:
        output: SQLite database path.
        symbols: Symbols to collect.
        date_from: Naive trade-server wall-clock start date.
        date_to: Naive trade-server wall-clock end date.
        datasets: Datasets to include (defaults to rates, history-orders,
            history-deals; pass ``{Dataset.ticks}`` to opt in to ticks,
            or ``{Dataset.symbols}`` to opt in to symbol metadata
            snapshots).
        timeframe: Rates timeframe as integer or name (e.g. ``M1``).
        flags: Tick copy flags as integer or name (e.g. ``ALL``).
        if_exists: Behavior when a target table already exists.
        with_views: Create ``cash_events`` and ``positions_reconstructed`` views.
        config: MT5 connection configuration.
    """
    start = ensure_trade_server_time(date_from)
    end = ensure_trade_server_time(date_to)
    selected = resolve_history_datasets(datasets)
    tf = parse_timeframe(timeframe)
    tick_flags = parse_tick_flags(flags)
    with (
        mt5_session(config) as client,
        closing(sqlite3.connect(output)) as conn,
        conn,
    ):
        conn.execute("PRAGMA journal_mode=WAL")
        conn.execute("PRAGMA synchronous=NORMAL")
        written_tables, written_columns = write_collected_datasets(
            conn,
            client,
            symbols,
            selected,
            tf,
            tick_flags,
            start,
            end,
            if_exists,
        )
        create_history_indexes(conn, written_columns)
        if with_views and Dataset.history_deals in written_tables:
            create_cash_events_view(conn, written_columns[Dataset.history_deals])
            create_positions_reconstructed_view(
                conn,
                written_columns[Dataset.history_deals],
            )
        elif with_views and Dataset.history_deals in selected:
            logger.info(
                "Skipping history-deal views: no history_deals data was collected",
            )
        elif with_views:
            logger.warning(
                "--with-views requires the history_deals dataset",
            )
    logger.info(
        "Collected %s for %d symbol(s) into %s",
        ", ".join(sorted(ds.value for ds in selected)),
        len(symbols),
        output,
    )

create_cash_events_view

create_cash_events_view(
    conn: Connection, deals_columns: set[str]
) -> bool

Create the cash_events SQLite view derived from history_deals.

Returns:

Type Description
bool

True if the view was created, False if required columns are missing.

Source code in mt5cli/history.py
def create_cash_events_view(
    conn: sqlite3.Connection,
    deals_columns: set[str],
) -> bool:
    """Create the cash_events SQLite view derived from history_deals.

    Returns:
        True if the view was created, False if required columns are missing.
    """
    if "type" not in deals_columns:
        logger.warning("Skipping cash_events view: history_deals.type is missing")
        return False
    conn.execute("DROP VIEW IF EXISTS cash_events")
    conn.execute(
        "CREATE VIEW cash_events AS"  # ruff: ignore[hardcoded-sql-expression]
        f" SELECT * FROM history_deals WHERE type NOT IN {_TRADE_DEAL_TYPES_SQL}",
    )
    return True

create_deal_portions_view

create_deal_portions_view(
    conn: Connection,
    deals_columns: set[str],
    *,
    temporary: bool = False,
) -> bool

Create the deal_portions view, the canonical leg-aware deal layer.

deal_portions holds one row per trade deal, except that a DEAL_ENTRY_INOUT reversal is split into a closing and an opening portion. positions_reconstructed and the analytics views are derived from it, so position reconstruction exists once.

Parameters:

Name Type Description Default
conn Connection

SQLite connection holding history_deals.

required
deals_columns set[str]

Columns available on history_deals.

required
temporary bool

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

False

Returns:

Type Description
bool

True if the view was created, False if required columns are missing.

Source code in mt5cli/history.py
def create_deal_portions_view(
    conn: sqlite3.Connection,
    deals_columns: set[str],
    *,
    temporary: bool = False,
) -> bool:
    """Create the deal_portions view, the canonical leg-aware deal layer.

    ``deal_portions`` holds one row per trade deal, except that a
    ``DEAL_ENTRY_INOUT`` reversal is split into a closing and an opening
    portion. ``positions_reconstructed`` and the analytics views are derived
    from it, so position reconstruction exists once.

    Args:
        conn: SQLite connection holding ``history_deals``.
        deals_columns: Columns available on ``history_deals``.
        temporary: Create a connection-local TEMP view so a read-only database
            is never modified.

    Returns:
        True if the view was created, False if required columns are missing.
    """
    if not has_position_reconstruction_columns(deals_columns):
        _warn_missing_position_columns(deals_columns, "deal_portions")
        return False
    _create_history_view(
        conn,
        "deal_portions",
        _deal_portions_select_sql(deals_columns),
        temporary=temporary,
    )
    return True

create_history_indexes

create_history_indexes(
    conn: Connection,
    written_columns: dict[Dataset, set[str]],
) -> None

Create useful indexes for collected history tables when present.

Source code in mt5cli/history.py
def create_history_indexes(
    conn: sqlite3.Connection,
    written_columns: dict[Dataset, set[str]],
) -> None:
    """Create useful indexes for collected history tables when present."""
    time_expr = _sqlite_normalized_time_expression("time")
    if {"symbol", "timeframe", "time"}.issubset(
        written_columns.get(Dataset.rates, set()),
    ):
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_rates_symbol_timeframe_time"
            " ON rates(symbol, timeframe, time)",
        )
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_rates_symbol_timeframe_history_cursor"
            f" ON rates(symbol, timeframe, {time_expr})",
        )
    if {"symbol", "time"}.issubset(written_columns.get(Dataset.ticks, set())):
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_ticks_symbol_time ON ticks(symbol, time)",
        )
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_ticks_symbol_history_cursor"
            f" ON ticks(symbol, {time_expr})",
        )
    if {"symbol", "time"}.issubset(
        written_columns.get(Dataset.history_orders, set()),
    ):
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_history_orders_symbol_history_cursor"
            f" ON history_orders(symbol, {time_expr})",
        )
    deals_columns = written_columns.get(Dataset.history_deals, set())
    if {"symbol", "time"}.issubset(deals_columns):
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_history_deals_symbol_history_cursor"
            f" ON history_deals(symbol, {time_expr})",
        )
    if "time" in deals_columns:
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_history_deals_history_cursor"
            f" ON history_deals({time_expr})",
        )
    if {"position_id", "symbol"}.issubset(deals_columns):
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol"
            " ON history_deals(position_id, symbol)",
        )

create_positions_reconstructed_view

create_positions_reconstructed_view(
    conn: Connection,
    deals_columns: set[str],
    *,
    temporary: bool = False,
) -> bool

Create the positions_reconstructed SQLite view derived from history_deals.

The view is a position-level summary of the deal_portions view: a reversal's portions are re-merged through their entry value, so its columns keep their documented meaning (volume_close and volume_reversal count the whole reversal volume, deals_count counts deals).

Parameters:

Name Type Description Default
conn Connection

SQLite connection holding history_deals.

required
deals_columns set[str]

Columns available on history_deals.

required
temporary bool

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

False

Returns:

Type Description
bool

True if the view was created, False if required columns are missing.

Source code in mt5cli/history.py
def create_positions_reconstructed_view(
    conn: sqlite3.Connection,
    deals_columns: set[str],
    *,
    temporary: bool = False,
) -> bool:
    """Create the positions_reconstructed SQLite view derived from history_deals.

    The view is a position-level summary of the ``deal_portions`` view: a
    reversal's portions are re-merged through their ``entry`` value, so its
    columns keep their documented meaning (``volume_close`` and
    ``volume_reversal`` count the whole reversal volume, ``deals_count`` counts
    deals).

    Args:
        conn: SQLite connection holding ``history_deals``.
        deals_columns: Columns available on ``history_deals``.
        temporary: Create a connection-local TEMP view so a read-only database
            is never modified.

    Returns:
        True if the view was created, False if required columns are missing.
    """
    if not has_position_reconstruction_columns(deals_columns):
        _warn_missing_position_columns(deals_columns, "positions_reconstructed")
        return False
    create_deal_portions_view(conn, deals_columns, temporary=temporary)
    _create_history_view(
        conn,
        "positions_reconstructed",
        "SELECT"
        " position_id,"
        " symbol,"
        " MIN(CASE WHEN entry = 0 THEN time END) AS open_time,"
        " MAX(CASE WHEN entry IN (1, 2, 3) THEN time END) AS close_time,"
        " MIN(CASE WHEN entry = 0 THEN type END) AS direction,"
        " SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) AS volume_open,"
        " SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) AS volume_close,"
        " SUM(CASE WHEN entry = 2 THEN volume ELSE 0 END) AS volume_reversal,"
        " CASE"
        " WHEN SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) > 0"
        " THEN SUM(CASE WHEN entry = 0 THEN price * volume ELSE 0 END)"
        " / SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END)"
        " END AS open_price,"
        " CASE"
        " WHEN SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) > 0"
        " THEN SUM(CASE WHEN entry IN (1, 2, 3) THEN price * volume ELSE 0 END)"
        " / SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END)"
        " END AS close_price,"
        " SUM(profit) AS total_profit,"
        " COUNT(DISTINCT CASE WHEN entry = 2 THEN ticket END) AS reversal_count,"
        " COUNT(DISTINCT ticket) AS deals_count"
        " FROM deal_portions"
        " GROUP BY position_id, symbol"
        " HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0",
        temporary=temporary,
    )
    return True

deduplicate_history_tables

deduplicate_history_tables(
    conn: Connection,
    written_columns: dict[Dataset, set[str]],
    written_tables: set[Dataset],
    dedup_scopes: Mapping[Dataset, Sequence[DedupScope]]
    | None = None,
) -> None

Deduplicate appended history tables by stable identifiers.

Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead.

Source code in mt5cli/history.py
def deduplicate_history_tables(
    conn: sqlite3.Connection,
    written_columns: dict[Dataset, set[str]],
    written_tables: set[Dataset],
    dedup_scopes: Mapping[Dataset, Sequence[DedupScope]] | None = None,
) -> None:
    """Deduplicate appended history tables by stable identifiers.

    Scopes whose required columns are not present in the written table are
    skipped. If all scopes for a dataset are skipped, the table receives one
    unscoped deduplication pass instead.
    """
    cursor = conn.cursor()
    for dataset in written_tables:
        columns = written_columns.get(dataset, set())
        table = dataset.table_name
        keys = next(
            (
                candidate
                for candidate in _HISTORY_DEDUP_KEYS[dataset]
                if set(candidate).issubset(columns)
            ),
            None,
        )
        if keys is None:
            logger.warning(
                "Skipping %s deduplication: no supported key columns",
                table,
            )
            continue
        raw_scopes: Sequence[DedupScope] = (
            dedup_scopes.get(dataset, ()) if dedup_scopes else ()
        )
        scopes = [scope for scope in raw_scopes if scope.required_columns <= columns]
        if scopes:
            for scope in scopes:
                drop_duplicates_in_table(
                    cursor,
                    table,
                    list(keys),
                    keep="last",
                    scope_where=scope.where,
                    scope_params=scope.params,
                )
            continue
        drop_duplicates_in_table(cursor, table, list(keys), keep="last")

drop_duplicates_in_table

drop_duplicates_in_table(
    cursor: Cursor,
    table: str,
    ids: list[str],
    *,
    keep: Literal["first", "last"] = "last",
    scope_where: str | None = None,
    scope_params: tuple[object, ...] = (),
) -> None

Remove duplicate rows, keeping the first or last ROWID per key group.

Raises:

Type Description
ValueError

If the table or column names are invalid.

Source code in mt5cli/history.py
def drop_duplicates_in_table(
    cursor: sqlite3.Cursor,
    table: str,
    ids: list[str],
    *,
    keep: Literal["first", "last"] = "last",
    scope_where: str | None = None,
    scope_params: tuple[object, ...] = (),
) -> None:
    """Remove duplicate rows, keeping the first or last ROWID per key group.

    Raises:
        ValueError: If the table or column names are invalid.
    """
    if not table.isidentifier():
        msg = f"Invalid table name: {table}"
        raise ValueError(msg)
    if invalid := {column for column in ids if not column.isidentifier()}:
        msg = f"Invalid column names: {', '.join(sorted(invalid))}"
        raise ValueError(msg)
    ids_csv = ", ".join(_sqlite_dedup_key_expression(column) for column in ids)
    rowid_selector = "MIN" if keep == "first" else "MAX"
    prepared_scope_params = tuple(
        _require_serialized_sqlite_timestamp(value)
        if isinstance(value, datetime)
        else value
        for value in scope_params
    )
    if scope_where:
        delete_sql = (
            f"DELETE FROM {table} WHERE {scope_where} AND ROWID NOT IN"  # ruff: ignore[hardcoded-sql-expression]
            f" (SELECT {rowid_selector}(ROWID) FROM {table} WHERE {scope_where}"
            f" GROUP BY {ids_csv})"
        )
        cursor.execute(delete_sql, prepared_scope_params + prepared_scope_params)
        return
    cursor.execute(
        f"DELETE FROM {table} WHERE ROWID NOT IN"  # ruff: ignore[hardcoded-sql-expression]
        f" (SELECT {rowid_selector}(ROWID) FROM {table} GROUP BY {ids_csv})",
    )

drop_forming_rate_bar

drop_forming_rate_bar(df_rate: DataFrame) -> DataFrame

Return closed bars from chronologically ordered MT5 rate data.

MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results.

Parameters:

Name Type Description Default
df_rate DataFrame

Rate data ordered oldest-to-newest with the forming bar last.

required

Returns:

Type Description
DataFrame

A new DataFrame with all rows except the last. Index and columns are

DataFrame

preserved. The input frame is not modified.

Source code in mt5cli/history.py
def drop_forming_rate_bar(df_rate: pd.DataFrame) -> pd.DataFrame:
    """Return closed bars from chronologically ordered MT5 rate data.

    MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming
    current bar as the last row. Slice it off so downstream logic only sees
    completed bars. Empty frames and single-row frames return empty results.

    Args:
        df_rate: Rate data ordered oldest-to-newest with the forming bar last.

    Returns:
        A new DataFrame with all rows except the last. Index and columns are
        preserved. The input frame is not modified.
    """
    return df_rate.iloc[:-1].copy()

filter_incremental_history_deals_frame

filter_incremental_history_deals_frame(
    frame: DataFrame,
    symbols: Sequence[str],
    start_by_symbol: dict[str, datetime],
    account_event_start: datetime,
) -> DataFrame

Filter incrementally fetched history_deals by symbol and event start times.

Returns:

Type Description
DataFrame

Rows for selected symbols at or after each symbol start, plus account

DataFrame

events at or after account_event_start.

Source code in mt5cli/history.py
def filter_incremental_history_deals_frame(
    frame: pd.DataFrame,
    symbols: Sequence[str],
    start_by_symbol: dict[str, datetime],
    account_event_start: datetime,
) -> pd.DataFrame:
    """Filter incrementally fetched history_deals by symbol and event start times.

    Returns:
        Rows for selected symbols at or after each symbol start, plus account
        events at or after ``account_event_start``.
    """
    if frame.empty:
        return frame.copy()
    start_by_symbol = {
        symbol: ensure_trade_server_time(start)
        for symbol, start in start_by_symbol.items()
    }
    account_event_start = ensure_trade_server_time(account_event_start)
    parsed_times = _frame_parsed_times(frame)
    time_valid = parsed_times.notna()
    account_event_mask = _history_deals_account_event_mask(frame)
    account_keep = account_event_mask & (parsed_times >= account_event_start)
    trade_keep = pd.Series(data=False, index=frame.index)
    if "symbol" in frame.columns:
        for symbol in symbols:
            trade_keep |= (
                (frame["symbol"] == symbol)
                & (parsed_times >= start_by_symbol[symbol])
                & ~account_event_mask
            )
    keep = (account_keep | trade_keep) & time_valid
    return frame.loc[keep].copy()

filter_trade_history_frame

filter_trade_history_frame(
    frame: DataFrame,
    symbols: Sequence[str],
    *,
    include_account_events: bool,
) -> DataFrame

Filter trade history rows to selected symbols and account events.

Returns:

Type Description
DataFrame

Filtered history rows.

Source code in mt5cli/history.py
def filter_trade_history_frame(
    frame: pd.DataFrame,
    symbols: Sequence[str],
    *,
    include_account_events: bool,
) -> pd.DataFrame:
    """Filter trade history rows to selected symbols and account events.

    Returns:
        Filtered history rows.
    """
    if "symbol" not in frame.columns:
        return frame
    symbol_mask = frame["symbol"].isin(symbols)
    if not include_account_events:
        return frame.loc[symbol_mask].copy()
    account_event_mask = _history_deals_account_event_mask(frame)
    return frame.loc[symbol_mask | account_event_mask].copy()

get_history_deals_account_event_start_datetime

get_history_deals_account_event_start_datetime(
    conn: Connection, *, fallback_start: datetime
) -> datetime

Return the next update start for account-level history_deals rows.

Source code in mt5cli/history.py
def get_history_deals_account_event_start_datetime(
    conn: sqlite3.Connection,
    *,
    fallback_start: datetime,
) -> datetime:
    """Return the next update start for account-level history_deals rows."""
    fallback_start = ensure_trade_server_time(fallback_start)
    table = Dataset.history_deals.table_name
    columns = get_table_columns(conn, table)
    if "time" not in columns:
        return fallback_start
    if "type" in columns:
        where_clause = f"type NOT IN {_TRADE_DEAL_TYPES_SQL}"
    elif "symbol" in columns:
        where_clause = "symbol IS NULL OR symbol = ''"
    else:
        return fallback_start
    parsed = _load_latest_parseable_time(
        conn,
        table,
        where_clause=where_clause,
    )
    return ensure_trade_server_time(parsed) if parsed is not None else fallback_start

get_incremental_start_datetime

get_incremental_start_datetime(
    conn: Connection,
    dataset: Dataset,
    *,
    symbol: str,
    timeframe: int | None,
    fallback_start: datetime,
) -> datetime

Return the next update start datetime from existing MAX(time).

Source code in mt5cli/history.py
def get_incremental_start_datetime(
    conn: sqlite3.Connection,
    dataset: Dataset,
    *,
    symbol: str,
    timeframe: int | None,
    fallback_start: datetime,
) -> datetime:
    """Return the next update start datetime from existing MAX(time)."""
    timeframes = [timeframe] if timeframe is not None else None
    starts = load_incremental_start_datetimes(
        conn,
        dataset,
        symbols=[symbol],
        timeframes=timeframes,
        fallback_start=fallback_start,
    )
    return starts[symbol, timeframe]

get_table_columns

get_table_columns(conn: Connection, table: str) -> set[str]

Return existing SQLite columns for a table.

Source code in mt5cli/history.py
def get_table_columns(conn: sqlite3.Connection, table: str) -> set[str]:
    """Return existing SQLite columns for a table."""
    rows = conn.execute(
        "SELECT name FROM pragma_table_info(?)",
        (table,),
    ).fetchall()
    return {str(row[0]) for row in rows}

has_position_reconstruction_columns

has_position_reconstruction_columns(
    deals_columns: set[str],
) -> bool

Return whether history_deals can support position reconstruction.

Source code in mt5cli/history.py
def has_position_reconstruction_columns(deals_columns: set[str]) -> bool:
    """Return whether ``history_deals`` can support position reconstruction."""
    return _POSITIONS_VIEW_REQUIRED_COLUMNS.issubset(deals_columns)

load_incremental_start_datetimes

load_incremental_start_datetimes(
    conn: Connection,
    dataset: Dataset,
    *,
    symbols: Sequence[str],
    timeframes: Sequence[int] | None = None,
    fallback_start: datetime,
) -> dict[tuple[str, int | None], datetime]

Return next update start datetimes keyed by symbol and optional timeframe.

Source code in mt5cli/history.py
def load_incremental_start_datetimes(
    conn: sqlite3.Connection,
    dataset: Dataset,
    *,
    symbols: Sequence[str],
    timeframes: Sequence[int] | None = None,
    fallback_start: datetime,
) -> dict[tuple[str, int | None], datetime]:
    """Return next update start datetimes keyed by symbol and optional timeframe."""
    fallback_start = ensure_trade_server_time(fallback_start)
    table = dataset.table_name
    columns = get_table_columns(conn, table)
    if dataset is Dataset.rates and columns:
        _validate_rates_schema(columns)

    # MT5 history orders carry ``time_setup``/``time_done`` instead of ``time``.
    # MT5 selects history orders by completion time, so resume from the latest
    # ``time_done`` (inclusive; the overlap is deduplicated by ticket). Resuming
    # from ``time_setup`` would re-read everything completed since a long-lived
    # pending order was placed, so it is only a fallback when no usable
    # ``time_done`` exists.
    time_columns: tuple[str, ...] = ("time",) if "time" in columns else ()
    if dataset is Dataset.history_orders and not time_columns:
        time_columns = tuple(
            column for column in _HISTORY_ORDER_CURSOR_COLUMNS if column in columns
        )

    if not time_columns:
        if dataset is Dataset.rates and timeframes is not None:
            return {
                (symbol, timeframe): fallback_start
                for symbol in symbols
                for timeframe in timeframes
            }
        return {(symbol, None): fallback_start for symbol in symbols}

    if (
        dataset is Dataset.rates
        and timeframes is not None
        and {"symbol", "timeframe"}.issubset(columns)
    ):
        return _load_grouped_rate_start_datetimes(
            conn,
            table,
            symbols=symbols,
            timeframes=timeframes,
            fallback_start=fallback_start,
        )

    if "symbol" in columns:
        return _load_symbol_start_datetimes(
            conn,
            table,
            symbols=symbols,
            fallback_start=fallback_start,
            time_columns=time_columns,
        )

    parsed = _load_latest_cursor_time(conn, table, time_columns)
    shared_start = (
        ensure_trade_server_time(parsed) if parsed is not None else fallback_start
    )
    return {(symbol, None): shared_start for symbol in symbols}

load_rate_data

load_rate_data(
    conn_or_path: SqliteConnOrPath,
    table: str,
    count: int | None = None,
) -> DataFrame

Load rate-like data from a SQLite database path or connection.

Parameters:

Name Type Description Default
conn_or_path SqliteConnOrPath

SQLite database path or open connection.

required
table str

Source table or view name.

required
count int | None

Optional number of most recent rows to load.

None

Returns:

Type Description
DataFrame

DataFrame indexed by ascending time.

Source code in mt5cli/history.py
def load_rate_data(
    conn_or_path: SqliteConnOrPath,
    table: str,
    count: int | None = None,
) -> pd.DataFrame:
    """Load rate-like data from a SQLite database path or connection.

    Args:
        conn_or_path: SQLite database path or open connection.
        table: Source table or view name.
        count: Optional number of most recent rows to load.

    Returns:
        DataFrame indexed by ascending ``time``.

    """
    conn, should_close = open_existing_sqlite_database(conn_or_path)
    try:
        return load_rate_data_from_connection(conn, table, count=count)
    finally:
        if should_close:
            conn.close()

load_rate_data_from_connection

load_rate_data_from_connection(
    connection: Connection,
    table: str,
    count: int | None = None,
) -> DataFrame

Load rate-like data from a SQLite table or view.

Parameters:

Name Type Description Default
connection Connection

Open SQLite connection.

required
table str

Source table or view name.

required
count int | None

Optional number of most recent rows to load.

None

Returns:

Type Description
DataFrame

DataFrame indexed by ascending time.

Raises:

Type Description
ValueError

If inputs, schema, timestamps are invalid, or the table or view contains no rows.

Source code in mt5cli/history.py
def load_rate_data_from_connection(
    connection: sqlite3.Connection,
    table: str,
    count: int | None = None,
) -> pd.DataFrame:
    """Load rate-like data from a SQLite table or view.

    Args:
        connection: Open SQLite connection.
        table: Source table or view name.
        count: Optional number of most recent rows to load.

    Returns:
        DataFrame indexed by ascending ``time``.

    Raises:
        ValueError: If inputs, schema, timestamps are invalid, or the table
            or view contains no rows.
    """
    table_name = _validate_rate_load_request(table, count)
    columns = get_table_columns(connection, table_name)
    _ensure_rate_columns(columns, table_name)
    quoted_table = quote_sqlite_identifier(table_name)
    if count is None:
        frame = cast(
            "pd.DataFrame",
            pd.read_sql_query(  # type: ignore[reportUnknownMemberType]
                f"SELECT * FROM {quoted_table} ORDER BY time ASC",  # ruff: ignore[hardcoded-sql-expression]
                connection,
            ),
        )
    else:
        frame = cast(
            "pd.DataFrame",
            pd.read_sql_query(  # type: ignore[reportUnknownMemberType]
                f"SELECT * FROM {quoted_table} ORDER BY time DESC LIMIT ?",  # ruff: ignore[hardcoded-sql-expression]
                connection,
                params=(count,),
            ),
        )
    if frame.empty:
        msg = f"SQLite table or view {table_name!r} contains no rows."
        raise ValueError(msg)
    return _parse_rate_time_index(frame, table_name)

open_existing_sqlite_database

open_existing_sqlite_database(
    conn_or_path: SqliteConnOrPath,
) -> tuple[Connection, bool]

Open a read-only SQLite database or reuse an existing connection.

Returns:

Type Description
tuple[Connection, bool]

Tuple of connection and whether the caller should close it.

Raises:

Type Description
ValueError

If the database path does not exist or is not a file.

Source code in mt5cli/history.py
def open_existing_sqlite_database(
    conn_or_path: SqliteConnOrPath,
) -> tuple[sqlite3.Connection, bool]:
    """Open a read-only SQLite database or reuse an existing connection.

    Returns:
        Tuple of connection and whether the caller should close it.

    Raises:
        ValueError: If the database path does not exist or is not a file.
    """
    if isinstance(conn_or_path, sqlite3.Connection):
        return conn_or_path, False
    path = Path(conn_or_path)
    if not path.exists():
        msg = f"SQLite database not found: {path}"
        raise ValueError(msg)
    if not path.is_file():
        msg = f"SQLite database path is not a file: {path}"
        raise ValueError(msg)
    conn = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True)
    return conn, True

parse_sqlite_timestamp

parse_sqlite_timestamp(value: object) -> datetime | None

Parse a SQLite history timestamp without inventing a timezone.

Naive values remain MT5 trade-server wall-clock labels. Explicitly aware values are normalized to UTC while preserving their instant. Numeric epoch values follow pdmt5's naive wall-clock representation.

Returns:

Type Description
datetime | None

Parsed datetime preserving timestamp semantics, or None.

Source code in mt5cli/history.py
def parse_sqlite_timestamp(value: object) -> datetime | None:
    """Parse a SQLite history timestamp without inventing a timezone.

    Naive values remain MT5 trade-server wall-clock labels. Explicitly
    aware values are normalized to UTC while preserving their instant.
    Numeric epoch values follow pdmt5's naive wall-clock representation.

    Returns:
        Parsed datetime preserving timestamp semantics, or ``None``.
    """
    if value is None:
        return None
    if isinstance(value, datetime):
        return value.astimezone(UTC) if value.tzinfo is not None else value
    if isinstance(value, int | float):
        parsed = pd.to_datetime(value, unit="s", errors="coerce")
        if pd.isna(parsed):
            return None
        return parsed.to_pydatetime()
    if isinstance(value, str):
        return _parse_string_sqlite_timestamp(value)
    logger.warning("Ignoring unsupported history timestamp type: %s", type(value))
    return None

persist_history_datasets

persist_history_datasets(capture: HistoryCapture) -> None

Persist a :func:capture_history_datasets result into SQLite.

Opens and owns its own SQLite connection. 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.

Source code in mt5cli/history.py
def persist_history_datasets(capture: HistoryCapture) -> None:
    """Persist a :func:`capture_history_datasets` result into SQLite.

    Opens and owns its own SQLite connection. 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.
    """
    logger.info(
        "Persisting captured history to SQLite: datasets=%s, path=%s",
        sorted(dataset.value for dataset in capture.selected_datasets),
        capture.output,
    )
    with closing(sqlite3.connect(capture.output)) as conn, conn:
        conn.execute("PRAGMA journal_mode=WAL")
        conn.execute("PRAGMA synchronous=NORMAL")
        m = get_metrics()
        with m.record_history_update(dataset="history"):
            before = conn.total_changes
            written_columns: dict[Dataset, set[str]] = {}
            written_tables: set[Dataset] = set()
            dedup_scopes: dict[Dataset, list[DedupScope]] = {}
            for group in capture.groups:
                _persist_captured_group(
                    conn,
                    group,
                    written_columns,
                    written_tables,
                    dedup_scopes,
                )
            _finalize_incremental_writes(
                conn,
                set(capture.selected_datasets),
                written_columns,
                written_tables,
                dedup_scopes,
                deduplicate=capture.deduplicate,
                with_views=capture.with_views,
            )
            m.add_history_rows(conn.total_changes - before, dataset="history")

quote_sqlite_identifier

quote_sqlite_identifier(identifier: str) -> str

Return a safely quoted SQLite identifier using double quotes.

Source code in mt5cli/history.py
def quote_sqlite_identifier(identifier: str) -> str:
    """Return a safely quoted SQLite identifier using double quotes."""
    return '"' + identifier.replace('"', '""') + '"'

record_written_columns

record_written_columns(
    written_columns: dict[Dataset, set[str]],
    dataset: Dataset,
    frame: DataFrame,
) -> None

Remember columns for datasets written during collection.

Source code in mt5cli/history.py
def record_written_columns(
    written_columns: dict[Dataset, set[str]],
    dataset: Dataset,
    frame: pd.DataFrame,
) -> None:
    """Remember columns for datasets written during collection."""
    columns = set(frame.columns)
    if dataset in written_columns:
        written_columns[dataset].update(columns)
    else:
        written_columns[dataset] = columns

report_rate_gaps

report_rate_gaps(
    conn: Connection,
    table: str,
    *,
    granularity_seconds: int | None = None,
    min_gap_intervals: int = 1,
) -> DataFrame

Return one row per detected gap from a SQLite rate table.

The canonical rates table infers each series interval from its timeframe column. Custom tables without timeframe metadata must provide granularity_seconds explicitly.

Raises:

Type Description
ValueError

If the table/schema/timestamps or gap parameters are invalid.

Source code in mt5cli/history.py
def report_rate_gaps(  # ruff: ignore[complex-structure, too-many-locals]
    conn: sqlite3.Connection,
    table: str,
    *,
    granularity_seconds: int | None = None,
    min_gap_intervals: int = 1,
) -> pd.DataFrame:
    """Return one row per detected gap from a SQLite rate table.

    The canonical ``rates`` table infers each series interval from its
    ``timeframe`` column. Custom tables without timeframe metadata must
    provide ``granularity_seconds`` explicitly.

    Raises:
        ValueError: If the table/schema/timestamps or gap parameters are invalid.
    """
    table_name = _validate_rate_load_request(table, count=None)
    if granularity_seconds is not None and granularity_seconds <= 0:
        msg = "granularity_seconds must be positive."
        raise ValueError(msg)
    if min_gap_intervals <= 0:
        msg = "min_gap_intervals must be positive."
        raise ValueError(msg)

    columns = get_table_columns(conn, table_name)
    _ensure_rate_columns(columns, table_name)
    quoted_table = quote_sqlite_identifier(table_name)
    frame = cast(
        "pd.DataFrame",
        pd.read_sql_query(  # type: ignore[reportUnknownMemberType]
            f"SELECT * FROM {quoted_table} ORDER BY time ASC",  # ruff: ignore[hardcoded-sql-expression]
            conn,
        ),
    )
    if frame.empty:
        return _empty_rate_gap_report()

    parsed_times = frame["time"].map(parse_sqlite_timestamp)
    if parsed_times.isna().any():
        msg = f"SQLite table {table_name!r} contains unparsable time values."
        raise ValueError(msg)

    series_frame = frame.copy()
    series_frame["time"] = parsed_times
    rows: list[dict[str, object]] = []
    for group in _iter_rate_gap_groups(series_frame):
        metadata = _rate_gap_metadata(table_name, group)
        interval_seconds = granularity_seconds or _infer_rate_gap_interval_seconds(
            table_name, metadata
        )
        if interval_seconds is None:
            continue

        unique_times = group["time"].drop_duplicates()
        awareness = [
            isinstance(value, datetime) and value.tzinfo is not None
            for value in unique_times
        ]
        if any(awareness) and not all(awareness):
            msg = (
                "A rate gap series cannot mix timezone-naive MT5 wall-clock "
                "timestamps with timezone-aware instants."
            )
            raise ValueError(msg)
        sort_keys = pd.to_datetime(
            unique_times,
            errors="coerce",
            format="mixed",
            utc=all(awareness),
        )
        order = sort_keys.argsort()
        ordered_times = unique_times.iloc[order].reset_index(drop=True)
        ordered_keys = pd.Series(sort_keys.iloc[order]).reset_index(drop=True)
        if len(ordered_times) < _MIN_TIMESTAMPS_FOR_GAPS:
            continue
        deltas = ordered_keys.diff().dropna()
        for index, delta in enumerate(deltas, start=1):
            delta_seconds = int(delta.total_seconds())
            missing_intervals = max(
                ((delta_seconds + (interval_seconds - 1)) // interval_seconds) - 1,
                0,
            )
            if missing_intervals < min_gap_intervals:
                continue
            previous_time = ordered_times.iloc[index - 1]
            next_time = ordered_times.iloc[index]
            rows.append({
                **metadata,
                "granularity_seconds": interval_seconds,
                "gap_start": previous_time + timedelta(seconds=interval_seconds),
                "gap_end": next_time - timedelta(seconds=interval_seconds),
                "missing_intervals": missing_intervals,
            })
    return pd.DataFrame(rows, columns=_RATE_GAP_COLUMNS)

resolve_granularity_name

resolve_granularity_name(timeframe: int) -> str

Return a granularity name for a timeframe integer when known.

Source code in mt5cli/history.py
def resolve_granularity_name(timeframe: int) -> str:
    """Return a granularity name for a timeframe integer when known."""
    try:
        name = _get_timeframe_name(timeframe)
    except ValueError:
        return str(timeframe)
    return name.removeprefix("TIMEFRAME_")

resolve_history_datasets

resolve_history_datasets(
    datasets: set[Dataset] | None,
) -> set[Dataset]

Resolve configured history datasets.

Returns:

Type Description
set[Dataset]

DEFAULT_HISTORY_DATASETS (rates, history-orders, history-deals)

set[Dataset]

when datasets is None, otherwise the configured selection (which

set[Dataset]

may be empty or explicitly include Dataset.ticks /

set[Dataset]

Dataset.symbols).

Source code in mt5cli/history.py
def resolve_history_datasets(datasets: set[Dataset] | None) -> set[Dataset]:
    """Resolve configured history datasets.

    Returns:
        ``DEFAULT_HISTORY_DATASETS`` (rates, history-orders, history-deals)
        when ``datasets`` is None, otherwise the configured selection (which
        may be empty or explicitly include ``Dataset.ticks`` /
        ``Dataset.symbols``).
    """
    if datasets is None:
        return set(DEFAULT_HISTORY_DATASETS)
    return set(datasets)

resolve_history_tick_flags

resolve_history_tick_flags(flags: int | str) -> int

Resolve tick copy flags from an integer or name.

Returns:

Type Description
int

Integer tick flag value.

Source code in mt5cli/history.py
def resolve_history_tick_flags(flags: int | str) -> int:
    """Resolve tick copy flags from an integer or name.

    Returns:
        Integer tick flag value.
    """
    return parse_tick_flags(flags)

resolve_history_timeframes

resolve_history_timeframes(
    timeframes: Sequence[int | str] | None,
) -> list[int]

Resolve rate timeframes, deduplicating aliases for the same integer.

Returns:

Type Description
list[int]

Ordered list of unique timeframe integers.

Source code in mt5cli/history.py
def resolve_history_timeframes(
    timeframes: Sequence[int | str] | None,
) -> list[int]:
    """Resolve rate timeframes, deduplicating aliases for the same integer.

    Returns:
        Ordered list of unique timeframe integers.
    """
    raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES
    seen: set[int] = set()
    resolved: list[int] = []
    for value in raw:
        tf = parse_timeframe(value)
        if tf not in seen:
            seen.add(tf)
            resolved.append(tf)
    return resolved

resolve_rate_table_name

resolve_rate_table_name(
    symbol: str, granularity: str
) -> str

Return the canonical normalized SQLite rate table name.

Returns:

Type Description
str

Canonical normalized rates table name.

Raises:

Type Description
ValueError

If symbol or granularity is invalid.

Source code in mt5cli/history.py
def resolve_rate_table_name(symbol: str, granularity: str) -> str:
    """Return the canonical normalized SQLite rate table name.

    Returns:
        Canonical normalized rates table name.

    Raises:
        ValueError: If ``symbol`` or ``granularity`` is invalid.
    """
    parse_timeframe(granularity)
    if not symbol.strip():
        msg = "symbol must not be empty."
        raise ValueError(msg)
    return Dataset.rates.table_name

timeframe_interval_seconds

timeframe_interval_seconds(timeframe: int) -> int | None

Return the bar interval in seconds for a timeframe integer.

Returns:

Type Description
int | None

Interval seconds when the timeframe maps to a known granularity name

int | None

(for example M1 -> 60), otherwise None.

Source code in mt5cli/history.py
def timeframe_interval_seconds(timeframe: int) -> int | None:
    """Return the bar interval in seconds for a timeframe integer.

    Returns:
        Interval seconds when the timeframe maps to a known granularity name
        (for example ``M1`` -> ``60``), otherwise ``None``.
    """
    granularity = resolve_granularity_name(timeframe)
    units = {
        "M": 60,
        "H": 3600,
        "D": 86400,
        "W": 604800,
    }
    for prefix, seconds in units.items():
        suffix = granularity.removeprefix(prefix)
        if granularity.startswith(prefix) and suffix.isdigit():
            return int(suffix) * seconds
    return None

update_history

update_history(
    *,
    client: HistoryClient,
    output: Path | str,
    symbols: Sequence[str],
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    date_to: datetime | str | None = None,
    deduplicate: bool = True,
    with_views: bool = False,
    include_account_events: bool = True,
) -> None

Incrementally append MT5 history into a SQLite database.

Uses an already-connected client and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours. Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True, account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows.

Parameters:

Name Type Description Default
client HistoryClient

Connected MT5 client implementation.

required
output Path | str

SQLite database path.

required
symbols Sequence[str]

Symbols to update.

required
datasets set[Dataset] | None

Datasets to include (defaults to rates, history-orders, history-deals; pass {Dataset.ticks} to opt in to ticks, or {Dataset.symbols} to opt in to symbol metadata snapshots).

None
timeframes Sequence[int | str] | None

Rate timeframes to update (defaults to all fixed MT5 timeframes when None).

None
flags int | str

Tick copy flags as integer or name (e.g. ALL).

'ALL'
lookback_hours float

First-run lookback when a table has no prior rows.

24.0
date_to datetime | str | None

Optional naive trade-server end datetime. Required when any datasets are selected because mt5cli cannot determine the current MT5 trade-server time.

None
deduplicate bool

Remove duplicate rows after append, keeping latest ROWID.

True
with_views bool

Create cash_events and positions_reconstructed views.

False
include_account_events bool

Include account-level cash events in history_deals when True.

True
Source code in mt5cli/history.py
def update_history(  # ruff: ignore[too-many-arguments]
    *,
    client: HistoryClient,
    output: Path | str,
    symbols: Sequence[str],
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    date_to: datetime | str | None = None,
    deduplicate: bool = True,
    with_views: bool = False,
    include_account_events: bool = True,
) -> None:
    """Incrementally append MT5 history into a SQLite database.

    Uses an already-connected client and does not create or close the MT5
    connection. For first-time tables, data is fetched from
    ``date_to - lookback_hours``. Subsequent runs resume from existing
    ``MAX(time)`` per symbol (and timeframe for rates); when
    ``include_account_events=True``, account-level deals use a separate cursor
    over ``type NOT IN (0, 1)`` / empty-symbol rows.

    Args:
        client: Connected MT5 client implementation.
        output: SQLite database path.
        symbols: Symbols to update.
        datasets: Datasets to include (defaults to rates, history-orders,
            history-deals; pass ``{Dataset.ticks}`` to opt in to ticks,
            or ``{Dataset.symbols}`` to opt in to symbol metadata
            snapshots).
        timeframes: Rate timeframes to update (defaults to all fixed MT5
            timeframes when None).
        flags: Tick copy flags as integer or name (e.g. ``ALL``).
        lookback_hours: First-run lookback when a table has no prior rows.
        date_to: Optional naive trade-server end datetime. Required when any
            datasets are selected because mt5cli cannot determine the current
            MT5 trade-server time.
        deduplicate: Remove duplicate rows after append, keeping latest ROWID.
        with_views: Create ``cash_events`` and ``positions_reconstructed`` views.
        include_account_events: Include account-level cash events in
            ``history_deals`` when True.
    """
    request = _resolve_update_history_request(
        output=output,
        symbols=symbols,
        datasets=datasets,
        timeframes=timeframes,
        flags=flags,
        lookback_hours=lookback_hours,
        date_to=date_to,
    )
    if request is None:
        return
    logger.info(
        "Updating history in SQLite: symbols=%s, datasets=%s, path=%s",
        list(symbols),
        sorted(dataset.value for dataset in request.selected),
        request.output_path,
    )
    with closing(sqlite3.connect(request.output_path)) as conn, conn:
        conn.execute("PRAGMA journal_mode=WAL")
        conn.execute("PRAGMA synchronous=NORMAL")
        m = get_metrics()
        with m.record_history_update(dataset="history"):
            before = conn.total_changes
            write_incremental_datasets(
                conn,
                client,
                symbols,
                request.selected,
                request.resolved_timeframes,
                request.resolved_tick_flags,
                request.fallback_start,
                request.end,
                deduplicate=deduplicate,
                with_views=with_views,
                include_account_events=include_account_events,
            )
            m.add_history_rows(conn.total_changes - before, dataset="history")

update_history_with_config

update_history_with_config(
    *,
    output: Path | str,
    symbols: Sequence[str],
    config: Mt5Config | None = None,
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    date_to: datetime | str | None = None,
    deduplicate: bool = True,
    with_views: bool = False,
    include_account_events: bool = True,
) -> None

Incrementally append MT5 history, opening and closing the MT5 connection.

Convenience wrapper around :func:update_history for standalone use.

Source code in mt5cli/history.py
def update_history_with_config(  # ruff: ignore[too-many-arguments]
    *,
    output: Path | str,
    symbols: Sequence[str],
    config: Mt5Config | None = None,
    datasets: set[Dataset] | None = None,
    timeframes: Sequence[int | str] | None = None,
    flags: int | str = "ALL",
    lookback_hours: float = 24.0,
    date_to: datetime | str | None = None,
    deduplicate: bool = True,
    with_views: bool = False,
    include_account_events: bool = True,
) -> None:
    """Incrementally append MT5 history, opening and closing the MT5 connection.

    Convenience wrapper around :func:`update_history` for standalone use.
    """
    request = _resolve_update_history_request(
        output=output,
        symbols=symbols,
        datasets=datasets,
        timeframes=timeframes,
        flags=flags,
        lookback_hours=lookback_hours,
        date_to=date_to,
    )
    if request is None:
        return
    with mt5_session(config) as client:
        update_history(
            client=client,
            output=output,
            symbols=symbols,
            datasets=datasets,
            timeframes=timeframes,
            flags=flags,
            lookback_hours=lookback_hours,
            date_to=date_to,
            deduplicate=deduplicate,
            with_views=with_views,
            include_account_events=include_account_events,
        )

write_collected_datasets

write_collected_datasets(
    conn: Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    datasets: set[Dataset],
    timeframe: int,
    flags: int,
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
) -> tuple[set[Dataset], dict[Dataset, set[str]]]

Collect selected datasets and stream each symbol frame into SQLite.

Returns:

Type Description
tuple[set[Dataset], dict[Dataset, set[str]]]

Written datasets and their columns.

Source code in mt5cli/history.py
def write_collected_datasets(
    conn: sqlite3.Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    datasets: set[Dataset],
    timeframe: int,
    flags: int,
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
) -> tuple[set[Dataset], dict[Dataset, set[str]]]:
    """Collect selected datasets and stream each symbol frame into SQLite.

    Returns:
        Written datasets and their columns.
    """
    date_from = ensure_trade_server_time(date_from)
    date_to = ensure_trade_server_time(date_to)
    written_columns: dict[Dataset, set[str]] = {}
    written_tables: set[Dataset] = set()
    if Dataset.rates in datasets and write_rates_dataset(
        conn,
        client,
        symbols,
        timeframe,
        date_from,
        date_to,
        if_exists,
        written_columns,
    ):
        written_tables.add(Dataset.rates)
    if Dataset.ticks in datasets and write_ticks_dataset(
        conn,
        client,
        symbols,
        flags,
        date_from,
        date_to,
        if_exists,
        written_columns,
    ):
        written_tables.add(Dataset.ticks)
    if Dataset.history_orders in datasets and write_history_dataset(
        conn,
        client.history_orders,
        Dataset.history_orders,
        symbols,
        date_from,
        date_to,
        if_exists,
        written_columns,
        include_account_events=False,
    ):
        written_tables.add(Dataset.history_orders)
    if Dataset.history_deals in datasets and write_history_dataset(
        conn,
        client.history_deals,
        Dataset.history_deals,
        symbols,
        date_from,
        date_to,
        if_exists,
        written_columns,
        include_account_events=False,
    ):
        written_tables.add(Dataset.history_deals)
    if Dataset.symbols in datasets and write_symbols_dataset(
        conn,
        client,
        symbols,
        date_to,
        if_exists,
        written_columns,
    ):
        written_tables.add(Dataset.symbols)
    return written_tables, written_columns

write_history_dataset

write_history_dataset(
    conn: Connection,
    fetch: Callable[..., DataFrame],
    dataset: Dataset,
    symbols: Sequence[str],
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
    *,
    include_account_events: bool = False,
) -> bool

Stream a history dataset into SQLite.

Returns:

Type Description
bool

True if the target table was written.

Source code in mt5cli/history.py
def write_history_dataset(
    conn: sqlite3.Connection,
    fetch: Callable[..., pd.DataFrame],
    dataset: Dataset,
    symbols: Sequence[str],
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
    *,
    include_account_events: bool = False,
) -> bool:
    """Stream a history dataset into SQLite.

    Returns:
        True if the target table was written.
    """
    date_from = ensure_trade_server_time(date_from)
    date_to = ensure_trade_server_time(date_to)
    if include_account_events:
        frame = filter_trade_history_frame(
            fetch(date_from=date_from, date_to=date_to),
            symbols,
            include_account_events=True,
        )
        return write_streamed_frame(
            conn,
            frame,
            dataset,
            table_exists=False,
            if_exists=if_exists,
            written_columns=written_columns,
        )
    return _stream_symbol_frames(
        conn,
        symbols,
        dataset,
        if_exists,
        written_columns,
        lambda sym: _fetch_history_dataset_frame(fetch, sym, date_from, date_to),
    )

write_incremental_datasets

write_incremental_datasets(
    conn: Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    selected_datasets: set[Dataset],
    resolved_timeframes: list[int],
    resolved_tick_flags: int,
    fallback_start: datetime,
    end_date: datetime,
    *,
    deduplicate: bool,
    with_views: bool,
    include_account_events: bool,
) -> tuple[set[Dataset], dict[Dataset, set[str]]]

Append selected datasets incrementally and refresh indexes and views.

Returns:

Type Description
tuple[set[Dataset], dict[Dataset, set[str]]]

Written datasets and their columns.

Source code in mt5cli/history.py
def write_incremental_datasets(  # ruff: ignore[too-many-arguments]
    conn: sqlite3.Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    selected_datasets: set[Dataset],
    resolved_timeframes: list[int],
    resolved_tick_flags: int,
    fallback_start: datetime,
    end_date: datetime,
    *,
    deduplicate: bool,
    with_views: bool,
    include_account_events: bool,
) -> tuple[set[Dataset], dict[Dataset, set[str]]]:
    """Append selected datasets incrementally and refresh indexes and views.

    Returns:
        Written datasets and their columns.
    """
    fallback_start = ensure_trade_server_time(fallback_start)
    end_date = ensure_trade_server_time(end_date)
    written_columns: dict[Dataset, set[str]] = {}
    written_tables: set[Dataset] = set()
    dedup_scopes: dict[Dataset, list[DedupScope]] = {}
    if Dataset.rates in selected_datasets:
        _write_incremental_rates(
            conn,
            client,
            symbols,
            resolved_timeframes,
            fallback_start,
            end_date,
            written_columns,
            written_tables,
            dedup_scopes,
        )
    if Dataset.ticks in selected_datasets:
        _write_incremental_ticks(
            conn,
            client,
            symbols,
            resolved_tick_flags,
            fallback_start,
            end_date,
            written_columns,
            written_tables,
            dedup_scopes,
        )
    if Dataset.history_orders in selected_datasets:
        _write_incremental_history_orders(
            conn,
            client,
            symbols,
            fallback_start,
            end_date,
            written_columns,
            written_tables,
            dedup_scopes,
        )
    if Dataset.history_deals in selected_datasets:
        _write_incremental_history_deals(
            conn,
            client,
            symbols,
            fallback_start,
            end_date,
            written_columns,
            written_tables,
            dedup_scopes,
            include_account_events=include_account_events,
        )
    if Dataset.symbols in selected_datasets:
        _write_incremental_symbols(
            conn,
            client,
            symbols,
            end_date,
            written_columns,
            written_tables,
        )
    _finalize_incremental_writes(
        conn,
        selected_datasets,
        written_columns,
        written_tables,
        dedup_scopes,
        deduplicate=deduplicate,
        with_views=with_views,
    )
    return written_tables, written_columns

write_rates_dataset

write_rates_dataset(
    conn: Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool

Stream rates frames into SQLite.

Returns:

Type Description
bool

True if the rates table was written.

Source code in mt5cli/history.py
def write_rates_dataset(
    conn: sqlite3.Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool:
    """Stream rates frames into SQLite.

    Returns:
        True if the rates table was written.
    """
    date_from = ensure_trade_server_time(date_from)
    date_to = ensure_trade_server_time(date_to)
    return _stream_symbol_frames(
        conn,
        symbols,
        Dataset.rates,
        if_exists,
        written_columns,
        lambda sym: _fetch_rates_frame(client, sym, timeframe, date_from, date_to),
    )

write_streamed_frame

write_streamed_frame(
    conn: Connection,
    frame: DataFrame,
    dataset: Dataset,
    table_exists: bool,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool

Write one streamed dataset frame and track table state.

Returns:

Type Description
bool

True if the dataset table exists after this write attempt.

Source code in mt5cli/history.py
def write_streamed_frame(
    conn: sqlite3.Connection,
    frame: pd.DataFrame,
    dataset: Dataset,
    table_exists: bool,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool:
    """Write one streamed dataset frame and track table state.

    Returns:
        True if the dataset table exists after this write attempt.
    """
    for column in sorted(_SQLITE_TEXT_TIME_COLUMNS & set(frame.columns)):
        for value in frame[column]:
            parsed = parse_sqlite_timestamp(value)
            if parsed is not None:
                ensure_trade_server_time(parsed)
    write_mode = IfExists.APPEND if table_exists else if_exists
    if append_dataframe(
        conn,
        frame,
        dataset.table_name,
        write_mode,
        empty_log_level=_empty_dataset_log_level(dataset),
    ):
        record_written_columns(written_columns, dataset, frame)
        return True
    return table_exists

write_symbols_dataset

write_symbols_dataset(
    conn: Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    snapshot_time: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool

Snapshot per-symbol metadata (point, digits, contract size, volume limits).

Broker-reported symbol metadata is only valid for the account/broker that produced the snapshot. When a symbol's metadata cannot be retrieved, or when its point is missing or zero (the terminal has no valid metadata for it), a row is still persisted with NULL metadata and a warning is logged; the sync is never aborted for a single bad symbol.

Returns:

Type Description
bool

True if the symbols table was written.

Source code in mt5cli/history.py
def write_symbols_dataset(
    conn: sqlite3.Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    snapshot_time: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool:
    """Snapshot per-symbol metadata (point, digits, contract size, volume limits).

    Broker-reported symbol metadata is only valid for the account/broker that
    produced the snapshot. When a symbol's metadata cannot be retrieved, or
    when its ``point`` is missing or zero (the terminal has no valid metadata
    for it), a row is still persisted with NULL metadata and a warning is
    logged; the sync is never aborted for a single bad symbol.

    Returns:
        True if the symbols table was written.
    """
    snapshot_time = ensure_trade_server_time(snapshot_time)
    return _stream_symbol_frames(
        conn,
        symbols,
        Dataset.symbols,
        if_exists,
        written_columns,
        lambda sym: _fetch_symbol_metadata_frame(client, sym, snapshot_time),
    )

write_ticks_dataset

write_ticks_dataset(
    conn: Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    flags: int,
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool

Stream ticks frames into SQLite.

Returns:

Type Description
bool

True if the ticks table was written.

Source code in mt5cli/history.py
def write_ticks_dataset(
    conn: sqlite3.Connection,
    client: HistoryClient,
    symbols: Sequence[str],
    flags: int,
    date_from: datetime,
    date_to: datetime,
    if_exists: IfExists,
    written_columns: dict[Dataset, set[str]],
) -> bool:
    """Stream ticks frames into SQLite.

    Returns:
        True if the ticks table was written.
    """
    date_from = ensure_trade_server_time(date_from)
    date_to = ensure_trade_server_time(date_to)
    return _stream_symbol_frames(
        conn,
        symbols,
        Dataset.ticks,
        if_exists,
        written_columns,
        lambda sym: _fetch_ticks_frame(client, sym, flags, date_from, date_to),
    )

collect-history schema

The collect-history command (and the matching collect_history SDK function) writes selected MT5 datasets into one SQLite database. Each dataset becomes a table; column names and types mirror the pdmt5 DataFrame schema for that export, with two additions:

  • symbol is prepended on every table.
  • timeframe is prepended on rates so appended runs at different bar sizes stay distinguishable.

SQLite does not declare foreign keys. Rows are linked logically by symbol, time windows, and (for deals) position_id / order. Duplicate rows are removed on append using dataset-specific keys (for example ticket on history tables, or (symbol, timeframe, time) on rates).

Optional views are created when --with-views is set and the history-deals dataset was written.

All MT5 history query bounds are timezone-naive trade-server wall-clock datetimes, matching pdmt5. Offset-bearing strings and timezone-aware datetime values are rejected; incremental cursors and returned history frames use the same naive contract, and no broker-time conversion is inferred. Incremental updates require an explicit date_to because mt5cli cannot determine the current MT5 trade-server time.

ticks and symbols are opt-in datasets (pass --dataset ticks / --dataset symbols); they are excluded from the default rates, history-orders, history-deals selection. Unlike the other datasets, symbols is not a time-windowed history table: each collection or update writes one row per requested symbol, timestamped with the collection's date_to (one-shot collect-history) or the update's end time (incremental update_history). It snapshots broker-reported symbol metadata (point, digits, trade_contract_size, volume_min, volume_max, volume_step, trade_tick_size, trade_tick_value, currency_profit) so downstream consumers can convert rates.spread (points) into a relative spread without a live terminal connection. Metadata is only valid for the account/broker that produced the snapshot. When a symbol's point is missing or zero, the row is still written with NULL metadata and a warning is logged — a bad symbol never aborts the rest of the sync.

Entity-relationship diagram

Sample layout for a full collection with --with-views:

erDiagram
    rates {
        TEXT symbol "dedup key"
        INTEGER timeframe "dedup key"
        TEXT time "dedup key"
        REAL open
        REAL high
        REAL low
        REAL close
        INTEGER tick_volume
        INTEGER spread
        INTEGER real_volume
    }

    ticks {
        TEXT symbol "dedup key"
        TEXT time "dedup key"
        INTEGER time_msc "dedup key (preferred)"
        REAL bid
        REAL ask
        REAL last
        INTEGER volume
        INTEGER flags
        REAL volume_real
    }

    history_orders {
        INTEGER ticket "dedup key"
        TEXT symbol
        TEXT time
        INTEGER type
        INTEGER state
        REAL volume_initial
        REAL price_open
        REAL price_current
        INTEGER magic
    }

    history_deals {
        INTEGER ticket "dedup key"
        INTEGER order
        INTEGER position_id "groups position view"
        TEXT symbol
        TEXT time
        INTEGER type "0/1 trade, else cash event"
        INTEGER entry "0 IN, 1 OUT, 2 INOUT, 3 OUT_BY"
        REAL volume
        REAL price
        REAL profit
        REAL commission
        REAL swap
        REAL fee
    }

    symbols {
        TEXT symbol "dedup key"
        TEXT time "dedup key, snapshot moment"
        REAL point
        INTEGER digits
        REAL trade_contract_size
        REAL volume_min
        REAL volume_max
        REAL volume_step
        REAL trade_tick_size
        REAL trade_tick_value
        TEXT currency_profit
    }

    cash_events {
        INTEGER ticket
        TEXT symbol
        TEXT time
        INTEGER type
        REAL profit
    }

    deal_portions {
        INTEGER ticket
        INTEGER position_id
        TEXT symbol
        INTEGER leg
        TEXT role
        INTEGER position_start_known
        REAL volume
        REAL profit
        REAL commission
        REAL swap
        REAL fee
    }

    positions_reconstructed {
        INTEGER position_id
        TEXT symbol
        TEXT open_time
        TEXT close_time
        INTEGER direction
        REAL volume_open
        REAL volume_close
        REAL volume_reversal
        REAL open_price
        REAL close_price
        REAL total_profit
        INTEGER reversal_count
        INTEGER deals_count
    }

    rates ||--o{ history_deals : "symbol (logical)"
    ticks ||--o{ history_deals : "symbol (logical)"
    history_orders ||--o{ history_deals : "order ~ ticket (logical)"
    symbols ||--o{ rates : "symbol (logical)"
    history_deals ||--|| cash_events : "VIEW: type NOT IN (0,1)"
    history_deals ||--o{ deal_portions : "VIEW: deals split at reversals"
    deal_portions ||--o{ positions_reconstructed : "VIEW: GROUP BY position_id"

Tables and views

Object Kind Source Notes
rates table copy_rates_range Indexed on (symbol, timeframe, time) when columns exist.
ticks table copy_ticks_range Indexed on (symbol, time) when columns exist.
history_orders table history_orders_get Fetched per --symbol, then concatenated.
history_deals table history_deals_get Fetched per --symbol, then concatenated. Indexed on (position_id, symbol) when present.
symbols table symbol_info Opt-in. One row per symbol per collection/update, snapshotted at date_to / update end.
cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column.
deal_portions view history_deals Canonical leg-aware layer: trade deals, with each reversal (DEAL_ENTRY_INOUT) split into a closing and an opening portion (leg, role).
positions_reconstructed view deal_portions One row per closed position_id; volume-weighted prices and reversal stats (reversal volume counted whole).

The reversal split in deal_portions uses the balance of the visible deals, so it is reliable only for positions whose first visible deal is an entry-in (position_start_known = 1). When the captured history starts mid-position (position_start_known = 0), the leg numbering and the closing/opening split of a reversal are approximate, though every deal's cash totals are preserved and positions_reconstructed is unaffected. The flag is best-effort: a scale-in is also an entry-in deal, so if the capture window cuts a position and a later scale-in is the first visible deal, the missing earlier exposure cannot be detected from the deals alone.

Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing.

Incremental collection

The package-root mt5cli.update_history SDK path uses the normalized rates table and optional cash_events / positions_reconstructed views. It writes the canonical normalized rates table directly and does not maintain per-series compatibility views.

Rate data loading

The canonical managed rate store is the normalized rates table. Stable symbol/timeframe reads query that table directly; mt5cli does not create, discover, resolve, or maintain per-series rate_* compatibility views.

Use load_rate_series_from_sqlite() or load_rate_series_by_granularity() for canonical managed data:

from pathlib import Path

from mt5cli import (
    build_rate_targets,
    load_rate_series_by_granularity,
    load_rate_series_from_sqlite,
)

path = Path("history.db")
targets = build_rate_targets(["EURUSD", "GBPUSD"], ["M1", "H1"])
series = load_rate_series_from_sqlite(path, targets, count=1000)
eurusd_m1 = series["EURUSD", 1]

by_name = load_rate_series_by_granularity(
    path,
    symbols=["EURUSD", "GBPUSD"],
    granularities=["M1", "H1"],
    count=500,
)
eurusd_m1_named = by_name["EURUSD", "M1"]

Canonical reads apply count in SQLite and return the selected rows in chronological order. Each returned series uses an ascending DatetimeIndex named time. Timezone-naive MT5 trade-server wall-clock timestamps remain naive; explicitly timezone-aware timestamps preserve their instant and are normalized to UTC.

explicit_tables and the single-table table= form are reserved for intentionally named custom tables. They do not discover or fall back to managed per-series views. Explicit table counts must match target counts, and duplicate (symbol, timeframe) targets are rejected.

load_rate_data() / load_rate_data_from_connection() remain available for low-level explicit-table reads. These helpers validate that time exists and return an ascending DatetimeIndex named time.

Throttled incremental history updates

ThrottledHistoryUpdater wraps update_history() with a minimum interval between successful runs (using a monotonic clock), so an application loop can call it every iteration without over-fetching.

from datetime import datetime

from pdmt5 import Mt5Config

from mt5cli import ThrottledHistoryUpdater, mt5_session
from mt5cli.utils import Dataset

updater = ThrottledHistoryUpdater(
    output="history.db",
    datasets={Dataset.rates},
    timeframes=["M1"],
    interval_seconds=60,  # <= 0 updates on every call
)

with mt5_session(Mt5Config(login=12345)) as client:
    while True:
        updater.update(
            client,
            ["EURUSD", "GBPUSD"],
            date_to=datetime(2024, 2, 1),
        )  # no-op until 60s elapse
        # ... do other work; break when shutting down ...

Pass update_backend to substitute the default update_history implementation without monkey-patching mt5cli.history.update_history. The callable receives the same keyword arguments as update_history (client, output, symbols, datasets, timeframes, flags, lookback_hours, with_views, date_to, include_account_events). The resolved backend is stored on updater.update_backend for inspection or subclassing.

from mt5cli import ThrottledHistoryUpdater, update_history


def app_update_history(**kwargs) -> None:
    update_history(**kwargs)  # or delegate to application-specific logic


updater = ThrottledHistoryUpdater(
    output="history.db",
    interval_seconds=60,
    update_backend=app_update_history,
)

By default recoverable errors (Mt5RuntimeError, sqlite3.Error, ValueError, OSError) propagate so the caller controls logging; pass suppress_errors=True to swallow them and return False without advancing the throttle. AttributeError and TypeError are treated as caller programming errors and always propagate, even when suppress_errors=True — the client passed to update() must implement the canonical HistoryClient method names (copy_rates_range, copy_ticks_range, history_orders, history_deals, symbol_info_as_dict). Input validation (_resolve_update_history_request) runs before any MT5 or SQLite calls, but when suppress_errors=True the resulting ValueError is suppressed along with other recoverable errors.