History Collection (SQLite)¶
mt5cli.history ¶
History collection, incremental updates, and SQLite storage for MT5 data.
DEFAULT_HISTORY_DATASETS
module-attribute
¶
DEFAULT_HISTORY_DATASETS: frozenset[Dataset] = frozenset({
Dataset.rates,
Dataset.history_orders,
Dataset.history_deals,
})
DEFAULT_HISTORY_TIMEFRAMES
module-attribute
¶
DEFAULT_HISTORY_TIMEFRAMES: tuple[str, ...] = (
TIMEFRAME_NAMES
)
DedupScope
dataclass
¶
Scoped deduplication predicate and the columns it references.
Attributes:
| Name | Type | Description |
|---|---|---|
where |
str
|
SQL predicate appended to the duplicate-removal query. |
params |
tuple[object, ...]
|
Parameters bound to the scope predicate. |
required_columns |
frozenset[str]
|
Columns that must be present in the written table for the scope to run. |
HistoryCapture
dataclass
¶
HistoryCapture(
output: Path,
selected_datasets: frozenset[Dataset],
groups: tuple[_CapturedDatasetGroup, ...],
deduplicate: bool,
with_views: bool,
captured_at: datetime,
)
MT5-independent captured history data, ready for later SQLite persistence.
Produced by :func:capture_history_datasets on the MT5 connection thread;
consumed by :func:persist_history_datasets, which never touches MT5 or
any connection-scoped MT5 state and may run on a different thread.
RateTarget
dataclass
¶
A single rate series identified by symbol and timeframe.
Attributes:
| Name | Type | Description |
|---|---|---|
symbol |
str | None
|
MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). |
timeframe |
int | str
|
MT5 timeframe as an integer or name (for example |
__post_init__ ¶
Normalize accepted timeframe aliases to the stored integer value.
ThrottledHistoryUpdater ¶
ThrottledHistoryUpdater(
*,
output: Path | str,
datasets: set[Dataset] | None = None,
timeframes: Sequence[int | str] | None = None,
flags: int | str = "ALL",
lookback_hours: float = 24.0,
with_views: bool = False,
include_account_events: bool = True,
interval_seconds: float = 0.0,
suppress_errors: bool = False,
update_backend: UpdateHistoryBackend | None = None,
)
Throttled incremental SQLite history updater for long-running apps.
Wraps :func:update_history (or a custom update_backend) with a minimum
interval between successful updates, so a tight application loop can call
:meth:update every iteration without re-fetching MT5 history more often
than desired. Timing uses a monotonic clock, so it is unaffected by
wall-clock changes.
Downstream applications may pass update_backend to substitute the
default :func:update_history implementation—for example to add
application-specific logging, metrics, or test doubles—without monkey-
patching :func:update_history.
Initialize the throttled updater.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
Path | str
|
SQLite database path. |
required |
datasets
|
set[Dataset] | None
|
Datasets to include (defaults to rates, history-orders,
history-deals; pass |
None
|
timeframes
|
Sequence[int | str] | None
|
Rate timeframes to update (defaults to all fixed MT5 timeframes). |
None
|
flags
|
int | str
|
Tick copy flags as integer or name (e.g. |
'ALL'
|
lookback_hours
|
float
|
First-run lookback when a table has no prior rows. |
24.0
|
with_views
|
bool
|
Create |
False
|
include_account_events
|
bool
|
Include account-level cash events. |
True
|
interval_seconds
|
float
|
Minimum seconds between successful updates. Values
|
0.0
|
suppress_errors
|
bool
|
When True, recoverable errors ( |
False
|
update_backend
|
UpdateHistoryBackend | None
|
Callable invoked instead of :func: |
None
|
Source code in mt5cli/history.py
last_update_monotonic
property
¶
Monotonic timestamp of the last successful update.
update_backend
instance-attribute
¶
update_backend = (
update_history
if update_backend is None
else update_backend
)
should_update ¶
Return whether enough time has elapsed to run another update.
Returns:
| Type | Description |
|---|---|
bool
|
True when |
bool
|
yet, or when at least |
bool
|
last successful update. |
Source code in mt5cli/history.py
update ¶
update(
client: HistoryClient,
symbols: Sequence[str],
*,
date_to: datetime | str | None = None,
) -> bool
Run a throttled incremental history update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
HistoryClient
|
Connected MT5 data client. |
required |
symbols
|
Sequence[str]
|
Symbols to update. |
required |
date_to
|
datetime | str | None
|
Explicit naive MT5 trade-server end datetime. Required when datasets are selected; mt5cli cannot determine the current server time. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if an update ran successfully, False if it was throttled or |
bool
|
(when |
bool
|
When |
bool
|
propagate to the caller. |
Source code in mt5cli/history.py
append_dataframe ¶
append_dataframe(
conn: Connection,
frame: DataFrame,
table_name: str,
if_exists: IfExists,
*,
empty_log_level: int = WARNING,
) -> bool
Append a DataFrame to SQLite when it has a schema.
Returns:
| Type | Description |
|---|---|
bool
|
True if a table was written, False if the frame had no columns. |
Source code in mt5cli/history.py
augment_written_columns_from_sqlite ¶
augment_written_columns_from_sqlite(
conn: Connection,
datasets: set[Dataset],
written_columns: dict[Dataset, set[str]],
) -> None
Add existing table columns to the written column map.
Source code in mt5cli/history.py
build_rate_targets ¶
build_rate_targets(
symbols: Sequence[str],
timeframes: Sequence[int | str],
*,
allow_missing_symbol: bool = False,
) -> list[RateTarget]
Build rate targets for every symbol and timeframe combination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
Sequence[str]
|
MT5 symbol names. May be empty when |
required |
timeframes
|
Sequence[int | str]
|
MT5 timeframes as integers or names (for example |
required |
allow_missing_symbol
|
bool
|
When True and |
False
|
Returns:
| Type | Description |
|---|---|
list[RateTarget]
|
Targets in row-major order: every timeframe for the first symbol, then |
list[RateTarget]
|
every timeframe for the next symbol, and so on. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mt5cli/history.py
capture_history_datasets ¶
capture_history_datasets(
*,
client: HistoryClient,
output: Path | str,
symbols: Sequence[str],
datasets: set[Dataset] | None = None,
timeframes: Sequence[int | str] | None = None,
flags: int | str = "ALL",
lookback_hours: float = 24.0,
date_to: datetime | str | None = None,
deduplicate: bool = True,
with_views: bool = False,
include_account_events: bool = True,
) -> HistoryCapture | None
Capture incremental MT5 history as plain data, without writing SQLite.
Reads the existing output database (if any), read-only, only to
resolve each dataset's incremental cursor, then fetches MT5 data for the
resolved range using client. Performs no SQLite writes. Pass the
result to :func:persist_history_datasets -- from any thread, without MT5
access -- to append it.
Capturing again before a prior capture for the same output has been
persisted re-reads the same not-yet-advanced cursor and may re-fetch an
overlapping range (safe under deduplication, but wasteful); callers that
queue persistence work should avoid capturing a new batch while one for
the same target is still pending.
Returns:
| Type | Description |
|---|---|
HistoryCapture | None
|
A capture bundle, or None when no datasets are selected. |
Source code in mt5cli/history.py
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 | |
collect_history ¶
collect_history(
output: Path,
symbols: list[str],
date_from: datetime | str,
date_to: datetime | str,
*,
datasets: set[Dataset] | None = None,
timeframe: int | str = 1,
flags: int | str = "ALL",
if_exists: IfExists = FAIL,
with_views: bool = False,
config: Mt5Config | None = None,
) -> None
Collect historical datasets into a single SQLite database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
Path
|
SQLite database path. |
required |
symbols
|
list[str]
|
Symbols to collect. |
required |
date_from
|
datetime | str
|
Naive trade-server wall-clock start date. |
required |
date_to
|
datetime | str
|
Naive trade-server wall-clock end date. |
required |
datasets
|
set[Dataset] | None
|
Datasets to include (defaults to rates, history-orders,
history-deals; pass |
None
|
timeframe
|
int | str
|
Rates timeframe as integer or name (e.g. |
1
|
flags
|
int | str
|
Tick copy flags as integer or name (e.g. |
'ALL'
|
if_exists
|
IfExists
|
Behavior when a target table already exists. |
FAIL
|
with_views
|
bool
|
Create |
False
|
config
|
Mt5Config | None
|
MT5 connection configuration. |
None
|
Source code in mt5cli/history.py
3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 | |
create_cash_events_view ¶
Create the cash_events SQLite view derived from history_deals.
Returns:
| Type | Description |
|---|---|
bool
|
True if the view was created, False if required columns are missing. |
Source code in mt5cli/history.py
create_deal_portions_view ¶
create_deal_portions_view(
conn: Connection,
deals_columns: set[str],
*,
temporary: bool = False,
) -> bool
Create the deal_portions view, the canonical leg-aware deal layer.
deal_portions holds one row per trade deal, except that a
DEAL_ENTRY_INOUT reversal is split into a closing and an opening
portion. positions_reconstructed and the analytics views are derived
from it, so position reconstruction exists once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
SQLite connection holding |
required |
deals_columns
|
set[str]
|
Columns available on |
required |
temporary
|
bool
|
Create a connection-local TEMP view so a read-only database is never modified. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the view was created, False if required columns are missing. |
Source code in mt5cli/history.py
create_history_indexes ¶
create_history_indexes(
conn: Connection,
written_columns: dict[Dataset, set[str]],
) -> None
Create useful indexes for collected history tables when present.
Source code in mt5cli/history.py
create_positions_reconstructed_view ¶
create_positions_reconstructed_view(
conn: Connection,
deals_columns: set[str],
*,
temporary: bool = False,
) -> bool
Create the positions_reconstructed SQLite view derived from history_deals.
The view is a position-level summary of the deal_portions view: a
reversal's portions are re-merged through their entry value, so its
columns keep their documented meaning (volume_close and
volume_reversal count the whole reversal volume, deals_count counts
deals).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
SQLite connection holding |
required |
deals_columns
|
set[str]
|
Columns available on |
required |
temporary
|
bool
|
Create a connection-local TEMP view so a read-only database is never modified. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the view was created, False if required columns are missing. |
Source code in mt5cli/history.py
deduplicate_history_tables ¶
deduplicate_history_tables(
conn: Connection,
written_columns: dict[Dataset, set[str]],
written_tables: set[Dataset],
dedup_scopes: Mapping[Dataset, Sequence[DedupScope]]
| None = None,
) -> None
Deduplicate appended history tables by stable identifiers.
Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead.
Source code in mt5cli/history.py
drop_duplicates_in_table ¶
drop_duplicates_in_table(
cursor: Cursor,
table: str,
ids: list[str],
*,
keep: Literal["first", "last"] = "last",
scope_where: str | None = None,
scope_params: tuple[object, ...] = (),
) -> None
Remove duplicate rows, keeping the first or last ROWID per key group.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the table or column names are invalid. |
Source code in mt5cli/history.py
drop_forming_rate_bar ¶
Return closed bars from chronologically ordered MT5 rate data.
MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming
current bar as the last row. Slice it off so downstream logic only sees
completed bars. Empty frames and single-row frames return empty results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_rate
|
DataFrame
|
Rate data ordered oldest-to-newest with the forming bar last. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A new DataFrame with all rows except the last. Index and columns are |
DataFrame
|
preserved. The input frame is not modified. |
Source code in mt5cli/history.py
filter_incremental_history_deals_frame ¶
filter_incremental_history_deals_frame(
frame: DataFrame,
symbols: Sequence[str],
start_by_symbol: dict[str, datetime],
account_event_start: datetime,
) -> DataFrame
Filter incrementally fetched history_deals by symbol and event start times.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Rows for selected symbols at or after each symbol start, plus account |
DataFrame
|
events at or after |
Source code in mt5cli/history.py
filter_trade_history_frame ¶
filter_trade_history_frame(
frame: DataFrame,
symbols: Sequence[str],
*,
include_account_events: bool,
) -> DataFrame
Filter trade history rows to selected symbols and account events.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Filtered history rows. |
Source code in mt5cli/history.py
get_history_deals_account_event_start_datetime ¶
get_history_deals_account_event_start_datetime(
conn: Connection, *, fallback_start: datetime
) -> datetime
Return the next update start for account-level history_deals rows.
Source code in mt5cli/history.py
get_incremental_start_datetime ¶
get_incremental_start_datetime(
conn: Connection,
dataset: Dataset,
*,
symbol: str,
timeframe: int | None,
fallback_start: datetime,
) -> datetime
Return the next update start datetime from existing MAX(time).
Source code in mt5cli/history.py
get_table_columns ¶
Return existing SQLite columns for a table.
Source code in mt5cli/history.py
has_position_reconstruction_columns ¶
Return whether history_deals can support position reconstruction.
load_incremental_start_datetimes ¶
load_incremental_start_datetimes(
conn: Connection,
dataset: Dataset,
*,
symbols: Sequence[str],
timeframes: Sequence[int] | None = None,
fallback_start: datetime,
) -> dict[tuple[str, int | None], datetime]
Return next update start datetimes keyed by symbol and optional timeframe.
Source code in mt5cli/history.py
load_rate_data ¶
load_rate_data(
conn_or_path: SqliteConnOrPath,
table: str,
count: int | None = None,
) -> DataFrame
Load rate-like data from a SQLite database path or connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn_or_path
|
SqliteConnOrPath
|
SQLite database path or open connection. |
required |
table
|
str
|
Source table or view name. |
required |
count
|
int | None
|
Optional number of most recent rows to load. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame indexed by ascending |
Source code in mt5cli/history.py
load_rate_data_from_connection ¶
load_rate_data_from_connection(
connection: Connection,
table: str,
count: int | None = None,
) -> DataFrame
Load rate-like data from a SQLite table or view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Open SQLite connection. |
required |
table
|
str
|
Source table or view name. |
required |
count
|
int | None
|
Optional number of most recent rows to load. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame indexed by ascending |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs, schema, timestamps are invalid, or the table or view contains no rows. |
Source code in mt5cli/history.py
open_existing_sqlite_database ¶
open_existing_sqlite_database(
conn_or_path: SqliteConnOrPath,
) -> tuple[Connection, bool]
Open a read-only SQLite database or reuse an existing connection.
Returns:
| Type | Description |
|---|---|
tuple[Connection, bool]
|
Tuple of connection and whether the caller should close it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the database path does not exist or is not a file. |
Source code in mt5cli/history.py
parse_sqlite_timestamp ¶
Parse a SQLite history timestamp without inventing a timezone.
Naive values remain MT5 trade-server wall-clock labels. Explicitly aware values are normalized to UTC while preserving their instant. Numeric epoch values follow pdmt5's naive wall-clock representation.
Returns:
| Type | Description |
|---|---|
datetime | None
|
Parsed datetime preserving timestamp semantics, or |
Source code in mt5cli/history.py
persist_history_datasets ¶
persist_history_datasets(capture: HistoryCapture) -> None
Persist a :func:capture_history_datasets result into SQLite.
Opens and owns its own SQLite connection. Never accesses MT5 or any connection-scoped MT5 state, so it is safe to call from a dedicated persistence-writer thread that holds no MT5 client.
Source code in mt5cli/history.py
quote_sqlite_identifier ¶
record_written_columns ¶
record_written_columns(
written_columns: dict[Dataset, set[str]],
dataset: Dataset,
frame: DataFrame,
) -> None
Remember columns for datasets written during collection.
Source code in mt5cli/history.py
report_rate_gaps ¶
report_rate_gaps(
conn: Connection,
table: str,
*,
granularity_seconds: int | None = None,
min_gap_intervals: int = 1,
) -> DataFrame
Return one row per detected gap from a SQLite rate table.
The canonical rates table infers each series interval from its
timeframe column. Custom tables without timeframe metadata must
provide granularity_seconds explicitly.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the table/schema/timestamps or gap parameters are invalid. |
Source code in mt5cli/history.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | |
resolve_granularity_name ¶
Return a granularity name for a timeframe integer when known.
Source code in mt5cli/history.py
resolve_history_datasets ¶
Resolve configured history datasets.
Returns:
| Type | Description |
|---|---|
set[Dataset]
|
|
set[Dataset]
|
when |
set[Dataset]
|
may be empty or explicitly include |
set[Dataset]
|
|
Source code in mt5cli/history.py
resolve_history_tick_flags ¶
Resolve tick copy flags from an integer or name.
Returns:
| Type | Description |
|---|---|
int
|
Integer tick flag value. |
resolve_history_timeframes ¶
Resolve rate timeframes, deduplicating aliases for the same integer.
Returns:
| Type | Description |
|---|---|
list[int]
|
Ordered list of unique timeframe integers. |
Source code in mt5cli/history.py
resolve_rate_table_name ¶
Return the canonical normalized SQLite rate table name.
Returns:
| Type | Description |
|---|---|
str
|
Canonical normalized rates table name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mt5cli/history.py
timeframe_interval_seconds ¶
Return the bar interval in seconds for a timeframe integer.
Returns:
| Type | Description |
|---|---|
int | None
|
Interval seconds when the timeframe maps to a known granularity name |
int | None
|
(for example |
Source code in mt5cli/history.py
update_history ¶
update_history(
*,
client: HistoryClient,
output: Path | str,
symbols: Sequence[str],
datasets: set[Dataset] | None = None,
timeframes: Sequence[int | str] | None = None,
flags: int | str = "ALL",
lookback_hours: float = 24.0,
date_to: datetime | str | None = None,
deduplicate: bool = True,
with_views: bool = False,
include_account_events: bool = True,
) -> None
Incrementally append MT5 history into a SQLite database.
Uses an already-connected client and does not create or close the MT5
connection. For first-time tables, data is fetched from
date_to - lookback_hours. Subsequent runs resume from existing
MAX(time) per symbol (and timeframe for rates); when
include_account_events=True, account-level deals use a separate cursor
over type NOT IN (0, 1) / empty-symbol rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
HistoryClient
|
Connected MT5 client implementation. |
required |
output
|
Path | str
|
SQLite database path. |
required |
symbols
|
Sequence[str]
|
Symbols to update. |
required |
datasets
|
set[Dataset] | None
|
Datasets to include (defaults to rates, history-orders,
history-deals; pass |
None
|
timeframes
|
Sequence[int | str] | None
|
Rate timeframes to update (defaults to all fixed MT5 timeframes when None). |
None
|
flags
|
int | str
|
Tick copy flags as integer or name (e.g. |
'ALL'
|
lookback_hours
|
float
|
First-run lookback when a table has no prior rows. |
24.0
|
date_to
|
datetime | str | None
|
Optional naive trade-server end datetime. Required when any datasets are selected because mt5cli cannot determine the current MT5 trade-server time. |
None
|
deduplicate
|
bool
|
Remove duplicate rows after append, keeping latest ROWID. |
True
|
with_views
|
bool
|
Create |
False
|
include_account_events
|
bool
|
Include account-level cash events in
|
True
|
Source code in mt5cli/history.py
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 | |
update_history_with_config ¶
update_history_with_config(
*,
output: Path | str,
symbols: Sequence[str],
config: Mt5Config | None = None,
datasets: set[Dataset] | None = None,
timeframes: Sequence[int | str] | None = None,
flags: int | str = "ALL",
lookback_hours: float = 24.0,
date_to: datetime | str | None = None,
deduplicate: bool = True,
with_views: bool = False,
include_account_events: bool = True,
) -> None
Incrementally append MT5 history, opening and closing the MT5 connection.
Convenience wrapper around :func:update_history for standalone use.
Source code in mt5cli/history.py
write_collected_datasets ¶
write_collected_datasets(
conn: Connection,
client: HistoryClient,
symbols: Sequence[str],
datasets: set[Dataset],
timeframe: int,
flags: int,
date_from: datetime,
date_to: datetime,
if_exists: IfExists,
) -> tuple[set[Dataset], dict[Dataset, set[str]]]
Collect selected datasets and stream each symbol frame into SQLite.
Returns:
| Type | Description |
|---|---|
tuple[set[Dataset], dict[Dataset, set[str]]]
|
Written datasets and their columns. |
Source code in mt5cli/history.py
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 | |
write_history_dataset ¶
write_history_dataset(
conn: Connection,
fetch: Callable[..., DataFrame],
dataset: Dataset,
symbols: Sequence[str],
date_from: datetime,
date_to: datetime,
if_exists: IfExists,
written_columns: dict[Dataset, set[str]],
*,
include_account_events: bool = False,
) -> bool
Stream a history dataset into SQLite.
Returns:
| Type | Description |
|---|---|
bool
|
True if the target table was written. |
Source code in mt5cli/history.py
write_incremental_datasets ¶
write_incremental_datasets(
conn: Connection,
client: HistoryClient,
symbols: Sequence[str],
selected_datasets: set[Dataset],
resolved_timeframes: list[int],
resolved_tick_flags: int,
fallback_start: datetime,
end_date: datetime,
*,
deduplicate: bool,
with_views: bool,
include_account_events: bool,
) -> tuple[set[Dataset], dict[Dataset, set[str]]]
Append selected datasets incrementally and refresh indexes and views.
Returns:
| Type | Description |
|---|---|
tuple[set[Dataset], dict[Dataset, set[str]]]
|
Written datasets and their columns. |
Source code in mt5cli/history.py
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 | |
write_rates_dataset ¶
write_rates_dataset(
conn: Connection,
client: HistoryClient,
symbols: Sequence[str],
timeframe: int,
date_from: datetime,
date_to: datetime,
if_exists: IfExists,
written_columns: dict[Dataset, set[str]],
) -> bool
Stream rates frames into SQLite.
Returns:
| Type | Description |
|---|---|
bool
|
True if the rates table was written. |
Source code in mt5cli/history.py
write_streamed_frame ¶
write_streamed_frame(
conn: Connection,
frame: DataFrame,
dataset: Dataset,
table_exists: bool,
if_exists: IfExists,
written_columns: dict[Dataset, set[str]],
) -> bool
Write one streamed dataset frame and track table state.
Returns:
| Type | Description |
|---|---|
bool
|
True if the dataset table exists after this write attempt. |
Source code in mt5cli/history.py
write_symbols_dataset ¶
write_symbols_dataset(
conn: Connection,
client: HistoryClient,
symbols: Sequence[str],
snapshot_time: datetime,
if_exists: IfExists,
written_columns: dict[Dataset, set[str]],
) -> bool
Snapshot per-symbol metadata (point, digits, contract size, volume limits).
Broker-reported symbol metadata is only valid for the account/broker that
produced the snapshot. When a symbol's metadata cannot be retrieved, or
when its point is missing or zero (the terminal has no valid metadata
for it), a row is still persisted with NULL metadata and a warning is
logged; the sync is never aborted for a single bad symbol.
Returns:
| Type | Description |
|---|---|
bool
|
True if the symbols table was written. |
Source code in mt5cli/history.py
write_ticks_dataset ¶
write_ticks_dataset(
conn: Connection,
client: HistoryClient,
symbols: Sequence[str],
flags: int,
date_from: datetime,
date_to: datetime,
if_exists: IfExists,
written_columns: dict[Dataset, set[str]],
) -> bool
Stream ticks frames into SQLite.
Returns:
| Type | Description |
|---|---|
bool
|
True if the ticks table was written. |
Source code in mt5cli/history.py
collect-history schema¶
The collect-history command (and the matching collect_history SDK function) writes
selected MT5 datasets into one SQLite database. Each dataset becomes a table; column
names and types mirror the pdmt5 DataFrame schema for that export, with two additions:
symbolis prepended on every table.timeframeis prepended onratesso appended runs at different bar sizes stay distinguishable.
SQLite does not declare foreign keys. Rows are linked logically by symbol, time
windows, and (for deals) position_id / order. Duplicate rows are removed on
append using dataset-specific keys (for example ticket on history tables, or
(symbol, timeframe, time) on rates).
Optional views are created when --with-views is set and the history-deals dataset
was written.
All MT5 history query bounds are timezone-naive trade-server wall-clock
datetimes, matching pdmt5. Offset-bearing strings and timezone-aware
datetime values are rejected; incremental cursors and returned history
frames use the same naive contract, and no broker-time conversion is inferred.
Incremental updates require an explicit date_to because mt5cli cannot
determine the current MT5 trade-server time.
ticks and symbols are opt-in datasets (pass --dataset ticks /
--dataset symbols); they are excluded from the default rates,
history-orders, history-deals selection. Unlike the other datasets,
symbols is not a time-windowed history table: each collection or update
writes one row per requested symbol, timestamped with the collection's
date_to (one-shot collect-history) or the update's end time (incremental
update_history). It snapshots broker-reported symbol metadata (point,
digits, trade_contract_size, volume_min, volume_max, volume_step,
trade_tick_size, trade_tick_value, currency_profit) so downstream
consumers can convert rates.spread (points) into a relative spread without a
live terminal connection. Metadata is only valid for the account/broker that
produced the snapshot. When a symbol's point is missing or zero, the row is
still written with NULL metadata and a warning is logged — a bad symbol never
aborts the rest of the sync.
Entity-relationship diagram¶
Sample layout for a full collection with --with-views:
erDiagram
rates {
TEXT symbol "dedup key"
INTEGER timeframe "dedup key"
TEXT time "dedup key"
REAL open
REAL high
REAL low
REAL close
INTEGER tick_volume
INTEGER spread
INTEGER real_volume
}
ticks {
TEXT symbol "dedup key"
TEXT time "dedup key"
INTEGER time_msc "dedup key (preferred)"
REAL bid
REAL ask
REAL last
INTEGER volume
INTEGER flags
REAL volume_real
}
history_orders {
INTEGER ticket "dedup key"
TEXT symbol
TEXT time
INTEGER type
INTEGER state
REAL volume_initial
REAL price_open
REAL price_current
INTEGER magic
}
history_deals {
INTEGER ticket "dedup key"
INTEGER order
INTEGER position_id "groups position view"
TEXT symbol
TEXT time
INTEGER type "0/1 trade, else cash event"
INTEGER entry "0 IN, 1 OUT, 2 INOUT, 3 OUT_BY"
REAL volume
REAL price
REAL profit
REAL commission
REAL swap
REAL fee
}
symbols {
TEXT symbol "dedup key"
TEXT time "dedup key, snapshot moment"
REAL point
INTEGER digits
REAL trade_contract_size
REAL volume_min
REAL volume_max
REAL volume_step
REAL trade_tick_size
REAL trade_tick_value
TEXT currency_profit
}
cash_events {
INTEGER ticket
TEXT symbol
TEXT time
INTEGER type
REAL profit
}
deal_portions {
INTEGER ticket
INTEGER position_id
TEXT symbol
INTEGER leg
TEXT role
INTEGER position_start_known
REAL volume
REAL profit
REAL commission
REAL swap
REAL fee
}
positions_reconstructed {
INTEGER position_id
TEXT symbol
TEXT open_time
TEXT close_time
INTEGER direction
REAL volume_open
REAL volume_close
REAL volume_reversal
REAL open_price
REAL close_price
REAL total_profit
INTEGER reversal_count
INTEGER deals_count
}
rates ||--o{ history_deals : "symbol (logical)"
ticks ||--o{ history_deals : "symbol (logical)"
history_orders ||--o{ history_deals : "order ~ ticket (logical)"
symbols ||--o{ rates : "symbol (logical)"
history_deals ||--|| cash_events : "VIEW: type NOT IN (0,1)"
history_deals ||--o{ deal_portions : "VIEW: deals split at reversals"
deal_portions ||--o{ positions_reconstructed : "VIEW: GROUP BY position_id"
Tables and views¶
| Object | Kind | Source | Notes |
|---|---|---|---|
rates |
table | copy_rates_range |
Indexed on (symbol, timeframe, time) when columns exist. |
ticks |
table | copy_ticks_range |
Indexed on (symbol, time) when columns exist. |
history_orders |
table | history_orders_get |
Fetched per --symbol, then concatenated. |
history_deals |
table | history_deals_get |
Fetched per --symbol, then concatenated. Indexed on (position_id, symbol) when present. |
symbols |
table | symbol_info |
Opt-in. One row per symbol per collection/update, snapshotted at date_to / update end. |
cash_events |
view | history_deals |
Non-trade deal types (deposits, balance ops, etc.). Requires type column. |
deal_portions |
view | history_deals |
Canonical leg-aware layer: trade deals, with each reversal (DEAL_ENTRY_INOUT) split into a closing and an opening portion (leg, role). |
positions_reconstructed |
view | deal_portions |
One row per closed position_id; volume-weighted prices and reversal stats (reversal volume counted whole). |
The reversal split in deal_portions uses the balance of the visible deals, so it
is reliable only for positions whose first visible deal is an entry-in
(position_start_known = 1). When the captured history starts mid-position
(position_start_known = 0), the leg numbering and the closing/opening split of a
reversal are approximate, though every deal's cash totals are preserved and
positions_reconstructed is unaffected. The flag is best-effort: a scale-in is also
an entry-in deal, so if the capture window cuts a position and a later scale-in is
the first visible deal, the missing earlier exposure cannot be detected from the
deals alone.
Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing.
Incremental collection¶
The package-root mt5cli.update_history SDK path uses the normalized rates
table and optional cash_events / positions_reconstructed views. It writes the canonical normalized rates table directly and does not
maintain per-series compatibility views.
Rate data loading¶
The canonical managed rate store is the normalized rates table. Stable
symbol/timeframe reads query that table directly; mt5cli does not create,
discover, resolve, or maintain per-series rate_* compatibility views.
Use load_rate_series_from_sqlite() or
load_rate_series_by_granularity() for canonical managed data:
from pathlib import Path
from mt5cli import (
build_rate_targets,
load_rate_series_by_granularity,
load_rate_series_from_sqlite,
)
path = Path("history.db")
targets = build_rate_targets(["EURUSD", "GBPUSD"], ["M1", "H1"])
series = load_rate_series_from_sqlite(path, targets, count=1000)
eurusd_m1 = series["EURUSD", 1]
by_name = load_rate_series_by_granularity(
path,
symbols=["EURUSD", "GBPUSD"],
granularities=["M1", "H1"],
count=500,
)
eurusd_m1_named = by_name["EURUSD", "M1"]
Canonical reads apply count in SQLite and return the selected rows in
chronological order. Each returned series uses an ascending DatetimeIndex
named time. Timezone-naive MT5 trade-server wall-clock timestamps remain
naive; explicitly timezone-aware timestamps preserve their instant and are
normalized to UTC.
explicit_tables and the single-table table= form are reserved for
intentionally named custom tables. They do not discover or fall back to
managed per-series views. Explicit table counts must match target counts, and
duplicate (symbol, timeframe) targets are rejected.
load_rate_data() / load_rate_data_from_connection() remain available for
low-level explicit-table reads. These helpers validate that time exists and
return an ascending DatetimeIndex named time.
Throttled incremental history updates¶
ThrottledHistoryUpdater wraps update_history() with a minimum interval
between successful runs (using a monotonic clock), so an application loop can
call it every iteration without over-fetching.
from datetime import datetime
from pdmt5 import Mt5Config
from mt5cli import ThrottledHistoryUpdater, mt5_session
from mt5cli.utils import Dataset
updater = ThrottledHistoryUpdater(
output="history.db",
datasets={Dataset.rates},
timeframes=["M1"],
interval_seconds=60, # <= 0 updates on every call
)
with mt5_session(Mt5Config(login=12345)) as client:
while True:
updater.update(
client,
["EURUSD", "GBPUSD"],
date_to=datetime(2024, 2, 1),
) # no-op until 60s elapse
# ... do other work; break when shutting down ...
Pass update_backend to substitute the default update_history implementation
without monkey-patching mt5cli.history.update_history. The callable receives the
same keyword arguments as update_history (client, output, symbols,
datasets, timeframes, flags, lookback_hours, with_views,
date_to, include_account_events). The resolved backend is stored on
updater.update_backend for inspection or subclassing.
from mt5cli import ThrottledHistoryUpdater, update_history
def app_update_history(**kwargs) -> None:
update_history(**kwargs) # or delegate to application-specific logic
updater = ThrottledHistoryUpdater(
output="history.db",
interval_seconds=60,
update_backend=app_update_history,
)
By default recoverable errors (Mt5RuntimeError, sqlite3.Error,
ValueError, OSError) propagate so the caller controls logging; pass
suppress_errors=True to swallow them and return False without advancing the
throttle. AttributeError and TypeError are treated as caller programming
errors and always propagate, even when suppress_errors=True — the client
passed to update() must implement the canonical HistoryClient method names
(copy_rates_range, copy_ticks_range, history_orders, history_deals,
symbol_info_as_dict). Input validation (_resolve_update_history_request)
runs before any MT5 or SQLite calls, but when suppress_errors=True the
resulting ValueError is suppressed along with other recoverable errors.