381
-382
-383
+ | def __init__(
- self,
- *,
- path: str | None = None,
- login: int | None = None,
- password: str | None = None,
- server: str | None = None,
- timeout: int | None = None,
- retry_count: int = 3,
- 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.
- retry_count: Number of MT5 initialization retries for sessions
- opened by this client.
- 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._retry_count = retry_count
- self._client = client
- self._owns_client = client is None
+416
+417
+418
| def __init__(
+ self,
+ *,
+ path: str | None = None,
+ login: int | None = None,
+ password: str | None = None,
+ server: str | None = None,
+ timeout: int | None = None,
+ retry_count: int = 3,
+ 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.
+ retry_count: Number of MT5 initialization retries for sessions
+ opened by this client.
+ 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._retry_count = retry_count
+ self._client = client
+ self._owns_client = client is None
|
@@ -671,9 +671,7 @@ not implement strategy logic, signal generation, or trade sizing.
Source code in mt5cli/sdk.py
- 301
-302
-303
+ 303
304
305
306
@@ -690,26 +688,28 @@ not implement strategy logic, signal generation, or trade sizing.
317
318
319
-320 | 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,
- )
+320
+321
+322
| 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,
+ )
|
diff --git a/api/converters/index.html b/api/converters/index.html
index 2923c6c..e047802 100644
--- a/api/converters/index.html
+++ b/api/converters/index.html
@@ -938,47 +938,47 @@ suffixes (for example XAUUSDm, US500.cash, or EU
Source code in mt5cli/utils.py
- 329
-330
-331
-332
-333
-334
-335
-336
-337
-338
-339
-340
-341
-342
-343
+ | 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
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
| 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
|
@@ -1080,49 +1080,49 @@ suffixes (for example XAUUSDm, US500.cash, or EU
Source code in mt5cli/utils.py
- 376
-377
-378
-379
-380
-381
-382
-383
-384
-385
-386
-387
-388
-389
-390
+ | def parse_tick_flags(value: object) -> int:
- """Parse tick flags string or integer value.
-
- Args:
- value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value.
-
- Returns:
- Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``.
-
- Raises:
- ValueError: If the flag is invalid.
- """
- try:
- return _parse_copy_ticks(value)
- except ValueError:
- display = value if isinstance(value, str) else repr(value)
- valid = ", ".join(_TICK_FLAG_NAMES)
- msg = (
- f"Invalid tick flags: '{display}'. "
- f"Use one of: {valid}, or a supported integer."
- )
- raise ValueError(msg) from None
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
| def parse_tick_flags(value: object) -> int:
+ """Parse tick flags string or integer value.
+
+ Args:
+ value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value.
+
+ Returns:
+ Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``.
+
+ Raises:
+ ValueError: If the flag is invalid.
+ """
+ try:
+ return _parse_copy_ticks(value)
+ except ValueError:
+ display = value if isinstance(value, str) else repr(value)
+ valid = ", ".join(_TICK_FLAG_NAMES)
+ msg = (
+ f"Invalid tick flags: '{display}'. "
+ f"Use one of: {valid}, or a supported integer."
+ )
+ raise ValueError(msg) from None
|
@@ -1224,49 +1224,49 @@ suffixes (for example XAUUSDm, US500.cash, or EU
Source code in mt5cli/utils.py
- 352
-353
-354
-355
-356
-357
-358
-359
-360
-361
-362
-363
-364
-365
-366
+ | def parse_timeframe(value: object) -> 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.
- """
- try:
- return _parse_timeframe(value)
- except ValueError:
- display = value if isinstance(value, str) else repr(value)
- valid = ", ".join(TIMEFRAME_NAMES)
- msg = (
- f"Invalid timeframe: '{display}'. "
- f"Use one of: {valid}, or a supported integer."
- )
- raise ValueError(msg) from None
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
| def parse_timeframe(value: object) -> 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.
+ """
+ try:
+ return _parse_timeframe(value)
+ except ValueError:
+ display = value if isinstance(value, str) else repr(value)
+ valid = ", ".join(TIMEFRAME_NAMES)
+ msg = (
+ f"Invalid timeframe: '{display}'. "
+ f"Use one of: {valid}, or a supported integer."
+ )
+ raise ValueError(msg) from None
|
diff --git a/api/history/index.html b/api/history/index.html
index a75da3e..52b69d9 100644
--- a/api/history/index.html
+++ b/api/history/index.html
@@ -613,13 +613,13 @@ by an explicit table (for example a custom SQLite view).
Source code in mt5cli/history.py
- | def __post_init__(self) -> None:
- """Normalize accepted timeframe aliases to the stored integer value."""
- if not isinstance(self.timeframe, int):
- object.__setattr__(self, "timeframe", parse_timeframe(self.timeframe))
+ | 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))
|
@@ -681,49 +681,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
|
@@ -752,33 +752,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
|
@@ -944,27 +944,7 @@ with symbol=None for each timeframe instead of raising.
Source code in mt5cli/history.py
- 535
-536
-537
-538
-539
-540
-541
-542
-543
-544
-545
-546
-547
-548
-549
-550
-551
-552
-553
-554
-555
+ | 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
- ]
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
| 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
+ ]
|
@@ -1126,41 +1126,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
|
@@ -1188,51 +1188,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)",
+ )
|
@@ -1282,127 +1282,7 @@ 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
- 1303
-1304
-1305
-1306
+ | 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}",
- )
+1333
+1334
+1335
+1336
+1337
+1338
+1339
+1340
+1341
+1342
+1343
+1344
+1345
+1346
+1347
+1348
+1349
+1350
+1351
+1352
| 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}",
+ )
|
@@ -1498,97 +1498,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")
|
@@ -1644,73 +1644,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})",
+ )
|
@@ -1855,21 +1855,21 @@ completed bars. Empty frames and single-row frames return empty results.
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}")
|
@@ -1932,61 +1932,61 @@ completed bars. Empty frames and single-row frames return empty results.
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()
|
@@ -2039,41 +2039,41 @@ completed bars. Empty frames and single-row frames return empty results.
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()
|
@@ -2100,47 +2100,47 @@ completed bars. Empty frames and single-row frames return empty results.
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
|
@@ -2172,41 +2172,41 @@ completed bars. Empty frames and single-row frames return empty results.
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]
|
@@ -2231,15 +2231,15 @@ completed bars. Empty frames and single-row frames return empty results.
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}
|
@@ -2271,69 +2271,7 @@ completed bars. Empty frames and single-row frames return empty results.
Source code in mt5cli/history.py
- 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
+ 916
917
918
919
@@ -2344,80 +2282,142 @@ completed bars. Empty frames and single-row frames return empty results.
924
925
926
-927 | 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}
+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
+969
+970
+971
+972
+973
+974
+975
+976
+977
+978
+979
+980
+981
+982
+983
+984
+985
+986
+987
+988
+989
| 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}
|
@@ -2542,49 +2542,49 @@ completed bars. Empty frames and single-row frames return empty results.
Source code in mt5cli/history.py
- | def load_rate_data(
- conn_or_path: SqliteConnOrPath,
- table: str,
- count: int | None = None,
-) -> pd.DataFrame:
- """Load rate-like data from a SQLite database path or connection.
-
- Args:
- conn_or_path: SQLite database path or open connection.
- table: Source table or view name.
- count: Optional number of most recent rows to load.
-
- Returns:
- DataFrame indexed by ascending ``time``.
-
- """
- conn, should_close = _open_existing_sqlite_database(conn_or_path)
- try:
- return load_rate_data_from_connection(conn, table, count=count)
- finally:
- if should_close:
- conn.close()
+ | 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()
|
@@ -2723,27 +2723,7 @@ or view contains no rows.
Source code in mt5cli/history.py
- 234
-235
-236
-237
-238
-239
-240
-241
-242
-243
-244
-245
-246
-247
-248
-249
-250
-251
-252
-253
-254
+ | 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)
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
| 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)
|
@@ -3022,7 +3022,371 @@ with symbol=None for each granularity instead of raising.
Source code in mt5cli/history.py
- 727
+ | 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
+
+
+
+
+ load_rate_series_from_sqlite(
+ conn_or_path: SqliteConnOrPath,
+ targets: None = None,
+ count: int | None = None,
+ explicit_tables: None = None,
+ *,
+ table: str,
+) -> DataFrame
+
load_rate_series_from_sqlite(
+ conn_or_path: SqliteConnOrPath,
+ targets: None = None,
+ count: int | None = None,
+ explicit_tables: Sequence[str] | None = None,
+ *,
+ table: None = None,
+) -> dict[tuple[str | None, int], DataFrame]
+
load_rate_series_from_sqlite(
+ conn_or_path: SqliteConnOrPath,
+ targets: Sequence[RateTarget],
+ count: int,
+ explicit_tables: Sequence[str] | None = None,
+ *,
+ table: None = None,
+) -> dict[tuple[str | None, int], DataFrame]
+
+ load_rate_series_from_sqlite(
+ conn_or_path: SqliteConnOrPath,
+ targets: Sequence[RateTarget] | None = None,
+ count: int | None = None,
+ explicit_tables: Sequence[str] | None = None,
+ *,
+ table: str | None = None,
+) -> dict[tuple[str | None, int], DataFrame] | DataFrame
+
+
+
+
+ Load one table/view or 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] | None
+ |
+
+
+ Rate targets to load. Each (symbol, timeframe_int) pair must
+be unique. Omit when loading a single explicit table.
+
+ |
+
+ None
+ |
+
+
+
+ count
+ |
+
+ int | None
+ |
+
+
+ Optional number of most recent rows to load per series.
+
+ |
+
+ None
+ |
+
+
+
+ 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
+ |
+
+
+
+ table
+ |
+
+ str | None
+ |
+
+
+ Optional single table or view name to load directly.
+
+ |
+
+ None
+ |
+
+
+
+
+
+ Returns:
+
+
+
+ | Type |
+ Description |
+
+
+
+
+
+ dict[tuple[str | None, int], DataFrame] | DataFrame
+ |
+
+
+ A DataFrame when table is provided, otherwise a mapping keyed by
+
+ |
+
+
+
+ dict[tuple[str | None, int], DataFrame] | DataFrame
+ |
+
+
+ (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
+ | 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
-
-
-
- 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
- | 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()
+773
+774
+775
+776
+777
+778
+779
+780
+781
+782
+783
+784
+785
+786
| def load_rate_series_from_sqlite(
+ conn_or_path: SqliteConnOrPath,
+ targets: Sequence[RateTarget] | None = None,
+ count: int | None = None,
+ explicit_tables: Sequence[str] | None = None,
+ *,
+ table: str | None = None,
+) -> dict[tuple[str | None, int], pd.DataFrame] | pd.DataFrame:
+ """Load one table/view or 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. Omit when loading a single explicit ``table``.
+ count: Optional 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.
+ table: Optional single table or view name to load directly.
+
+ Returns:
+ A DataFrame when ``table`` is provided, otherwise a 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 table is not None:
+ return load_rate_data(conn_or_path, table, count=count)
+ if count is None or count <= 0:
+ msg = "count must be positive."
+ raise ValueError(msg)
+ if targets is None:
+ msg = "targets are required when table is not provided."
+ 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()
|
@@ -3478,37 +3570,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
|
@@ -3566,27 +3658,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
|
@@ -3853,6 +3945,116 @@ fails.
+
+ resolve_rate_table_name
+
+
+
+ resolve_rate_table_name(
+ symbol: str, granularity: str
+) -> str
+
+
+
+
+ Return the canonical normalized SQLite rate table name.
+ The normalized history table stores all symbols and timeframes in
+rates; use :func:resolve_rate_view_name for per-symbol compatibility
+view names.
+
+
+ Returns:
+
+
+
+ | Type |
+ Description |
+
+
+
+
+
+ str
+ |
+
+
+ Canonical normalized rates table name.
+
+ |
+
+
+
+
+
+ Raises:
+
+
+
+ | Type |
+ Description |
+
+
+
+
+
+ ValueError
+ |
+
+
+ If symbol or granularity is invalid.
+
+ |
+
+
+
+
+
+
+ Source code in mt5cli/history.py
+ | def resolve_rate_table_name(symbol: str, granularity: str) -> str:
+ """Return the canonical normalized SQLite rate table name.
+
+ The normalized history table stores all symbols and timeframes in
+ ``rates``; use :func:`resolve_rate_view_name` for per-symbol compatibility
+ view names.
+
+ Returns:
+ Canonical normalized rates table name.
+
+ Raises:
+ ValueError: If ``symbol`` or ``granularity`` is invalid.
+ """
+ parse_timeframe(granularity)
+ if not symbol.strip():
+ msg = "symbol must not be empty."
+ raise ValueError(msg)
+ return Dataset.rates.table_name
+
|
+
+
+
+
+
+
+
+
resolve_rate_tables
@@ -4027,27 +4229,7 @@ database or a managed view is missing.
Source code in mt5cli/history.py
- 572
-573
-574
-575
-576
-577
-578
-579
-580
-581
-582
-583
-584
-585
-586
-587
-588
-589
-590
-591
-592
+ | 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()
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
| 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()
|
@@ -4357,27 +4559,7 @@ default view name is returned without creating a database file.
Source code in mt5cli/history.py
- 400
-401
-402
-403
-404
-405
-406
-407
-408
-409
-410
-411
-412
-413
-414
-415
-416
-417
-418
-419
-420
+ 420
421
422
423
@@ -4409,59 +4591,79 @@ default view name is returned without creating a database file.
449
450
451
-452 | 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()
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
| 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()
|
@@ -4616,27 +4818,7 @@ default view names are returned without creating a database file.
Source code in mt5cli/history.py
- 455
-456
-457
-458
-459
-460
-461
-462
-463
-464
-465
-466
-467
-468
-469
-470
-471
-472
-473
-474
-475
+ 475
476
477
478
@@ -4669,60 +4851,80 @@ default view names are returned without creating a database file.
505
506
507
-508 | 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()
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
| 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()
|
@@ -4780,135 +4982,135 @@ default view names are returned without creating a database file.
Source code in mt5cli/history.py
- 1838
-1839
-1840
-1841
-1842
-1843
-1844
-1845
-1846
-1847
-1848
-1849
-1850
-1851
-1852
-1853
-1854
-1855
-1856
-1857
-1858
-1859
-1860
-1861
-1862
-1863
-1864
-1865
-1866
-1867
-1868
-1869
-1870
-1871
-1872
-1873
-1874
-1875
-1876
-1877
-1878
-1879
-1880
-1881
-1882
-1883
-1884
-1885
-1886
-1887
-1888
-1889
-1890
-1891
-1892
-1893
-1894
-1895
-1896
-1897
-1898
-1899
-1900
+ | 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
+1902
+1903
+1904
+1905
+1906
+1907
+1908
+1909
+1910
+1911
+1912
+1913
+1914
+1915
+1916
+1917
+1918
+1919
+1920
+1921
+1922
+1923
+1924
+1925
+1926
+1927
+1928
+1929
+1930
+1931
+1932
+1933
+1934
+1935
+1936
+1937
+1938
+1939
+1940
+1941
+1942
+1943
+1944
+1945
+1946
+1947
+1948
+1949
+1950
+1951
+1952
+1953
+1954
+1955
+1956
+1957
+1958
+1959
+1960
+1961
+1962
+1963
+1964
| 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
|
@@ -4967,101 +5169,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,
- )
-
- def _fetch_history_frame(sym: str) -> pd.DataFrame:
- return filter_trade_history_frame(
- fetch(date_from=date_from, date_to=date_to, symbol=sym),
- [sym],
- include_account_events=False,
- )
-
- return _stream_symbol_frames(
- conn,
- symbols,
- dataset,
- if_exists,
- written_columns,
- _fetch_history_frame,
- )
+ | 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,
+ )
+
+ def _fetch_history_frame(sym: str) -> pd.DataFrame:
+ return filter_trade_history_frame(
+ fetch(date_from=date_from, date_to=date_to, symbol=sym),
+ [sym],
+ include_account_events=False,
+ )
+
+ return _stream_symbol_frames(
+ conn,
+ symbols,
+ dataset,
+ if_exists,
+ written_columns,
+ _fetch_history_frame,
+ )
|
@@ -5123,69 +5325,7 @@ default view names are returned without creating a database file.
Source code in mt5cli/history.py
- 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
-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
+ | 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
+1835
+1836
+1837
+1838
+1839
+1840
+1841
+1842
+1843
+1844
+1845
+1846
+1847
+1848
+1849
+1850
+1851
+1852
+1853
+1854
+1855
+1856
+1857
+1858
+1859
+1860
+1861
+1862
+1863
+1864
+1865
+1866
+1867
+1868
+1869
+1870
+1871
+1872
+1873
+1874
+1875
+1876
+1877
+1878
+1879
+1880
+1881
+1882
+1883
+1884
+1885
+1886
+1887
+1888
+1889
+1890
+1891
+1892
+1893
+1894
+1895
+1896
+1897
| 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
|
@@ -5340,77 +5542,77 @@ 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.
- """
-
- def _fetch_rates_frame(sym: str) -> pd.DataFrame:
- 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)
- return frame
-
- return _stream_symbol_frames(
- conn,
- symbols,
- Dataset.rates,
- if_exists,
- written_columns,
- _fetch_rates_frame,
- )
+ | 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.
+ """
+
+ def _fetch_rates_frame(sym: str) -> pd.DataFrame:
+ 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)
+ return frame
+
+ return _stream_symbol_frames(
+ conn,
+ symbols,
+ Dataset.rates,
+ if_exists,
+ written_columns,
+ _fetch_rates_frame,
+ )
|
@@ -5465,41 +5667,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
|
@@ -5556,75 +5758,75 @@ 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.
- """
-
- def _fetch_ticks_frame(sym: str) -> pd.DataFrame:
- 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)
- return frame
-
- return _stream_symbol_frames(
- conn,
- symbols,
- Dataset.ticks,
- if_exists,
- written_columns,
- _fetch_ticks_frame,
- )
+ | 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.
+ """
+
+ def _fetch_ticks_frame(sym: str) -> pd.DataFrame:
+ 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)
+ return frame
+
+ return _stream_symbol_frames(
+ conn,
+ symbols,
+ Dataset.ticks,
+ if_exists,
+ written_columns,
+ _fetch_ticks_frame,
+ )
|
@@ -5825,16 +6027,40 @@ schemes:
Accepts either a SQLite path or an open sqlite3.Connection.
Rate data loading
-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:
+The canonical normalized rate table is rates; compatibility views are named
+with rate_<symbol>__<timeframe> for single-timeframe symbols or
+rate_<symbol>__<granularity>_<timeframe> when a symbol has multiple stored
+timeframes. resolve_rate_table_name() returns rates, while
+resolve_rate_view_name() returns the per-symbol compatibility view name.
+Use load_rate_data() or load_rate_series_from_sqlite(..., table=...) to load
+a single table or view from a SQLite path. Use
+load_rate_series_by_granularity() to load multiple instrument/granularity
+targets without hard-coding view names:
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)
+from mt5cli import (
+ load_rate_data,
+ load_rate_series_by_granularity,
+ load_rate_series_from_sqlite,
+ resolve_rate_table_name,
+)
+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)
+same_rates = load_rate_series_from_sqlite(Path("history.db"), table=view, count=1000)
+
+table = resolve_rate_table_name("EURUSD", "M1") # "rates"
+series = load_rate_series_by_granularity(
+ Path("history.db"),
+ symbols=["EURUSD", "GBPUSD"],
+ granularities=["M1", "H1"],
+ count=500,
+)
+count returns the latest rows while preserving chronological order. Missing
+tables/views and mismatched explicit_tables lengths raise ValueError with
+the requested database target in the message.
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.
diff --git a/api/sdk/index.html b/api/sdk/index.html
index 97c216a..0bb6bfc 100644
--- a/api/sdk/index.html
+++ b/api/sdk/index.html
@@ -235,30 +235,31 @@
"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",
-]
+ "fetch_latest_closed_rates",
+ "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",
+]
@@ -786,9 +787,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 381
-382
-383
+ | def __init__(
- self,
- *,
- path: str | None = None,
- login: int | None = None,
- password: str | None = None,
- server: str | None = None,
- timeout: int | None = None,
- retry_count: int = 3,
- 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.
- retry_count: Number of MT5 initialization retries for sessions
- opened by this client.
- 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._retry_count = retry_count
- self._client = client
- self._owns_client = client is None
+416
+417
+418
| def __init__(
+ self,
+ *,
+ path: str | None = None,
+ login: int | None = None,
+ password: str | None = None,
+ server: str | None = None,
+ timeout: int | None = None,
+ retry_count: int = 3,
+ 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.
+ retry_count: Number of MT5 initialization retries for sessions
+ opened by this client.
+ 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._retry_count = retry_count
+ self._client = client
+ self._owns_client = client is None
|
@@ -938,9 +939,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 435
-436
-437
+ | 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, retry_count=self._retry_count)
- 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
+451
+452
+453
| 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, retry_count=self._retry_count)
+ 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
|
@@ -999,25 +1000,25 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 453
-454
-455
+ | 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
+462
+463
+464
| 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
|
@@ -1042,11 +1043,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())
|
@@ -1123,9 +1124,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 520
-521
-522
+ | 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
- },
- )
+555
+556
+557
| 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
+ },
+ )
|
@@ -1223,9 +1224,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 472
-473
-474
+ | 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,
- ),
- )
+489
+490
+491
| 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,
+ ),
+ )
|
@@ -1287,9 +1288,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 491
-492
-493
+ | 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,
- ),
- )
+507
+508
+509
| 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,
+ ),
+ )
|
@@ -1349,9 +1350,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 557
-558
-559
+ | 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,
- ),
- )
+575
+576
+577
| 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,
+ ),
+ )
|
@@ -1415,9 +1416,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 577
-578
-579
+ | 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,
- ),
- )
+594
+595
+596
| 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,
+ ),
+ )
|
@@ -1479,9 +1480,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 596
-597
-598
+ | 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,
- ),
- )
+614
+615
+616
| 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,
+ ),
+ )
|
@@ -1569,9 +1570,7 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 418
-419
-420
+ | @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)
+428
+429
+430
| @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)
|
@@ -1621,9 +1622,7 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|