From 8994954964bd6e95120ad1847c9a12558ea75e9f Mon Sep 17 00:00:00 2001 From: dceoy Date: Tue, 9 Jun 2026 15:15:52 +0000 Subject: [PATCH] deploy: 5b1d54bfe9ebeea3033037a7c0ee4e7daa6a856f --- api/history/index.html | 2987 ++++++++++++---------- api/sdk/index.html | 5122 ++++++++++++++++++++++++++------------ index.html | 2 +- objects.inv | Bin 2156 -> 2380 bytes search/search_index.json | 2 +- 5 files changed, 5226 insertions(+), 2887 deletions(-) diff --git a/api/history/index.html b/api/history/index.html index 5f7bde8..5b6e7b5 100644 --- a/api/history/index.html +++ b/api/history/index.html @@ -657,49 +657,49 @@ by an explicit table (for example a custom SQLite view).

Source code in mt5cli/history.py -
def append_dataframe(
-    conn: sqlite3.Connection,
-    frame: pd.DataFrame,
-    table_name: str,
-    if_exists: IfExists,
-) -> 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.warning("Skipping %s: dataset returned no columns", table_name)
-        return False
-    frame.to_sql(  # type: ignore[reportUnknownMemberType]
-        table_name,
-        conn,
-        if_exists=if_exists.value,
-        index=False,
-        chunksize=50_000,
-    )
-    return True
+              
def append_dataframe(
+    conn: sqlite3.Connection,
+    frame: pd.DataFrame,
+    table_name: str,
+    if_exists: IfExists,
+) -> 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.warning("Skipping %s: dataset returned no columns", table_name)
+        return False
+    frame.to_sql(  # type: ignore[reportUnknownMemberType]
+        table_name,
+        conn,
+        if_exists=if_exists.value,
+        index=False,
+        chunksize=50_000,
+    )
+    return True
 
@@ -728,33 +728,33 @@ by an explicit table (for example a custom SQLite view).

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
+              
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
 
@@ -1102,41 +1102,41 @@ a symbol such as EURUSD_M1 cannot collide with EURUSD
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"  # noqa: S608
-        f" SELECT * FROM history_deals WHERE type NOT IN {_TRADE_DEAL_TYPES_SQL}",
-    )
-    return True
+              
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"  # noqa: S608
+        f" SELECT * FROM history_deals WHERE type NOT IN {_TRADE_DEAL_TYPES_SQL}",
+    )
+    return True
 
@@ -1164,51 +1164,51 @@ a symbol such as EURUSD_M1 cannot collide with EURUSD
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."""
-    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)",
-        )
-    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)",
-        )
-    if {"position_id", "symbol"}.issubset(
-        written_columns.get(Dataset.history_deals, set()),
-    ):
-        conn.execute(
-            "CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol"
-            " ON history_deals(position_id, symbol)",
-        )
+              
def create_history_indexes(
+    conn: sqlite3.Connection,
+    written_columns: dict[Dataset, set[str]],
+) -> None:
+    """Create useful indexes for collected history tables when present."""
+    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)",
+        )
+    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)",
+        )
+    if {"position_id", "symbol"}.issubset(
+        written_columns.get(Dataset.history_deals, set()),
+    ):
+        conn.execute(
+            "CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol"
+            " ON history_deals(position_id, symbol)",
+        )
 
@@ -1258,124 +1258,17 @@ a symbol such as EURUSD_M1 cannot collide with EURUSD
Source code in mt5cli/history.py -
def create_positions_reconstructed_view(
-    conn: sqlite3.Connection,
-    deals_columns: set[str],
-) -> bool:
-    """Create the positions_reconstructed SQLite view derived from history_deals.
-
-    Returns:
-        True if the view was created, False if required columns are missing.
-    """
-    if not _POSITIONS_VIEW_REQUIRED_COLUMNS.issubset(deals_columns):
-        missing = ", ".join(sorted(_POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns))
-        logger.warning(
-            "Skipping positions_reconstructed view: history_deals missing columns: %s",
-            missing,
-        )
-        return False
-    conn.execute("DROP VIEW IF EXISTS positions_reconstructed")
-    conn.execute(
-        "CREATE VIEW positions_reconstructed AS"  # noqa: S608
-        " 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,"
-        " SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,"
-        " COUNT(*) AS deals_count"
-        " FROM history_deals"
-        f" WHERE type IN {_TRADE_DEAL_TYPES_SQL} AND position_id != 0"
-        " GROUP BY position_id, symbol"
-        " HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0",
-    )
-    return True
-
-
- - - - -
- - -

- create_rate_compatibility_views - - -

-
create_rate_compatibility_views(conn: Connection) -> None
-
- -
- -

Create rate compatibility views from the normalized rates table.

- - -
- Source code in mt5cli/history.py -
1236
+              
1226
+1227
+1228
+1229
+1230
+1231
+1232
+1233
+1234
+1235
+1236
 1237
 1238
 1239
@@ -1405,37 +1298,144 @@ a symbol such as EURUSD_M1 cannot collide with EURUSD
 1263
 1264
 1265
-1266
def create_rate_compatibility_views(conn: sqlite3.Connection) -> None:
-    """Create rate compatibility views from the normalized rates table."""
-    columns = get_table_columns(conn, Dataset.rates.table_name)
-    if not {"symbol", "timeframe", "time"}.issubset(columns):
-        return
-    drop_rate_compatibility_views(conn)
-    select_columns = sorted(columns - {"symbol", "timeframe"})
-    quoted_columns = ", ".join(f'"{column}"' for column in select_columns)
-    rows = conn.execute(
-        "SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe",
-    ).fetchall()
-    timeframes_by_symbol: dict[str, list[int]] = {}
-    for symbol, timeframe in rows:
-        timeframes_by_symbol.setdefault(str(symbol), []).append(int(timeframe))
-    for symbol, timeframes in timeframes_by_symbol.items():
-        for timeframe in timeframes:
-            granularity = resolve_granularity_name(timeframe)
-            view_name = build_rate_view_name(
-                symbol=symbol,
-                granularity=granularity,
-                granularity_count=len(timeframes),
-                timeframe=timeframe,
-            )
-            quoted_view_name = quote_sqlite_identifier(view_name)
-            escaped_symbol = symbol.replace("'", "''")
-            conn.execute(
-                f"CREATE VIEW {quoted_view_name} AS"  # noqa: S608
-                f" SELECT {quoted_columns} FROM rates"
-                f" WHERE symbol = '{escaped_symbol}'"
-                f" AND timeframe = {timeframe}",
-            )
+1266
+1267
+1268
+1269
+1270
+1271
+1272
def create_positions_reconstructed_view(
+    conn: sqlite3.Connection,
+    deals_columns: set[str],
+) -> bool:
+    """Create the positions_reconstructed SQLite view derived from history_deals.
+
+    Returns:
+        True if the view was created, False if required columns are missing.
+    """
+    if not _POSITIONS_VIEW_REQUIRED_COLUMNS.issubset(deals_columns):
+        missing = ", ".join(sorted(_POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns))
+        logger.warning(
+            "Skipping positions_reconstructed view: history_deals missing columns: %s",
+            missing,
+        )
+        return False
+    conn.execute("DROP VIEW IF EXISTS positions_reconstructed")
+    conn.execute(
+        "CREATE VIEW positions_reconstructed AS"  # noqa: S608
+        " 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,"
+        " SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,"
+        " COUNT(*) AS deals_count"
+        " FROM history_deals"
+        f" WHERE type IN {_TRADE_DEAL_TYPES_SQL} AND position_id != 0"
+        " GROUP BY position_id, symbol"
+        " HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0",
+    )
+    return True
+
+ +
+ + + +
+ + +

+ create_rate_compatibility_views + + +

+
create_rate_compatibility_views(conn: Connection) -> None
+
+ +
+ +

Create rate compatibility views from the normalized rates table.

+ + +
+ Source code in mt5cli/history.py +
def create_rate_compatibility_views(conn: sqlite3.Connection) -> None:
+    """Create rate compatibility views from the normalized rates table."""
+    columns = get_table_columns(conn, Dataset.rates.table_name)
+    if not {"symbol", "timeframe", "time"}.issubset(columns):
+        return
+    drop_rate_compatibility_views(conn)
+    select_columns = sorted(columns - {"symbol", "timeframe"})
+    quoted_columns = ", ".join(f'"{column}"' for column in select_columns)
+    rows = conn.execute(
+        "SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe",
+    ).fetchall()
+    timeframes_by_symbol: dict[str, list[int]] = {}
+    for symbol, timeframe in rows:
+        timeframes_by_symbol.setdefault(str(symbol), []).append(int(timeframe))
+    for symbol, timeframes in timeframes_by_symbol.items():
+        for timeframe in timeframes:
+            granularity = resolve_granularity_name(timeframe)
+            view_name = build_rate_view_name(
+                symbol=symbol,
+                granularity=granularity,
+                granularity_count=len(timeframes),
+                timeframe=timeframe,
+            )
+            quoted_view_name = quote_sqlite_identifier(view_name)
+            escaped_symbol = symbol.replace("'", "''")
+            conn.execute(
+                f"CREATE VIEW {quoted_view_name} AS"  # noqa: S608
+                f" SELECT {quoted_columns} FROM rates"
+                f" WHERE symbol = '{escaped_symbol}'"
+                f" AND timeframe = {timeframe}",
+            )
 
@@ -1474,97 +1474,97 @@ 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")
+              
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")
 
@@ -1620,73 +1620,73 @@ unscoped deduplication pass instead.

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(f'"{column}"' for column in ids)
-    rowid_selector = "MIN" if keep == "first" else "MAX"
-    if scope_where:
-        delete_sql = (
-            f"DELETE FROM {table} WHERE {scope_where} AND ROWID NOT IN"  # noqa: S608
-            f" (SELECT {rowid_selector}(ROWID) FROM {table} WHERE {scope_where}"
-            f" GROUP BY {ids_csv})"
-        )
-        cursor.execute(delete_sql, scope_params + scope_params)
-        return
-    cursor.execute(
-        f"DELETE FROM {table} WHERE ROWID NOT IN"  # noqa: S608
-        f" (SELECT {rowid_selector}(ROWID) FROM {table} GROUP BY {ids_csv})",
-    )
+              
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(f'"{column}"' for column in ids)
+    rowid_selector = "MIN" if keep == "first" else "MAX"
+    if scope_where:
+        delete_sql = (
+            f"DELETE FROM {table} WHERE {scope_where} AND ROWID NOT IN"  # noqa: S608
+            f" (SELECT {rowid_selector}(ROWID) FROM {table} WHERE {scope_where}"
+            f" GROUP BY {ids_csv})"
+        )
+        cursor.execute(delete_sql, scope_params + scope_params)
+        return
+    cursor.execute(
+        f"DELETE FROM {table} WHERE ROWID NOT IN"  # noqa: S608
+        f" (SELECT {rowid_selector}(ROWID) FROM {table} GROUP BY {ids_csv})",
+    )
 
@@ -1711,21 +1711,21 @@ unscoped deduplication pass instead.

Source code in mt5cli/history.py -
def drop_rate_compatibility_views(conn: sqlite3.Connection) -> None:
-    """Drop all mt5cli-managed ``rate_*`` compatibility views."""
-    rows = conn.execute(
-        "SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'",
-    ).fetchall()
-    for (view_name,) in rows:
-        quoted_view_name = quote_sqlite_identifier(str(view_name))
-        conn.execute(f"DROP VIEW IF EXISTS {quoted_view_name}")
+              
def drop_rate_compatibility_views(conn: sqlite3.Connection) -> None:
+    """Drop all mt5cli-managed ``rate_*`` compatibility views."""
+    rows = conn.execute(
+        "SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'",
+    ).fetchall()
+    for (view_name,) in rows:
+        quoted_view_name = quote_sqlite_identifier(str(view_name))
+        conn.execute(f"DROP VIEW IF EXISTS {quoted_view_name}")
 
@@ -1788,61 +1788,61 @@ unscoped deduplication pass instead.

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()
-    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()
+              
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()
+    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()
 
@@ -1895,41 +1895,41 @@ unscoped deduplication pass instead.

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()
+              
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()
 
@@ -1956,47 +1956,47 @@ unscoped deduplication pass instead.

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."""
-    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
-    row = conn.execute(
-        f"SELECT MAX(time) FROM {table} WHERE {where_clause}",  # noqa: S608
-    ).fetchone()
-    parsed = parse_sqlite_timestamp(row[0] if row else None)
-    return parsed if parsed is not None else fallback_start
+              
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."""
+    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
+    row = conn.execute(
+        f"SELECT MAX(time) FROM {table} WHERE {where_clause}",  # noqa: S608
+    ).fetchone()
+    parsed = parse_sqlite_timestamp(row[0] if row else None)
+    return parsed if parsed is not None else fallback_start
 
@@ -2028,41 +2028,41 @@ unscoped deduplication pass instead.

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]
+              
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]
 
@@ -2087,15 +2087,15 @@ unscoped deduplication pass instead.

Source code in mt5cli/history.py -
def get_table_columns(conn: sqlite3.Connection, table: str) -> set[str]:
-    """Return existing SQLite columns for a table."""
-    quoted_table = quote_sqlite_identifier(table)
-    rows = conn.execute(f"PRAGMA table_info({quoted_table})").fetchall()
-    return {str(row[1]) for row in rows}
+              
def get_table_columns(conn: sqlite3.Connection, table: str) -> set[str]:
+    """Return existing SQLite columns for a table."""
+    quoted_table = quote_sqlite_identifier(table)
+    rows = conn.execute(f"PRAGMA table_info({quoted_table})").fetchall()
+    return {str(row[1]) for row in rows}
 
@@ -2127,56 +2127,7 @@ unscoped deduplication pass instead.

Source code in mt5cli/history.py -
787
-788
-789
-790
-791
-792
-793
-794
-795
-796
-797
-798
-799
-800
-801
-802
-803
-804
-805
-806
-807
-808
-809
-810
-811
-812
-813
-814
-815
-816
-817
-818
-819
-820
-821
-822
-823
-824
-825
-826
-827
-828
-829
-830
-831
-832
-833
-834
-835
-836
+              
836
 837
 838
 839
@@ -2200,80 +2151,129 @@ unscoped deduplication pass instead.

857 858 859 -860
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."""
-    table = dataset.table_name
-    columns = get_table_columns(conn, table)
-    if dataset is Dataset.rates and columns:
-        _validate_rates_schema(columns)
-
-    if "time" not in 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}
-
-    parsed_by_key: dict[tuple[str, int | None], datetime] = {}
-    if (
-        dataset is Dataset.rates
-        and timeframes is not None
-        and {"symbol", "timeframe"}.issubset(columns)
-    ):
-        symbol_placeholders = ", ".join("?" for _ in symbols)
-        timeframe_placeholders = ", ".join("?" for _ in timeframes)
-        grouped_rates_query = (
-            "SELECT symbol, timeframe, MAX(time) FROM "  # noqa: S608
-            f"{table} WHERE symbol IN ({symbol_placeholders})"
-            f" AND timeframe IN ({timeframe_placeholders})"
-            " GROUP BY symbol, timeframe"
-        )
-        rows = conn.execute(
-            grouped_rates_query,
-            [*symbols, *timeframes],
-        ).fetchall()
-        for row_symbol, row_timeframe, max_time in rows:
-            parsed = parse_sqlite_timestamp(max_time)
-            if parsed is not None:
-                parsed_by_key[str(row_symbol), int(row_timeframe)] = parsed
-        return {
-            (symbol, timeframe): parsed_by_key.get(
-                (symbol, timeframe),
-                fallback_start,
-            )
-            for symbol in symbols
-            for timeframe in timeframes
-        }
-
-    if "symbol" in columns:
-        symbol_placeholders = ", ".join("?" for _ in symbols)
-        rows = conn.execute(
-            f"SELECT symbol, MAX(time) FROM {table}"  # noqa: S608
-            f" WHERE symbol IN ({symbol_placeholders}) GROUP BY symbol",
-            list(symbols),
-        ).fetchall()
-        for row_symbol, max_time in rows:
-            parsed = parse_sqlite_timestamp(max_time)
-            if parsed is not None:
-                parsed_by_key[str(row_symbol), None] = parsed
-        return {
-            (symbol, None): parsed_by_key.get((symbol, None), fallback_start)
-            for symbol in symbols
-        }
-
-    row = conn.execute(f"SELECT MAX(time) FROM {table}").fetchone()  # noqa: S608
-    parsed = parse_sqlite_timestamp(row[0] if row else None)
-    shared_start = parsed if parsed is not None else fallback_start
-    return {(symbol, None): shared_start for symbol in symbols}
+860
+861
+862
+863
+864
+865
+866
+867
+868
+869
+870
+871
+872
+873
+874
+875
+876
+877
+878
+879
+880
+881
+882
+883
+884
+885
+886
+887
+888
+889
+890
+891
+892
+893
+894
+895
+896
+897
+898
+899
+900
+901
+902
+903
+904
+905
+906
+907
+908
+909
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."""
+    table = dataset.table_name
+    columns = get_table_columns(conn, table)
+    if dataset is Dataset.rates and columns:
+        _validate_rates_schema(columns)
+
+    if "time" not in 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}
+
+    parsed_by_key: dict[tuple[str, int | None], datetime] = {}
+    if (
+        dataset is Dataset.rates
+        and timeframes is not None
+        and {"symbol", "timeframe"}.issubset(columns)
+    ):
+        symbol_placeholders = ", ".join("?" for _ in symbols)
+        timeframe_placeholders = ", ".join("?" for _ in timeframes)
+        grouped_rates_query = (
+            "SELECT symbol, timeframe, MAX(time) FROM "  # noqa: S608
+            f"{table} WHERE symbol IN ({symbol_placeholders})"
+            f" AND timeframe IN ({timeframe_placeholders})"
+            " GROUP BY symbol, timeframe"
+        )
+        rows = conn.execute(
+            grouped_rates_query,
+            [*symbols, *timeframes],
+        ).fetchall()
+        for row_symbol, row_timeframe, max_time in rows:
+            parsed = parse_sqlite_timestamp(max_time)
+            if parsed is not None:
+                parsed_by_key[str(row_symbol), int(row_timeframe)] = parsed
+        return {
+            (symbol, timeframe): parsed_by_key.get(
+                (symbol, timeframe),
+                fallback_start,
+            )
+            for symbol in symbols
+            for timeframe in timeframes
+        }
+
+    if "symbol" in columns:
+        symbol_placeholders = ", ".join("?" for _ in symbols)
+        rows = conn.execute(
+            f"SELECT symbol, MAX(time) FROM {table}"  # noqa: S608
+            f" WHERE symbol IN ({symbol_placeholders}) GROUP BY symbol",
+            list(symbols),
+        ).fetchall()
+        for row_symbol, max_time in rows:
+            parsed = parse_sqlite_timestamp(max_time)
+            if parsed is not None:
+                parsed_by_key[str(row_symbol), None] = parsed
+        return {
+            (symbol, None): parsed_by_key.get((symbol, None), fallback_start)
+            for symbol in symbols
+        }
+
+    row = conn.execute(f"SELECT MAX(time) FROM {table}").fetchone()  # noqa: S608
+    parsed = parse_sqlite_timestamp(row[0] if row else None)
+    shared_start = parsed if parsed is not None else fallback_start
+    return {(symbol, None): shared_start for symbol in symbols}
 
@@ -2675,6 +2675,311 @@ or view contains no rows.

+

+ load_rate_series_by_granularity + + +

+
load_rate_series_by_granularity(
+    conn_or_path: SqliteConnOrPath,
+    symbols: Sequence[str],
+    granularities: Sequence[int | str],
+    count: int,
+    *,
+    explicit_tables: Sequence[str] | None = None,
+    allow_missing_symbol: bool = False,
+) -> dict[tuple[str | None, str], DataFrame]
+
+ +
+ +

Load rate series keyed by symbol and string granularity name.

+

Builds targets with :func:build_rate_targets and loads them with +:func:load_rate_series_from_sqlite, then rekeys the result by granularity +name (for example M1) instead of the integer timeframe to reduce +downstream boilerplate.

+ + +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
+ conn_or_path + + SqliteConnOrPath + +
+

SQLite database path or open connection.

+
+
+ required +
+ symbols + + Sequence[str] + +
+

MT5 symbol names. May be empty when allow_missing_symbol.

+
+
+ required +
+ granularities + + Sequence[int | str] + +
+

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

+
+
+ required +
+ count + + int + +
+

Number of most recent rows to load per series.

+
+
+ required +
+ explicit_tables + + Sequence[str] | None + +
+

Optional explicit table or view names matching the +built targets in row-major order. Required when symbols are omitted.

+
+
+ None +
+ allow_missing_symbol + + bool + +
+

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

+
+
+ False +
+ + +

Returns:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
TypeDescription
+ dict[tuple[str | None, str], DataFrame] + +
+

Mapping keyed by (symbol | None, granularity_name) to each rate

+
+
+ dict[tuple[str | None, str], DataFrame] + +
+

DataFrame. Propagates ValueError (via :func:build_rate_targets and

+
+
+ dict[tuple[str | None, str], DataFrame] + +
+

func:load_rate_series_from_sqlite) when inputs are empty or invalid,

+
+
+ dict[tuple[str | None, str], DataFrame] + +
+

table resolution fails, or duplicate targets are present.

+
+
+ + +
+ Source code in mt5cli/history.py +
def load_rate_series_by_granularity(
+    conn_or_path: SqliteConnOrPath,
+    symbols: Sequence[str],
+    granularities: Sequence[int | str],
+    count: int,
+    *,
+    explicit_tables: Sequence[str] | None = None,
+    allow_missing_symbol: bool = False,
+) -> dict[tuple[str | None, str], pd.DataFrame]:
+    """Load rate series keyed by symbol and string granularity name.
+
+    Builds targets with :func:`build_rate_targets` and loads them with
+    :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity
+    name (for example ``M1``) instead of the integer timeframe to reduce
+    downstream boilerplate.
+
+    Args:
+        conn_or_path: SQLite database path or open connection.
+        symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``.
+        granularities: MT5 timeframes as integers or names (for example ``M1``).
+        count: Number of most recent rows to load per series.
+        explicit_tables: Optional explicit table or view names matching the
+            built targets in row-major order. Required when symbols are omitted.
+        allow_missing_symbol: When True and ``symbols`` is empty, build targets
+            with ``symbol=None`` for each granularity instead of raising.
+
+    Returns:
+        Mapping keyed by ``(symbol | None, granularity_name)`` to each rate
+        DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and
+        :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid,
+        table resolution fails, or duplicate targets are present.
+    """
+    targets = build_rate_targets(
+        symbols,
+        granularities,
+        allow_missing_symbol=allow_missing_symbol,
+    )
+    series = load_rate_series_from_sqlite(
+        conn_or_path,
+        targets,
+        count,
+        explicit_tables=explicit_tables,
+    )
+    return {
+        (symbol, resolve_granularity_name(timeframe)): frame
+        for (symbol, timeframe), frame in series.items()
+    }
+
+
+
+ +
+ +
+ +

load_rate_series_from_sqlite @@ -3029,37 +3334,37 @@ fails.

Source code in mt5cli/history.py -
def parse_sqlite_timestamp(value: object) -> datetime | None:
-    """Parse a SQLite history timestamp value.
-
-    Returns:
-        Parsed timezone-aware datetime, or None when parsing fails.
-    """
-    if value is None:
-        return None
-    if isinstance(value, datetime):
-        return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
-    if isinstance(value, int | float):
-        return datetime.fromtimestamp(float(value), tz=UTC)
-    if isinstance(value, str):
-        return _parse_string_sqlite_timestamp(value)
-    logger.warning("Ignoring unsupported history timestamp type: %s", type(value))
-    return None
+              
def parse_sqlite_timestamp(value: object) -> datetime | None:
+    """Parse a SQLite history timestamp value.
+
+    Returns:
+        Parsed timezone-aware datetime, or None when parsing fails.
+    """
+    if value is None:
+        return None
+    if isinstance(value, datetime):
+        return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+    if isinstance(value, int | float):
+        return datetime.fromtimestamp(float(value), tz=UTC)
+    if isinstance(value, str):
+        return _parse_string_sqlite_timestamp(value)
+    logger.warning("Ignoring unsupported history timestamp type: %s", type(value))
+    return None
 
@@ -3117,27 +3422,27 @@ fails.

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
+              
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
 
@@ -4333,56 +4638,7 @@ default view names are returned without creating a database file.

Source code in mt5cli/history.py -
1728
-1729
-1730
-1731
-1732
-1733
-1734
-1735
-1736
-1737
-1738
-1739
-1740
-1741
-1742
-1743
-1744
-1745
-1746
-1747
-1748
-1749
-1750
-1751
-1752
-1753
-1754
-1755
-1756
-1757
-1758
-1759
-1760
-1761
-1762
-1763
-1764
-1765
-1766
-1767
-1768
-1769
-1770
-1771
-1772
-1773
-1774
-1775
-1776
-1777
+              
1777
 1778
 1779
 1780
@@ -4397,71 +4653,120 @@ default view names are returned without creating a database file.

1789 1790 1791 -1792
def write_collected_datasets(
-    conn: sqlite3.Connection,
-    client: Mt5DataClient,
-    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.
-    """
-    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_get_as_df,
-        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_get_as_df,
-        Dataset.history_deals,
-        symbols,
-        date_from,
-        date_to,
-        if_exists,
-        written_columns,
-        include_account_events=False,
-    ):
-        written_tables.add(Dataset.history_deals)
-    return written_tables, written_columns
+1792
+1793
+1794
+1795
+1796
+1797
+1798
+1799
+1800
+1801
+1802
+1803
+1804
+1805
+1806
+1807
+1808
+1809
+1810
+1811
+1812
+1813
+1814
+1815
+1816
+1817
+1818
+1819
+1820
+1821
+1822
+1823
+1824
+1825
+1826
+1827
+1828
+1829
+1830
+1831
+1832
+1833
+1834
+1835
+1836
+1837
+1838
+1839
+1840
+1841
def write_collected_datasets(
+    conn: sqlite3.Connection,
+    client: Mt5DataClient,
+    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.
+    """
+    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_get_as_df,
+        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_get_as_df,
+        Dataset.history_deals,
+        symbols,
+        date_from,
+        date_to,
+        if_exists,
+        written_columns,
+        include_account_events=False,
+    ):
+        written_tables.add(Dataset.history_deals)
+    return written_tables, written_columns
 
@@ -4520,101 +4825,101 @@ default view names are returned without creating a database file.

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.
-    """
-    table_exists = False
-    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,
-            if_exists,
-            written_columns,
-        )
-    for sym in symbols:
-        frame = fetch(date_from=date_from, date_to=date_to, symbol=sym)
-        frame = filter_trade_history_frame(
-            frame,
-            [sym],
-            include_account_events=False,
-        )
-        table_exists = write_streamed_frame(
-            conn,
-            frame,
-            dataset,
-            table_exists,
-            if_exists,
-            written_columns,
-        )
-    return table_exists
+              
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.
+    """
+    table_exists = False
+    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,
+            if_exists,
+            written_columns,
+        )
+    for sym in symbols:
+        frame = fetch(date_from=date_from, date_to=date_to, symbol=sym)
+        frame = filter_trade_history_frame(
+            frame,
+            [sym],
+            include_account_events=False,
+        )
+        table_exists = write_streamed_frame(
+            conn,
+            frame,
+            dataset,
+            table_exists,
+            if_exists,
+            written_columns,
+        )
+    return table_exists
 
@@ -4676,56 +4981,7 @@ default view names are returned without creating a database file.

Source code in mt5cli/history.py -
1645
-1646
-1647
-1648
-1649
-1650
-1651
-1652
-1653
-1654
-1655
-1656
-1657
-1658
-1659
-1660
-1661
-1662
-1663
-1664
-1665
-1666
-1667
-1668
-1669
-1670
-1671
-1672
-1673
-1674
-1675
-1676
-1677
-1678
-1679
-1680
-1681
-1682
-1683
-1684
-1685
-1686
-1687
-1688
-1689
-1690
-1691
-1692
-1693
-1694
+              
1694
 1695
 1696
 1697
@@ -4756,87 +5012,136 @@ default view names are returned without creating a database file.

1722 1723 1724 -1725
def write_incremental_datasets(  # noqa: PLR0913
-    conn: sqlite3.Connection,
-    client: Mt5DataClient,
-    symbols: Sequence[str],
-    selected_datasets: set[Dataset],
-    resolved_timeframes: list[int],
-    resolved_tick_flags: int,
-    fallback_start: datetime,
-    end_date: datetime,
-    *,
-    deduplicate: bool,
-    create_rate_views: 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.
-    """
-    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,
-        )
-    _finalize_incremental_writes(
-        conn,
-        selected_datasets,
-        written_columns,
-        written_tables,
-        dedup_scopes,
-        deduplicate=deduplicate,
-        create_rate_views=create_rate_views,
-        with_views=with_views,
-    )
-    return written_tables, written_columns
+1725
+1726
+1727
+1728
+1729
+1730
+1731
+1732
+1733
+1734
+1735
+1736
+1737
+1738
+1739
+1740
+1741
+1742
+1743
+1744
+1745
+1746
+1747
+1748
+1749
+1750
+1751
+1752
+1753
+1754
+1755
+1756
+1757
+1758
+1759
+1760
+1761
+1762
+1763
+1764
+1765
+1766
+1767
+1768
+1769
+1770
+1771
+1772
+1773
+1774
def write_incremental_datasets(  # noqa: PLR0913
+    conn: sqlite3.Connection,
+    client: Mt5DataClient,
+    symbols: Sequence[str],
+    selected_datasets: set[Dataset],
+    resolved_timeframes: list[int],
+    resolved_tick_flags: int,
+    fallback_start: datetime,
+    end_date: datetime,
+    *,
+    deduplicate: bool,
+    create_rate_views: 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.
+    """
+    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,
+        )
+    _finalize_incremental_writes(
+        conn,
+        selected_datasets,
+        written_columns,
+        written_tables,
+        dedup_scopes,
+        deduplicate=deduplicate,
+        create_rate_views=create_rate_views,
+        with_views=with_views,
+    )
+    return written_tables, written_columns
 
@@ -4893,75 +5198,75 @@ default view names are returned without creating a database file.

Source code in mt5cli/history.py -
def write_rates_dataset(
-    conn: sqlite3.Connection,
-    client: Mt5DataClient,
-    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.
-    """
-    table_exists = False
-    for sym in symbols:
-        frame = client.copy_rates_range_as_df(
-            symbol=sym,
-            timeframe=timeframe,
-            date_from=date_from,
-            date_to=date_to,
-        ).drop(columns=["symbol", "timeframe"], errors="ignore")
-        if len(frame.columns) != 0:
-            frame.insert(0, "symbol", sym)
-            frame.insert(1, "timeframe", timeframe)
-        table_exists = write_streamed_frame(
-            conn,
-            frame,
-            Dataset.rates,
-            table_exists,
-            if_exists,
-            written_columns,
-        )
-    return table_exists
+              
def write_rates_dataset(
+    conn: sqlite3.Connection,
+    client: Mt5DataClient,
+    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.
+    """
+    table_exists = False
+    for sym in symbols:
+        frame = client.copy_rates_range_as_df(
+            symbol=sym,
+            timeframe=timeframe,
+            date_from=date_from,
+            date_to=date_to,
+        ).drop(columns=["symbol", "timeframe"], errors="ignore")
+        if len(frame.columns) != 0:
+            frame.insert(0, "symbol", sym)
+            frame.insert(1, "timeframe", timeframe)
+        table_exists = write_streamed_frame(
+            conn,
+            frame,
+            Dataset.rates,
+            table_exists,
+            if_exists,
+            written_columns,
+        )
+    return table_exists
 
@@ -5016,41 +5321,41 @@ default view names are returned without creating a database file.

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.
-    """
-    write_mode = IfExists.APPEND if table_exists else if_exists
-    if append_dataframe(conn, frame, dataset.table_name, write_mode):
-        record_written_columns(written_columns, dataset, frame)
-        return True
-    return table_exists
+              
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.
+    """
+    write_mode = IfExists.APPEND if table_exists else if_exists
+    if append_dataframe(conn, frame, dataset.table_name, write_mode):
+        record_written_columns(written_columns, dataset, frame)
+        return True
+    return table_exists
 
@@ -5107,73 +5412,73 @@ default view names are returned without creating a database file.

Source code in mt5cli/history.py -
def write_ticks_dataset(
-    conn: sqlite3.Connection,
-    client: Mt5DataClient,
-    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.
-    """
-    table_exists = False
-    for sym in symbols:
-        frame = client.copy_ticks_range_as_df(
-            symbol=sym,
-            date_from=date_from,
-            date_to=date_to,
-            flags=flags,
-        ).drop(columns=["symbol"], errors="ignore")
-        if len(frame.columns) != 0:
-            frame.insert(0, "symbol", sym)
-        table_exists = write_streamed_frame(
-            conn,
-            frame,
-            Dataset.ticks,
-            table_exists,
-            if_exists,
-            written_columns,
-        )
-    return table_exists
+              
def write_ticks_dataset(
+    conn: sqlite3.Connection,
+    client: Mt5DataClient,
+    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.
+    """
+    table_exists = False
+    for sym in symbols:
+        frame = client.copy_ticks_range_as_df(
+            symbol=sym,
+            date_from=date_from,
+            date_to=date_to,
+            flags=flags,
+        ).drop(columns=["symbol"], errors="ignore")
+        if len(frame.columns) != 0:
+            frame.insert(0, "symbol", sym)
+        table_exists = write_streamed_frame(
+            conn,
+            frame,
+            Dataset.ticks,
+            table_exists,
+            if_exists,
+            written_columns,
+        )
+    return table_exists
 
@@ -5415,7 +5720,17 @@ compatibility-view rules, or you can pass explicit_tables to bypass requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. - +
  • load_rate_series_by_granularity() is a thin wrapper that builds the targets, + loads the series, and rekeys the result by granularity name to avoid + converting integer timeframes downstream:
  • + +
    from mt5cli import load_rate_series_by_granularity
    +
    +series = load_rate_series_by_granularity(
    +    "history.db", ["EURUSD"], ["M1", "H1"], count=1000
    +)
    +frame = series["EURUSD", "M1"]  # keyed by (symbol | None, granularity_name)
    +
    diff --git a/api/sdk/index.html b/api/sdk/index.html index f334cd0..950a170 100644 --- a/api/sdk/index.html +++ b/api/sdk/index.html @@ -108,6 +108,10 @@ + @@ -188,37 +192,42 @@
    __all__ = [
         "AccountSpec",
         "Mt5CliClient",
    -    "account_info",
    -    "build_config",
    -    "collect_history",
    -    "collect_latest_rates",
    -    "collect_latest_rates_for_accounts",
    -    "copy_rates_from",
    -    "copy_rates_from_pos",
    -    "copy_rates_range",
    -    "copy_ticks_from",
    -    "copy_ticks_range",
    -    "history_deals",
    -    "history_orders",
    -    "last_error",
    -    "latest_rates",
    -    "market_book",
    -    "minimum_margins",
    -    "mt5_session",
    -    "mt5_summary",
    -    "mt5_summary_as_df",
    -    "orders",
    -    "positions",
    -    "recent_history_deals",
    -    "recent_ticks",
    -    "symbol_info",
    -    "symbol_info_tick",
    -    "symbols",
    -    "terminal_info",
    -    "update_history",
    -    "update_history_with_config",
    -    "version",
    -]
    +    "ThrottledHistoryUpdater",
    +    "account_info",
    +    "build_config",
    +    "collect_history",
    +    "collect_latest_rates",
    +    "collect_latest_rates_for_accounts",
    +    "collect_latest_rates_for_accounts_with_retries",
    +    "copy_rates_from",
    +    "copy_rates_from_pos",
    +    "copy_rates_range",
    +    "copy_ticks_from",
    +    "copy_ticks_range",
    +    "history_deals",
    +    "history_orders",
    +    "last_error",
    +    "latest_rates",
    +    "market_book",
    +    "minimum_margins",
    +    "mt5_session",
    +    "mt5_summary",
    +    "mt5_summary_as_df",
    +    "orders",
    +    "positions",
    +    "recent_history_deals",
    +    "recent_ticks",
    +    "resolve_account_spec",
    +    "resolve_account_specs",
    +    "substitute_env_placeholders",
    +    "symbol_info",
    +    "symbol_info_tick",
    +    "symbols",
    +    "terminal_info",
    +    "update_history",
    +    "update_history_with_config",
    +    "version",
    +]
     
    @@ -428,7 +437,7 @@ non-empty.

    -
    login: int | str | None = None
    +
    login: int | str | None = field(default=None, repr=False)
     
    @@ -728,15 +737,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    306
    -307
    -308
    -309
    -310
    -311
    -312
    -313
    -314
    +                    
    314
     315
     316
     317
    @@ -759,38 +760,46 @@ clients are reused as-is and are not initialized or shut down.

    334 335 336 -337
    def __init__(
    -    self,
    -    *,
    -    path: str | None = None,
    -    login: int | None = None,
    -    password: str | None = None,
    -    server: str | None = None,
    -    timeout: int | None = None,
    -    config: Mt5Config | None = None,
    -    client: Mt5DataClient | None = None,
    -) -> None:
    -    """Initialize the SDK client.
    -
    -    Args:
    -        path: Path to MetaTrader5 terminal EXE file.
    -        login: Trading account login.
    -        password: Trading account password.
    -        server: Trading server name.
    -        timeout: Connection timeout in milliseconds.
    -        config: Optional pre-built ``Mt5Config`` (overrides other args).
    -        client: Optional already-connected ``Mt5DataClient``. Injected
    -            clients are reused as-is and are not initialized or shut down.
    -    """
    -    self._config = config or build_config(
    -        path=path,
    -        login=login,
    -        password=password,
    -        server=server,
    -        timeout=timeout,
    -    )
    -    self._client = client
    -    self._owns_client = client is None
    +337
    +338
    +339
    +340
    +341
    +342
    +343
    +344
    +345
    def __init__(
    +    self,
    +    *,
    +    path: str | None = None,
    +    login: int | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    timeout: int | None = None,
    +    config: Mt5Config | None = None,
    +    client: Mt5DataClient | None = None,
    +) -> None:
    +    """Initialize the SDK client.
    +
    +    Args:
    +        path: Path to MetaTrader5 terminal EXE file.
    +        login: Trading account login.
    +        password: Trading account password.
    +        server: Trading server name.
    +        timeout: Connection timeout in milliseconds.
    +        config: Optional pre-built ``Mt5Config`` (overrides other args).
    +        client: Optional already-connected ``Mt5DataClient``. Injected
    +            clients are reused as-is and are not initialized or shut down.
    +    """
    +    self._config = config or build_config(
    +        path=path,
    +        login=login,
    +        password=password,
    +        server=server,
    +        timeout=timeout,
    +    )
    +    self._client = client
    +    self._owns_client = client is None
     
    @@ -872,15 +881,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    356
    -357
    -358
    -359
    -360
    -361
    -362
    -363
    -364
    +              
    364
     365
     366
     367
    @@ -888,23 +889,31 @@ clients are reused as-is and are not initialized or shut down.

    369 370 371 -372
    def __enter__(self) -> Self:
    -    """Open a persistent MT5 connection for multiple calls.
    -
    -    Returns:
    -        This client instance.
    -    """
    -    if self._client is not None:
    -        return self
    -    client = Mt5DataClient(config=self._config)
    -    try:
    -        client.initialize_and_login_mt5()
    -    except Exception:
    -        client.shutdown()
    -        raise
    -    self._client = client
    -    self._owns_client = True  # only set when this method created the client
    -    return self
    +372
    +373
    +374
    +375
    +376
    +377
    +378
    +379
    +380
    def __enter__(self) -> Self:
    +    """Open a persistent MT5 connection for multiple calls.
    +
    +    Returns:
    +        This client instance.
    +    """
    +    if self._client is not None:
    +        return self
    +    client = Mt5DataClient(config=self._config)
    +    try:
    +        client.initialize_and_login_mt5()
    +    except Exception:
    +        client.shutdown()
    +        raise
    +    self._client = client
    +    self._owns_client = True  # only set when this method created the client
    +    return self
     
    @@ -933,25 +942,25 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    def __exit__(
    -    self,
    -    exc_type: type[BaseException] | None,
    -    exc: BaseException | None,
    -    tb: object,
    -) -> None:
    -    """Shut down the persistent MT5 connection."""
    -    if self._client is not None and self._owns_client:
    -        self._client.shutdown()
    -        self._client = None
    +              
    def __exit__(
    +    self,
    +    exc_type: type[BaseException] | None,
    +    exc: BaseException | None,
    +    tb: object,
    +) -> None:
    +    """Shut down the persistent MT5 connection."""
    +    if self._client is not None and self._owns_client:
    +        self._client.shutdown()
    +        self._client = None
     
    @@ -976,11 +985,11 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    def account_info(self) -> pd.DataFrame:
    -    """Return account information."""
    -    return self._fetch(lambda c: c.account_info_as_df())
    +              
    def account_info(self) -> pd.DataFrame:
    +    """Return account information."""
    +    return self._fetch(lambda c: c.account_info_as_df())
     
    @@ -1057,15 +1066,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    441
    -442
    -443
    -444
    -445
    -446
    -447
    -448
    -449
    +              
    449
     450
     451
     452
    @@ -1092,42 +1093,50 @@ clients are reused as-is and are not initialized or shut down.

    473 474 475 -476
    def collect_latest_rates(
    -    self,
    -    symbols: Sequence[str],
    -    timeframes: Sequence[int | str],
    -    *,
    -    count: int,
    -    start_pos: int = 0,
    -) -> dict[tuple[str, int], pd.DataFrame]:
    -    """Return latest rates for each symbol/timeframe pair.
    -
    -    Returns:
    -        Mapping keyed by ``(symbol, timeframe_int)``.
    -
    -    Raises:
    -        ValueError: If ``count`` is not positive or inputs are empty.
    -    """
    -    _require_positive(count, "count")
    -    if not symbols:
    -        msg = "At least one symbol is required."
    -        raise ValueError(msg)
    -    if not timeframes:
    -        msg = "At least one timeframe is required."
    -        raise ValueError(msg)
    -    resolved_timeframes = [_coerce_timeframe(timeframe) for timeframe in timeframes]
    -    return self._fetch_value(
    -        lambda c: {
    -            (symbol, timeframe): c.copy_rates_from_pos_as_df(
    -                symbol=symbol,
    -                timeframe=timeframe,
    -                start_pos=start_pos,
    -                count=count,
    -            )
    -            for symbol in symbols
    -            for timeframe in resolved_timeframes
    -        },
    -    )
    +476
    +477
    +478
    +479
    +480
    +481
    +482
    +483
    +484
    def collect_latest_rates(
    +    self,
    +    symbols: Sequence[str],
    +    timeframes: Sequence[int | str],
    +    *,
    +    count: int,
    +    start_pos: int = 0,
    +) -> dict[tuple[str, int], pd.DataFrame]:
    +    """Return latest rates for each symbol/timeframe pair.
    +
    +    Returns:
    +        Mapping keyed by ``(symbol, timeframe_int)``.
    +
    +    Raises:
    +        ValueError: If ``count`` is not positive or inputs are empty.
    +    """
    +    _require_positive(count, "count")
    +    if not symbols:
    +        msg = "At least one symbol is required."
    +        raise ValueError(msg)
    +    if not timeframes:
    +        msg = "At least one timeframe is required."
    +        raise ValueError(msg)
    +    resolved_timeframes = [_coerce_timeframe(timeframe) for timeframe in timeframes]
    +    return self._fetch_value(
    +        lambda c: {
    +            (symbol, timeframe): c.copy_rates_from_pos_as_df(
    +                symbol=symbol,
    +                timeframe=timeframe,
    +                start_pos=start_pos,
    +                count=count,
    +            )
    +            for symbol in symbols
    +            for timeframe in resolved_timeframes
    +        },
    +    )
     
    @@ -1157,15 +1166,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    393
    -394
    -395
    -396
    -397
    -398
    -399
    -400
    -401
    +              
    401
     402
     403
     404
    @@ -1174,24 +1175,32 @@ clients are reused as-is and are not initialized or shut down.

    407 408 409 -410
    def copy_rates_from(
    -    self,
    -    symbol: str,
    -    timeframe: int | str,
    -    date_from: datetime | str,
    -    count: int,
    -) -> pd.DataFrame:
    -    """Return rates starting from a date."""
    -    tf = _coerce_timeframe(timeframe)
    -    start = _require_datetime(date_from)
    -    return self._fetch(
    -        lambda c: c.copy_rates_from_as_df(
    -            symbol=symbol,
    -            timeframe=tf,
    -            date_from=start,
    -            count=count,
    -        ),
    -    )
    +410
    +411
    +412
    +413
    +414
    +415
    +416
    +417
    +418
    def copy_rates_from(
    +    self,
    +    symbol: str,
    +    timeframe: int | str,
    +    date_from: datetime | str,
    +    count: int,
    +) -> pd.DataFrame:
    +    """Return rates starting from a date."""
    +    tf = _coerce_timeframe(timeframe)
    +    start = _require_datetime(date_from)
    +    return self._fetch(
    +        lambda c: c.copy_rates_from_as_df(
    +            symbol=symbol,
    +            timeframe=tf,
    +            date_from=start,
    +            count=count,
    +        ),
    +    )
     
    @@ -1221,15 +1230,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    412
    -413
    -414
    -415
    -416
    -417
    -418
    -419
    -420
    +              
    420
     421
     422
     423
    @@ -1237,23 +1238,31 @@ clients are reused as-is and are not initialized or shut down.

    425 426 427 -428
    def copy_rates_from_pos(
    -    self,
    -    symbol: str,
    -    timeframe: int | str,
    -    start_pos: int,
    -    count: int,
    -) -> pd.DataFrame:
    -    """Return rates starting from a bar position."""
    -    tf = _coerce_timeframe(timeframe)
    -    return self._fetch(
    -        lambda c: c.copy_rates_from_pos_as_df(
    -            symbol=symbol,
    -            timeframe=tf,
    -            start_pos=start_pos,
    -            count=count,
    -        ),
    -    )
    +428
    +429
    +430
    +431
    +432
    +433
    +434
    +435
    +436
    def copy_rates_from_pos(
    +    self,
    +    symbol: str,
    +    timeframe: int | str,
    +    start_pos: int,
    +    count: int,
    +) -> pd.DataFrame:
    +    """Return rates starting from a bar position."""
    +    tf = _coerce_timeframe(timeframe)
    +    return self._fetch(
    +        lambda c: c.copy_rates_from_pos_as_df(
    +            symbol=symbol,
    +            timeframe=tf,
    +            start_pos=start_pos,
    +            count=count,
    +        ),
    +    )
     
    @@ -1283,15 +1292,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    478
    -479
    -480
    -481
    -482
    -483
    -484
    -485
    -486
    +              
    486
     487
     488
     489
    @@ -1301,25 +1302,33 @@ clients are reused as-is and are not initialized or shut down.

    493 494 495 -496
    def copy_rates_range(
    -    self,
    -    symbol: str,
    -    timeframe: int | str,
    -    date_from: datetime | str,
    -    date_to: datetime | str,
    -) -> pd.DataFrame:
    -    """Return rates for a date range."""
    -    tf = _coerce_timeframe(timeframe)
    -    start = _require_datetime(date_from)
    -    end = _require_datetime(date_to)
    -    return self._fetch(
    -        lambda c: c.copy_rates_range_as_df(
    -            symbol=symbol,
    -            timeframe=tf,
    -            date_from=start,
    -            date_to=end,
    -        ),
    -    )
    +496
    +497
    +498
    +499
    +500
    +501
    +502
    +503
    +504
    def copy_rates_range(
    +    self,
    +    symbol: str,
    +    timeframe: int | str,
    +    date_from: datetime | str,
    +    date_to: datetime | str,
    +) -> pd.DataFrame:
    +    """Return rates for a date range."""
    +    tf = _coerce_timeframe(timeframe)
    +    start = _require_datetime(date_from)
    +    end = _require_datetime(date_to)
    +    return self._fetch(
    +        lambda c: c.copy_rates_range_as_df(
    +            symbol=symbol,
    +            timeframe=tf,
    +            date_from=start,
    +            date_to=end,
    +        ),
    +    )
     
    @@ -1349,15 +1358,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    498
    -499
    -500
    -501
    -502
    -503
    -504
    -505
    -506
    +              
    506
     507
     508
     509
    @@ -1366,24 +1367,32 @@ clients are reused as-is and are not initialized or shut down.

    512 513 514 -515
    def copy_ticks_from(
    -    self,
    -    symbol: str,
    -    date_from: datetime | str,
    -    count: int,
    -    flags: int | str,
    -) -> pd.DataFrame:
    -    """Return ticks starting from a date."""
    -    start = _require_datetime(date_from)
    -    tick_flags = _coerce_tick_flags(flags)
    -    return self._fetch(
    -        lambda c: c.copy_ticks_from_as_df(
    -            symbol=symbol,
    -            date_from=start,
    -            count=count,
    -            flags=tick_flags,
    -        ),
    -    )
    +515
    +516
    +517
    +518
    +519
    +520
    +521
    +522
    +523
    def copy_ticks_from(
    +    self,
    +    symbol: str,
    +    date_from: datetime | str,
    +    count: int,
    +    flags: int | str,
    +) -> pd.DataFrame:
    +    """Return ticks starting from a date."""
    +    start = _require_datetime(date_from)
    +    tick_flags = _coerce_tick_flags(flags)
    +    return self._fetch(
    +        lambda c: c.copy_ticks_from_as_df(
    +            symbol=symbol,
    +            date_from=start,
    +            count=count,
    +            flags=tick_flags,
    +        ),
    +    )
     
    @@ -1413,15 +1422,7 @@ clients are reused as-is and are not initialized or shut down.

    Source code in mt5cli/sdk.py -
    517
    -518
    -519
    -520
    -521
    -522
    -523
    -524
    -525
    +              
    525
     526
     527
     528
    @@ -1431,25 +1432,33 @@ clients are reused as-is and are not initialized or shut down.

    532 533 534 -535
    def copy_ticks_range(
    -    self,
    -    symbol: str,
    -    date_from: datetime | str,
    -    date_to: datetime | str,
    -    flags: int | str,
    -) -> pd.DataFrame:
    -    """Return ticks for a date range."""
    -    start = _require_datetime(date_from)
    -    end = _require_datetime(date_to)
    -    tick_flags = _coerce_tick_flags(flags)
    -    return self._fetch(
    -        lambda c: c.copy_ticks_range_as_df(
    -            symbol=symbol,
    -            date_from=start,
    -            date_to=end,
    -            flags=tick_flags,
    -        ),
    -    )
    +535
    +536
    +537
    +538
    +539
    +540
    +541
    +542
    +543
    def copy_ticks_range(
    +    self,
    +    symbol: str,
    +    date_from: datetime | str,
    +    date_to: datetime | str,
    +    flags: int | str,
    +) -> pd.DataFrame:
    +    """Return ticks for a date range."""
    +    start = _require_datetime(date_from)
    +    end = _require_datetime(date_to)
    +    tick_flags = _coerce_tick_flags(flags)
    +    return self._fetch(
    +        lambda c: c.copy_ticks_range_as_df(
    +            symbol=symbol,
    +            date_from=start,
    +            date_to=end,
    +            flags=tick_flags,
    +        ),
    +    )
     
    @@ -1503,27 +1512,27 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    339
    -340
    -341
    -342
    -343
    -344
    -345
    -346
    -347
    +              
    @classmethod
    -def from_connected_client(cls, client: Mt5DataClient) -> Self:
    -    """Bind to an already-connected ``Mt5DataClient`` without owning it.
    -
    -    The returned ``Mt5CliClient`` never initializes or shuts down the
    -    injected client, including when used as a context manager.
    -
    -    Returns:
    -        Client wrapper bound to the injected connection.
    -    """
    -    return cls(client=client)
    +349
    +350
    +351
    +352
    +353
    +354
    +355
    +356
    +357
    @classmethod
    +def from_connected_client(cls, client: Mt5DataClient) -> Self:
    +    """Bind to an already-connected ``Mt5DataClient`` without owning it.
    +
    +    The returned ``Mt5CliClient`` never initializes or shuts down the
    +    injected client, including when used as a context manager.
    +
    +    Returns:
    +        Client wrapper bound to the injected connection.
    +    """
    +    return cls(client=client)
     
    @@ -1555,15 +1564,7 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    606
    -607
    -608
    -609
    -610
    -611
    -612
    -613
    -614
    +              
    614
     615
     616
     617
    @@ -1576,28 +1577,36 @@ injected client, including when used as a context manager.

    624 625 626 -627
    def history_deals(
    -    self,
    -    date_from: datetime | str | None = None,
    -    date_to: datetime | str | None = None,
    -    group: str | None = None,
    -    symbol: str | None = None,
    -    ticket: int | None = None,
    -    position: int | None = None,
    -) -> pd.DataFrame:
    -    """Return historical deals."""
    -    start = _coerce_datetime(date_from)
    -    end = _coerce_datetime(date_to)
    -    return self._fetch(
    -        lambda c: c.history_deals_get_as_df(
    -            date_from=start,
    -            date_to=end,
    -            group=group,
    -            symbol=symbol,
    -            ticket=ticket,
    -            position=position,
    -        ),
    -    )
    +627
    +628
    +629
    +630
    +631
    +632
    +633
    +634
    +635
    def history_deals(
    +    self,
    +    date_from: datetime | str | None = None,
    +    date_to: datetime | str | None = None,
    +    group: str | None = None,
    +    symbol: str | None = None,
    +    ticket: int | None = None,
    +    position: int | None = None,
    +) -> pd.DataFrame:
    +    """Return historical deals."""
    +    start = _coerce_datetime(date_from)
    +    end = _coerce_datetime(date_to)
    +    return self._fetch(
    +        lambda c: c.history_deals_get_as_df(
    +            date_from=start,
    +            date_to=end,
    +            group=group,
    +            symbol=symbol,
    +            ticket=ticket,
    +            position=position,
    +        ),
    +    )
     
    @@ -1629,15 +1638,7 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    583
    -584
    -585
    -586
    -587
    -588
    -589
    -590
    -591
    +              
    591
     592
     593
     594
    @@ -1650,28 +1651,36 @@ injected client, including when used as a context manager.

    601 602 603 -604
    def history_orders(
    -    self,
    -    date_from: datetime | str | None = None,
    -    date_to: datetime | str | None = None,
    -    group: str | None = None,
    -    symbol: str | None = None,
    -    ticket: int | None = None,
    -    position: int | None = None,
    -) -> pd.DataFrame:
    -    """Return historical orders."""
    -    start = _coerce_datetime(date_from)
    -    end = _coerce_datetime(date_to)
    -    return self._fetch(
    -        lambda c: c.history_orders_get_as_df(
    -            date_from=start,
    -            date_to=end,
    -            group=group,
    -            symbol=symbol,
    -            ticket=ticket,
    -            position=position,
    -        ),
    -    )
    +604
    +605
    +606
    +607
    +608
    +609
    +610
    +611
    +612
    def history_orders(
    +    self,
    +    date_from: datetime | str | None = None,
    +    date_to: datetime | str | None = None,
    +    group: str | None = None,
    +    symbol: str | None = None,
    +    ticket: int | None = None,
    +    position: int | None = None,
    +) -> pd.DataFrame:
    +    """Return historical orders."""
    +    start = _coerce_datetime(date_from)
    +    end = _coerce_datetime(date_to)
    +    return self._fetch(
    +        lambda c: c.history_orders_get_as_df(
    +            date_from=start,
    +            date_to=end,
    +            group=group,
    +            symbol=symbol,
    +            ticket=ticket,
    +            position=position,
    +        ),
    +    )
     
    @@ -1696,11 +1705,11 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    def last_error(self) -> pd.DataFrame:
    -    """Return the last error information."""
    -    return self._fetch(lambda c: c.last_error_as_df())
    +              
    def last_error(self) -> pd.DataFrame:
    +    """Return the last error information."""
    +    return self._fetch(lambda c: c.last_error_as_df())
     
    @@ -1730,25 +1739,25 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    def latest_rates(
    -    self,
    -    symbol: str,
    -    timeframe: int | str,
    -    count: int,
    -    start_pos: int = 0,
    -) -> pd.DataFrame:
    -    """Return the latest rates from a bar position."""
    -    _require_positive(count, "count")
    -    return self.copy_rates_from_pos(symbol, timeframe, start_pos, count)
    +              
    def latest_rates(
    +    self,
    +    symbol: str,
    +    timeframe: int | str,
    +    count: int,
    +    start_pos: int = 0,
    +) -> pd.DataFrame:
    +    """Return the latest rates from a bar position."""
    +    _require_positive(count, "count")
    +    return self.copy_rates_from_pos(symbol, timeframe, start_pos, count)
     
    @@ -1773,11 +1782,11 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    def market_book(self, symbol: str) -> pd.DataFrame:
    -    """Return market depth for a symbol."""
    -    return self._fetch(lambda c: c.market_book_get_as_df(symbol=symbol))
    +              
    def market_book(self, symbol: str) -> pd.DataFrame:
    +    """Return market depth for a symbol."""
    +    return self._fetch(lambda c: c.market_book_get_as_df(symbol=symbol))
     
    @@ -1866,27 +1875,27 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    702
    -703
    -704
    -705
    -706
    -707
    -708
    -709
    -710
    +              
    def minimum_margins(self, symbol: str) -> pd.DataFrame:
    -    """Return minimum-volume buy and sell margin requirements.
    -
    -    Args:
    -        symbol: Symbol name.
    -
    -    Returns:
    -        One-row DataFrame with columns ``symbol``, ``account_currency``,
    -        ``volume_min``, ``buy_margin``, and ``sell_margin``.
    -    """
    -    return self._fetch(lambda c: _fetch_minimum_margins(c, symbol))
    +712
    +713
    +714
    +715
    +716
    +717
    +718
    +719
    +720
    def minimum_margins(self, symbol: str) -> pd.DataFrame:
    +    """Return minimum-volume buy and sell margin requirements.
    +
    +    Args:
    +        symbol: Symbol name.
    +
    +    Returns:
    +        One-row DataFrame with columns ``symbol``, ``account_currency``,
    +        ``volume_min``, ``buy_margin``, and ``sell_margin``.
    +    """
    +    return self._fetch(lambda c: _fetch_minimum_margins(c, symbol))
     
    @@ -1911,15 +1920,7 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    714
    -715
    -716
    -717
    -718
    -719
    -720
    -721
    -722
    +              
    722
     723
     724
     725
    @@ -1930,26 +1931,34 @@ injected client, including when used as a context manager.

    730 731 732 -733
    def mt5_summary(self) -> dict[str, object]:
    -    """Return a compact terminal/account status summary."""
    -
    -    def _summary(client: Mt5DataClient) -> dict[str, object]:
    -        return {
    -            "version": _plain_mt5_value(
    -                _call_required_client_method(client, "version"),
    -            ),
    -            "terminal_info": _plain_mt5_value(
    -                _call_required_client_method(client, "terminal_info"),
    -            ),
    -            "account_info": _plain_mt5_value(
    -                _call_required_client_method(client, "account_info"),
    -            ),
    -            "symbols_total": _plain_mt5_value(
    -                _call_required_client_method(client, "symbols_total"),
    -            ),
    -        }
    -
    -    return self._fetch_value(_summary)
    +733
    +734
    +735
    +736
    +737
    +738
    +739
    +740
    +741
    def mt5_summary(self) -> dict[str, object]:
    +    """Return a compact terminal/account status summary."""
    +
    +    def _summary(client: Mt5DataClient) -> dict[str, object]:
    +        return {
    +            "version": _plain_mt5_value(
    +                _call_required_client_method(client, "version"),
    +            ),
    +            "terminal_info": _plain_mt5_value(
    +                _call_required_client_method(client, "terminal_info"),
    +            ),
    +            "account_info": _plain_mt5_value(
    +                _call_required_client_method(client, "account_info"),
    +            ),
    +            "symbols_total": _plain_mt5_value(
    +                _call_required_client_method(client, "symbols_total"),
    +            ),
    +        }
    +
    +    return self._fetch_value(_summary)
     
    @@ -1974,27 +1983,27 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    735
    -736
    -737
    -738
    -739
    -740
    -741
    -742
    -743
    +              
    def mt5_summary_as_df(self) -> pd.DataFrame:
    -    """Return an export-safe one-row terminal/account summary DataFrame."""
    -    summary = self.mt5_summary()
    -    return pd.DataFrame(
    -        [
    -            {
    -                key: _mt5_summary_export_value(value)
    -                for key, value in summary.items()
    -            },
    -        ],
    -    )
    +745
    +746
    +747
    +748
    +749
    +750
    +751
    +752
    +753
    def mt5_summary_as_df(self) -> pd.DataFrame:
    +    """Return an export-safe one-row terminal/account summary DataFrame."""
    +    summary = self.mt5_summary()
    +    return pd.DataFrame(
    +        [
    +            {
    +                key: _mt5_summary_export_value(value)
    +                for key, value in summary.items()
    +            },
    +        ],
    +    )
     
    @@ -2023,33 +2032,33 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    553
    -554
    -555
    -556
    -557
    -558
    -559
    -560
    -561
    +              
    def orders(
    -    self,
    -    symbol: str | None = None,
    -    group: str | None = None,
    -    ticket: int | None = None,
    -) -> pd.DataFrame:
    -    """Return active orders."""
    -    return self._fetch(
    -        lambda c: c.orders_get_as_df(
    -            symbol=symbol,
    -            group=group,
    -            ticket=ticket,
    -        ),
    -    )
    +566
    +567
    +568
    +569
    +570
    +571
    +572
    +573
    +574
    def orders(
    +    self,
    +    symbol: str | None = None,
    +    group: str | None = None,
    +    ticket: int | None = None,
    +) -> pd.DataFrame:
    +    """Return active orders."""
    +    return self._fetch(
    +        lambda c: c.orders_get_as_df(
    +            symbol=symbol,
    +            group=group,
    +            ticket=ticket,
    +        ),
    +    )
     
    @@ -2078,33 +2087,33 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    568
    -569
    -570
    -571
    -572
    -573
    -574
    -575
    -576
    +              
    def positions(
    -    self,
    -    symbol: str | None = None,
    -    group: str | None = None,
    -    ticket: int | None = None,
    -) -> pd.DataFrame:
    -    """Return open positions."""
    -    return self._fetch(
    -        lambda c: c.positions_get_as_df(
    -            symbol=symbol,
    -            group=group,
    -            ticket=ticket,
    -        ),
    -    )
    +581
    +582
    +583
    +584
    +585
    +586
    +587
    +588
    +589
    def positions(
    +    self,
    +    symbol: str | None = None,
    +    group: str | None = None,
    +    ticket: int | None = None,
    +) -> pd.DataFrame:
    +    """Return open positions."""
    +    return self._fetch(
    +        lambda c: c.positions_get_as_df(
    +            symbol=symbol,
    +            group=group,
    +            ticket=ticket,
    +        ),
    +    )
     
    @@ -2134,15 +2143,7 @@ injected client, including when used as a context manager.

    Source code in mt5cli/sdk.py -
    629
    -630
    -631
    -632
    -633
    -634
    -635
    -636
    -637
    +              
    637
     638
     639
     640
    @@ -2150,23 +2151,31 @@ injected client, including when used as a context manager.

    642 643 644 -645
    def recent_history_deals(
    -    self,
    -    hours: float,
    -    date_to: datetime | str | None = None,
    -    group: str | None = None,
    -    symbol: str | None = None,
    -) -> pd.DataFrame:
    -    """Return historical deals from a recent trailing window."""
    -    _require_positive(hours, "hours")
    -    end = _require_datetime(date_to) if date_to is not None else datetime.now(UTC)
    -    start = end - timedelta(hours=hours)
    -    return self.history_deals(
    -        date_from=start,
    -        date_to=end,
    -        group=group,
    -        symbol=symbol,
    -    )
    +645
    +646
    +647
    +648
    +649
    +650
    +651
    +652
    +653
    def recent_history_deals(
    +    self,
    +    hours: float,
    +    date_to: datetime | str | None = None,
    +    group: str | None = None,
    +    symbol: str | None = None,
    +) -> pd.DataFrame:
    +    """Return historical deals from a recent trailing window."""
    +    _require_positive(hours, "hours")
    +    end = _require_datetime(date_to) if date_to is not None else datetime.now(UTC)
    +    start = end - timedelta(hours=hours)
    +    return self.history_deals(
    +        date_from=start,
    +        date_to=end,
    +        group=group,
    +        symbol=symbol,
    +    )
     
    @@ -2330,15 +2339,7 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    663
    -664
    -665
    -666
    -667
    -668
    -669
    -670
    -671
    +              
    671
     672
     673
     674
    @@ -2367,44 +2368,52 @@ fetching the entire range.

    697 698 699 -700
    def recent_ticks(
    -    self,
    -    symbol: str,
    -    seconds: float,
    -    *,
    -    date_to: datetime | str | None = None,
    -    count: int = 10000,
    -    flags: int | str = "ALL",
    -) -> pd.DataFrame:
    -    """Return ticks from a recent time window.
    -
    -    Args:
    -        symbol: Symbol name.
    -        seconds: Lookback window in seconds ending at ``date_to``.
    -        date_to: Window end time. When ``None``, uses the latest
    -            ``symbol_info_tick().time`` rather than wall-clock now.
    -        count: Maximum ticks to return. Values ``<= 0`` return the full
    -            window without trimming. Positive values keep the most recent
    -            ticks; when the window is sparse, ``copy_ticks_from`` avoids
    -            fetching the entire range.
    -        flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer.
    -
    -    Returns:
    -        Tick DataFrame with MT5 tick columns such as ``time``, ``bid``,
    -        ``ask``, ``last``, and ``volume``.
    -    """
    -    tick_flags = _coerce_tick_flags(flags)
    -    end = _coerce_datetime(date_to)
    -    return self._fetch(
    -        lambda c: _fetch_recent_ticks(
    -            c,
    -            symbol,
    -            seconds,
    -            end,
    -            count,
    -            tick_flags,
    -        ),
    -    )
    +700
    +701
    +702
    +703
    +704
    +705
    +706
    +707
    +708
    def recent_ticks(
    +    self,
    +    symbol: str,
    +    seconds: float,
    +    *,
    +    date_to: datetime | str | None = None,
    +    count: int = 10000,
    +    flags: int | str = "ALL",
    +) -> pd.DataFrame:
    +    """Return ticks from a recent time window.
    +
    +    Args:
    +        symbol: Symbol name.
    +        seconds: Lookback window in seconds ending at ``date_to``.
    +        date_to: Window end time. When ``None``, uses the latest
    +            ``symbol_info_tick().time`` rather than wall-clock now.
    +        count: Maximum ticks to return. Values ``<= 0`` return the full
    +            window without trimming. Positive values keep the most recent
    +            ticks; when the window is sparse, ``copy_ticks_from`` avoids
    +            fetching the entire range.
    +        flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer.
    +
    +    Returns:
    +        Tick DataFrame with MT5 tick columns such as ``time``, ``bid``,
    +        ``ask``, ``last``, and ``volume``.
    +    """
    +    tick_flags = _coerce_tick_flags(flags)
    +    end = _coerce_datetime(date_to)
    +    return self._fetch(
    +        lambda c: _fetch_recent_ticks(
    +            c,
    +            symbol,
    +            seconds,
    +            end,
    +            count,
    +            tick_flags,
    +        ),
    +    )
     
    @@ -2429,11 +2438,11 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def symbol_info(self, symbol: str) -> pd.DataFrame:
    -    """Return details for one symbol."""
    -    return self._fetch(lambda c: c.symbol_info_as_df(symbol=symbol))
    +              
    def symbol_info(self, symbol: str) -> pd.DataFrame:
    +    """Return details for one symbol."""
    +    return self._fetch(lambda c: c.symbol_info_as_df(symbol=symbol))
     
    @@ -2458,11 +2467,11 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def symbol_info_tick(self, symbol: str) -> pd.DataFrame:
    -    """Return the last tick for a symbol."""
    -    return self._fetch(lambda c: c.symbol_info_tick_as_df(symbol=symbol))
    +              
    def symbol_info_tick(self, symbol: str) -> pd.DataFrame:
    +    """Return the last tick for a symbol."""
    +    return self._fetch(lambda c: c.symbol_info_tick_as_df(symbol=symbol))
     
    @@ -2487,11 +2496,11 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def symbols(self, group: str | None = None) -> pd.DataFrame:
    -    """Return the symbol list."""
    -    return self._fetch(lambda c: c.symbols_get_as_df(group=group))
    +              
    def symbols(self, group: str | None = None) -> pd.DataFrame:
    +    """Return the symbol list."""
    +    return self._fetch(lambda c: c.symbols_get_as_df(group=group))
     
    @@ -2516,11 +2525,11 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def terminal_info(self) -> pd.DataFrame:
    -    """Return terminal information."""
    -    return self._fetch(lambda c: c.terminal_info_as_df())
    +              
    def terminal_info(self) -> pd.DataFrame:
    +    """Return terminal information."""
    +    return self._fetch(lambda c: c.terminal_info_as_df())
     
    @@ -2545,11 +2554,862 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def version(self) -> pd.DataFrame:
    -    """Return MetaTrader5 version information."""
    -    return self._fetch(lambda c: c.version_as_df())
    +              
    def version(self) -> pd.DataFrame:
    +    """Return MetaTrader5 version information."""
    +    return self._fetch(lambda c: c.version_as_df())
    +
    + +
    + + + + + + + + + + + +
    + + + +

    + 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,
    +)
    +
    + +
    + + + +

    Throttled incremental SQLite history updater for long-running apps.

    +

    Wraps :func:update_history 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.

    + +

    Initialize the throttled updater.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + output + + Path | str + +
    +

    SQLite database path.

    +
    +
    + required +
    + datasets + + set[Dataset] | None + +
    +

    Datasets to include (defaults to all).

    +
    +
    + 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, Mt5TradingError, Mt5RuntimeError, +and sqlite3.Error raised during an update are swallowed and +:meth:update returns False without advancing the throttle. When +False (default), such errors propagate so callers control logging.

    +
    +
    + False +
    + + + + + + + + +
    + Source code in mt5cli/sdk.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,
    +) -> None:
    +    """Initialize the throttled updater.
    +
    +    Args:
    +        output: SQLite database path.
    +        datasets: Datasets to include (defaults to all).
    +        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, ``Mt5TradingError``, ``Mt5RuntimeError``,
    +            and ``sqlite3.Error`` raised during an update are swallowed and
    +            :meth:`update` returns False without advancing the throttle. When
    +            False (default), such errors propagate so callers control logging.
    +    """
    +    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._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
    +
    + +
    + +

    Return the 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
    +
    + +
    + +
    + +
    + +
    + + + +

    + with_views + + + + instance-attribute + + +

    +
    with_views = with_views
    +
    + +
    + +
    + +
    + + + + +
    + + +

    + should_update + + +

    +
    should_update() -> bool
    +
    + +
    + +

    Return whether enough time has elapsed to run another update.

    + + +

    Returns:

    + + + + + + + + + + + + + + + + + + + + + +
    TypeDescription
    + 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/sdk.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: Mt5DataClient, symbols: Sequence[str]
    +) -> bool
    +
    + +
    + +

    Run a throttled incremental history update.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + client + + Mt5DataClient + +
    +

    Connected MT5 data client.

    +
    +
    + required +
    + symbols + + Sequence[str] + +
    +

    Symbols to update.

    +
    +
    + required +
    + + +

    Returns:

    + + + + + + + + + + + + + + + + + +
    TypeDescription
    + bool + +
    +

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

    +
    +
    + bool + +
    +

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

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + + + + + + + + + +
    TypeDescription
    + Mt5TradingError + +
    +

    If the update fails and suppress_errors is False.

    +
    +
    + Mt5RuntimeError + +
    +

    If the update fails and suppress_errors is False.

    +
    +
    + Error + +
    +

    If the SQLite write fails and suppress_errors is +False.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def update(self, client: Mt5DataClient, symbols: Sequence[str]) -> bool:
    +    """Run a throttled incremental history update.
    +
    +    Args:
    +        client: Connected MT5 data client.
    +        symbols: Symbols to update.
    +
    +    Returns:
    +        True if an update ran successfully, False if it was throttled or
    +        (when ``suppress_errors`` is True) failed with a recoverable error.
    +
    +    Raises:
    +        Mt5TradingError: If the update fails and ``suppress_errors`` is False.
    +        Mt5RuntimeError: If the update fails and ``suppress_errors`` is False.
    +        sqlite3.Error: If the SQLite write fails and ``suppress_errors`` is
    +            False.
    +    """
    +    if not self.should_update():
    +        return False
    +    try:
    +        update_history(
    +            client=client,
    +            output=self.output,
    +            symbols=symbols,
    +            datasets=self.datasets,
    +            timeframes=self.timeframes,
    +            flags=self.flags,
    +            lookback_hours=self.lookback_hours,
    +            with_views=self.with_views,
    +            include_account_events=self.include_account_events,
    +        )
    +    except (Mt5TradingError, Mt5RuntimeError, sqlite3.Error):
    +        if self.suppress_errors:
    +            logger.warning("Suppressed history update error", exc_info=True)
    +            return False
    +        raise
    +    self._last_update_monotonic = time.monotonic()
    +    return True
     
    @@ -2585,11 +3445,11 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def account_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    -    """Return account information."""
    -    return _make_client(config=config).account_info()
    +              
    def account_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return account information."""
    +    return _make_client(config=config).account_info()
     
    @@ -2644,15 +3504,7 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    226
    -227
    -228
    -229
    -230
    -231
    -232
    -233
    -234
    +              
    234
     235
     236
     237
    @@ -2663,26 +3515,34 @@ fetching the entire range.

    242 243 244 -245
    def build_config(
    -    *,
    -    path: str | None = None,
    -    login: int | None = None,
    -    password: str | None = None,
    -    server: str | None = None,
    -    timeout: int | None = None,
    -) -> Mt5Config:
    -    """Build an ``Mt5Config`` from optional connection parameters.
    -
    -    Returns:
    -        Configured ``Mt5Config`` instance.
    -    """
    -    return Mt5Config(
    -        path=path,
    -        login=login,
    -        password=password,
    -        server=server,
    -        timeout=timeout,
    -    )
    +245
    +246
    +247
    +248
    +249
    +250
    +251
    +252
    +253
    def build_config(
    +    *,
    +    path: str | None = None,
    +    login: int | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    timeout: int | None = None,
    +) -> Mt5Config:
    +    """Build an ``Mt5Config`` from optional connection parameters.
    +
    +    Returns:
    +        Configured ``Mt5Config`` instance.
    +    """
    +    return Mt5Config(
    +        path=path,
    +        login=login,
    +        password=password,
    +        server=server,
    +        timeout=timeout,
    +    )
     
    @@ -2906,133 +3766,133 @@ fetching the entire range.

    Source code in mt5cli/sdk.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 = 1,
    -    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: Start date.
    -        date_to: End date.
    -        datasets: Datasets to include (defaults to all).
    -        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 = _require_datetime(date_from)
    -    end = _require_datetime(date_to)
    -    selected = datasets if datasets is not None else set(Dataset)
    -    tf = _coerce_timeframe(timeframe)
    -    tick_flags = _coerce_tick_flags(flags)
    -    mt5_config = config or build_config()
    -    with _connected_client(mt5_config) as client, sqlite3.connect(output) as 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:
    -            logger.warning(
    -                "--with-views ignored: history_deals table was not written",
    -            )
    -    logger.info(
    -        "Collected %s for %d symbol(s) into %s",
    -        ", ".join(sorted(ds.value for ds in selected)),
    -        len(symbols),
    -        output,
    -    )
    +              
    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 = 1,
    +    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: Start date.
    +        date_to: End date.
    +        datasets: Datasets to include (defaults to all).
    +        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 = _require_datetime(date_from)
    +    end = _require_datetime(date_to)
    +    selected = datasets if datasets is not None else set(Dataset)
    +    tf = _coerce_timeframe(timeframe)
    +    tick_flags = _coerce_tick_flags(flags)
    +    mt5_config = config or build_config()
    +    with _connected_client(mt5_config) as client, sqlite3.connect(output) as 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:
    +            logger.warning(
    +                "--with-views ignored: history_deals table was not written",
    +            )
    +    logger.info(
    +        "Collected %s for %d symbol(s) into %s",
    +        ", ".join(sorted(ds.value for ds in selected)),
    +        len(symbols),
    +        output,
    +    )
     
    @@ -3064,35 +3924,35 @@ fetching the entire range.

    Source code in mt5cli/sdk.py -
    def collect_latest_rates(
    -    symbols: Sequence[str],
    -    timeframes: Sequence[int | str],
    -    *,
    -    count: int,
    -    start_pos: int = 0,
    -    config: Mt5Config | None = None,
    -) -> dict[tuple[str, int], pd.DataFrame]:
    -    """Return latest rates for each symbol/timeframe pair."""
    -    return _make_client(config=config).collect_latest_rates(
    -        symbols,
    -        timeframes,
    -        count=count,
    -        start_pos=start_pos,
    -    )
    +              
    def collect_latest_rates(
    +    symbols: Sequence[str],
    +    timeframes: Sequence[int | str],
    +    *,
    +    count: int,
    +    start_pos: int = 0,
    +    config: Mt5Config | None = None,
    +) -> dict[tuple[str, int], pd.DataFrame]:
    +    """Return latest rates for each symbol/timeframe pair."""
    +    return _make_client(config=config).collect_latest_rates(
    +        symbols,
    +        timeframes,
    +        count=count,
    +        start_pos=start_pos,
    +    )
     
    @@ -3289,111 +4149,460 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def collect_latest_rates_for_accounts(
    -    accounts: Sequence[AccountSpec],
    -    timeframes: Sequence[int | str],
    -    count: int,
    -    *,
    -    start_pos: int = 0,
    -    base_config: Mt5Config | None = None,
    -) -> dict[tuple[str, int], pd.DataFrame]:
    -    """Collect latest rates across multiple MT5 account groups.
    -
    -    Each account is connected in turn, its symbols are read for every
    -    timeframe, and the resulting frames are merged into a single mapping.
    -
    -    Args:
    -        accounts: Account groups to read. Each must define at least one symbol.
    -        timeframes: MT5 timeframes as integers or names (for example ``M1``).
    -        count: Number of most recent bars to read per symbol/timeframe.
    -        start_pos: Initial bar position offset.
    -        base_config: Optional base configuration whose fields fill any value not
    -            set on an individual account.
    -
    -    Returns:
    -        Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a
    -        symbol/timeframe pair, the last account processed wins.
    -
    -    Raises:
    -        ValueError: If ``accounts``, ``timeframes``, or any account's symbols are
    -            empty, or ``count`` is not positive.
    -    """
    -    account_list = list(accounts)
    -    if not account_list:
    -        msg = "At least one account is required."
    -        raise ValueError(msg)
    -    if not timeframes:
    -        msg = "At least one timeframe is required."
    -        raise ValueError(msg)
    -    if any(not account.symbols for account in account_list):
    -        msg = "Each account requires at least one symbol."
    -        raise ValueError(msg)
    -    _require_positive(count, "count")
    -    result: dict[tuple[str, int], pd.DataFrame] = {}
    -    for account in account_list:
    -        config = _build_account_config(account, base_config)
    -        with Mt5CliClient(config=config) as client:
    -            result.update(
    -                client.collect_latest_rates(
    -                    account.symbols,
    -                    timeframes,
    -                    count=count,
    -                    start_pos=start_pos,
    -                ),
    -            )
    -    return result
    +              
    def collect_latest_rates_for_accounts(
    +    accounts: Sequence[AccountSpec],
    +    timeframes: Sequence[int | str],
    +    count: int,
    +    *,
    +    start_pos: int = 0,
    +    base_config: Mt5Config | None = None,
    +) -> dict[tuple[str, int], pd.DataFrame]:
    +    """Collect latest rates across multiple MT5 account groups.
    +
    +    Each account is connected in turn, its symbols are read for every
    +    timeframe, and the resulting frames are merged into a single mapping.
    +
    +    Args:
    +        accounts: Account groups to read. Each must define at least one symbol.
    +        timeframes: MT5 timeframes as integers or names (for example ``M1``).
    +        count: Number of most recent bars to read per symbol/timeframe.
    +        start_pos: Initial bar position offset.
    +        base_config: Optional base configuration whose fields fill any value not
    +            set on an individual account.
    +
    +    Returns:
    +        Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a
    +        symbol/timeframe pair, the last account processed wins.
    +
    +    Raises:
    +        ValueError: If ``accounts``, ``timeframes``, or any account's symbols are
    +            empty, or ``count`` is not positive.
    +    """
    +    account_list = list(accounts)
    +    if not account_list:
    +        msg = "At least one account is required."
    +        raise ValueError(msg)
    +    if not timeframes:
    +        msg = "At least one timeframe is required."
    +        raise ValueError(msg)
    +    if any(not account.symbols for account in account_list):
    +        msg = "Each account requires at least one symbol."
    +        raise ValueError(msg)
    +    _require_positive(count, "count")
    +    result: dict[tuple[str, int], pd.DataFrame] = {}
    +    for account in account_list:
    +        config = _build_account_config(account, base_config)
    +        with Mt5CliClient(config=config) as client:
    +            result.update(
    +                client.collect_latest_rates(
    +                    account.symbols,
    +                    timeframes,
    +                    count=count,
    +                    start_pos=start_pos,
    +                ),
    +            )
    +    return result
    +
    + +
    + + + +
    + + +

    + collect_latest_rates_for_accounts_with_retries + + +

    +
    collect_latest_rates_for_accounts_with_retries(
    +    accounts: Sequence[AccountSpec],
    +    timeframes: Sequence[int | str],
    +    count: int,
    +    *,
    +    start_pos: int = 0,
    +    base_config: Mt5Config | None = None,
    +    retry_count: int = 0,
    +    backoff_base: float = 2.0,
    +) -> dict[tuple[str, int], DataFrame]
    +
    + +
    + +

    Collect latest rates across accounts, retrying transient MT5 failures.

    +

    Wraps :func:collect_latest_rates_for_accounts with bounded exponential +backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are +retried; other exceptions propagate immediately. The final failure is +re-raised once retries are exhausted.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + accounts + + Sequence[AccountSpec] + +
    +

    Account groups to read. Each must define at least one symbol.

    +
    +
    + required +
    + timeframes + + Sequence[int | str] + +
    +

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

    +
    +
    + required +
    + count + + int + +
    +

    Number of most recent bars to read per symbol/timeframe.

    +
    +
    + required +
    + start_pos + + int + +
    +

    Initial bar position offset.

    +
    +
    + 0 +
    + base_config + + Mt5Config | None + +
    +

    Optional base configuration whose fields fill any value not +set on an individual account.

    +
    +
    + None +
    + retry_count + + int + +
    +

    Maximum number of retries after the first attempt. 0 +disables retries.

    +
    +
    + 0 +
    + backoff_base + + float + +
    +

    Base for exponential backoff. The delay before retry +attempt n (1-indexed) is backoff_base ** n seconds.

    +
    +
    + 2.0 +
    + + +

    Returns:

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    TypeDescription
    + dict[tuple[str, int], DataFrame] + +
    +

    Mapping keyed by (symbol, timeframe_int). Propagates ValueError

    +
    +
    + dict[tuple[str, int], DataFrame] + +
    +

    for invalid inputs (see :func:collect_latest_rates_for_accounts) and

    +
    +
    + dict[tuple[str, int], DataFrame] + +
    +

    re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError

    +
    +
    + dict[tuple[str, int], DataFrame] + +
    +

    once retries are exhausted.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def collect_latest_rates_for_accounts_with_retries(
    +    accounts: Sequence[AccountSpec],
    +    timeframes: Sequence[int | str],
    +    count: int,
    +    *,
    +    start_pos: int = 0,
    +    base_config: Mt5Config | None = None,
    +    retry_count: int = 0,
    +    backoff_base: float = 2.0,
    +) -> dict[tuple[str, int], pd.DataFrame]:
    +    """Collect latest rates across accounts, retrying transient MT5 failures.
    +
    +    Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential
    +    backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are
    +    retried; other exceptions propagate immediately. The final failure is
    +    re-raised once retries are exhausted.
    +
    +    Args:
    +        accounts: Account groups to read. Each must define at least one symbol.
    +        timeframes: MT5 timeframes as integers or names (for example ``M1``).
    +        count: Number of most recent bars to read per symbol/timeframe.
    +        start_pos: Initial bar position offset.
    +        base_config: Optional base configuration whose fields fill any value not
    +            set on an individual account.
    +        retry_count: Maximum number of retries after the first attempt. ``0``
    +            disables retries.
    +        backoff_base: Base for exponential backoff. The delay before retry
    +            attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds.
    +
    +    Returns:
    +        Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError``
    +        for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and
    +        re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError``
    +        once retries are exhausted.
    +    """
    +    attempts = max(retry_count, 0) + 1
    +
    +    def _collect() -> dict[tuple[str, int], pd.DataFrame]:
    +        return collect_latest_rates_for_accounts(
    +            accounts,
    +            timeframes,
    +            count,
    +            start_pos=start_pos,
    +            base_config=base_config,
    +        )
    +
    +    for attempt in range(attempts - 1):
    +        try:
    +            return _collect()
    +        except (Mt5TradingError, Mt5RuntimeError) as exc:
    +            delay = backoff_base ** (attempt + 1)
    +            logger.warning(
    +                "Rate collection failed (attempt %d/%d): %s; retrying in %.1fs",
    +                attempt + 1,
    +                attempts,
    +                exc,
    +                delay,
    +            )
    +            time.sleep(delay)
    +    return _collect()
     
    @@ -3425,35 +4634,35 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def copy_rates_from(
    -    symbol: str,
    -    timeframe: int | str,
    -    date_from: datetime | str,
    -    count: int,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return rates starting from a date."""
    -    return _make_client(config=config).copy_rates_from(
    -        symbol,
    -        timeframe,
    -        date_from,
    -        count,
    -    )
    +              
    def copy_rates_from(
    +    symbol: str,
    +    timeframe: int | str,
    +    date_from: datetime | str,
    +    count: int,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return rates starting from a date."""
    +    return _make_client(config=config).copy_rates_from(
    +        symbol,
    +        timeframe,
    +        date_from,
    +        count,
    +    )
     
    @@ -3485,35 +4694,35 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def copy_rates_from_pos(
    -    symbol: str,
    -    timeframe: int | str,
    -    start_pos: int,
    -    count: int,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return rates starting from a bar position."""
    -    return _make_client(config=config).copy_rates_from_pos(
    -        symbol,
    -        timeframe,
    -        start_pos,
    -        count,
    -    )
    +              
    def copy_rates_from_pos(
    +    symbol: str,
    +    timeframe: int | str,
    +    start_pos: int,
    +    count: int,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return rates starting from a bar position."""
    +    return _make_client(config=config).copy_rates_from_pos(
    +        symbol,
    +        timeframe,
    +        start_pos,
    +        count,
    +    )
     
    @@ -3545,35 +4754,35 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def copy_rates_range(
    -    symbol: str,
    -    timeframe: int | str,
    -    date_from: datetime | str,
    -    date_to: datetime | str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return rates for a date range."""
    -    return _make_client(config=config).copy_rates_range(
    -        symbol,
    -        timeframe,
    -        date_from,
    -        date_to,
    -    )
    +              
    def copy_rates_range(
    +    symbol: str,
    +    timeframe: int | str,
    +    date_from: datetime | str,
    +    date_to: datetime | str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return rates for a date range."""
    +    return _make_client(config=config).copy_rates_range(
    +        symbol,
    +        timeframe,
    +        date_from,
    +        date_to,
    +    )
     
    @@ -3605,35 +4814,35 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def copy_ticks_from(
    -    symbol: str,
    -    date_from: datetime | str,
    -    count: int,
    -    flags: int | str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return ticks starting from a date."""
    -    return _make_client(config=config).copy_ticks_from(
    -        symbol,
    -        date_from,
    -        count,
    -        flags,
    -    )
    +              
    def copy_ticks_from(
    +    symbol: str,
    +    date_from: datetime | str,
    +    count: int,
    +    flags: int | str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return ticks starting from a date."""
    +    return _make_client(config=config).copy_ticks_from(
    +        symbol,
    +        date_from,
    +        count,
    +        flags,
    +    )
     
    @@ -3665,35 +4874,35 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def copy_ticks_range(
    -    symbol: str,
    -    date_from: datetime | str,
    -    date_to: datetime | str,
    -    flags: int | str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return ticks for a date range."""
    -    return _make_client(config=config).copy_ticks_range(
    -        symbol,
    -        date_from,
    -        date_to,
    -        flags,
    -    )
    +              
    def copy_ticks_range(
    +    symbol: str,
    +    date_from: datetime | str,
    +    date_to: datetime | str,
    +    flags: int | str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return ticks for a date range."""
    +    return _make_client(config=config).copy_ticks_range(
    +        symbol,
    +        date_from,
    +        date_to,
    +        flags,
    +    )
     
    @@ -3727,43 +4936,43 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def history_deals(
    -    date_from: datetime | str | None = None,
    -    date_to: datetime | str | None = None,
    -    group: str | None = None,
    -    symbol: str | None = None,
    -    ticket: int | None = None,
    -    position: int | None = None,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return historical deals."""
    -    return _make_client(config=config).history_deals(
    -        date_from=date_from,
    -        date_to=date_to,
    -        group=group,
    -        symbol=symbol,
    -        ticket=ticket,
    -        position=position,
    -    )
    +              
    def history_deals(
    +    date_from: datetime | str | None = None,
    +    date_to: datetime | str | None = None,
    +    group: str | None = None,
    +    symbol: str | None = None,
    +    ticket: int | None = None,
    +    position: int | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return historical deals."""
    +    return _make_client(config=config).history_deals(
    +        date_from=date_from,
    +        date_to=date_to,
    +        group=group,
    +        symbol=symbol,
    +        ticket=ticket,
    +        position=position,
    +    )
     
    @@ -3797,43 +5006,43 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def history_orders(
    -    date_from: datetime | str | None = None,
    -    date_to: datetime | str | None = None,
    -    group: str | None = None,
    -    symbol: str | None = None,
    -    ticket: int | None = None,
    -    position: int | None = None,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return historical orders."""
    -    return _make_client(config=config).history_orders(
    -        date_from=date_from,
    -        date_to=date_to,
    -        group=group,
    -        symbol=symbol,
    -        ticket=ticket,
    -        position=position,
    -    )
    +              
    def history_orders(
    +    date_from: datetime | str | None = None,
    +    date_to: datetime | str | None = None,
    +    group: str | None = None,
    +    symbol: str | None = None,
    +    ticket: int | None = None,
    +    position: int | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return historical orders."""
    +    return _make_client(config=config).history_orders(
    +        date_from=date_from,
    +        date_to=date_to,
    +        group=group,
    +        symbol=symbol,
    +        ticket=ticket,
    +        position=position,
    +    )
     
    @@ -3858,11 +5067,11 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def last_error(*, config: Mt5Config | None = None) -> pd.DataFrame:
    -    """Return the last error information."""
    -    return _make_client(config=config).last_error()
    +              
    def last_error(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return the last error information."""
    +    return _make_client(config=config).last_error()
     
    @@ -3894,35 +5103,35 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def latest_rates(
    -    symbol: str,
    -    timeframe: int | str,
    -    count: int,
    -    start_pos: int = 0,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return the latest rates from a bar position."""
    -    return _make_client(config=config).latest_rates(
    -        symbol,
    -        timeframe,
    -        count,
    -        start_pos=start_pos,
    -    )
    +              
    def latest_rates(
    +    symbol: str,
    +    timeframe: int | str,
    +    count: int,
    +    start_pos: int = 0,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return the latest rates from a bar position."""
    +    return _make_client(config=config).latest_rates(
    +        symbol,
    +        timeframe,
    +        count,
    +        start_pos=start_pos,
    +    )
     
    @@ -3949,19 +5158,19 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def market_book(
    -    symbol: str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return market depth for a symbol."""
    -    return _make_client(config=config).market_book(symbol)
    +              
    def market_book(
    +    symbol: str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return market depth for a symbol."""
    +    return _make_client(config=config).market_book(symbol)
     
    @@ -3989,25 +5198,25 @@ empty, or count is not positive.

    Source code in mt5cli/sdk.py -
    def minimum_margins(
    -    symbol: str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return minimum-volume buy and sell margin requirements.
    -
    -    See ``Mt5CliClient.minimum_margins`` for return details.
    -    """
    -    return _make_client(config=config).minimum_margins(symbol)
    +              
    def minimum_margins(
    +    symbol: str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return minimum-volume buy and sell margin requirements.
    +
    +    See ``Mt5CliClient.minimum_margins`` for return details.
    +    """
    +    return _make_client(config=config).minimum_margins(symbol)
     
    @@ -4092,15 +5301,7 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    283
    -284
    -285
    -286
    -287
    -288
    -289
    -290
    -291
    +              
    291
     292
     293
     294
    @@ -4109,24 +5310,32 @@ attaches to a running terminal.

    297 298 299 -300
    @contextmanager
    -def mt5_session(config: Mt5Config | None = None) -> Iterator[Mt5CliClient]:
    -    """Open an MT5 terminal session and yield a connected client.
    -
    -    Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set),
    -    logs in, yields a connected :class:`Mt5CliClient`, and always shuts the
    -    terminal down on exit.
    -
    -    Args:
    -        config: MT5 connection configuration. Defaults to an empty config that
    -            attaches to a running terminal.
    +300
    +301
    +302
    +303
    +304
    +305
    +306
    +307
    +308
    @contextmanager
    +def mt5_session(config: Mt5Config | None = None) -> Iterator[Mt5CliClient]:
    +    """Open an MT5 terminal session and yield a connected client.
     
    -    Yields:
    -        Connected ``Mt5CliClient`` bound to the session.
    -    """
    -    mt5_config = config or build_config()
    -    with _connected_client(mt5_config) as client:
    -        yield Mt5CliClient.from_connected_client(client)
    +    Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set),
    +    logs in, yields a connected :class:`Mt5CliClient`, and always shuts the
    +    terminal down on exit.
    +
    +    Args:
    +        config: MT5 connection configuration. Defaults to an empty config that
    +            attaches to a running terminal.
    +
    +    Yields:
    +        Connected ``Mt5CliClient`` bound to the session.
    +    """
    +    mt5_config = config or build_config()
    +    with _connected_client(mt5_config) as client:
    +        yield Mt5CliClient.from_connected_client(client)
     
    @@ -4153,11 +5362,11 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def mt5_summary(*, config: Mt5Config | None = None) -> dict[str, object]:
    -    """Return a compact terminal/account status summary."""
    -    return _make_client(config=config).mt5_summary()
    +              
    def mt5_summary(*, config: Mt5Config | None = None) -> dict[str, object]:
    +    """Return a compact terminal/account status summary."""
    +    return _make_client(config=config).mt5_summary()
     
    @@ -4184,11 +5393,11 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def mt5_summary_as_df(*, config: Mt5Config | None = None) -> pd.DataFrame:
    -    """Return an export-safe terminal/account status summary DataFrame."""
    -    return _make_client(config=config).mt5_summary_as_df()
    +              
    def mt5_summary_as_df(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return an export-safe terminal/account status summary DataFrame."""
    +    return _make_client(config=config).mt5_summary_as_df()
     
    @@ -4219,31 +5428,31 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def orders(
    -    symbol: str | None = None,
    -    group: str | None = None,
    -    ticket: int | None = None,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return active orders."""
    -    return _make_client(config=config).orders(
    -        symbol=symbol,
    -        group=group,
    -        ticket=ticket,
    -    )
    +              
    def orders(
    +    symbol: str | None = None,
    +    group: str | None = None,
    +    ticket: int | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return active orders."""
    +    return _make_client(config=config).orders(
    +        symbol=symbol,
    +        group=group,
    +        ticket=ticket,
    +    )
     
    @@ -4274,31 +5483,31 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def positions(
    -    symbol: str | None = None,
    -    group: str | None = None,
    -    ticket: int | None = None,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return open positions."""
    -    return _make_client(config=config).positions(
    -        symbol=symbol,
    -        group=group,
    -        ticket=ticket,
    -    )
    +              
    def positions(
    +    symbol: str | None = None,
    +    group: str | None = None,
    +    ticket: int | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return open positions."""
    +    return _make_client(config=config).positions(
    +        symbol=symbol,
    +        group=group,
    +        ticket=ticket,
    +    )
     
    @@ -4330,35 +5539,35 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def recent_history_deals(
    -    hours: float,
    -    date_to: datetime | str | None = None,
    -    group: str | None = None,
    -    symbol: str | None = None,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return historical deals from a recent trailing window."""
    -    return _make_client(config=config).recent_history_deals(
    -        hours,
    -        date_to=date_to,
    -        group=group,
    -        symbol=symbol,
    -    )
    +              
    def recent_history_deals(
    +    hours: float,
    +    date_to: datetime | str | None = None,
    +    group: str | None = None,
    +    symbol: str | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return historical deals from a recent trailing window."""
    +    return _make_client(config=config).recent_history_deals(
    +        hours,
    +        date_to=date_to,
    +        group=group,
    +        symbol=symbol,
    +    )
     
    @@ -4392,45 +5601,796 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def recent_ticks(
    -    symbol: str,
    -    seconds: float,
    -    *,
    -    date_to: datetime | str | None = None,
    -    count: int = 10000,
    -    flags: int | str = "ALL",
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return ticks from a recent time window ending at ``date_to`` or now.
    -
    -    See ``Mt5CliClient.recent_ticks`` for parameter and return details.
    -    """
    -    return _make_client(config=config).recent_ticks(
    -        symbol,
    -        seconds,
    -        date_to=date_to,
    -        count=count,
    -        flags=flags,
    -    )
    +              
    def recent_ticks(
    +    symbol: str,
    +    seconds: float,
    +    *,
    +    date_to: datetime | str | None = None,
    +    count: int = 10000,
    +    flags: int | str = "ALL",
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return ticks from a recent time window ending at ``date_to`` or now.
    +
    +    See ``Mt5CliClient.recent_ticks`` for parameter and return details.
    +    """
    +    return _make_client(config=config).recent_ticks(
    +        symbol,
    +        seconds,
    +        date_to=date_to,
    +        count=count,
    +        flags=flags,
    +    )
    +
    + +
    + + + +
    + + +

    + resolve_account_spec + + +

    +
    resolve_account_spec(
    +    account: AccountSpec,
    +    *,
    +    login: int | str | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    path: str | None = None,
    +    timeout: int | None = None,
    +) -> AccountSpec
    +
    + +
    + +

    Resolve an account's credentials from overrides and ${ENV_VAR} values.

    +

    Explicit override arguments take precedence over the corresponding +:class:AccountSpec fields. The resolved string fields (login, +password, server, path) have any ${ENV_VAR} placeholders +substituted from the environment.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + account + + AccountSpec + +
    +

    Source account specification.

    +
    +
    + required +
    + login + + int | str | None + +
    +

    Optional explicit login override.

    +
    +
    + None +
    + password + + str | None + +
    +

    Optional explicit password override.

    +
    +
    + None +
    + server + + str | None + +
    +

    Optional explicit server override.

    +
    +
    + None +
    + path + + str | None + +
    +

    Optional explicit terminal path override.

    +
    +
    + None +
    + timeout + + int | None + +
    +

    Optional explicit connection timeout override.

    +
    +
    + None +
    + + +

    Returns:

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    TypeDescription
    + AccountSpec + +
    +

    A new :class:AccountSpec with resolved credentials and the original

    +
    +
    + AccountSpec + +
    +

    symbols preserved. Raises ValueError (via

    +
    +
    + AccountSpec + +
    +

    func:substitute_env_placeholders) if a referenced environment

    +
    +
    + AccountSpec + +
    +

    variable is not set.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def resolve_account_spec(
    +    account: AccountSpec,
    +    *,
    +    login: int | str | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    path: str | None = None,
    +    timeout: int | None = None,
    +) -> AccountSpec:
    +    """Resolve an account's credentials from overrides and ``${ENV_VAR}`` values.
    +
    +    Explicit override arguments take precedence over the corresponding
    +    :class:`AccountSpec` fields. The resolved string fields (``login``,
    +    ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders
    +    substituted from the environment.
    +
    +    Args:
    +        account: Source account specification.
    +        login: Optional explicit login override.
    +        password: Optional explicit password override.
    +        server: Optional explicit server override.
    +        path: Optional explicit terminal path override.
    +        timeout: Optional explicit connection timeout override.
    +
    +    Returns:
    +        A new :class:`AccountSpec` with resolved credentials and the original
    +        symbols preserved. Raises ``ValueError`` (via
    +        :func:`substitute_env_placeholders`) if a referenced environment
    +        variable is not set.
    +    """
    +    return AccountSpec(
    +        symbols=account.symbols,
    +        login=_resolve_login(login, account.login),
    +        password=_resolve_field(password, account.password),
    +        server=_resolve_field(server, account.server),
    +        path=_resolve_field(path, account.path),
    +        timeout=timeout if timeout is not None else account.timeout,
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + resolve_account_specs + + +

    +
    resolve_account_specs(
    +    accounts: Sequence[AccountSpec],
    +    *,
    +    login: int | str | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    path: str | None = None,
    +    timeout: int | None = None,
    +) -> list[AccountSpec]
    +
    + +
    + +

    Resolve credentials for multiple accounts.

    +

    Applies the same overrides and ${ENV_VAR} substitution as +:func:resolve_account_spec to every account.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + accounts + + Sequence[AccountSpec] + +
    +

    Source account specifications.

    +
    +
    + required +
    + login + + int | str | None + +
    +

    Optional explicit login override applied to each account.

    +
    +
    + None +
    + password + + str | None + +
    +

    Optional explicit password override applied to each account.

    +
    +
    + None +
    + server + + str | None + +
    +

    Optional explicit server override applied to each account.

    +
    +
    + None +
    + path + + str | None + +
    +

    Optional explicit terminal path override applied to each account.

    +
    +
    + None +
    + timeout + + int | None + +
    +

    Optional explicit timeout override applied to each account.

    +
    +
    + None +
    + + +

    Returns:

    + + + + + + + + + + + + + + + + + + + + + +
    TypeDescription
    + list[AccountSpec] + +
    +

    Resolved account specifications in the original order. Raises

    +
    +
    + list[AccountSpec] + +
    +

    ValueError (via :func:substitute_env_placeholders) if a referenced

    +
    +
    + list[AccountSpec] + +
    +

    environment variable is not set.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def resolve_account_specs(
    +    accounts: Sequence[AccountSpec],
    +    *,
    +    login: int | str | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    path: str | None = None,
    +    timeout: int | None = None,
    +) -> list[AccountSpec]:
    +    """Resolve credentials for multiple accounts.
    +
    +    Applies the same overrides and ``${ENV_VAR}`` substitution as
    +    :func:`resolve_account_spec` to every account.
    +
    +    Args:
    +        accounts: Source account specifications.
    +        login: Optional explicit login override applied to each account.
    +        password: Optional explicit password override applied to each account.
    +        server: Optional explicit server override applied to each account.
    +        path: Optional explicit terminal path override applied to each account.
    +        timeout: Optional explicit timeout override applied to each account.
    +
    +    Returns:
    +        Resolved account specifications in the original order. Raises
    +        ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced
    +        environment variable is not set.
    +    """
    +    return [
    +        resolve_account_spec(
    +            account,
    +            login=login,
    +            password=password,
    +            server=server,
    +            path=path,
    +            timeout=timeout,
    +        )
    +        for account in accounts
    +    ]
    +
    +
    +
    + +
    + +
    + + +

    + substitute_env_placeholders + + +

    +
    substitute_env_placeholders(value: str) -> str
    +
    + +
    + +

    Replace ${ENV_VAR} placeholders in a string with environment values.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + value + + str + +
    +

    String that may contain one or more ${ENV_VAR} placeholders.

    +
    +
    + required +
    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + str + +
    +

    The string with every placeholder replaced by its environment value.

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If a referenced environment variable is not set.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def substitute_env_placeholders(value: str) -> str:
    +    """Replace ``${ENV_VAR}`` placeholders in a string with environment values.
    +
    +    Args:
    +        value: String that may contain one or more ``${ENV_VAR}`` placeholders.
    +
    +    Returns:
    +        The string with every placeholder replaced by its environment value.
    +
    +    Raises:
    +        ValueError: If a referenced environment variable is not set.
    +    """
    +    parts: list[str] = []
    +    last_end = 0
    +    for match in _ENV_PLACEHOLDER_PATTERN.finditer(value):
    +        parts.append(value[last_end : match.start()])
    +        name = match.group("name")
    +        if name not in os.environ:
    +            msg = f"Environment variable {name!r} is not set."
    +            raise ValueError(msg)
    +        parts.append(os.environ[name])
    +        last_end = match.end()
    +    parts.append(value[last_end:])
    +    return "".join(parts)
     
    @@ -4457,19 +6417,19 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def symbol_info(
    -    symbol: str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return details for one symbol."""
    -    return _make_client(config=config).symbol_info(symbol)
    +              
    def symbol_info(
    +    symbol: str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return details for one symbol."""
    +    return _make_client(config=config).symbol_info(symbol)
     
    @@ -4496,19 +6456,19 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def symbol_info_tick(
    -    symbol: str,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return the last tick for a symbol."""
    -    return _make_client(config=config).symbol_info_tick(symbol)
    +              
    def symbol_info_tick(
    +    symbol: str,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return the last tick for a symbol."""
    +    return _make_client(config=config).symbol_info_tick(symbol)
     
    @@ -4537,19 +6497,19 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def symbols(
    -    group: str | None = None,
    -    *,
    -    config: Mt5Config | None = None,
    -) -> pd.DataFrame:
    -    """Return the symbol list."""
    -    return _make_client(config=config).symbols(group=group)
    +              
    def symbols(
    +    group: str | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> pd.DataFrame:
    +    """Return the symbol list."""
    +    return _make_client(config=config).symbols(group=group)
     
    @@ -4576,11 +6536,11 @@ attaches to a running terminal.

    Source code in mt5cli/sdk.py -
    def terminal_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    -    """Return terminal information."""
    -    return _make_client(config=config).terminal_info()
    +              
    def terminal_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return terminal information."""
    +    return _make_client(config=config).terminal_info()
     
    @@ -4834,15 +6794,7 @@ timeframes when None).

    Source code in mt5cli/sdk.py -
    839
    -840
    -841
    -842
    -843
    -844
    -845
    -846
    -847
    +              
    847
     848
     849
     850
    @@ -4907,80 +6859,88 @@ timeframes when None).

    909 910 911 -912
    def update_history(  # noqa: PLR0913
    -    *,
    -    client: Mt5DataClient,
    -    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,
    -    create_rate_views: bool = True,
    -    with_views: bool = False,
    -    include_account_events: bool = True,
    -) -> None:
    -    """Incrementally append MT5 history into a SQLite database.
    -
    -    Uses an already-connected ``Mt5DataClient`` 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 data client.
    -        output: SQLite database path.
    -        symbols: Symbols to update.
    -        datasets: Datasets to include (defaults to all).
    -        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 update end datetime. Defaults to now (UTC).
    -        deduplicate: Remove duplicate rows after append, keeping latest ROWID.
    -        create_rate_views: Create ``rate_<symbol>__<timeframe>`` views.
    -        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,
    +912
    +913
    +914
    +915
    +916
    +917
    +918
    +919
    +920
    def update_history(  # noqa: PLR0913
    +    *,
    +    client: Mt5DataClient,
    +    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,
    +    create_rate_views: bool = True,
    +    with_views: bool = False,
    +    include_account_events: bool = True,
    +) -> None:
    +    """Incrementally append MT5 history into a SQLite database.
    +
    +    Uses an already-connected ``Mt5DataClient`` 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 data client.
    +        output: SQLite database path.
    +        symbols: Symbols to update.
    +        datasets: Datasets to include (defaults to all).
    +        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 update end datetime. Defaults to now (UTC).
    +        deduplicate: Remove duplicate rows after append, keeping latest ROWID.
    +        create_rate_views: Create ``rate_<symbol>__<timeframe>`` views.
    +        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,
         )
    -    with sqlite3.connect(request.output_path) as conn:
    -        conn.execute("PRAGMA journal_mode=WAL")
    -        conn.execute("PRAGMA synchronous=NORMAL")
    -        write_incremental_datasets(
    -            conn,
    -            client,
    -            symbols,
    -            request.selected,
    -            request.resolved_timeframes,
    -            request.resolved_tick_flags,
    -            request.fallback_start,
    -            request.end,
    -            deduplicate=deduplicate,
    -            create_rate_views=create_rate_views,
    -            with_views=with_views,
    -            include_account_events=include_account_events,
    -        )
    +    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 sqlite3.connect(request.output_path) as conn:
    +        conn.execute("PRAGMA journal_mode=WAL")
    +        conn.execute("PRAGMA synchronous=NORMAL")
    +        write_incremental_datasets(
    +            conn,
    +            client,
    +            symbols,
    +            request.selected,
    +            request.resolved_timeframes,
    +            request.resolved_tick_flags,
    +            request.fallback_start,
    +            request.end,
    +            deduplicate=deduplicate,
    +            create_rate_views=create_rate_views,
    +            with_views=with_views,
    +            include_account_events=include_account_events,
    +        )
     
    @@ -5020,15 +6980,7 @@ timeframes when None).

    Source code in mt5cli/sdk.py -
    915
    -916
    -917
    -918
    -919
    -920
    -921
    -922
    -923
    +              
    923
     924
     925
     926
    @@ -5065,52 +7017,60 @@ timeframes when None).

    957 958 959 -960
    def update_history_with_config(  # noqa: PLR0913
    -    *,
    -    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,
    -    create_rate_views: 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
    -    mt5_config = config or build_config()
    -    with _connected_client(mt5_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,
    -            create_rate_views=create_rate_views,
    -            with_views=with_views,
    -            include_account_events=include_account_events,
    -        )
    +960
    +961
    +962
    +963
    +964
    +965
    +966
    +967
    +968
    def update_history_with_config(  # noqa: PLR0913
    +    *,
    +    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,
    +    create_rate_views: 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
    +    mt5_config = config or build_config()
    +    with _connected_client(mt5_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,
    +            create_rate_views=create_rate_views,
    +            with_views=with_views,
    +            include_account_events=include_account_events,
    +        )
     
    @@ -5135,11 +7095,11 @@ timeframes when None).

    Source code in mt5cli/sdk.py -
    def version(*, config: Mt5Config | None = None) -> pd.DataFrame:
    -    """Return MetaTrader5 version information."""
    -    return _make_client(config=config).version()
    +              
    def version(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return MetaTrader5 version information."""
    +    return _make_client(config=config).version()
     
    @@ -5152,7 +7112,71 @@ timeframes when None).

    - +

    Resilient multi-account orchestration

    +

    The SDK ships strategy-agnostic helpers for building long-running collectors on +top of the read-only client. None of them depend on a particular trading +application.

    +

    Retrying transient rate collection

    +

    collect_latest_rates_for_accounts_with_retries() wraps +collect_latest_rates_for_accounts() with bounded exponential backoff. Only +pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final +failure is re-raised once retry_count is exhausted.

    +
    from mt5cli import AccountSpec, collect_latest_rates_for_accounts_with_retries
    +
    +accounts = [AccountSpec(symbols=["EURUSD"], login=12345)]
    +rates = collect_latest_rates_for_accounts_with_retries(
    +    accounts,
    +    ["M1", "H1"],
    +    count=500,
    +    retry_count=3,
    +    backoff_base=2,  # sleeps 2s, 4s, 8s between attempts
    +)
    +
    +

    Resolving credentials and ${ENV_VAR} placeholders

    +

    resolve_account_spec() / resolve_account_specs() merge explicit override +values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping +secrets out of plan/config files. A missing environment variable raises +ValueError.

    +
    import os
    +
    +from mt5cli import AccountSpec, resolve_account_specs
    +
    +os.environ["MT5_LOGIN"] = "12345"
    +os.environ["MT5_PASSWORD"] = "secret"
    +accounts = [
    +    AccountSpec(symbols=["EURUSD"], login="${MT5_LOGIN}", password="${MT5_PASSWORD}")
    +]
    +
    +resolved = resolve_account_specs(accounts, server="Broker-Demo")
    +# resolved[0].login == "12345", resolved[0].server == "Broker-Demo"
    +
    +

    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 pdmt5 import Mt5Config, Mt5DataClient
    +
    +from mt5cli import Dataset, ThrottledHistoryUpdater
    +
    +updater = ThrottledHistoryUpdater(
    +    output="history.db",
    +    datasets={Dataset.rates},
    +    timeframes=["M1"],
    +    interval_seconds=60,  # <= 0 updates on every call
    +)
    +
    +client = Mt5DataClient(config=Mt5Config(login=12345))
    +client.initialize_and_login_mt5()
    +try:
    +    while True:
    +        updater.update(client, ["EURUSD", "GBPUSD"])  # no-op until 60s elapse
    +        # ... do other work; break when shutting down ...
    +finally:
    +    client.shutdown()
    +
    +

    By default Mt5TradingError, Mt5RuntimeError, and sqlite3.Error propagate so +the caller controls logging; pass suppress_errors=True to swallow them and +return False without advancing the throttle.

    diff --git a/index.html b/index.html index 64be68d..9735aa9 100644 --- a/index.html +++ b/index.html @@ -614,5 +614,5 @@ diff --git a/objects.inv b/objects.inv index eb3c13613ddcfea1e17cc20e5560be984a86e046..1be5912b4703a25b04d06e08fe2bd2b0ccba59bd 100644 GIT binary patch delta 2265 zcmV;~2qyRJ5X=&gi+{D8OLN;c5XbNR6q#wRRVMA^(wiE~iKl*5cBYdPh9)5i4N1@h zDBIt@04YHLiN^v|X5z$-_y1dfcrAdXD*h=i$zqx3w5$0;gY$RI+n;%vG4}5FcUeO| zu;RyuU#r1Pd~cZk_RHZH7a7kO=3{NgNy(JD|4ErD?bT-WN`Dw<5V5jV>Kp#)b4kP> zT=P)T4O>N6XBG#~C8!Yf^wh+(*DyD$ z%k}bR1;*(1C(N#;oR_%xIu!X^BRIGXJs_7%akHWE5vey+!ZuxXzbOY1gM9mnQ^M|MWx~AJ}yvHSkpll7oUB{b_U(&Y9Kov3U z4bpn`&$rdXBlNi%<_1WO-v=mbtQg^r;}}dc1P07GN`KuQE^8X))NPg1vcx$@ht3XU z7nn=YMm67PDA}rKY788HZD`ApEb6AU4^A6#A~T?e8leJbB?H#$sG)6vTc}9%T#j(t z(iSY>SV-iI0`@_-+hMW~v}cu(8py1&_6O$ZiP9fX1*u8ZRY)keq=uGVe2Z9D2@$k= z^^YIrJAa)2h*B_I7cl~84I0XbG=bXpEsHiSt)c};_=*y>S-r(j1{~T(7brr#(5y8zd&oF^)VeO<_Ytl}nc>*ck(vvj;Kb-ylvAdoBr2MQZ@%M4Jy`R`FE>@SzZ`Y6L>(#^K-TFIHf$PI4K=DFmY+@7x7hUrpS{I)%0MAObXfp9! z`hSszce5OKL_D~YYJucjA-5xhBV<{EfS6(J zj;Ow-<)p%Dpv{nrO7IB8LqC8%)4INE?=!xO=<;Ve2|D7$22aGhjtM7RnylMaG8%ko z3Fo*zcH?0su*@@IV&DKL3Sd8|2_y0rOMiKuu^qyDEEiviN~0VDWl|UT6|*#m+C0ec zPW;2$F6Uy}NH13ZfO1+j87EIfG}K!Ui!EOvXQ7hhdQExuR7O{{Xla8Ki;2fIa8fX5 zs@sN?BGMNn5sysvauM(wyB?G>Vh&K=X2t1=rGUiH7!~JuzSDPE#KiFF*KI6ksec5x zUhmnkzAg1tE<#_@tnid33DDydd z`Xp>UDe?(K48*X#f4G;Xk;nlZDuDWy=2_K5R%L+5xE*cEY|Em`rpcUOEr5vN9#s?U zb4R(VG$}-fCmVv>$Xd%)qAkYDa(^_0(Q=RVE}62L9x-aN8X|Ev6XR&o6wskDQbC7c zC1KGs2&vJE9THm<*;V=pTAo7SBDIwU%&4i882W@it1!b^!knUra0`n^S|qL017bKh zNGgQoh}C{VVcJhHmeXoK=O9oZ#~p)VFacQ{ zhL?S)M?1;w(iIy-`qMGWnd?r--pac53E{aUa$rV^6H4A3VaDujIl*YwCc<+0?d;wTI$A0@cq$lA0cVZ#&K{bbIV7{+*x4V{$yUjO7iD&mRW^q9 z%LyDdm}`(BVmNLX*&)9x2!FH4yik@%wUpHxJ^E)YC&KB(+b5xJY&{ehd&W9akclH# zYzp(BtL^BNTqp-1;DF8cpw+>=iT-%%nC}f6djcfLT<)QVEDG&RIHYL={zc5W(X!zP zIYJ`V@BOf=j1iq~$s<&=e+0|-fPJzw5iPz+2qgL0-}Gf?kOM2nHT zveJNzq|%4-)q((bntzy0`Z&5cu-b&)M2MCy^qoOq{c#~w$e*YubzXJ_HgDqQ0ma{Y zdF3UqeTzA$eirTeA5cYW%4tpVIXp2TK4oHyv!h)*r(m?t%AWyXq6B4es2jA8x>#M) zh}{Dl)|)xiGPib#kh9dOPaISi;DM4Ll$GTWh6aXkLe%Me#ec^w3BOz5Qzb0^afzfe zIPMHlA2cOaP7jY0BjU6mI5F;pWb62k3tR-78(%sP$jcaDa{^BH0eSS&4EHH_@fUS#JSOz%$+i=+HCW2AHS(um?3``;xF@ z2_EamNn_pq)PECto1>q0N^f`elTPZTGuAyZPIxCKYh3S9Q)W5d(K2F4#&1v)_oQ*# z(3G9$VUH3Q@R_0^w2F!|e5bs#ls z8)DjNgPcJ!f-x{dtBSi{+X1G%!g#v6oih?RK+f(Dfqxp}lLNUpPOi)j3+Vfio#S%~ z0-EvV56FBPvTFNVsP+{6M2J-=8lf4opzG=TCPCpb3;<}Rw_q^)#q$1sb$b!%WpTN@ zx{lSXSNGS;&nuv8`auye`^ClTuWw%>oh(-C_1!vFbai`q7pwVqxxT%+g_h6$Sr>54 zB4_&qS5k}r7_C!uB94CUFi(*V`DA|prPhz`@Jn1D(g9Q%Z(fBowzsvQnux-=-$C{3 nyf2)_Ngc12`XQdJBt$6RpTvwu>%7V1A*pRcIZ^%(T6WQW>-9^* delta 2039 zcmVOW)kY*#^y3CyQdA2u7kEHo8Jl zIlg^K$)-t($B^@3iGDM1QPomHL{0IV-66K`I_9 zx?!sbYs|?5X4`4;pM7>Sy@t77U96Ya zD=gIvMIPsu9lyer7b=bj|~?bFYvhRx!9`LL2*fF8cztpMF++MB2u zQ)vD)l0UEN?G~5n~q=9ti+&-81@Efz54sx>iz-Ru7X{k?N8X#7aU_en zVfM*sBTi%nbXOyk6I`^wdhIne%L#*u#K`4{Fjh0LfD<8+D+<_0z11}n!2UZ1Zv;+ zEZVTTjDHp&;VVkSaJ3~+1<6D{gHmRO2-{kivxfDN;G=x3icM1a z?wSwen4&JYsc@ktlNW^RRW{^w00nu2#DqD9uYZT7DQu{ya_JHUJ7WHD^xR?mKZw_; zeJLnUMQZ@%M4O7n&Oz-#PA9gD^VP-j+tma5^YZ@TcKscxeDQvi7kD8v_6~|c@~*iT zy-N-lfM=yzG+4AtKT|O0EKbYFOGg=z+sC3St3=A%6JaDmI&aHlISq(txPxkeKiDl%YO!Q`bb4bee|%{^5t?BDrlzHl;g)Dx}rI& z8>CpRXs&^if;m#%Hnb24wkU~cGC9gco^5P4P|A$iK{>Hrf<;+eVd5lR3d!$dBOeRTJz>S94Wq znu{SyHNpa4QcD*m7uNIp>zdia^*{ie|wBtUWVMcor!UDX$ol98L6OM zdXW&O3_@ytVTZ&PMGlpINtH(hB!5rsr2#YQ>LiA~M9(VBu=}4=6p?dNLfa|}j90?sjZxD`gFacQ{ z1_CwIodu(uxo$G-O|DxX5T2_I2WF%=pyYiAX`&G}=5mub+^1{Dlp#$c@PBV&9gCI?r;ZqpleFYUG zx1{qxNP6%2UO)xKz-LEL&NLMT>itiWV&ty(NkB$Y=|eA3@g{at6r=)`A&YRosKl z4lwN%#xoA>oRPo*a*j<1)DRyW$N(@oDBcB$(~+IyJI#P*eB=o-pQdHnfg4nN2=EbN zm2O37hUaM2^xsZm{&Bbl3=AY&I=JEzwKKr-6aLpoXUlUv{{%z|jMJIB_myYlh z>F_e)H=xw|>9Swq`bZh5GM>PPG`45+P)$VP+#dt^b>1(3;-rpmeEbm4b_pVsAF_zO VZ?w+)CNLzmZJH*^{{Ri!AIIu`>qr0q diff --git a/search/search_index.json b/search/search_index.json index 0cd4f2c..1f1da65 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"mt5cli \u00b6 Command-line tool for MetaTrader 5 data export. Overview \u00b6 mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5. Features \u00b6 Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows Installation \u00b6 pip install mt5cli Programmatic usage / SDK usage \u00b6 mt5cli can be used as a small Python SDK for read-only MetaTrader 5 data collection. SDK functions return pandas DataFrames without writing files. Use export_dataframe or export_dataframe_to_sqlite when you need to persist results. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Mt5CliClient , collect_history , copy_rates_range , export_dataframe , export_dataframe_to_sqlite , load_rate_data , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # One-off fetch with module-level helpers rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) export_dataframe ( rates , Path ( \"rates.csv\" ), \"csv\" ) # Resolve SQLite rate compatibility views for downstream tools view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # Recent tick window and minimum margin summary ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Reuse one MT5 connection for multiple calls with Mt5CliClient ( login = 12345 , password = \"secret\" , server = \"Broker-Demo\" ) as client : account = client . account_info () positions = client . positions () latest = client . latest_rates ( \"EURUSD\" , \"M1\" , count = 100 ) summary = client . mt5_summary () summary_table = client . mt5_summary_as_df () # Bulk SQLite collection (same behavior as the collect-history CLI command) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), timeframe = \"M1\" , flags = \"ALL\" , with_views = True , ) Timeframes, tick flags, and ISO 8601 date strings are accepted wherever noted in the SDK API. Mt5CliClient.mt5_summary() returns the SDK structured form as plain nested Python values. Use Mt5CliClient.mt5_summary_as_df() when you need a one-row DataFrame for export. The mt5-summary CLI command uses this tabular form, so nested terminal/account fields are JSON-encoded strings that are safe for CSV, JSON, Parquet, and SQLite output. Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions Commands \u00b6 Rates \u00b6 Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range Ticks \u00b6 Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window Information \u00b6 Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book) Trading \u00b6 Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes . Bulk Collection \u00b6 Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database. Global Options \u00b6 Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR) Requirements \u00b6 Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform API Reference \u00b6 Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities Development \u00b6 This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings License \u00b6 MIT License - see LICENSE file for details.","title":"Home"},{"location":"#mt5cli","text":"Command-line tool for MetaTrader 5 data export.","title":"mt5cli"},{"location":"#overview","text":"mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5.","title":"Overview"},{"location":"#features","text":"Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows","title":"Features"},{"location":"#installation","text":"pip install mt5cli","title":"Installation"},{"location":"#programmatic-usage-sdk-usage","text":"mt5cli can be used as a small Python SDK for read-only MetaTrader 5 data collection. SDK functions return pandas DataFrames without writing files. Use export_dataframe or export_dataframe_to_sqlite when you need to persist results. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Mt5CliClient , collect_history , copy_rates_range , export_dataframe , export_dataframe_to_sqlite , load_rate_data , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # One-off fetch with module-level helpers rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) export_dataframe ( rates , Path ( \"rates.csv\" ), \"csv\" ) # Resolve SQLite rate compatibility views for downstream tools view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # Recent tick window and minimum margin summary ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Reuse one MT5 connection for multiple calls with Mt5CliClient ( login = 12345 , password = \"secret\" , server = \"Broker-Demo\" ) as client : account = client . account_info () positions = client . positions () latest = client . latest_rates ( \"EURUSD\" , \"M1\" , count = 100 ) summary = client . mt5_summary () summary_table = client . mt5_summary_as_df () # Bulk SQLite collection (same behavior as the collect-history CLI command) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), timeframe = \"M1\" , flags = \"ALL\" , with_views = True , ) Timeframes, tick flags, and ISO 8601 date strings are accepted wherever noted in the SDK API. Mt5CliClient.mt5_summary() returns the SDK structured form as plain nested Python values. Use Mt5CliClient.mt5_summary_as_df() when you need a one-row DataFrame for export. The mt5-summary CLI command uses this tabular form, so nested terminal/account fields are JSON-encoded strings that are safe for CSV, JSON, Parquet, and SQLite output.","title":"Programmatic usage / SDK usage"},{"location":"#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions","title":"Quick Start"},{"location":"#commands","text":"","title":"Commands"},{"location":"#rates","text":"Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range","title":"Rates"},{"location":"#ticks","text":"Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window","title":"Ticks"},{"location":"#information","text":"Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book)","title":"Information"},{"location":"#trading","text":"Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes .","title":"Trading"},{"location":"#bulk-collection","text":"Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database.","title":"Bulk Collection"},{"location":"#global-options","text":"Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR)","title":"Global Options"},{"location":"#requirements","text":"Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform","title":"Requirements"},{"location":"#api-reference","text":"Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities","title":"API Reference"},{"location":"#development","text":"This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings","title":"Development"},{"location":"#license","text":"MIT License - see LICENSE file for details.","title":"License"},{"location":"api/","text":"API Reference \u00b6 This section contains the complete API documentation for mt5cli. Modules \u00b6 The mt5cli package consists of the following modules: CLI \u00b6 Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats. Utils \u00b6 Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data. SDK \u00b6 Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection. History Collection (SQLite) \u00b6 SQLite storage helpers for the collect-history command schema, incremental updates, deduplication, indexes, and optional views. Architecture Overview \u00b6 The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands that delegate to the SDK and export results. SDK Layer ( sdk.py ): Read-only data access functions, Mt5CliClient , and collect_history orchestration. Utils Layer ( utils.py ): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access. Usage Guidelines \u00b6 All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" Python API \u00b6 from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Dataset , IfExists , Mt5CliClient , collect_history , copy_rates_range , detect_format , export_dataframe , export_dataframe_to_sqlite , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # Fetch rates programmatically rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame export_dataframe ( rates , Path ( \"output.csv\" ), \"csv\" ) # Append to SQLite with deduplication export_dataframe_to_sqlite ( rates , Path ( \"history.db\" ), \"rates\" , if_exists = IfExists . APPEND , deduplicate_on = ( \"symbol\" , \"timeframe\" , \"time\" ), ) # Resolve rate compatibility views and fetch recent ticks view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Collect history into SQLite collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), ) Examples \u00b6 See individual module pages for detailed usage examples and code samples.","title":"Overview"},{"location":"api/#api-reference","text":"This section contains the complete API documentation for mt5cli.","title":"API Reference"},{"location":"api/#modules","text":"The mt5cli package consists of the following modules:","title":"Modules"},{"location":"api/#cli","text":"Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats.","title":"CLI"},{"location":"api/#utils","text":"Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data.","title":"Utils"},{"location":"api/#sdk","text":"Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection.","title":"SDK"},{"location":"api/#history-collection-sqlite","text":"SQLite storage helpers for the collect-history command schema, incremental updates, deduplication, indexes, and optional views.","title":"History Collection (SQLite)"},{"location":"api/#architecture-overview","text":"The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands that delegate to the SDK and export results. SDK Layer ( sdk.py ): Read-only data access functions, Mt5CliClient , and collect_history orchestration. Utils Layer ( utils.py ): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access.","title":"Architecture Overview"},{"location":"api/#usage-guidelines","text":"All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation","title":"Usage Guidelines"},{"location":"api/#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\"","title":"Quick Start"},{"location":"api/#python-api","text":"from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Dataset , IfExists , Mt5CliClient , collect_history , copy_rates_range , detect_format , export_dataframe , export_dataframe_to_sqlite , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # Fetch rates programmatically rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame export_dataframe ( rates , Path ( \"output.csv\" ), \"csv\" ) # Append to SQLite with deduplication export_dataframe_to_sqlite ( rates , Path ( \"history.db\" ), \"rates\" , if_exists = IfExists . APPEND , deduplicate_on = ( \"symbol\" , \"timeframe\" , \"time\" ), ) # Resolve rate compatibility views and fetch recent ticks view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Collect history into SQLite collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), )","title":"Python API"},{"location":"api/#examples","text":"See individual module pages for detailed usage examples and code samples.","title":"Examples"},{"location":"api/cli/","text":"CLI Module \u00b6 mt5cli.cli \u00b6 Command-line interface for MetaTrader 5 data export. app module-attribute \u00b6 app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , ) logger module-attribute \u00b6 logger = getLogger ( __name__ ) account_info \u00b6 account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 366 367 368 369 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . account_info ) collect_history \u00b6 collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , ) history_deals \u00b6 history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 540 541 542 543 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . last_error ) latest_rates \u00b6 latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos ), ) main \u00b6 main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 714 715 716 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app () market_book \u00b6 market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 556 557 558 559 560 561 562 563 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . market_book ( symbol )) minimum_margins \u00b6 minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 401 402 403 404 405 406 407 408 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . minimum_margins ( symbol )) mt5_summary \u00b6 mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 527 528 529 530 531 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , client . mt5_summary_as_df ) order_check \u00b6 order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_check_as_df ( request = request ), ) _execute_export ( ctx , _fetch ) order_send \u00b6 order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_send_as_df ( request = request ), ) _execute_export ( ctx , _fetch ) orders \u00b6 orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 411 412 413 414 415 416 417 418 419 420 421 422 423 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . orders ( symbol = symbol , group = group , ticket = ticket ), ) positions \u00b6 positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 426 427 428 429 430 431 432 433 434 435 436 437 438 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . positions ( symbol = symbol , group = group , ticket = ticket ), ) rates_from \u00b6 rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from ( symbol , timeframe , date_from , count ), ) rates_from_pos \u00b6 rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count ), ) rates_range \u00b6 rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), ) recent_history_deals \u00b6 recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), ) symbol_info \u00b6 symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 391 392 393 394 395 396 397 398 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info ( symbol )) symbol_info_tick \u00b6 symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 546 547 548 549 550 551 552 553 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info_tick ( symbol )) symbols \u00b6 symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 378 379 380 381 382 383 384 385 386 387 388 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbols ( group = group )) terminal_info \u00b6 terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 372 373 374 375 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . terminal_info ) ticks_from \u00b6 ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_from ( symbol , date_from , count , flags ), ) ticks_range \u00b6 ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_range ( symbol , date_from , date_to , flags ), ) ticks_recent \u00b6 ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), ) version \u00b6 version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 534 535 536 537 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . version )","title":"CLI"},{"location":"api/cli/#cli-module","text":"","title":"CLI Module"},{"location":"api/cli/#mt5cli.cli","text":"Command-line interface for MetaTrader 5 data export.","title":"cli"},{"location":"api/cli/#mt5cli.cli.app","text":"app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , )","title":"app"},{"location":"api/cli/#mt5cli.cli.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/cli/#mt5cli.cli.account_info","text":"account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 366 367 368 369 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . account_info )","title":"account_info"},{"location":"api/cli/#mt5cli.cli.collect_history","text":"collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , )","title":"collect_history"},{"location":"api/cli/#mt5cli.cli.history_deals","text":"history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/cli/#mt5cli.cli.history_orders","text":"history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/cli/#mt5cli.cli.last_error","text":"last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 540 541 542 543 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . last_error )","title":"last_error"},{"location":"api/cli/#mt5cli.cli.latest_rates","text":"latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos ), )","title":"latest_rates"},{"location":"api/cli/#mt5cli.cli.main","text":"main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 714 715 716 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app ()","title":"main"},{"location":"api/cli/#mt5cli.cli.market_book","text":"market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 556 557 558 559 560 561 562 563 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . market_book ( symbol ))","title":"market_book"},{"location":"api/cli/#mt5cli.cli.minimum_margins","text":"minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 401 402 403 404 405 406 407 408 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . minimum_margins ( symbol ))","title":"minimum_margins"},{"location":"api/cli/#mt5cli.cli.mt5_summary","text":"mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 527 528 529 530 531 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , client . mt5_summary_as_df )","title":"mt5_summary"},{"location":"api/cli/#mt5cli.cli.order_check","text":"order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_check_as_df ( request = request ), ) _execute_export ( ctx , _fetch )","title":"order_check"},{"location":"api/cli/#mt5cli.cli.order_send","text":"order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_send_as_df ( request = request ), ) _execute_export ( ctx , _fetch )","title":"order_send"},{"location":"api/cli/#mt5cli.cli.orders","text":"orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 411 412 413 414 415 416 417 418 419 420 421 422 423 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . orders ( symbol = symbol , group = group , ticket = ticket ), )","title":"orders"},{"location":"api/cli/#mt5cli.cli.positions","text":"positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 426 427 428 429 430 431 432 433 434 435 436 437 438 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . positions ( symbol = symbol , group = group , ticket = ticket ), )","title":"positions"},{"location":"api/cli/#mt5cli.cli.rates_from","text":"rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from ( symbol , timeframe , date_from , count ), )","title":"rates_from"},{"location":"api/cli/#mt5cli.cli.rates_from_pos","text":"rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count ), )","title":"rates_from_pos"},{"location":"api/cli/#mt5cli.cli.rates_range","text":"rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), )","title":"rates_range"},{"location":"api/cli/#mt5cli.cli.recent_history_deals","text":"recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), )","title":"recent_history_deals"},{"location":"api/cli/#mt5cli.cli.symbol_info","text":"symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 391 392 393 394 395 396 397 398 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info ( symbol ))","title":"symbol_info"},{"location":"api/cli/#mt5cli.cli.symbol_info_tick","text":"symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 546 547 548 549 550 551 552 553 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info_tick ( symbol ))","title":"symbol_info_tick"},{"location":"api/cli/#mt5cli.cli.symbols","text":"symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 378 379 380 381 382 383 384 385 386 387 388 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbols ( group = group ))","title":"symbols"},{"location":"api/cli/#mt5cli.cli.terminal_info","text":"terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 372 373 374 375 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . terminal_info )","title":"terminal_info"},{"location":"api/cli/#mt5cli.cli.ticks_from","text":"ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_from ( symbol , date_from , count , flags ), )","title":"ticks_from"},{"location":"api/cli/#mt5cli.cli.ticks_range","text":"ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_range ( symbol , date_from , date_to , flags ), )","title":"ticks_range"},{"location":"api/cli/#mt5cli.cli.ticks_recent","text":"ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), )","title":"ticks_recent"},{"location":"api/cli/#mt5cli.cli.version","text":"version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 534 535 536 537 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . version )","title":"version"},{"location":"api/history/","text":"History Collection (SQLite) \u00b6 mt5cli.history \u00b6 SQLite storage helpers for the collect-history incremental data pipeline. DEFAULT_HISTORY_TIMEFRAMES module-attribute \u00b6 DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = tuple ( TIMEFRAME_MAP ) SqliteConnOrPath module-attribute \u00b6 SqliteConnOrPath = Connection | Path | str logger module-attribute \u00b6 logger = getLogger ( __name__ ) DedupScope dataclass \u00b6 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 \u00b6 params : tuple [ object , ... ] required_columns instance-attribute \u00b6 required_columns : frozenset [ str ] where instance-attribute \u00b6 where : str RateTarget dataclass \u00b6 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 \u00b6 symbol : str | None timeframe instance-attribute \u00b6 timeframe : int | str timeframe_int property \u00b6 timeframe_int : int Return the timeframe as its integer MT5 value. __post_init__ \u00b6 __post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 506 507 508 509 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 )) append_dataframe \u00b6 append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> 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 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> 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 . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . 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 \u00b6 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 920 921 922 923 924 925 926 927 928 929 930 931 932 933 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 \u00b6 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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 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 ] build_rate_view_name \u00b6 build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \" create_cash_events_view \u00b6 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 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 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\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True create_history_indexes \u00b6 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 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" 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)\" , ) 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)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , ) create_positions_reconstructed_view \u00b6 create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed 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 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" 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,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True create_rate_compatibility_views \u00b6 create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , ) deduplicate_history_tables \u00b6 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 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 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 \u00b6 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 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 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 ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , ) drop_rate_compatibility_views \u00b6 drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1226 1227 1228 1229 1230 1231 1232 1233 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" ) filter_incremental_history_deals_frame \u00b6 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 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 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 () 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 \u00b6 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 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 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 \u00b6 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 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 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.\"\"\" 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 row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start get_incremental_start_datetime \u00b6 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 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 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 \u00b6 get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 709 710 711 712 713 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows } load_incremental_start_datetimes \u00b6 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 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 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.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in 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 } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols } load_rate_data \u00b6 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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 \u00b6 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 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 ) load_rate_series_from_sqlite \u00b6 load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] Load multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] Rate targets to load. Each (symbol, timeframe_int) pair must be unique. required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ]: \"\"\"Load multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. Returns: Mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close () parse_sqlite_timestamp \u00b6 parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None quote_sqlite_identifier \u00b6 quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 54 55 56 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"' record_written_columns \u00b6 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 907 908 909 910 911 912 913 914 915 916 917 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 resolve_granularity_name \u00b6 resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" for name , value in TIMEFRAME_MAP . items (): if value == timeframe : return name return str ( timeframe ) resolve_history_datasets \u00b6 resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 59 60 61 62 63 64 65 66 67 68 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets ) resolve_history_tick_flags \u00b6 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 90 91 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" if isinstance ( flags , int ): return flags return parse_tick_flags ( flags ) resolve_history_timeframes \u00b6 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 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 = value if isinstance ( value , int ) else parse_timeframe ( str ( value )) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved resolve_rate_tables \u00b6 resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () resolve_rate_view_name \u00b6 resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close () resolve_rate_view_names \u00b6 resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () write_collected_datasets \u00b6 write_collected_datasets ( conn : Connection , client : Mt5DataClient , 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 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" 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_get_as_df , 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_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns write_history_dataset \u00b6 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 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 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. \"\"\" table_exists = False 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 , if_exists , written_columns , ) for sym in symbols : frame = fetch ( date_from = date_from , date_to = date_to , symbol = sym ) frame = filter_trade_history_frame ( frame , [ sym ], include_account_events = False , ) table_exists = write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) return table_exists write_incremental_datasets \u00b6 write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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. \"\"\" 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 , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns write_rates_dataset \u00b6 write_rates_dataset ( conn : Connection , client : Mt5DataClient , 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 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) table_exists = write_streamed_frame ( conn , frame , Dataset . rates , table_exists , if_exists , written_columns , ) return table_exists write_streamed_frame \u00b6 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 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 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. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists write_ticks_dataset \u00b6 write_ticks_dataset ( conn : Connection , client : Mt5DataClient , 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 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) table_exists = write_streamed_frame ( conn , frame , Dataset . ticks , table_exists , if_exists , written_columns , ) return table_exists collect-history schema \u00b6 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. Entity-relationship diagram \u00b6 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 } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } 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)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\" Tables and views \u00b6 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. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing. Incremental collection \u00b6 The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True . Rate view resolution \u00b6 Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection . Rate data loading \u00b6 Use load_rate_data() to load a table or view from a SQLite path, or load_rate_data_from_connection() when you already have a connection: from pathlib import Path from mt5cli import load_rate_data from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time . Multi-series rate loading \u00b6 For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected.","title":"History Collection (SQLite)"},{"location":"api/history/#history-collection-sqlite","text":"","title":"History Collection (SQLite)"},{"location":"api/history/#mt5cli.history","text":"SQLite storage helpers for the collect-history incremental data pipeline.","title":"history"},{"location":"api/history/#mt5cli.history.DEFAULT_HISTORY_TIMEFRAMES","text":"DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = tuple ( TIMEFRAME_MAP )","title":"DEFAULT_HISTORY_TIMEFRAMES"},{"location":"api/history/#mt5cli.history.SqliteConnOrPath","text":"SqliteConnOrPath = Connection | Path | str","title":"SqliteConnOrPath"},{"location":"api/history/#mt5cli.history.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/history/#mt5cli.history.DedupScope","text":"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.","title":"DedupScope"},{"location":"api/history/#mt5cli.history.DedupScope.params","text":"params : tuple [ object , ... ]","title":"params"},{"location":"api/history/#mt5cli.history.DedupScope.required_columns","text":"required_columns : frozenset [ str ]","title":"required_columns"},{"location":"api/history/#mt5cli.history.DedupScope.where","text":"where : str","title":"where"},{"location":"api/history/#mt5cli.history.RateTarget","text":"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 ).","title":"RateTarget"},{"location":"api/history/#mt5cli.history.RateTarget.symbol","text":"symbol : str | None","title":"symbol"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe","text":"timeframe : int | str","title":"timeframe"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe_int","text":"timeframe_int : int Return the timeframe as its integer MT5 value.","title":"timeframe_int"},{"location":"api/history/#mt5cli.history.RateTarget.__post_init__","text":"__post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 506 507 508 509 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 ))","title":"__post_init__"},{"location":"api/history/#mt5cli.history.append_dataframe","text":"append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> 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 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> 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 . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = False , chunksize = 50_000 , ) return True","title":"append_dataframe"},{"location":"api/history/#mt5cli.history.augment_written_columns_from_sqlite","text":"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 920 921 922 923 924 925 926 927 928 929 930 931 932 933 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","title":"augment_written_columns_from_sqlite"},{"location":"api/history/#mt5cli.history.build_rate_targets","text":"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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 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 ]","title":"build_rate_targets"},{"location":"api/history/#mt5cli.history.build_rate_view_name","text":"build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \"","title":"build_rate_view_name"},{"location":"api/history/#mt5cli.history.create_cash_events_view","text":"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 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 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\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True","title":"create_cash_events_view"},{"location":"api/history/#mt5cli.history.create_history_indexes","text":"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 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" 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)\" , ) 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)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , )","title":"create_history_indexes"},{"location":"api/history/#mt5cli.history.create_positions_reconstructed_view","text":"create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed 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 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" 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,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True","title":"create_positions_reconstructed_view"},{"location":"api/history/#mt5cli.history.create_rate_compatibility_views","text":"create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , )","title":"create_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.deduplicate_history_tables","text":"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 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 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\" )","title":"deduplicate_history_tables"},{"location":"api/history/#mt5cli.history.drop_duplicates_in_table","text":"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 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 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 ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , )","title":"drop_duplicates_in_table"},{"location":"api/history/#mt5cli.history.drop_rate_compatibility_views","text":"drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1226 1227 1228 1229 1230 1231 1232 1233 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" )","title":"drop_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.filter_incremental_history_deals_frame","text":"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 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 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 () 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 ()","title":"filter_incremental_history_deals_frame"},{"location":"api/history/#mt5cli.history.filter_trade_history_frame","text":"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 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 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 ()","title":"filter_trade_history_frame"},{"location":"api/history/#mt5cli.history.get_history_deals_account_event_start_datetime","text":"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 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 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.\"\"\" 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 row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start","title":"get_history_deals_account_event_start_datetime"},{"location":"api/history/#mt5cli.history.get_incremental_start_datetime","text":"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 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 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 ]","title":"get_incremental_start_datetime"},{"location":"api/history/#mt5cli.history.get_table_columns","text":"get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 709 710 711 712 713 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows }","title":"get_table_columns"},{"location":"api/history/#mt5cli.history.load_incremental_start_datetimes","text":"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 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 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.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in 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 } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols }","title":"load_incremental_start_datetimes"},{"location":"api/history/#mt5cli.history.load_rate_data","text":"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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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 ()","title":"load_rate_data"},{"location":"api/history/#mt5cli.history.load_rate_data_from_connection","text":"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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 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 )","title":"load_rate_data_from_connection"},{"location":"api/history/#mt5cli.history.load_rate_series_from_sqlite","text":"load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] Load multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] Rate targets to load. Each (symbol, timeframe_int) pair must be unique. required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ]: \"\"\"Load multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. Returns: Mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close ()","title":"load_rate_series_from_sqlite"},{"location":"api/history/#mt5cli.history.parse_sqlite_timestamp","text":"parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None","title":"parse_sqlite_timestamp"},{"location":"api/history/#mt5cli.history.quote_sqlite_identifier","text":"quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 54 55 56 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"'","title":"quote_sqlite_identifier"},{"location":"api/history/#mt5cli.history.record_written_columns","text":"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 907 908 909 910 911 912 913 914 915 916 917 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","title":"record_written_columns"},{"location":"api/history/#mt5cli.history.resolve_granularity_name","text":"resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" for name , value in TIMEFRAME_MAP . items (): if value == timeframe : return name return str ( timeframe )","title":"resolve_granularity_name"},{"location":"api/history/#mt5cli.history.resolve_history_datasets","text":"resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 59 60 61 62 63 64 65 66 67 68 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets )","title":"resolve_history_datasets"},{"location":"api/history/#mt5cli.history.resolve_history_tick_flags","text":"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 90 91 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" if isinstance ( flags , int ): return flags return parse_tick_flags ( flags )","title":"resolve_history_tick_flags"},{"location":"api/history/#mt5cli.history.resolve_history_timeframes","text":"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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 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 = value if isinstance ( value , int ) else parse_timeframe ( str ( value )) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved","title":"resolve_history_timeframes"},{"location":"api/history/#mt5cli.history.resolve_rate_tables","text":"resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_tables"},{"location":"api/history/#mt5cli.history.resolve_rate_view_name","text":"resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_name"},{"location":"api/history/#mt5cli.history.resolve_rate_view_names","text":"resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_names"},{"location":"api/history/#mt5cli.history.write_collected_datasets","text":"write_collected_datasets ( conn : Connection , client : Mt5DataClient , 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 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" 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_get_as_df , 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_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns","title":"write_collected_datasets"},{"location":"api/history/#mt5cli.history.write_history_dataset","text":"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 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 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. \"\"\" table_exists = False 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 , if_exists , written_columns , ) for sym in symbols : frame = fetch ( date_from = date_from , date_to = date_to , symbol = sym ) frame = filter_trade_history_frame ( frame , [ sym ], include_account_events = False , ) table_exists = write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) return table_exists","title":"write_history_dataset"},{"location":"api/history/#mt5cli.history.write_incremental_datasets","text":"write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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. \"\"\" 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 , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns","title":"write_incremental_datasets"},{"location":"api/history/#mt5cli.history.write_rates_dataset","text":"write_rates_dataset ( conn : Connection , client : Mt5DataClient , 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 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) table_exists = write_streamed_frame ( conn , frame , Dataset . rates , table_exists , if_exists , written_columns , ) return table_exists","title":"write_rates_dataset"},{"location":"api/history/#mt5cli.history.write_streamed_frame","text":"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 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 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. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists","title":"write_streamed_frame"},{"location":"api/history/#mt5cli.history.write_ticks_dataset","text":"write_ticks_dataset ( conn : Connection , client : Mt5DataClient , 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 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) table_exists = write_streamed_frame ( conn , frame , Dataset . ticks , table_exists , if_exists , written_columns , ) return table_exists","title":"write_ticks_dataset"},{"location":"api/history/#collect-history-schema","text":"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.","title":"collect-history schema"},{"location":"api/history/#entity-relationship-diagram","text":"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 } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } 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)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\"","title":"Entity-relationship diagram"},{"location":"api/history/#tables-and-views","text":"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. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing.","title":"Tables and views"},{"location":"api/history/#incremental-collection","text":"The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True .","title":"Incremental collection"},{"location":"api/history/#rate-view-resolution","text":"Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection .","title":"Rate view resolution"},{"location":"api/history/#rate-data-loading","text":"Use load_rate_data() to load a table or view from a SQLite path, or load_rate_data_from_connection() when you already have a connection: from pathlib import Path from mt5cli import load_rate_data from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time .","title":"Rate data loading"},{"location":"api/history/#multi-series-rate-loading","text":"For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected.","title":"Multi-series rate loading"},{"location":"api/sdk/","text":"SDK Module \u00b6 mt5cli.sdk \u00b6 Programmatic SDK for MetaTrader 5 data collection. T module-attribute \u00b6 T = TypeVar ( 'T' ) __all__ module-attribute \u00b6 __all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ] logger module-attribute \u00b6 logger = getLogger ( __name__ ) AccountSpec dataclass \u00b6 AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds. login class-attribute instance-attribute \u00b6 login : int | str | None = None password class-attribute instance-attribute \u00b6 password : str | None = field ( default = None , repr = False ) path class-attribute instance-attribute \u00b6 path : str | None = None server class-attribute instance-attribute \u00b6 server : str | None = None symbols instance-attribute \u00b6 symbols : Sequence [ str ] timeout class-attribute instance-attribute \u00b6 timeout : int | None = None Mt5CliClient \u00b6 Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _client = client self . _owns_client = client is None config property \u00b6 config : Mt5Config Return the underlying MT5 configuration. __enter__ \u00b6 __enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self __exit__ \u00b6 __exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 374 375 376 377 378 379 380 381 382 383 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None account_info \u00b6 account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 537 538 539 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ()) collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, ) copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), ) from_connected_client classmethod \u00b6 from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 339 340 341 342 343 344 345 346 347 348 349 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 651 652 653 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ()) latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 430 431 432 433 434 435 436 437 438 439 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count ) market_book \u00b6 market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 659 660 661 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol )) minimum_margins \u00b6 minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 702 703 704 705 706 707 708 709 710 711 712 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol )) mt5_summary \u00b6 mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary ) mt5_summary_as_df \u00b6 mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 735 736 737 738 739 740 741 742 743 744 745 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], ) orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 553 554 555 556 557 558 559 560 561 562 563 564 565 566 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 568 569 570 571 572 573 574 575 576 577 578 579 580 581 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), ) symbol_info \u00b6 symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 549 550 551 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol )) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 655 656 657 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol )) symbols \u00b6 symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 545 546 547 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group )) terminal_info \u00b6 terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 541 542 543 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ()) version \u00b6 version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 647 648 649 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ()) account_info \u00b6 account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1266 1267 1268 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info () build_config \u00b6 build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 def build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Returns: Configured ``Mt5Config`` instance. \"\"\" return Mt5Config ( path = path , login = login , password = password , server = server , timeout = timeout , ) collect_history \u00b6 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 = 1 , 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 Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 ). 1 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/sdk.py 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 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 = 1 , 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: Start date. date_to: End date. datasets: Datasets to include (defaults to all). 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 = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with _connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as 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 : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , ) collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , ) collect_latest_rates_for_accounts \u00b6 collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) last_error \u00b6 last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 1388 1389 1390 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error () latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ) market_book \u00b6 market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 1402 1403 1404 1405 1406 1407 1408 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol ) minimum_margins \u00b6 minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol ) mt5_session \u00b6 mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with _connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client ) mt5_summary \u00b6 mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 1445 1446 1447 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary () mt5_summary_as_df \u00b6 mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 1450 1451 1452 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df () orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ) symbol_info \u00b6 symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1285 1286 1287 1288 1289 1290 1291 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol ) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 1393 1394 1395 1396 1397 1398 1399 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol ) symbols \u00b6 symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1276 1277 1278 1279 1280 1281 1282 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group ) terminal_info \u00b6 terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1271 1272 1273 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info () update_history \u00b6 update_history ( * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient 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 Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. 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/sdk.py 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` 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 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. 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 sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) update_history_with_config \u00b6 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 , create_rate_views : 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/sdk.py 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 def update_history_with_config ( # noqa: PLR0913 * , 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 , create_rate_views : 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 mt5_config = config or build_config () with _connected_client ( mt5_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 , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) version \u00b6 version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 1383 1384 1385 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","title":"SDK"},{"location":"api/sdk/#sdk-module","text":"","title":"SDK Module"},{"location":"api/sdk/#mt5cli.sdk","text":"Programmatic SDK for MetaTrader 5 data collection.","title":"sdk"},{"location":"api/sdk/#mt5cli.sdk.T","text":"T = TypeVar ( 'T' )","title":"T"},{"location":"api/sdk/#mt5cli.sdk.__all__","text":"__all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ]","title":"__all__"},{"location":"api/sdk/#mt5cli.sdk.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec","text":"AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds.","title":"AccountSpec"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.login","text":"login : int | str | None = None","title":"login"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.password","text":"password : str | None = field ( default = None , repr = False )","title":"password"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.path","text":"path : str | None = None","title":"path"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.server","text":"server : str | None = None","title":"server"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.symbols","text":"symbols : Sequence [ str ]","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.timeout","text":"timeout : int | None = None","title":"timeout"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient","text":"Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _client = client self . _owns_client = client is None","title":"Mt5CliClient"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.config","text":"config : Mt5Config Return the underlying MT5 configuration.","title":"config"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__enter__","text":"__enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self","title":"__enter__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__exit__","text":"__exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 374 375 376 377 378 379 380 381 382 383 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None","title":"__exit__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.account_info","text":"account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 537 538 539 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ())","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.from_connected_client","text":"from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 339 340 341 342 343 344 345 346 347 348 349 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client )","title":"from_connected_client"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.last_error","text":"last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 651 652 653 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ())","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 430 431 432 433 434 435 436 437 438 439 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.market_book","text":"market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 659 660 661 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol ))","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.minimum_margins","text":"minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 702 703 704 705 706 707 708 709 710 711 712 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol ))","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary","text":"mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary )","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary_as_df","text":"mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 735 736 737 738 739 740 741 742 743 744 745 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], )","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 553 554 555 556 557 558 559 560 561 562 563 564 565 566 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 568 569 570 571 572 573 574 575 576 577 578 579 580 581 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info","text":"symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 549 550 551 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol ))","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info_tick","text":"symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 655 656 657 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol ))","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbols","text":"symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 545 546 547 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group ))","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.terminal_info","text":"terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 541 542 543 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ())","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.version","text":"version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 647 648 649 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ())","title":"version"},{"location":"api/sdk/#mt5cli.sdk.account_info","text":"account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1266 1267 1268 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info ()","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.build_config","text":"build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 def build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Returns: Configured ``Mt5Config`` instance. \"\"\" return Mt5Config ( path = path , login = login , password = password , server = server , timeout = timeout , )","title":"build_config"},{"location":"api/sdk/#mt5cli.sdk.collect_history","text":"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 = 1 , 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 Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 ). 1 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/sdk.py 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 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 = 1 , 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: Start date. date_to: End date. datasets: Datasets to include (defaults to all). 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 = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with _connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as 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 : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , )","title":"collect_history"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts","text":"collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result","title":"collect_latest_rates_for_accounts"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.last_error","text":"last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 1388 1389 1390 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error ()","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.market_book","text":"market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 1402 1403 1404 1405 1406 1407 1408 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol )","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.minimum_margins","text":"minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol )","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.mt5_session","text":"mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with _connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client )","title":"mt5_session"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary","text":"mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 1445 1446 1447 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary ()","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary_as_df","text":"mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 1450 1451 1452 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df ()","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.symbol_info","text":"symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1285 1286 1287 1288 1289 1290 1291 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol )","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.symbol_info_tick","text":"symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 1393 1394 1395 1396 1397 1398 1399 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol )","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.symbols","text":"symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1276 1277 1278 1279 1280 1281 1282 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group )","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.terminal_info","text":"terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1271 1272 1273 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info ()","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.update_history","text":"update_history ( * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient 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 Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. 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/sdk.py 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` 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 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. 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 sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history"},{"location":"api/sdk/#mt5cli.sdk.update_history_with_config","text":"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 , create_rate_views : 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/sdk.py 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 def update_history_with_config ( # noqa: PLR0913 * , 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 , create_rate_views : 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 mt5_config = config or build_config () with _connected_client ( mt5_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 , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history_with_config"},{"location":"api/sdk/#mt5cli.sdk.version","text":"version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 1383 1384 1385 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","title":"version"},{"location":"api/utils/","text":"Utils Module \u00b6 mt5cli.utils \u00b6 Utility constants, types, and functions for the mt5cli package. DATETIME_TYPE module-attribute \u00b6 DATETIME_TYPE = _DateTimeType () REQUEST_TYPE module-attribute \u00b6 REQUEST_TYPE = _RequestType () TICK_FLAGS_TYPE module-attribute \u00b6 TICK_FLAGS_TYPE = _TickFlagsType () TICK_FLAG_MAP module-attribute \u00b6 TICK_FLAG_MAP : dict [ str , int ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , } TIMEFRAME_MAP module-attribute \u00b6 TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , } TIMEFRAME_TYPE module-attribute \u00b6 TIMEFRAME_TYPE = _TimeframeType () Dataset \u00b6 Bases: StrEnum Datasets supported by the collect-history command. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history-deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history-orders' rates class-attribute instance-attribute \u00b6 rates = 'rates' table_name property \u00b6 table_name : str Return the SQLite table name for this dataset. ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' IfExists \u00b6 Bases: StrEnum SQLite table conflict behavior for the collect-history command. APPEND class-attribute instance-attribute \u00b6 APPEND = 'append' FAIL class-attribute instance-attribute \u00b6 FAIL = 'fail' REPLACE class-attribute instance-attribute \u00b6 REPLACE = 'replace' LogLevel \u00b6 Bases: StrEnum Logging verbosity levels. DEBUG class-attribute instance-attribute \u00b6 DEBUG = 'DEBUG' ERROR class-attribute instance-attribute \u00b6 ERROR = 'ERROR' INFO class-attribute instance-attribute \u00b6 INFO = 'INFO' WARNING class-attribute instance-attribute \u00b6 WARNING = 'WARNING' OutputFormat \u00b6 Bases: StrEnum Supported output file formats. csv class-attribute instance-attribute \u00b6 csv = 'csv' json class-attribute instance-attribute \u00b6 json = 'json' parquet class-attribute instance-attribute \u00b6 parquet = 'parquet' sqlite3 class-attribute instance-attribute \u00b6 sqlite3 = 'sqlite3' detect_format \u00b6 detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg ) export_dataframe \u00b6 export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) export_dataframe_to_sqlite \u00b6 export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit () parse_datetime \u00b6 parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt parse_request \u00b6 parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed parse_tick_flags \u00b6 parse_tick_flags ( value : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 def parse_timeframe ( value : str ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"Utils"},{"location":"api/utils/#utils-module","text":"","title":"Utils Module"},{"location":"api/utils/#mt5cli.utils","text":"Utility constants, types, and functions for the mt5cli package.","title":"utils"},{"location":"api/utils/#mt5cli.utils.DATETIME_TYPE","text":"DATETIME_TYPE = _DateTimeType ()","title":"DATETIME_TYPE"},{"location":"api/utils/#mt5cli.utils.REQUEST_TYPE","text":"REQUEST_TYPE = _RequestType ()","title":"REQUEST_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAGS_TYPE","text":"TICK_FLAGS_TYPE = _TickFlagsType ()","title":"TICK_FLAGS_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAG_MAP","text":"TICK_FLAG_MAP : dict [ str , int ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , }","title":"TICK_FLAG_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_MAP","text":"TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , }","title":"TIMEFRAME_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_TYPE","text":"TIMEFRAME_TYPE = _TimeframeType ()","title":"TIMEFRAME_TYPE"},{"location":"api/utils/#mt5cli.utils.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/utils/#mt5cli.utils.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/utils/#mt5cli.utils.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/utils/#mt5cli.utils.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/utils/#mt5cli.utils.Dataset.table_name","text":"table_name : str Return the SQLite table name for this dataset.","title":"table_name"},{"location":"api/utils/#mt5cli.utils.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/utils/#mt5cli.utils.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/utils/#mt5cli.utils.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/utils/#mt5cli.utils.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/utils/#mt5cli.utils.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/utils/#mt5cli.utils.LogLevel","text":"Bases: StrEnum Logging verbosity levels.","title":"LogLevel"},{"location":"api/utils/#mt5cli.utils.LogLevel.DEBUG","text":"DEBUG = 'DEBUG'","title":"DEBUG"},{"location":"api/utils/#mt5cli.utils.LogLevel.ERROR","text":"ERROR = 'ERROR'","title":"ERROR"},{"location":"api/utils/#mt5cli.utils.LogLevel.INFO","text":"INFO = 'INFO'","title":"INFO"},{"location":"api/utils/#mt5cli.utils.LogLevel.WARNING","text":"WARNING = 'WARNING'","title":"WARNING"},{"location":"api/utils/#mt5cli.utils.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/utils/#mt5cli.utils.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/utils/#mt5cli.utils.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/utils/#mt5cli.utils.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/utils/#mt5cli.utils.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/utils/#mt5cli.utils.detect_format","text":"detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg )","title":"detect_format"},{"location":"api/utils/#mt5cli.utils.export_dataframe","text":"export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"location":"api/utils/#mt5cli.utils.export_dataframe_to_sqlite","text":"export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit ()","title":"export_dataframe_to_sqlite"},{"location":"api/utils/#mt5cli.utils.parse_datetime","text":"parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt","title":"parse_datetime"},{"location":"api/utils/#mt5cli.utils.parse_request","text":"parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed","title":"parse_request"},{"location":"api/utils/#mt5cli.utils.parse_tick_flags","text":"parse_tick_flags ( value : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/utils/#mt5cli.utils.parse_timeframe","text":"parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 def parse_timeframe ( value : str ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_timeframe"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"mt5cli \u00b6 Command-line tool for MetaTrader 5 data export. Overview \u00b6 mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5. Features \u00b6 Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows Installation \u00b6 pip install mt5cli Programmatic usage / SDK usage \u00b6 mt5cli can be used as a small Python SDK for read-only MetaTrader 5 data collection. SDK functions return pandas DataFrames without writing files. Use export_dataframe or export_dataframe_to_sqlite when you need to persist results. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Mt5CliClient , collect_history , copy_rates_range , export_dataframe , export_dataframe_to_sqlite , load_rate_data , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # One-off fetch with module-level helpers rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) export_dataframe ( rates , Path ( \"rates.csv\" ), \"csv\" ) # Resolve SQLite rate compatibility views for downstream tools view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # Recent tick window and minimum margin summary ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Reuse one MT5 connection for multiple calls with Mt5CliClient ( login = 12345 , password = \"secret\" , server = \"Broker-Demo\" ) as client : account = client . account_info () positions = client . positions () latest = client . latest_rates ( \"EURUSD\" , \"M1\" , count = 100 ) summary = client . mt5_summary () summary_table = client . mt5_summary_as_df () # Bulk SQLite collection (same behavior as the collect-history CLI command) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), timeframe = \"M1\" , flags = \"ALL\" , with_views = True , ) Timeframes, tick flags, and ISO 8601 date strings are accepted wherever noted in the SDK API. Mt5CliClient.mt5_summary() returns the SDK structured form as plain nested Python values. Use Mt5CliClient.mt5_summary_as_df() when you need a one-row DataFrame for export. The mt5-summary CLI command uses this tabular form, so nested terminal/account fields are JSON-encoded strings that are safe for CSV, JSON, Parquet, and SQLite output. Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions Commands \u00b6 Rates \u00b6 Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range Ticks \u00b6 Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window Information \u00b6 Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book) Trading \u00b6 Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes . Bulk Collection \u00b6 Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database. Global Options \u00b6 Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR) Requirements \u00b6 Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform API Reference \u00b6 Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities Development \u00b6 This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings License \u00b6 MIT License - see LICENSE file for details.","title":"Home"},{"location":"#mt5cli","text":"Command-line tool for MetaTrader 5 data export.","title":"mt5cli"},{"location":"#overview","text":"mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5.","title":"Overview"},{"location":"#features","text":"Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows","title":"Features"},{"location":"#installation","text":"pip install mt5cli","title":"Installation"},{"location":"#programmatic-usage-sdk-usage","text":"mt5cli can be used as a small Python SDK for read-only MetaTrader 5 data collection. SDK functions return pandas DataFrames without writing files. Use export_dataframe or export_dataframe_to_sqlite when you need to persist results. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Mt5CliClient , collect_history , copy_rates_range , export_dataframe , export_dataframe_to_sqlite , load_rate_data , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # One-off fetch with module-level helpers rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) export_dataframe ( rates , Path ( \"rates.csv\" ), \"csv\" ) # Resolve SQLite rate compatibility views for downstream tools view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # Recent tick window and minimum margin summary ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Reuse one MT5 connection for multiple calls with Mt5CliClient ( login = 12345 , password = \"secret\" , server = \"Broker-Demo\" ) as client : account = client . account_info () positions = client . positions () latest = client . latest_rates ( \"EURUSD\" , \"M1\" , count = 100 ) summary = client . mt5_summary () summary_table = client . mt5_summary_as_df () # Bulk SQLite collection (same behavior as the collect-history CLI command) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), timeframe = \"M1\" , flags = \"ALL\" , with_views = True , ) Timeframes, tick flags, and ISO 8601 date strings are accepted wherever noted in the SDK API. Mt5CliClient.mt5_summary() returns the SDK structured form as plain nested Python values. Use Mt5CliClient.mt5_summary_as_df() when you need a one-row DataFrame for export. The mt5-summary CLI command uses this tabular form, so nested terminal/account fields are JSON-encoded strings that are safe for CSV, JSON, Parquet, and SQLite output.","title":"Programmatic usage / SDK usage"},{"location":"#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions","title":"Quick Start"},{"location":"#commands","text":"","title":"Commands"},{"location":"#rates","text":"Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range","title":"Rates"},{"location":"#ticks","text":"Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window","title":"Ticks"},{"location":"#information","text":"Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book)","title":"Information"},{"location":"#trading","text":"Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes .","title":"Trading"},{"location":"#bulk-collection","text":"Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database.","title":"Bulk Collection"},{"location":"#global-options","text":"Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR)","title":"Global Options"},{"location":"#requirements","text":"Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform","title":"Requirements"},{"location":"#api-reference","text":"Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities","title":"API Reference"},{"location":"#development","text":"This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings","title":"Development"},{"location":"#license","text":"MIT License - see LICENSE file for details.","title":"License"},{"location":"api/","text":"API Reference \u00b6 This section contains the complete API documentation for mt5cli. Modules \u00b6 The mt5cli package consists of the following modules: CLI \u00b6 Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats. Utils \u00b6 Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data. SDK \u00b6 Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection. History Collection (SQLite) \u00b6 SQLite storage helpers for the collect-history command schema, incremental updates, deduplication, indexes, and optional views. Architecture Overview \u00b6 The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands that delegate to the SDK and export results. SDK Layer ( sdk.py ): Read-only data access functions, Mt5CliClient , and collect_history orchestration. Utils Layer ( utils.py ): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access. Usage Guidelines \u00b6 All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" Python API \u00b6 from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Dataset , IfExists , Mt5CliClient , collect_history , copy_rates_range , detect_format , export_dataframe , export_dataframe_to_sqlite , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # Fetch rates programmatically rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame export_dataframe ( rates , Path ( \"output.csv\" ), \"csv\" ) # Append to SQLite with deduplication export_dataframe_to_sqlite ( rates , Path ( \"history.db\" ), \"rates\" , if_exists = IfExists . APPEND , deduplicate_on = ( \"symbol\" , \"timeframe\" , \"time\" ), ) # Resolve rate compatibility views and fetch recent ticks view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Collect history into SQLite collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), ) Examples \u00b6 See individual module pages for detailed usage examples and code samples.","title":"Overview"},{"location":"api/#api-reference","text":"This section contains the complete API documentation for mt5cli.","title":"API Reference"},{"location":"api/#modules","text":"The mt5cli package consists of the following modules:","title":"Modules"},{"location":"api/#cli","text":"Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats.","title":"CLI"},{"location":"api/#utils","text":"Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data.","title":"Utils"},{"location":"api/#sdk","text":"Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection.","title":"SDK"},{"location":"api/#history-collection-sqlite","text":"SQLite storage helpers for the collect-history command schema, incremental updates, deduplication, indexes, and optional views.","title":"History Collection (SQLite)"},{"location":"api/#architecture-overview","text":"The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands that delegate to the SDK and export results. SDK Layer ( sdk.py ): Read-only data access functions, Mt5CliClient , and collect_history orchestration. Utils Layer ( utils.py ): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access.","title":"Architecture Overview"},{"location":"api/#usage-guidelines","text":"All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation","title":"Usage Guidelines"},{"location":"api/#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\"","title":"Quick Start"},{"location":"api/#python-api","text":"from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Dataset , IfExists , Mt5CliClient , collect_history , copy_rates_range , detect_format , export_dataframe , export_dataframe_to_sqlite , minimum_margins , recent_ticks , ) from mt5cli.history import resolve_rate_view_name # Fetch rates programmatically rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame export_dataframe ( rates , Path ( \"output.csv\" ), \"csv\" ) # Append to SQLite with deduplication export_dataframe_to_sqlite ( rates , Path ( \"history.db\" ), \"rates\" , if_exists = IfExists . APPEND , deduplicate_on = ( \"symbol\" , \"timeframe\" , \"time\" ), ) # Resolve rate compatibility views and fetch recent ticks view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) # Collect history into SQLite collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), )","title":"Python API"},{"location":"api/#examples","text":"See individual module pages for detailed usage examples and code samples.","title":"Examples"},{"location":"api/cli/","text":"CLI Module \u00b6 mt5cli.cli \u00b6 Command-line interface for MetaTrader 5 data export. app module-attribute \u00b6 app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , ) logger module-attribute \u00b6 logger = getLogger ( __name__ ) account_info \u00b6 account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 366 367 368 369 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . account_info ) collect_history \u00b6 collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , ) history_deals \u00b6 history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 540 541 542 543 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . last_error ) latest_rates \u00b6 latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos ), ) main \u00b6 main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 714 715 716 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app () market_book \u00b6 market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 556 557 558 559 560 561 562 563 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . market_book ( symbol )) minimum_margins \u00b6 minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 401 402 403 404 405 406 407 408 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . minimum_margins ( symbol )) mt5_summary \u00b6 mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 527 528 529 530 531 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , client . mt5_summary_as_df ) order_check \u00b6 order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_check_as_df ( request = request ), ) _execute_export ( ctx , _fetch ) order_send \u00b6 order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_send_as_df ( request = request ), ) _execute_export ( ctx , _fetch ) orders \u00b6 orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 411 412 413 414 415 416 417 418 419 420 421 422 423 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . orders ( symbol = symbol , group = group , ticket = ticket ), ) positions \u00b6 positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 426 427 428 429 430 431 432 433 434 435 436 437 438 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . positions ( symbol = symbol , group = group , ticket = ticket ), ) rates_from \u00b6 rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from ( symbol , timeframe , date_from , count ), ) rates_from_pos \u00b6 rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count ), ) rates_range \u00b6 rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), ) recent_history_deals \u00b6 recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), ) symbol_info \u00b6 symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 391 392 393 394 395 396 397 398 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info ( symbol )) symbol_info_tick \u00b6 symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 546 547 548 549 550 551 552 553 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info_tick ( symbol )) symbols \u00b6 symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 378 379 380 381 382 383 384 385 386 387 388 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbols ( group = group )) terminal_info \u00b6 terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 372 373 374 375 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . terminal_info ) ticks_from \u00b6 ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_from ( symbol , date_from , count , flags ), ) ticks_range \u00b6 ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_range ( symbol , date_from , date_to , flags ), ) ticks_recent \u00b6 ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), ) version \u00b6 version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 534 535 536 537 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . version )","title":"CLI"},{"location":"api/cli/#cli-module","text":"","title":"CLI Module"},{"location":"api/cli/#mt5cli.cli","text":"Command-line interface for MetaTrader 5 data export.","title":"cli"},{"location":"api/cli/#mt5cli.cli.app","text":"app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , )","title":"app"},{"location":"api/cli/#mt5cli.cli.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/cli/#mt5cli.cli.account_info","text":"account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 366 367 368 369 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . account_info )","title":"account_info"},{"location":"api/cli/#mt5cli.cli.collect_history","text":"collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , )","title":"collect_history"},{"location":"api/cli/#mt5cli.cli.history_deals","text":"history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/cli/#mt5cli.cli.history_orders","text":"history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/cli/#mt5cli.cli.last_error","text":"last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 540 541 542 543 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . last_error )","title":"last_error"},{"location":"api/cli/#mt5cli.cli.latest_rates","text":"latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos ), )","title":"latest_rates"},{"location":"api/cli/#mt5cli.cli.main","text":"main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 714 715 716 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app ()","title":"main"},{"location":"api/cli/#mt5cli.cli.market_book","text":"market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 556 557 558 559 560 561 562 563 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . market_book ( symbol ))","title":"market_book"},{"location":"api/cli/#mt5cli.cli.minimum_margins","text":"minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 401 402 403 404 405 406 407 408 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . minimum_margins ( symbol ))","title":"minimum_margins"},{"location":"api/cli/#mt5cli.cli.mt5_summary","text":"mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 527 528 529 530 531 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , client . mt5_summary_as_df )","title":"mt5_summary"},{"location":"api/cli/#mt5cli.cli.order_check","text":"order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_check_as_df ( request = request ), ) _execute_export ( ctx , _fetch )","title":"order_check"},{"location":"api/cli/#mt5cli.cli.order_send","text":"order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) export_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_send_as_df ( request = request ), ) _execute_export ( ctx , _fetch )","title":"order_send"},{"location":"api/cli/#mt5cli.cli.orders","text":"orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 411 412 413 414 415 416 417 418 419 420 421 422 423 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . orders ( symbol = symbol , group = group , ticket = ticket ), )","title":"orders"},{"location":"api/cli/#mt5cli.cli.positions","text":"positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 426 427 428 429 430 431 432 433 434 435 436 437 438 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . positions ( symbol = symbol , group = group , ticket = ticket ), )","title":"positions"},{"location":"api/cli/#mt5cli.cli.rates_from","text":"rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from ( symbol , timeframe , date_from , count ), )","title":"rates_from"},{"location":"api/cli/#mt5cli.cli.rates_from_pos","text":"rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count ), )","title":"rates_from_pos"},{"location":"api/cli/#mt5cli.cli.rates_range","text":"rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), )","title":"rates_range"},{"location":"api/cli/#mt5cli.cli.recent_history_deals","text":"recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), )","title":"recent_history_deals"},{"location":"api/cli/#mt5cli.cli.symbol_info","text":"symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 391 392 393 394 395 396 397 398 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info ( symbol ))","title":"symbol_info"},{"location":"api/cli/#mt5cli.cli.symbol_info_tick","text":"symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 546 547 548 549 550 551 552 553 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbol_info_tick ( symbol ))","title":"symbol_info_tick"},{"location":"api/cli/#mt5cli.cli.symbols","text":"symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 378 379 380 381 382 383 384 385 386 387 388 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbols ( group = group ))","title":"symbols"},{"location":"api/cli/#mt5cli.cli.terminal_info","text":"terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 372 373 374 375 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . terminal_info )","title":"terminal_info"},{"location":"api/cli/#mt5cli.cli.ticks_from","text":"ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_from ( symbol , date_from , count , flags ), )","title":"ticks_from"},{"location":"api/cli/#mt5cli.cli.ticks_range","text":"ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_range ( symbol , date_from , date_to , flags ), )","title":"ticks_range"},{"location":"api/cli/#mt5cli.cli.ticks_recent","text":"ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = 1 , ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), )","title":"ticks_recent"},{"location":"api/cli/#mt5cli.cli.version","text":"version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 534 535 536 537 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . version )","title":"version"},{"location":"api/history/","text":"History Collection (SQLite) \u00b6 mt5cli.history \u00b6 SQLite storage helpers for the collect-history incremental data pipeline. DEFAULT_HISTORY_TIMEFRAMES module-attribute \u00b6 DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = tuple ( TIMEFRAME_MAP ) SqliteConnOrPath module-attribute \u00b6 SqliteConnOrPath = Connection | Path | str logger module-attribute \u00b6 logger = getLogger ( __name__ ) DedupScope dataclass \u00b6 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 \u00b6 params : tuple [ object , ... ] required_columns instance-attribute \u00b6 required_columns : frozenset [ str ] where instance-attribute \u00b6 where : str RateTarget dataclass \u00b6 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 \u00b6 symbol : str | None timeframe instance-attribute \u00b6 timeframe : int | str timeframe_int property \u00b6 timeframe_int : int Return the timeframe as its integer MT5 value. __post_init__ \u00b6 __post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 506 507 508 509 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 )) append_dataframe \u00b6 append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> 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 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> 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 . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . 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 \u00b6 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 969 970 971 972 973 974 975 976 977 978 979 980 981 982 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 \u00b6 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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 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 ] build_rate_view_name \u00b6 build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \" create_cash_events_view \u00b6 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 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 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\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True create_history_indexes \u00b6 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 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" 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)\" , ) 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)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , ) create_positions_reconstructed_view \u00b6 create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed 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 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" 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,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True create_rate_compatibility_views \u00b6 create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , ) deduplicate_history_tables \u00b6 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 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 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 \u00b6 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 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 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 ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , ) drop_rate_compatibility_views \u00b6 drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1275 1276 1277 1278 1279 1280 1281 1282 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" ) filter_incremental_history_deals_frame \u00b6 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 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 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 () 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 \u00b6 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 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 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 \u00b6 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 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 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.\"\"\" 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 row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start get_incremental_start_datetime \u00b6 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 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 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 \u00b6 get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 758 759 760 761 762 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows } load_incremental_start_datetimes \u00b6 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 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 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.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in 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 } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols } load_rate_data \u00b6 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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 \u00b6 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 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 ) load_rate_series_by_granularity \u00b6 load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () } load_rate_series_from_sqlite \u00b6 load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] Load multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] Rate targets to load. Each (symbol, timeframe_int) pair must be unique. required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ]: \"\"\"Load multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. Returns: Mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close () parse_sqlite_timestamp \u00b6 parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None quote_sqlite_identifier \u00b6 quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 54 55 56 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"' record_written_columns \u00b6 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 956 957 958 959 960 961 962 963 964 965 966 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 resolve_granularity_name \u00b6 resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" for name , value in TIMEFRAME_MAP . items (): if value == timeframe : return name return str ( timeframe ) resolve_history_datasets \u00b6 resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 59 60 61 62 63 64 65 66 67 68 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets ) resolve_history_tick_flags \u00b6 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 90 91 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" if isinstance ( flags , int ): return flags return parse_tick_flags ( flags ) resolve_history_timeframes \u00b6 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 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 = value if isinstance ( value , int ) else parse_timeframe ( str ( value )) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved resolve_rate_tables \u00b6 resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () resolve_rate_view_name \u00b6 resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close () resolve_rate_view_names \u00b6 resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () write_collected_datasets \u00b6 write_collected_datasets ( conn : Connection , client : Mt5DataClient , 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 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" 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_get_as_df , 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_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns write_history_dataset \u00b6 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 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 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. \"\"\" table_exists = False 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 , if_exists , written_columns , ) for sym in symbols : frame = fetch ( date_from = date_from , date_to = date_to , symbol = sym ) frame = filter_trade_history_frame ( frame , [ sym ], include_account_events = False , ) table_exists = write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) return table_exists write_incremental_datasets \u00b6 write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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. \"\"\" 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 , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns write_rates_dataset \u00b6 write_rates_dataset ( conn : Connection , client : Mt5DataClient , 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 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) table_exists = write_streamed_frame ( conn , frame , Dataset . rates , table_exists , if_exists , written_columns , ) return table_exists write_streamed_frame \u00b6 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 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 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. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists write_ticks_dataset \u00b6 write_ticks_dataset ( conn : Connection , client : Mt5DataClient , 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 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) table_exists = write_streamed_frame ( conn , frame , Dataset . ticks , table_exists , if_exists , written_columns , ) return table_exists collect-history schema \u00b6 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. Entity-relationship diagram \u00b6 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 } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } 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)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\" Tables and views \u00b6 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. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing. Incremental collection \u00b6 The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True . Rate view resolution \u00b6 Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection . Rate data loading \u00b6 Use load_rate_data() to load a table or view from a SQLite path, or load_rate_data_from_connection() when you already have a connection: from pathlib import Path from mt5cli import load_rate_data from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time . Multi-series rate loading \u00b6 For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. load_rate_series_by_granularity() is a thin wrapper that builds the targets, loads the series, and rekeys the result by granularity name to avoid converting integer timeframes downstream: from mt5cli import load_rate_series_by_granularity series = load_rate_series_by_granularity ( \"history.db\" , [ \"EURUSD\" ], [ \"M1\" , \"H1\" ], count = 1000 ) frame = series [ \"EURUSD\" , \"M1\" ] # keyed by (symbol | None, granularity_name)","title":"History Collection (SQLite)"},{"location":"api/history/#history-collection-sqlite","text":"","title":"History Collection (SQLite)"},{"location":"api/history/#mt5cli.history","text":"SQLite storage helpers for the collect-history incremental data pipeline.","title":"history"},{"location":"api/history/#mt5cli.history.DEFAULT_HISTORY_TIMEFRAMES","text":"DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = tuple ( TIMEFRAME_MAP )","title":"DEFAULT_HISTORY_TIMEFRAMES"},{"location":"api/history/#mt5cli.history.SqliteConnOrPath","text":"SqliteConnOrPath = Connection | Path | str","title":"SqliteConnOrPath"},{"location":"api/history/#mt5cli.history.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/history/#mt5cli.history.DedupScope","text":"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.","title":"DedupScope"},{"location":"api/history/#mt5cli.history.DedupScope.params","text":"params : tuple [ object , ... ]","title":"params"},{"location":"api/history/#mt5cli.history.DedupScope.required_columns","text":"required_columns : frozenset [ str ]","title":"required_columns"},{"location":"api/history/#mt5cli.history.DedupScope.where","text":"where : str","title":"where"},{"location":"api/history/#mt5cli.history.RateTarget","text":"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 ).","title":"RateTarget"},{"location":"api/history/#mt5cli.history.RateTarget.symbol","text":"symbol : str | None","title":"symbol"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe","text":"timeframe : int | str","title":"timeframe"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe_int","text":"timeframe_int : int Return the timeframe as its integer MT5 value.","title":"timeframe_int"},{"location":"api/history/#mt5cli.history.RateTarget.__post_init__","text":"__post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 506 507 508 509 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 ))","title":"__post_init__"},{"location":"api/history/#mt5cli.history.append_dataframe","text":"append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> 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 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> 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 . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = False , chunksize = 50_000 , ) return True","title":"append_dataframe"},{"location":"api/history/#mt5cli.history.augment_written_columns_from_sqlite","text":"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 969 970 971 972 973 974 975 976 977 978 979 980 981 982 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","title":"augment_written_columns_from_sqlite"},{"location":"api/history/#mt5cli.history.build_rate_targets","text":"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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 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 ]","title":"build_rate_targets"},{"location":"api/history/#mt5cli.history.build_rate_view_name","text":"build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \"","title":"build_rate_view_name"},{"location":"api/history/#mt5cli.history.create_cash_events_view","text":"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 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 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\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True","title":"create_cash_events_view"},{"location":"api/history/#mt5cli.history.create_history_indexes","text":"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 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" 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)\" , ) 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)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , )","title":"create_history_indexes"},{"location":"api/history/#mt5cli.history.create_positions_reconstructed_view","text":"create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed 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 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" 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,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True","title":"create_positions_reconstructed_view"},{"location":"api/history/#mt5cli.history.create_rate_compatibility_views","text":"create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , )","title":"create_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.deduplicate_history_tables","text":"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 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 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\" )","title":"deduplicate_history_tables"},{"location":"api/history/#mt5cli.history.drop_duplicates_in_table","text":"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 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 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 ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , )","title":"drop_duplicates_in_table"},{"location":"api/history/#mt5cli.history.drop_rate_compatibility_views","text":"drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1275 1276 1277 1278 1279 1280 1281 1282 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" )","title":"drop_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.filter_incremental_history_deals_frame","text":"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 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 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 () 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 ()","title":"filter_incremental_history_deals_frame"},{"location":"api/history/#mt5cli.history.filter_trade_history_frame","text":"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 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 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 ()","title":"filter_trade_history_frame"},{"location":"api/history/#mt5cli.history.get_history_deals_account_event_start_datetime","text":"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 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 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.\"\"\" 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 row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start","title":"get_history_deals_account_event_start_datetime"},{"location":"api/history/#mt5cli.history.get_incremental_start_datetime","text":"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 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 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 ]","title":"get_incremental_start_datetime"},{"location":"api/history/#mt5cli.history.get_table_columns","text":"get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 758 759 760 761 762 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows }","title":"get_table_columns"},{"location":"api/history/#mt5cli.history.load_incremental_start_datetimes","text":"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 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 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.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in 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 } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols }","title":"load_incremental_start_datetimes"},{"location":"api/history/#mt5cli.history.load_rate_data","text":"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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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 ()","title":"load_rate_data"},{"location":"api/history/#mt5cli.history.load_rate_data_from_connection","text":"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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 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 )","title":"load_rate_data_from_connection"},{"location":"api/history/#mt5cli.history.load_rate_series_by_granularity","text":"load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () }","title":"load_rate_series_by_granularity"},{"location":"api/history/#mt5cli.history.load_rate_series_from_sqlite","text":"load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] Load multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] Rate targets to load. Each (symbol, timeframe_int) pair must be unique. required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ]: \"\"\"Load multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. Returns: Mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close ()","title":"load_rate_series_from_sqlite"},{"location":"api/history/#mt5cli.history.parse_sqlite_timestamp","text":"parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None","title":"parse_sqlite_timestamp"},{"location":"api/history/#mt5cli.history.quote_sqlite_identifier","text":"quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 54 55 56 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"'","title":"quote_sqlite_identifier"},{"location":"api/history/#mt5cli.history.record_written_columns","text":"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 956 957 958 959 960 961 962 963 964 965 966 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","title":"record_written_columns"},{"location":"api/history/#mt5cli.history.resolve_granularity_name","text":"resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" for name , value in TIMEFRAME_MAP . items (): if value == timeframe : return name return str ( timeframe )","title":"resolve_granularity_name"},{"location":"api/history/#mt5cli.history.resolve_history_datasets","text":"resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 59 60 61 62 63 64 65 66 67 68 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets )","title":"resolve_history_datasets"},{"location":"api/history/#mt5cli.history.resolve_history_tick_flags","text":"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 90 91 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" if isinstance ( flags , int ): return flags return parse_tick_flags ( flags )","title":"resolve_history_tick_flags"},{"location":"api/history/#mt5cli.history.resolve_history_timeframes","text":"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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 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 = value if isinstance ( value , int ) else parse_timeframe ( str ( value )) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved","title":"resolve_history_timeframes"},{"location":"api/history/#mt5cli.history.resolve_rate_tables","text":"resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_tables"},{"location":"api/history/#mt5cli.history.resolve_rate_view_name","text":"resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_name"},{"location":"api/history/#mt5cli.history.resolve_rate_view_names","text":"resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_names"},{"location":"api/history/#mt5cli.history.write_collected_datasets","text":"write_collected_datasets ( conn : Connection , client : Mt5DataClient , 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 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" 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_get_as_df , 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_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns","title":"write_collected_datasets"},{"location":"api/history/#mt5cli.history.write_history_dataset","text":"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 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 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. \"\"\" table_exists = False 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 , if_exists , written_columns , ) for sym in symbols : frame = fetch ( date_from = date_from , date_to = date_to , symbol = sym ) frame = filter_trade_history_frame ( frame , [ sym ], include_account_events = False , ) table_exists = write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) return table_exists","title":"write_history_dataset"},{"location":"api/history/#mt5cli.history.write_incremental_datasets","text":"write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : 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. \"\"\" 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 , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns","title":"write_incremental_datasets"},{"location":"api/history/#mt5cli.history.write_rates_dataset","text":"write_rates_dataset ( conn : Connection , client : Mt5DataClient , 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 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) table_exists = write_streamed_frame ( conn , frame , Dataset . rates , table_exists , if_exists , written_columns , ) return table_exists","title":"write_rates_dataset"},{"location":"api/history/#mt5cli.history.write_streamed_frame","text":"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 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 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. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists","title":"write_streamed_frame"},{"location":"api/history/#mt5cli.history.write_ticks_dataset","text":"write_ticks_dataset ( conn : Connection , client : Mt5DataClient , 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 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , 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. \"\"\" table_exists = False for sym in symbols : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) table_exists = write_streamed_frame ( conn , frame , Dataset . ticks , table_exists , if_exists , written_columns , ) return table_exists","title":"write_ticks_dataset"},{"location":"api/history/#collect-history-schema","text":"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.","title":"collect-history schema"},{"location":"api/history/#entity-relationship-diagram","text":"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 } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } 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)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\"","title":"Entity-relationship diagram"},{"location":"api/history/#tables-and-views","text":"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. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing.","title":"Tables and views"},{"location":"api/history/#incremental-collection","text":"The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True .","title":"Incremental collection"},{"location":"api/history/#rate-view-resolution","text":"Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection .","title":"Rate view resolution"},{"location":"api/history/#rate-data-loading","text":"Use load_rate_data() to load a table or view from a SQLite path, or load_rate_data_from_connection() when you already have a connection: from pathlib import Path from mt5cli import load_rate_data from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time .","title":"Rate data loading"},{"location":"api/history/#multi-series-rate-loading","text":"For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. load_rate_series_by_granularity() is a thin wrapper that builds the targets, loads the series, and rekeys the result by granularity name to avoid converting integer timeframes downstream: from mt5cli import load_rate_series_by_granularity series = load_rate_series_by_granularity ( \"history.db\" , [ \"EURUSD\" ], [ \"M1\" , \"H1\" ], count = 1000 ) frame = series [ \"EURUSD\" , \"M1\" ] # keyed by (symbol | None, granularity_name)","title":"Multi-series rate loading"},{"location":"api/sdk/","text":"SDK Module \u00b6 mt5cli.sdk \u00b6 Programmatic SDK for MetaTrader 5 data collection. T module-attribute \u00b6 T = TypeVar ( 'T' ) __all__ module-attribute \u00b6 __all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"ThrottledHistoryUpdater\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"collect_latest_rates_for_accounts_with_retries\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"resolve_account_spec\" , \"resolve_account_specs\" , \"substitute_env_placeholders\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ] logger module-attribute \u00b6 logger = getLogger ( __name__ ) AccountSpec dataclass \u00b6 AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds. login class-attribute instance-attribute \u00b6 login : int | str | None = field ( default = None , repr = False ) password class-attribute instance-attribute \u00b6 password : str | None = field ( default = None , repr = False ) path class-attribute instance-attribute \u00b6 path : str | None = None server class-attribute instance-attribute \u00b6 server : str | None = None symbols instance-attribute \u00b6 symbols : Sequence [ str ] timeout class-attribute instance-attribute \u00b6 timeout : int | None = None Mt5CliClient \u00b6 Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _client = client self . _owns_client = client is None config property \u00b6 config : Mt5Config Return the underlying MT5 configuration. __enter__ \u00b6 __enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self __exit__ \u00b6 __exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 382 383 384 385 386 387 388 389 390 391 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None account_info \u00b6 account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 545 546 547 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ()) collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, ) copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), ) from_connected_client classmethod \u00b6 from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 347 348 349 350 351 352 353 354 355 356 357 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 659 660 661 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ()) latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 438 439 440 441 442 443 444 445 446 447 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count ) market_book \u00b6 market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 667 668 669 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol )) minimum_margins \u00b6 minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 710 711 712 713 714 715 716 717 718 719 720 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol )) mt5_summary \u00b6 mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary ) mt5_summary_as_df \u00b6 mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 743 744 745 746 747 748 749 750 751 752 753 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], ) orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 561 562 563 564 565 566 567 568 569 570 571 572 573 574 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), ) symbol_info \u00b6 symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 557 558 559 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol )) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 663 664 665 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol )) symbols \u00b6 symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 553 554 555 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group )) terminal_info \u00b6 terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 549 550 551 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ()) version \u00b6 version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 655 656 657 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ()) ThrottledHistoryUpdater \u00b6 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 , ) Throttled incremental SQLite history updater for long-running apps. Wraps :func: update_history 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. 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 all). 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, Mt5TradingError , Mt5RuntimeError , and sqlite3.Error raised during an update are swallowed and :meth: update returns False without advancing the throttle. When False (default), such errors propagate so callers control logging. False Source code in mt5cli/sdk.py 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 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 , ) -> None : \"\"\"Initialize the throttled updater. Args: output: SQLite database path. datasets: Datasets to include (defaults to all). 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, ``Mt5TradingError``, ``Mt5RuntimeError``, and ``sqlite3.Error`` raised during an update are swallowed and :meth:`update` returns False without advancing the throttle. When False (default), such errors propagate so callers control logging. \"\"\" 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 . _last_update_monotonic : float | None = None datasets instance-attribute \u00b6 datasets = datasets flags instance-attribute \u00b6 flags = flags include_account_events instance-attribute \u00b6 include_account_events = include_account_events interval_seconds instance-attribute \u00b6 interval_seconds = interval_seconds last_update_monotonic property \u00b6 last_update_monotonic : float | None Return the monotonic timestamp of the last successful update. lookback_hours instance-attribute \u00b6 lookback_hours = lookback_hours output instance-attribute \u00b6 output = output suppress_errors instance-attribute \u00b6 suppress_errors = suppress_errors timeframes instance-attribute \u00b6 timeframes = timeframes with_views instance-attribute \u00b6 with_views = with_views should_update \u00b6 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/sdk.py 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 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 \u00b6 update ( client : Mt5DataClient , symbols : Sequence [ str ] ) -> bool Run a throttled incremental history update. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required symbols Sequence [ str ] Symbols to update. required 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. Raises: Type Description Mt5TradingError If the update fails and suppress_errors is False. Mt5RuntimeError If the update fails and suppress_errors is False. Error If the SQLite write fails and suppress_errors is False. Source code in mt5cli/sdk.py 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 def update ( self , client : Mt5DataClient , symbols : Sequence [ str ]) -> bool : \"\"\"Run a throttled incremental history update. Args: client: Connected MT5 data client. symbols: Symbols to update. Returns: True if an update ran successfully, False if it was throttled or (when ``suppress_errors`` is True) failed with a recoverable error. Raises: Mt5TradingError: If the update fails and ``suppress_errors`` is False. Mt5RuntimeError: If the update fails and ``suppress_errors`` is False. sqlite3.Error: If the SQLite write fails and ``suppress_errors`` is False. \"\"\" if not self . should_update (): return False try : update_history ( client = client , output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , with_views = self . with_views , include_account_events = self . include_account_events , ) except ( Mt5TradingError , Mt5RuntimeError , sqlite3 . Error ): if self . suppress_errors : logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise self . _last_update_monotonic = time . monotonic () return True account_info \u00b6 account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1587 1588 1589 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info () build_config \u00b6 build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 def build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Returns: Configured ``Mt5Config`` instance. \"\"\" return Mt5Config ( path = path , login = login , password = password , server = server , timeout = timeout , ) collect_history \u00b6 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 = 1 , 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 Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 ). 1 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/sdk.py 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 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 = 1 , 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: Start date. date_to: End date. datasets: Datasets to include (defaults to all). 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 = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with _connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as 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 : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , ) collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , ) collect_latest_rates_for_accounts \u00b6 collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result collect_latest_rates_for_accounts_with_retries \u00b6 collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func: collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Propagates ValueError dict [ tuple [ str , int ], DataFrame ] for invalid inputs (see :func: collect_latest_rates_for_accounts ) and dict [ tuple [ str , int ], DataFrame ] re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError dict [ tuple [ str , int ], DataFrame ] once retries are exhausted. Source code in mt5cli/sdk.py 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 def collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff. The delay before retry attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError`` for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError`` once retries are exhausted. \"\"\" attempts = max ( retry_count , 0 ) + 1 def _collect () -> dict [ tuple [ str , int ], pd . DataFrame ]: return collect_latest_rates_for_accounts ( accounts , timeframes , count , start_pos = start_pos , base_config = base_config , ) for attempt in range ( attempts - 1 ): try : return _collect () except ( Mt5TradingError , Mt5RuntimeError ) as exc : delay = backoff_base ** ( attempt + 1 ) logger . warning ( \"Rate collection failed (attempt %d / %d ): %s ; retrying in %.1f s\" , attempt + 1 , attempts , exc , delay , ) time . sleep ( delay ) return _collect () copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) last_error \u00b6 last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 1709 1710 1711 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error () latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ) market_book \u00b6 market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 1723 1724 1725 1726 1727 1728 1729 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol ) minimum_margins \u00b6 minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol ) mt5_session \u00b6 mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with _connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client ) mt5_summary \u00b6 mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 1766 1767 1768 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary () mt5_summary_as_df \u00b6 mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 1771 1772 1773 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df () orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ) resolve_account_spec \u00b6 resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> AccountSpec Resolve an account's credentials from overrides and ${ENV_VAR} values. Explicit override arguments take precedence over the corresponding :class: AccountSpec fields. The resolved string fields ( login , password , server , path ) have any ${ENV_VAR} placeholders substituted from the environment. Parameters: Name Type Description Default account AccountSpec Source account specification. required login int | str | None Optional explicit login override. None password str | None Optional explicit password override. None server str | None Optional explicit server override. None path str | None Optional explicit terminal path override. None timeout int | None Optional explicit connection timeout override. None Returns: Type Description AccountSpec A new :class: AccountSpec with resolved credentials and the original AccountSpec symbols preserved. Raises ValueError (via AccountSpec func: substitute_env_placeholders ) if a referenced environment AccountSpec variable is not set. Source code in mt5cli/sdk.py 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 def resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> AccountSpec : \"\"\"Resolve an account's credentials from overrides and ``${ENV_VAR}`` values. Explicit override arguments take precedence over the corresponding :class:`AccountSpec` fields. The resolved string fields (``login``, ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders substituted from the environment. Args: account: Source account specification. login: Optional explicit login override. password: Optional explicit password override. server: Optional explicit server override. path: Optional explicit terminal path override. timeout: Optional explicit connection timeout override. Returns: A new :class:`AccountSpec` with resolved credentials and the original symbols preserved. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return AccountSpec ( symbols = account . symbols , login = _resolve_login ( login , account . login ), password = _resolve_field ( password , account . password ), server = _resolve_field ( server , account . server ), path = _resolve_field ( path , account . path ), timeout = timeout if timeout is not None else account . timeout , ) resolve_account_specs \u00b6 resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> list [ AccountSpec ] Resolve credentials for multiple accounts. Applies the same overrides and ${ENV_VAR} substitution as :func: resolve_account_spec to every account. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Source account specifications. required login int | str | None Optional explicit login override applied to each account. None password str | None Optional explicit password override applied to each account. None server str | None Optional explicit server override applied to each account. None path str | None Optional explicit terminal path override applied to each account. None timeout int | None Optional explicit timeout override applied to each account. None Returns: Type Description list [ AccountSpec ] Resolved account specifications in the original order. Raises list [ AccountSpec ] ValueError (via :func: substitute_env_placeholders ) if a referenced list [ AccountSpec ] environment variable is not set. Source code in mt5cli/sdk.py 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 def resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> list [ AccountSpec ]: \"\"\"Resolve credentials for multiple accounts. Applies the same overrides and ``${ENV_VAR}`` substitution as :func:`resolve_account_spec` to every account. Args: accounts: Source account specifications. login: Optional explicit login override applied to each account. password: Optional explicit password override applied to each account. server: Optional explicit server override applied to each account. path: Optional explicit terminal path override applied to each account. timeout: Optional explicit timeout override applied to each account. Returns: Resolved account specifications in the original order. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return [ resolve_account_spec ( account , login = login , password = password , server = server , path = path , timeout = timeout , ) for account in accounts ] substitute_env_placeholders \u00b6 substitute_env_placeholders ( value : str ) -> str Replace ${ENV_VAR} placeholders in a string with environment values. Parameters: Name Type Description Default value str String that may contain one or more ${ENV_VAR} placeholders. required Returns: Type Description str The string with every placeholder replaced by its environment value. Raises: Type Description ValueError If a referenced environment variable is not set. Source code in mt5cli/sdk.py 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 def substitute_env_placeholders ( value : str ) -> str : \"\"\"Replace ``${ENV_VAR}`` placeholders in a string with environment values. Args: value: String that may contain one or more ``${ENV_VAR}`` placeholders. Returns: The string with every placeholder replaced by its environment value. Raises: ValueError: If a referenced environment variable is not set. \"\"\" parts : list [ str ] = [] last_end = 0 for match in _ENV_PLACEHOLDER_PATTERN . finditer ( value ): parts . append ( value [ last_end : match . start ()]) name = match . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) parts . append ( os . environ [ name ]) last_end = match . end () parts . append ( value [ last_end :]) return \"\" . join ( parts ) symbol_info \u00b6 symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1606 1607 1608 1609 1610 1611 1612 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol ) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 1714 1715 1716 1717 1718 1719 1720 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol ) symbols \u00b6 symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1597 1598 1599 1600 1601 1602 1603 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group ) terminal_info \u00b6 terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1592 1593 1594 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info () update_history \u00b6 update_history ( * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient 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 Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. 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/sdk.py 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` 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 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. 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 sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) update_history_with_config \u00b6 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 , create_rate_views : 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/sdk.py 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 def update_history_with_config ( # noqa: PLR0913 * , 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 , create_rate_views : 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 mt5_config = config or build_config () with _connected_client ( mt5_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 , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) version \u00b6 version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 1704 1705 1706 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version () Resilient multi-account orchestration \u00b6 The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application. Retrying transient rate collection \u00b6 collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final failure is re-raised once retry_count is exhausted. from mt5cli import AccountSpec , collect_latest_rates_for_accounts_with_retries accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )] rates = collect_latest_rates_for_accounts_with_retries ( accounts , [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , backoff_base = 2 , # sleeps 2s, 4s, 8s between attempts ) Resolving credentials and ${ENV_VAR} placeholders \u00b6 resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError . import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_LOGIN\" ] = \"12345\" os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = \"$ {MT5_LOGIN} \" , password = \"$ {MT5_PASSWORD} \" ) ] resolved = resolve_account_specs ( accounts , server = \"Broker-Demo\" ) # resolved[0].login == \"12345\", resolved[0].server == \"Broker-Demo\" Throttled incremental history updates \u00b6 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 pdmt5 import Mt5Config , Mt5DataClient from mt5cli import Dataset , ThrottledHistoryUpdater updater = ThrottledHistoryUpdater ( output = \"history.db\" , datasets = { Dataset . rates }, timeframes = [ \"M1\" ], interval_seconds = 60 , # <= 0 updates on every call ) client = Mt5DataClient ( config = Mt5Config ( login = 12345 )) client . initialize_and_login_mt5 () try : while True : updater . update ( client , [ \"EURUSD\" , \"GBPUSD\" ]) # no-op until 60s elapse # ... do other work; break when shutting down ... finally : client . shutdown () By default Mt5TradingError , Mt5RuntimeError , and sqlite3.Error propagate so the caller controls logging; pass suppress_errors=True to swallow them and return False without advancing the throttle.","title":"SDK"},{"location":"api/sdk/#sdk-module","text":"","title":"SDK Module"},{"location":"api/sdk/#mt5cli.sdk","text":"Programmatic SDK for MetaTrader 5 data collection.","title":"sdk"},{"location":"api/sdk/#mt5cli.sdk.T","text":"T = TypeVar ( 'T' )","title":"T"},{"location":"api/sdk/#mt5cli.sdk.__all__","text":"__all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"ThrottledHistoryUpdater\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"collect_latest_rates_for_accounts_with_retries\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"resolve_account_spec\" , \"resolve_account_specs\" , \"substitute_env_placeholders\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ]","title":"__all__"},{"location":"api/sdk/#mt5cli.sdk.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec","text":"AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds.","title":"AccountSpec"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.login","text":"login : int | str | None = field ( default = None , repr = False )","title":"login"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.password","text":"password : str | None = field ( default = None , repr = False )","title":"password"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.path","text":"path : str | None = None","title":"path"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.server","text":"server : str | None = None","title":"server"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.symbols","text":"symbols : Sequence [ str ]","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.timeout","text":"timeout : int | None = None","title":"timeout"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient","text":"Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _client = client self . _owns_client = client is None","title":"Mt5CliClient"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.config","text":"config : Mt5Config Return the underlying MT5 configuration.","title":"config"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__enter__","text":"__enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self","title":"__enter__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__exit__","text":"__exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 382 383 384 385 386 387 388 389 390 391 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None","title":"__exit__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.account_info","text":"account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 545 546 547 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ())","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.from_connected_client","text":"from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 347 348 349 350 351 352 353 354 355 356 357 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client )","title":"from_connected_client"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.last_error","text":"last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 659 660 661 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ())","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 438 439 440 441 442 443 444 445 446 447 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.market_book","text":"market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 667 668 669 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol ))","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.minimum_margins","text":"minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 710 711 712 713 714 715 716 717 718 719 720 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol ))","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary","text":"mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary )","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary_as_df","text":"mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 743 744 745 746 747 748 749 750 751 752 753 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], )","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 561 562 563 564 565 566 567 568 569 570 571 572 573 574 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info","text":"symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 557 558 559 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol ))","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info_tick","text":"symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 663 664 665 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol ))","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbols","text":"symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 553 554 555 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group ))","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.terminal_info","text":"terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 549 550 551 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ())","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.version","text":"version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 655 656 657 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ())","title":"version"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater","text":"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 , ) Throttled incremental SQLite history updater for long-running apps. Wraps :func: update_history 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. 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 all). 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, Mt5TradingError , Mt5RuntimeError , and sqlite3.Error raised during an update are swallowed and :meth: update returns False without advancing the throttle. When False (default), such errors propagate so callers control logging. False Source code in mt5cli/sdk.py 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 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 , ) -> None : \"\"\"Initialize the throttled updater. Args: output: SQLite database path. datasets: Datasets to include (defaults to all). 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, ``Mt5TradingError``, ``Mt5RuntimeError``, and ``sqlite3.Error`` raised during an update are swallowed and :meth:`update` returns False without advancing the throttle. When False (default), such errors propagate so callers control logging. \"\"\" 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 . _last_update_monotonic : float | None = None","title":"ThrottledHistoryUpdater"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.datasets","text":"datasets = datasets","title":"datasets"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.flags","text":"flags = flags","title":"flags"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.include_account_events","text":"include_account_events = include_account_events","title":"include_account_events"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.interval_seconds","text":"interval_seconds = interval_seconds","title":"interval_seconds"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.last_update_monotonic","text":"last_update_monotonic : float | None Return the monotonic timestamp of the last successful update.","title":"last_update_monotonic"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.lookback_hours","text":"lookback_hours = lookback_hours","title":"lookback_hours"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.output","text":"output = output","title":"output"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.suppress_errors","text":"suppress_errors = suppress_errors","title":"suppress_errors"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.timeframes","text":"timeframes = timeframes","title":"timeframes"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.with_views","text":"with_views = with_views","title":"with_views"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.should_update","text":"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/sdk.py 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 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","title":"should_update"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.update","text":"update ( client : Mt5DataClient , symbols : Sequence [ str ] ) -> bool Run a throttled incremental history update. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required symbols Sequence [ str ] Symbols to update. required 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. Raises: Type Description Mt5TradingError If the update fails and suppress_errors is False. Mt5RuntimeError If the update fails and suppress_errors is False. Error If the SQLite write fails and suppress_errors is False. Source code in mt5cli/sdk.py 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 def update ( self , client : Mt5DataClient , symbols : Sequence [ str ]) -> bool : \"\"\"Run a throttled incremental history update. Args: client: Connected MT5 data client. symbols: Symbols to update. Returns: True if an update ran successfully, False if it was throttled or (when ``suppress_errors`` is True) failed with a recoverable error. Raises: Mt5TradingError: If the update fails and ``suppress_errors`` is False. Mt5RuntimeError: If the update fails and ``suppress_errors`` is False. sqlite3.Error: If the SQLite write fails and ``suppress_errors`` is False. \"\"\" if not self . should_update (): return False try : update_history ( client = client , output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , with_views = self . with_views , include_account_events = self . include_account_events , ) except ( Mt5TradingError , Mt5RuntimeError , sqlite3 . Error ): if self . suppress_errors : logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise self . _last_update_monotonic = time . monotonic () return True","title":"update"},{"location":"api/sdk/#mt5cli.sdk.account_info","text":"account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1587 1588 1589 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info ()","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.build_config","text":"build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 def build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Returns: Configured ``Mt5Config`` instance. \"\"\" return Mt5Config ( path = path , login = login , password = password , server = server , timeout = timeout , )","title":"build_config"},{"location":"api/sdk/#mt5cli.sdk.collect_history","text":"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 = 1 , 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 Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 ). 1 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/sdk.py 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 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 = 1 , 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: Start date. date_to: End date. datasets: Datasets to include (defaults to all). 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 = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with _connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as 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 : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , )","title":"collect_history"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts","text":"collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result","title":"collect_latest_rates_for_accounts"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts_with_retries","text":"collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func: collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Propagates ValueError dict [ tuple [ str , int ], DataFrame ] for invalid inputs (see :func: collect_latest_rates_for_accounts ) and dict [ tuple [ str , int ], DataFrame ] re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError dict [ tuple [ str , int ], DataFrame ] once retries are exhausted. Source code in mt5cli/sdk.py 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 def collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff. The delay before retry attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError`` for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError`` once retries are exhausted. \"\"\" attempts = max ( retry_count , 0 ) + 1 def _collect () -> dict [ tuple [ str , int ], pd . DataFrame ]: return collect_latest_rates_for_accounts ( accounts , timeframes , count , start_pos = start_pos , base_config = base_config , ) for attempt in range ( attempts - 1 ): try : return _collect () except ( Mt5TradingError , Mt5RuntimeError ) as exc : delay = backoff_base ** ( attempt + 1 ) logger . warning ( \"Rate collection failed (attempt %d / %d ): %s ; retrying in %.1f s\" , attempt + 1 , attempts , exc , delay , ) time . sleep ( delay ) return _collect ()","title":"collect_latest_rates_for_accounts_with_retries"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.last_error","text":"last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 1709 1710 1711 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error ()","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.market_book","text":"market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 1723 1724 1725 1726 1727 1728 1729 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol )","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.minimum_margins","text":"minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol )","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.mt5_session","text":"mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with _connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client )","title":"mt5_session"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary","text":"mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 1766 1767 1768 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary ()","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary_as_df","text":"mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 1771 1772 1773 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df ()","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.resolve_account_spec","text":"resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> AccountSpec Resolve an account's credentials from overrides and ${ENV_VAR} values. Explicit override arguments take precedence over the corresponding :class: AccountSpec fields. The resolved string fields ( login , password , server , path ) have any ${ENV_VAR} placeholders substituted from the environment. Parameters: Name Type Description Default account AccountSpec Source account specification. required login int | str | None Optional explicit login override. None password str | None Optional explicit password override. None server str | None Optional explicit server override. None path str | None Optional explicit terminal path override. None timeout int | None Optional explicit connection timeout override. None Returns: Type Description AccountSpec A new :class: AccountSpec with resolved credentials and the original AccountSpec symbols preserved. Raises ValueError (via AccountSpec func: substitute_env_placeholders ) if a referenced environment AccountSpec variable is not set. Source code in mt5cli/sdk.py 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 def resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> AccountSpec : \"\"\"Resolve an account's credentials from overrides and ``${ENV_VAR}`` values. Explicit override arguments take precedence over the corresponding :class:`AccountSpec` fields. The resolved string fields (``login``, ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders substituted from the environment. Args: account: Source account specification. login: Optional explicit login override. password: Optional explicit password override. server: Optional explicit server override. path: Optional explicit terminal path override. timeout: Optional explicit connection timeout override. Returns: A new :class:`AccountSpec` with resolved credentials and the original symbols preserved. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return AccountSpec ( symbols = account . symbols , login = _resolve_login ( login , account . login ), password = _resolve_field ( password , account . password ), server = _resolve_field ( server , account . server ), path = _resolve_field ( path , account . path ), timeout = timeout if timeout is not None else account . timeout , )","title":"resolve_account_spec"},{"location":"api/sdk/#mt5cli.sdk.resolve_account_specs","text":"resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> list [ AccountSpec ] Resolve credentials for multiple accounts. Applies the same overrides and ${ENV_VAR} substitution as :func: resolve_account_spec to every account. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Source account specifications. required login int | str | None Optional explicit login override applied to each account. None password str | None Optional explicit password override applied to each account. None server str | None Optional explicit server override applied to each account. None path str | None Optional explicit terminal path override applied to each account. None timeout int | None Optional explicit timeout override applied to each account. None Returns: Type Description list [ AccountSpec ] Resolved account specifications in the original order. Raises list [ AccountSpec ] ValueError (via :func: substitute_env_placeholders ) if a referenced list [ AccountSpec ] environment variable is not set. Source code in mt5cli/sdk.py 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 def resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) -> list [ AccountSpec ]: \"\"\"Resolve credentials for multiple accounts. Applies the same overrides and ``${ENV_VAR}`` substitution as :func:`resolve_account_spec` to every account. Args: accounts: Source account specifications. login: Optional explicit login override applied to each account. password: Optional explicit password override applied to each account. server: Optional explicit server override applied to each account. path: Optional explicit terminal path override applied to each account. timeout: Optional explicit timeout override applied to each account. Returns: Resolved account specifications in the original order. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return [ resolve_account_spec ( account , login = login , password = password , server = server , path = path , timeout = timeout , ) for account in accounts ]","title":"resolve_account_specs"},{"location":"api/sdk/#mt5cli.sdk.substitute_env_placeholders","text":"substitute_env_placeholders ( value : str ) -> str Replace ${ENV_VAR} placeholders in a string with environment values. Parameters: Name Type Description Default value str String that may contain one or more ${ENV_VAR} placeholders. required Returns: Type Description str The string with every placeholder replaced by its environment value. Raises: Type Description ValueError If a referenced environment variable is not set. Source code in mt5cli/sdk.py 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 def substitute_env_placeholders ( value : str ) -> str : \"\"\"Replace ``${ENV_VAR}`` placeholders in a string with environment values. Args: value: String that may contain one or more ``${ENV_VAR}`` placeholders. Returns: The string with every placeholder replaced by its environment value. Raises: ValueError: If a referenced environment variable is not set. \"\"\" parts : list [ str ] = [] last_end = 0 for match in _ENV_PLACEHOLDER_PATTERN . finditer ( value ): parts . append ( value [ last_end : match . start ()]) name = match . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) parts . append ( os . environ [ name ]) last_end = match . end () parts . append ( value [ last_end :]) return \"\" . join ( parts )","title":"substitute_env_placeholders"},{"location":"api/sdk/#mt5cli.sdk.symbol_info","text":"symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1606 1607 1608 1609 1610 1611 1612 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol )","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.symbol_info_tick","text":"symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 1714 1715 1716 1717 1718 1719 1720 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol )","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.symbols","text":"symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1597 1598 1599 1600 1601 1602 1603 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group )","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.terminal_info","text":"terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1592 1593 1594 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info ()","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.update_history","text":"update_history ( * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient 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 Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. 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/sdk.py 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , 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 , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` 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 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). 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 update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. 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 sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history"},{"location":"api/sdk/#mt5cli.sdk.update_history_with_config","text":"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 , create_rate_views : 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/sdk.py 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 def update_history_with_config ( # noqa: PLR0913 * , 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 , create_rate_views : 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 mt5_config = config or build_config () with _connected_client ( mt5_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 , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history_with_config"},{"location":"api/sdk/#mt5cli.sdk.version","text":"version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 1704 1705 1706 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","title":"version"},{"location":"api/sdk/#resilient-multi-account-orchestration","text":"The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application.","title":"Resilient multi-account orchestration"},{"location":"api/sdk/#retrying-transient-rate-collection","text":"collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final failure is re-raised once retry_count is exhausted. from mt5cli import AccountSpec , collect_latest_rates_for_accounts_with_retries accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )] rates = collect_latest_rates_for_accounts_with_retries ( accounts , [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , backoff_base = 2 , # sleeps 2s, 4s, 8s between attempts )","title":"Retrying transient rate collection"},{"location":"api/sdk/#resolving-credentials-and-env_var-placeholders","text":"resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError . import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_LOGIN\" ] = \"12345\" os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = \"$ {MT5_LOGIN} \" , password = \"$ {MT5_PASSWORD} \" ) ] resolved = resolve_account_specs ( accounts , server = \"Broker-Demo\" ) # resolved[0].login == \"12345\", resolved[0].server == \"Broker-Demo\"","title":"Resolving credentials and ${ENV_VAR} placeholders"},{"location":"api/sdk/#throttled-incremental-history-updates","text":"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 pdmt5 import Mt5Config , Mt5DataClient from mt5cli import Dataset , ThrottledHistoryUpdater updater = ThrottledHistoryUpdater ( output = \"history.db\" , datasets = { Dataset . rates }, timeframes = [ \"M1\" ], interval_seconds = 60 , # <= 0 updates on every call ) client = Mt5DataClient ( config = Mt5Config ( login = 12345 )) client . initialize_and_login_mt5 () try : while True : updater . update ( client , [ \"EURUSD\" , \"GBPUSD\" ]) # no-op until 60s elapse # ... do other work; break when shutting down ... finally : client . shutdown () By default Mt5TradingError , Mt5RuntimeError , and sqlite3.Error propagate so the caller controls logging; pass suppress_errors=True to swallow them and return False without advancing the throttle.","title":"Throttled incremental history updates"},{"location":"api/utils/","text":"Utils Module \u00b6 mt5cli.utils \u00b6 Utility constants, types, and functions for the mt5cli package. DATETIME_TYPE module-attribute \u00b6 DATETIME_TYPE = _DateTimeType () REQUEST_TYPE module-attribute \u00b6 REQUEST_TYPE = _RequestType () TICK_FLAGS_TYPE module-attribute \u00b6 TICK_FLAGS_TYPE = _TickFlagsType () TICK_FLAG_MAP module-attribute \u00b6 TICK_FLAG_MAP : dict [ str , int ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , } TIMEFRAME_MAP module-attribute \u00b6 TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , } TIMEFRAME_TYPE module-attribute \u00b6 TIMEFRAME_TYPE = _TimeframeType () Dataset \u00b6 Bases: StrEnum Datasets supported by the collect-history command. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history-deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history-orders' rates class-attribute instance-attribute \u00b6 rates = 'rates' table_name property \u00b6 table_name : str Return the SQLite table name for this dataset. ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' IfExists \u00b6 Bases: StrEnum SQLite table conflict behavior for the collect-history command. APPEND class-attribute instance-attribute \u00b6 APPEND = 'append' FAIL class-attribute instance-attribute \u00b6 FAIL = 'fail' REPLACE class-attribute instance-attribute \u00b6 REPLACE = 'replace' LogLevel \u00b6 Bases: StrEnum Logging verbosity levels. DEBUG class-attribute instance-attribute \u00b6 DEBUG = 'DEBUG' ERROR class-attribute instance-attribute \u00b6 ERROR = 'ERROR' INFO class-attribute instance-attribute \u00b6 INFO = 'INFO' WARNING class-attribute instance-attribute \u00b6 WARNING = 'WARNING' OutputFormat \u00b6 Bases: StrEnum Supported output file formats. csv class-attribute instance-attribute \u00b6 csv = 'csv' json class-attribute instance-attribute \u00b6 json = 'json' parquet class-attribute instance-attribute \u00b6 parquet = 'parquet' sqlite3 class-attribute instance-attribute \u00b6 sqlite3 = 'sqlite3' detect_format \u00b6 detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg ) export_dataframe \u00b6 export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) export_dataframe_to_sqlite \u00b6 export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit () parse_datetime \u00b6 parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt parse_request \u00b6 parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed parse_tick_flags \u00b6 parse_tick_flags ( value : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 def parse_timeframe ( value : str ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"Utils"},{"location":"api/utils/#utils-module","text":"","title":"Utils Module"},{"location":"api/utils/#mt5cli.utils","text":"Utility constants, types, and functions for the mt5cli package.","title":"utils"},{"location":"api/utils/#mt5cli.utils.DATETIME_TYPE","text":"DATETIME_TYPE = _DateTimeType ()","title":"DATETIME_TYPE"},{"location":"api/utils/#mt5cli.utils.REQUEST_TYPE","text":"REQUEST_TYPE = _RequestType ()","title":"REQUEST_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAGS_TYPE","text":"TICK_FLAGS_TYPE = _TickFlagsType ()","title":"TICK_FLAGS_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAG_MAP","text":"TICK_FLAG_MAP : dict [ str , int ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , }","title":"TICK_FLAG_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_MAP","text":"TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , }","title":"TIMEFRAME_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_TYPE","text":"TIMEFRAME_TYPE = _TimeframeType ()","title":"TIMEFRAME_TYPE"},{"location":"api/utils/#mt5cli.utils.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/utils/#mt5cli.utils.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/utils/#mt5cli.utils.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/utils/#mt5cli.utils.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/utils/#mt5cli.utils.Dataset.table_name","text":"table_name : str Return the SQLite table name for this dataset.","title":"table_name"},{"location":"api/utils/#mt5cli.utils.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/utils/#mt5cli.utils.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/utils/#mt5cli.utils.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/utils/#mt5cli.utils.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/utils/#mt5cli.utils.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/utils/#mt5cli.utils.LogLevel","text":"Bases: StrEnum Logging verbosity levels.","title":"LogLevel"},{"location":"api/utils/#mt5cli.utils.LogLevel.DEBUG","text":"DEBUG = 'DEBUG'","title":"DEBUG"},{"location":"api/utils/#mt5cli.utils.LogLevel.ERROR","text":"ERROR = 'ERROR'","title":"ERROR"},{"location":"api/utils/#mt5cli.utils.LogLevel.INFO","text":"INFO = 'INFO'","title":"INFO"},{"location":"api/utils/#mt5cli.utils.LogLevel.WARNING","text":"WARNING = 'WARNING'","title":"WARNING"},{"location":"api/utils/#mt5cli.utils.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/utils/#mt5cli.utils.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/utils/#mt5cli.utils.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/utils/#mt5cli.utils.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/utils/#mt5cli.utils.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/utils/#mt5cli.utils.detect_format","text":"detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg )","title":"detect_format"},{"location":"api/utils/#mt5cli.utils.export_dataframe","text":"export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"location":"api/utils/#mt5cli.utils.export_dataframe_to_sqlite","text":"export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit ()","title":"export_dataframe_to_sqlite"},{"location":"api/utils/#mt5cli.utils.parse_datetime","text":"parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt","title":"parse_datetime"},{"location":"api/utils/#mt5cli.utils.parse_request","text":"parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed","title":"parse_request"},{"location":"api/utils/#mt5cli.utils.parse_tick_flags","text":"parse_tick_flags ( value : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/utils/#mt5cli.utils.parse_timeframe","text":"parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 def parse_timeframe ( value : str ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_timeframe"}]} \ No newline at end of file