SDK Module¶
mt5cli.sdk ¶
Programmatic SDK for MetaTrader 5 data collection.
__all__
module-attribute
¶
__all__ = [
"AccountSpec",
"Mt5CliClient",
"ThrottledHistoryUpdater",
"account_info",
"build_config",
"collect_history",
"collect_latest_closed_rates_by_granularity",
"collect_latest_closed_rates_for_accounts",
"collect_latest_rates",
"collect_latest_rates_for_accounts",
"collect_latest_rates_for_accounts_with_retries",
"connected_client",
"copy_rates_from",
"copy_rates_from_pos",
"copy_rates_range",
"copy_ticks_from",
"copy_ticks_range",
"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",
"report_rate_gaps",
"resolve_account_spec",
"resolve_account_specs",
"substitute_env_placeholders",
"substitute_mapping_values",
"symbol_info",
"symbol_info_tick",
"symbols",
"terminal_info",
"update_history",
"update_history_with_config",
"update_observability",
"update_observability_with_config",
"version",
]
AccountSpec
dataclass
¶
AccountSpec(
symbols: Sequence[str],
login: int | str | None = None,
password: str | None = None,
server: str | None = None,
path: str | None = None,
timeout: int | None = None,
)
Connection parameters and symbols for one MT5 account group.
Attributes:
| Name | Type | Description |
|---|---|---|
symbols |
Sequence[str]
|
Symbols to load latest rates for under this account. |
login |
int | str | None
|
Trading account login. String values are coerced to int when non-empty. |
password |
str | None
|
Trading account password. |
server |
str | None
|
Trading server name. |
path |
str | None
|
Path to the MetaTrader5 terminal EXE file. |
timeout |
int | None
|
Connection timeout in milliseconds. |
Mt5CliClient ¶
Mt5CliClient(
*,
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,
)
Programmatic client for read-only MetaTrader 5 data access.
Initialize the SDK client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to MetaTrader5 terminal EXE file. |
None
|
login
|
int | None
|
Trading account login. |
None
|
password
|
str | None
|
Trading account password. |
None
|
server
|
str | None
|
Trading server name. |
None
|
timeout
|
int | None
|
Connection timeout in milliseconds. |
None
|
retry_count
|
int
|
Number of MT5 initialization retries for sessions opened by this client. |
3
|
config
|
Mt5Config | None
|
Optional pre-built |
None
|
client
|
Mt5DataClient | None
|
Optional already-connected |
None
|
Source code in mt5cli/sdk.py
__enter__ ¶
Open a persistent MT5 connection for multiple calls.
Returns:
| Type | Description |
|---|---|
Self
|
This client instance. |
Source code in mt5cli/sdk.py
__exit__ ¶
Shut down the persistent MT5 connection.
Source code in mt5cli/sdk.py
account_info ¶
collect_latest_rates ¶
collect_latest_rates(
symbols: Sequence[str],
timeframes: Sequence[int | str],
*,
count: int,
start_pos: int = 0,
) -> dict[tuple[str, int], DataFrame]
Return latest rates for each symbol/timeframe pair.
Returns:
| Type | Description |
|---|---|
dict[tuple[str, int], DataFrame]
|
Mapping keyed by |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mt5cli/sdk.py
copy_rates_from ¶
copy_rates_from(
symbol: str,
timeframe: int | str,
date_from: datetime | str,
count: int,
) -> DataFrame
Return rates starting from a date.
Source code in mt5cli/sdk.py
copy_rates_from_pos ¶
Return rates starting from a bar position.
Source code in mt5cli/sdk.py
copy_rates_range ¶
copy_rates_range(
symbol: str,
timeframe: int | str,
date_from: datetime | str,
date_to: datetime | str,
) -> DataFrame
Return rates for a date range.
Source code in mt5cli/sdk.py
copy_ticks_from ¶
copy_ticks_from(
symbol: str,
date_from: datetime | str,
count: int,
flags: int | str,
) -> DataFrame
Return ticks starting from a date.
Source code in mt5cli/sdk.py
copy_ticks_range ¶
copy_ticks_range(
symbol: str,
date_from: datetime | str,
date_to: datetime | str,
flags: int | str,
) -> DataFrame
Return ticks for a date range.
Source code in mt5cli/sdk.py
from_connected_client
classmethod
¶
Bind to an already-connected Mt5DataClient without owning it.
The returned Mt5CliClient never initializes or shuts down the
injected client, including when used as a context manager.
Returns:
| Type | Description |
|---|---|
Self
|
Client wrapper bound to the injected connection. |
Source code in mt5cli/sdk.py
history_deals ¶
history_deals(
date_from: datetime | str | None = None,
date_to: datetime | str | None = None,
group: str | None = None,
symbol: str | None = None,
ticket: int | None = None,
position: int | None = None,
) -> DataFrame
Return historical deals.
Source code in mt5cli/sdk.py
history_orders ¶
history_orders(
date_from: datetime | str | None = None,
date_to: datetime | str | None = None,
group: str | None = None,
symbol: str | None = None,
ticket: int | None = None,
position: int | None = None,
) -> DataFrame
Return historical orders.
Source code in mt5cli/sdk.py
last_error ¶
latest_rates ¶
Return the latest rates from a bar position.
Source code in mt5cli/sdk.py
market_book ¶
minimum_margins ¶
Return minimum-volume buy and sell margin requirements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One-row DataFrame with columns |
DataFrame
|
|
Source code in mt5cli/sdk.py
mt5_summary ¶
Return a compact terminal/account status summary.
Source code in mt5cli/sdk.py
mt5_summary_as_df ¶
Return an export-safe one-row terminal/account summary DataFrame.
Source code in mt5cli/sdk.py
orders ¶
orders(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
) -> DataFrame
Return active orders.
Source code in mt5cli/sdk.py
positions ¶
positions(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
) -> DataFrame
Return open positions.
Source code in mt5cli/sdk.py
recent_history_deals ¶
recent_history_deals(
hours: float,
date_to: datetime | str | None = None,
group: str | None = None,
symbol: str | None = None,
) -> DataFrame
Return historical deals from a recent trailing window.
Source code in mt5cli/sdk.py
recent_ticks ¶
recent_ticks(
symbol: str,
seconds: float,
*,
date_to: datetime | str | None = None,
count: int = 10000,
flags: int | str = "ALL",
) -> DataFrame
Return ticks from a recent time window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
seconds
|
float
|
Lookback window in seconds ending at |
required |
date_to
|
datetime | str | None
|
Window end time. When |
None
|
count
|
int
|
Maximum ticks to return. Values |
10000
|
flags
|
int | str
|
Tick flags as |
'ALL'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tick DataFrame with MT5 tick columns such as |
DataFrame
|
|
Source code in mt5cli/sdk.py
symbol_info ¶
symbol_info_tick ¶
symbols ¶
terminal_info ¶
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 mt5cli.sdk.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/sdk.py
last_update_monotonic
property
¶
Return the 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/sdk.py
update ¶
Run a throttled incremental history update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Mt5DataClient
|
Connected MT5 data client. |
required |
symbols
|
Sequence[str]
|
Symbols to update. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if an update ran successfully, False if it was throttled or |
bool
|
(when |
bool
|
When |
bool
|
propagate to the caller. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
MT5 client capability mismatch when
|
TypeError
|
MT5 client capability mismatch when |
Source code in mt5cli/sdk.py
account_info ¶
build_config ¶
build_config(
*,
path: str | None = None,
login: int | str | None = None,
password: str | None = None,
server: str | None = None,
timeout: int | None = None,
allow_whole_dollar_env: bool = False,
) -> Mt5Config
Build an Mt5Config from optional connection parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Optional terminal executable path. |
None
|
login
|
int | str | None
|
Optional trading account login. Integers are preserved. String
values are coerced: empty or whitespace-only strings become
|
None
|
password
|
str | None
|
Optional trading account password. |
None
|
server
|
str | None
|
Optional trading server name. |
None
|
timeout
|
int | None
|
Optional connection timeout in milliseconds. |
None
|
allow_whole_dollar_env
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Mt5Config
|
Configured |
Source code in mt5cli/sdk.py
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
|
Start date. |
required |
date_to
|
datetime | str
|
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/sdk.py
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 | |
collect_latest_closed_rates_by_granularity ¶
collect_latest_closed_rates_by_granularity(
accounts: Sequence[AccountSpec],
granularities: Sequence[int | str],
count: int,
*,
start_pos: int = 0,
base_config: Mt5Config | None = None,
retry_count: int = 0,
backoff_base: float = 2.0,
) -> dict[tuple[str, str], DataFrame]
Collect latest closed rate bars keyed by symbol and granularity name.
Thin wrapper around :func:collect_latest_closed_rates_for_accounts that
rekeys the result by granularity name (for example M1) instead of the
integer timeframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Sequence[AccountSpec]
|
Account groups to read. Each must define at least one symbol. |
required |
granularities
|
Sequence[int | str]
|
MT5 timeframes as integers or names (for example |
required |
count
|
int
|
Number of closed bars to return per symbol/timeframe. |
required |
start_pos
|
int
|
Initial bar position offset passed to the underlying collector. |
0
|
base_config
|
Mt5Config | None
|
Optional base configuration whose fields fill any value not set on an individual account. |
None
|
retry_count
|
int
|
Maximum number of retries after the first attempt. |
0
|
backoff_base
|
float
|
Base for exponential backoff between retry attempts. |
2.0
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], DataFrame]
|
Mapping keyed by |
dict[tuple[str, str], DataFrame]
|
|
Source code in mt5cli/sdk.py
collect_latest_closed_rates_for_accounts ¶
collect_latest_closed_rates_for_accounts(
accounts: Sequence[AccountSpec],
timeframes: Sequence[int | str],
count: int,
*,
start_pos: int = 0,
base_config: Mt5Config | None = None,
retry_count: int = 0,
backoff_base: float = 2.0,
) -> dict[tuple[str, int], DataFrame]
Collect latest closed rate bars across multiple MT5 account groups.
When start_pos is 0 (the default), MetaTrader 5 includes the
still-forming current bar as the last row. This helper fetches
count + 1 bars, drops that bar with :func:drop_forming_rate_bar, and
validates that each resulting frame is non-empty. When start_pos is
greater than zero the forming bar is not in range, so only count bars
are fetched and no row is dropped.
Wraps :func:collect_latest_rates_for_accounts_with_retries for transient
MT5 error handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Sequence[AccountSpec]
|
Account groups to read. Each must define at least one symbol. |
required |
timeframes
|
Sequence[int | str]
|
MT5 timeframes as integers or names (for example |
required |
count
|
int
|
Number of closed bars to return per symbol/timeframe. |
required |
start_pos
|
int
|
Initial bar position offset passed to the underlying collector. |
0
|
base_config
|
Mt5Config | None
|
Optional base configuration whose fields fill any value not set on an individual account. |
None
|
retry_count
|
int
|
Maximum number of retries after the first attempt. |
0
|
backoff_base
|
float
|
Base for exponential backoff between retry attempts. |
2.0
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, int], DataFrame]
|
Mapping keyed by |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are invalid, or any series is empty (after
dropping the still-forming bar when |
Source code in mt5cli/sdk.py
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 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 | |
collect_latest_rates ¶
collect_latest_rates(
symbols: Sequence[str],
timeframes: Sequence[int | str],
*,
count: int,
start_pos: int = 0,
config: Mt5Config | None = None,
) -> dict[tuple[str, int], DataFrame]
Return latest rates for each symbol/timeframe pair.
Source code in mt5cli/sdk.py
collect_latest_rates_for_accounts ¶
collect_latest_rates_for_accounts(
accounts: Sequence[AccountSpec],
timeframes: Sequence[int | str],
count: int,
*,
start_pos: int = 0,
base_config: Mt5Config | None = None,
) -> dict[tuple[str, int], DataFrame]
Collect latest rates across multiple MT5 account groups.
Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Sequence[AccountSpec]
|
Account groups to read. Each must define at least one symbol. |
required |
timeframes
|
Sequence[int | str]
|
MT5 timeframes as integers or names (for example |
required |
count
|
int
|
Number of most recent bars to read per symbol/timeframe. |
required |
start_pos
|
int
|
Initial bar position offset. |
0
|
base_config
|
Mt5Config | None
|
Optional base configuration whose fields fill any value not set on an individual account. |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, int], DataFrame]
|
Mapping keyed by |
dict[tuple[str, int], DataFrame]
|
symbol/timeframe pair, the last account processed wins. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mt5cli/sdk.py
collect_latest_rates_for_accounts_with_retries ¶
collect_latest_rates_for_accounts_with_retries(
accounts: Sequence[AccountSpec],
timeframes: Sequence[int | str],
count: int,
*,
start_pos: int = 0,
base_config: Mt5Config | None = None,
retry_count: int = 0,
backoff_base: float = 2.0,
) -> dict[tuple[str, int], DataFrame]
Collect latest rates across accounts, retrying transient MT5 failures.
Wraps :func:collect_latest_rates_for_accounts with bounded exponential
backoff. Only pdmt5.Mt5RuntimeError is retried; other exceptions
propagate immediately. The final failure is re-raised once retries are
exhausted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Sequence[AccountSpec]
|
Account groups to read. Each must define at least one symbol. |
required |
timeframes
|
Sequence[int | str]
|
MT5 timeframes as integers or names (for example |
required |
count
|
int
|
Number of most recent bars to read per symbol/timeframe. |
required |
start_pos
|
int
|
Initial bar position offset. |
0
|
base_config
|
Mt5Config | None
|
Optional base configuration whose fields fill any value not set on an individual account. |
None
|
retry_count
|
int
|
Maximum number of retries after the first attempt. |
0
|
backoff_base
|
float
|
Base for exponential backoff. The delay before retry
attempt |
2.0
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, int], DataFrame]
|
Mapping keyed by |
dict[tuple[str, int], DataFrame]
|
for invalid inputs (see :func: |
dict[tuple[str, int], DataFrame]
|
re-raises the last |
dict[tuple[str, int], DataFrame]
|
exhausted. |
Source code in mt5cli/sdk.py
connected_client ¶
Initialize MT5, yield a connected client, and always shut down.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Mt5Config
|
MT5 connection configuration. |
required |
Yields:
| Type | Description |
|---|---|
Mt5DataClient
|
Connected |
Source code in mt5cli/sdk.py
copy_rates_from ¶
copy_rates_from(
symbol: str,
timeframe: int | str,
date_from: datetime | str,
count: int,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return rates starting from a date.
Source code in mt5cli/sdk.py
copy_rates_from_pos ¶
copy_rates_from_pos(
symbol: str,
timeframe: int | str,
start_pos: int,
count: int,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return rates starting from a bar position.
Source code in mt5cli/sdk.py
copy_rates_range ¶
copy_rates_range(
symbol: str,
timeframe: int | str,
date_from: datetime | str,
date_to: datetime | str,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return rates for a date range.
Source code in mt5cli/sdk.py
copy_ticks_from ¶
copy_ticks_from(
symbol: str,
date_from: datetime | str,
count: int,
flags: int | str,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return ticks starting from a date.
Source code in mt5cli/sdk.py
copy_ticks_range ¶
copy_ticks_range(
symbol: str,
date_from: datetime | str,
date_to: datetime | str,
flags: int | str,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return ticks for a date range.
Source code in mt5cli/sdk.py
fetch_latest_closed_rates ¶
fetch_latest_closed_rates(
client: Mt5CliClient,
*,
symbol: str,
granularity: str,
count: int,
) -> DataFrame
Fetch up to count most recent closed bars, oldest to newest.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Closed rate bars ordered oldest to newest. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mt5cli/sdk.py
history_deals ¶
history_deals(
date_from: datetime | str | None = None,
date_to: datetime | str | None = None,
group: str | None = None,
symbol: str | None = None,
ticket: int | None = None,
position: int | None = None,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return historical deals.
Source code in mt5cli/sdk.py
history_orders ¶
history_orders(
date_from: datetime | str | None = None,
date_to: datetime | str | None = None,
group: str | None = None,
symbol: str | None = None,
ticket: int | None = None,
position: int | None = None,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return historical orders.
Source code in mt5cli/sdk.py
last_error ¶
latest_rates ¶
latest_rates(
symbol: str,
timeframe: int | str,
count: int,
start_pos: int = 0,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return the latest rates from a bar position.
Source code in mt5cli/sdk.py
market_book ¶
minimum_margins ¶
Return minimum-volume buy and sell margin requirements.
See Mt5CliClient.minimum_margins for return details.
Source code in mt5cli/sdk.py
mt5_session ¶
mt5_session(
config: Mt5Config | None = None,
) -> Iterator[Mt5CliClient]
Open an MT5 terminal session and yield a connected client.
Launches the MetaTrader 5 terminal using Mt5Config.path (when set),
logs in, yields a connected :class:Mt5CliClient, and always shuts the
terminal down on exit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Mt5Config | None
|
MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. |
None
|
Yields:
| Type | Description |
|---|---|
Mt5CliClient
|
Connected |
Source code in mt5cli/sdk.py
mt5_summary ¶
mt5_summary_as_df ¶
Return an export-safe terminal/account status summary DataFrame.
orders ¶
orders(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return active orders.
Source code in mt5cli/sdk.py
positions ¶
positions(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return open positions.
Source code in mt5cli/sdk.py
recent_history_deals ¶
recent_history_deals(
hours: float,
date_to: datetime | str | None = None,
group: str | None = None,
symbol: str | None = None,
*,
config: Mt5Config | None = None,
) -> DataFrame
Return historical deals from a recent trailing window.
Source code in mt5cli/sdk.py
recent_ticks ¶
recent_ticks(
symbol: str,
seconds: float,
*,
date_to: datetime | str | None = None,
count: int = 10000,
flags: int | str = "ALL",
config: Mt5Config | None = None,
) -> DataFrame
Return ticks from a recent time window ending at date_to or now.
See Mt5CliClient.recent_ticks for parameter and return details.
Source code in mt5cli/sdk.py
report_rate_gaps ¶
report_rate_gaps(
conn: Connection,
table: str,
*,
granularity_seconds: int,
min_gap_intervals: int = 1,
) -> DataFrame
Return one row per detected gap from a SQLite rate table or view.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the table name, schema, timestamps, or gap parameters are invalid. |
Source code in mt5cli/history.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 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 | |
resolve_account_spec ¶
resolve_account_spec(
account: AccountSpec,
*,
login: int | str | None = None,
password: str | None = None,
server: str | None = None,
path: str | None = None,
timeout: int | None = None,
allow_whole_dollar_env: bool = False,
) -> AccountSpec
Resolve an account's credentials from overrides and ${ENV_VAR} values.
Explicit override arguments take precedence over the corresponding
:class:AccountSpec fields. The resolved string fields (login,
password, server, path) have any ${ENV_VAR} placeholders
substituted from the environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account
|
AccountSpec
|
Source account specification. |
required |
login
|
int | str | None
|
Optional explicit login override. |
None
|
password
|
str | None
|
Optional explicit password override. |
None
|
server
|
str | None
|
Optional explicit server override. |
None
|
path
|
str | None
|
Optional explicit terminal path override. |
None
|
timeout
|
int | None
|
Optional explicit connection timeout override. |
None
|
allow_whole_dollar_env
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
AccountSpec
|
A new :class: |
AccountSpec
|
symbols preserved. Raises |
AccountSpec
|
func: |
AccountSpec
|
variable is not set. |
Source code in mt5cli/sdk.py
resolve_account_specs ¶
resolve_account_specs(
accounts: Sequence[AccountSpec],
*,
login: int | str | None = None,
password: str | None = None,
server: str | None = None,
path: str | None = None,
timeout: int | None = None,
allow_whole_dollar_env: bool = False,
) -> list[AccountSpec]
Resolve credentials for multiple accounts.
Applies the same overrides and ${ENV_VAR} substitution as
:func:resolve_account_spec to every account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Sequence[AccountSpec]
|
Source account specifications. |
required |
login
|
int | str | None
|
Optional explicit login override applied to each account. |
None
|
password
|
str | None
|
Optional explicit password override applied to each account. |
None
|
server
|
str | None
|
Optional explicit server override applied to each account. |
None
|
path
|
str | None
|
Optional explicit terminal path override applied to each account. |
None
|
timeout
|
int | None
|
Optional explicit timeout override applied to each account. |
None
|
allow_whole_dollar_env
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
list[AccountSpec]
|
Resolved account specifications in the original order. Raises |
list[AccountSpec]
|
|
list[AccountSpec]
|
environment variable is not set. |
Source code in mt5cli/sdk.py
substitute_env_placeholders ¶
Replace ${ENV_VAR} placeholders in a string with environment values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String that may contain one or more |
required |
allow_whole_dollar_env
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The string with every placeholder replaced by its environment value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a referenced environment variable is not set. |
Source code in mt5cli/sdk.py
substitute_mapping_values ¶
substitute_mapping_values(
data: object,
*,
keys: Collection[str],
allow_whole_dollar_env: bool = False,
blank_string_keys_as_none: Collection[str] = (),
) -> object
Recursively substitute environment placeholders for selected mapping keys.
Traverses nested dicts and lists, expanding ${ENV_VAR} (and
$ENV_NAME when allow_whole_dollar_env=True) in string values
whose immediate parent dict key is in keys. Fields whose key is
not in keys are preserved exactly, including literal dollar signs.
Strings that are direct elements of a list are never substituted;
substitution only applies to strings that are immediate dict values.
This is a generic downstream config utility. Key names such as
mt5_login or mt5_password must be supplied by the caller;
mt5cli does not hard-code any application-specific key names.
Callers are responsible for ensuring data has bounded nesting depth;
deeply nested or self-referential structures will hit Python's recursion
limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
object
|
Arbitrarily nested dict/list/scalar value to process. |
required |
keys
|
Collection[str]
|
Mapping keys whose string values receive placeholder substitution. |
required |
allow_whole_dollar_env
|
bool
|
When |
False
|
blank_string_keys_as_none
|
Collection[str]
|
Mapping keys for which blank strings
(after any substitution) are normalised to |
()
|
Returns:
| Type | Description |
|---|---|
object
|
The processed value. Dicts and lists are rebuilt into new |
object
|
containers with selected string values substituted and |
object
|
blank-normalised. Scalar inputs (non-dict, non-list) are |
object
|
returned as-is. |
Source code in mt5cli/sdk.py
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 | |
symbol_info ¶
symbol_info_tick ¶
symbols ¶
terminal_info ¶
update_history ¶
update_history(
*,
client: Mt5DataClient,
output: Path | str,
symbols: Sequence[str],
datasets: set[Dataset] | None = None,
timeframes: Sequence[int | str] | None = None,
flags: int | str = "ALL",
lookback_hours: float = 24.0,
date_to: datetime | str | None = None,
deduplicate: bool = True,
create_rate_views: bool = True,
with_views: bool = False,
include_account_events: bool = True,
) -> None
Incrementally append MT5 history into a SQLite database.
Uses an already-connected Mt5DataClient and does not create or close
the MT5 connection. For first-time tables, data is fetched from
date_to - lookback_hours. Subsequent runs resume from existing
MAX(time) per symbol (and timeframe for rates); when
include_account_events=True, account-level deals use a separate cursor
over type NOT IN (0, 1) / empty-symbol rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Mt5DataClient
|
Connected MT5 data client. |
required |
output
|
Path | str
|
SQLite database path. |
required |
symbols
|
Sequence[str]
|
Symbols to update. |
required |
datasets
|
set[Dataset] | None
|
Datasets to include (defaults to 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 update end datetime. Defaults to now (UTC). |
None
|
deduplicate
|
bool
|
Remove duplicate rows after append, keeping latest ROWID. |
True
|
create_rate_views
|
bool
|
Create |
True
|
with_views
|
bool
|
Create |
False
|
include_account_events
|
bool
|
Include account-level cash events in
|
True
|
Source code in mt5cli/sdk.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 | |
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,
create_rate_views: bool = True,
with_views: bool = False,
include_account_events: bool = True,
) -> None
Incrementally append MT5 history, opening and closing the MT5 connection.
Convenience wrapper around :func:update_history for standalone use.
Source code in mt5cli/sdk.py
update_observability ¶
update_observability(
*,
client: Mt5DataClient,
output: Path | str,
symbols: Sequence[str] | None = None,
include_account: bool = True,
include_positions: bool = True,
include_orders: bool = True,
include_terminal: bool = True,
with_grafana_schema: bool = False,
) -> None
Snapshot current account/position/order/terminal state into SQLite.
Reads the current MT5 state and appends timestamped snapshot rows. Never places orders or modifies trading state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Mt5DataClient
|
Connected MT5 data client. |
required |
output
|
Path | str
|
SQLite database path. |
required |
symbols
|
Sequence[str] | None
|
Optional symbol filter for positions and orders. When None, all positions and orders are snapshotted. |
None
|
include_account
|
bool
|
Snapshot account info into |
True
|
include_positions
|
bool
|
Snapshot open positions into |
True
|
include_orders
|
bool
|
Snapshot active orders into |
True
|
include_terminal
|
bool
|
Snapshot terminal info into |
True
|
with_grafana_schema
|
bool
|
Ensure Grafana views and indexes exist. Defaults
to |
False
|
Source code in mt5cli/sdk.py
update_observability_with_config ¶
update_observability_with_config(
*,
output: Path | str,
config: Mt5Config | None = None,
symbols: Sequence[str] | None = None,
include_account: bool = True,
include_positions: bool = True,
include_orders: bool = True,
include_terminal: bool = True,
with_grafana_schema: bool = False,
) -> None
Snapshot current MT5 state, opening and closing the MT5 connection.
Convenience wrapper around :func:update_observability for standalone use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
Path | str
|
SQLite database path. |
required |
config
|
Mt5Config | None
|
MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. |
None
|
symbols
|
Sequence[str] | None
|
Optional symbol filter for positions and orders. |
None
|
include_account
|
bool
|
Snapshot account info. |
True
|
include_positions
|
bool
|
Snapshot open positions. |
True
|
include_orders
|
bool
|
Snapshot active orders. |
True
|
include_terminal
|
bool
|
Snapshot terminal info. |
True
|
with_grafana_schema
|
bool
|
Ensure Grafana views and indexes exist. |
False
|
Source code in mt5cli/sdk.py
version ¶
Resilient multi-account orchestration¶
The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application.
Retrying transient rate collection¶
collect_latest_rates_for_accounts_with_retries() wraps
collect_latest_rates_for_accounts() with bounded exponential backoff. Only
pdmt5.Mt5RuntimeError is retried; the final failure is re-raised once
retry_count is exhausted.
from mt5cli import AccountSpec, collect_latest_rates_for_accounts_with_retries
accounts = [AccountSpec(symbols=["EURUSD"], login=12345)]
rates = collect_latest_rates_for_accounts_with_retries(
accounts,
["M1", "H1"],
count=500,
retry_count=3,
backoff_base=2, # sleeps 2s, 4s, 8s between attempts
)
Latest closed rate bars¶
MetaTrader 5 start_pos=0 includes the still-forming current bar as the last
row. fetch_latest_closed_rates() handles one connected MT5Client; use
fetch_latest_closed_rates_for_trading_client() from an active trading
session created by create_trading_client(). Multi-account helpers fetch
count + 1 bars, drop
that row with drop_forming_rate_bar(), and validate each series is non-empty. Returned frames are ordered
oldest-to-newest and may contain fewer than count rows only when MT5 returns
fewer closed bars.
from mt5cli import (
AccountSpec,
collect_latest_closed_rates_by_granularity,
fetch_latest_closed_rates,
)
closed = fetch_latest_closed_rates(
client,
symbol="EURUSD",
granularity="M1",
count=500,
)
rates = collect_latest_closed_rates_by_granularity(
[AccountSpec(symbols=["EURUSD"], login=12345)],
["M1", "H1"],
count=500,
retry_count=3,
)
closed_m1 = rates["EURUSD", "M1"]
Use collect_latest_closed_rates_by_granularity() when callers prefer keys such
as ("EURUSD", "M1") instead of integer timeframes.
Resolving credentials and ${ENV_VAR} placeholders¶
resolve_account_spec() / resolve_account_specs() merge explicit override
values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping
secrets out of plan/config files. A missing environment variable raises
ValueError.
import os
from mt5cli import AccountSpec, resolve_account_specs
os.environ["MT5_LOGIN"] = "12345"
os.environ["MT5_PASSWORD"] = "secret"
accounts = [
AccountSpec(symbols=["EURUSD"], login="${MT5_LOGIN}", password="${MT5_PASSWORD}")
]
resolved = resolve_account_specs(accounts, server="Broker-Demo")
# resolved[0].login == "12345", resolved[0].server == "Broker-Demo"
Pass allow_whole_dollar_env=True to also expand strings whose entire value
is a bare $ENV_NAME identifier (no braces). This opt-in covers
substitute_env_placeholders(), resolve_account_spec(),
resolve_account_specs(), and build_config(). Note: build_config cannot
expand login because that parameter is int | None; use
resolve_account_spec for a string login placeholder. Partial strings such as
"plan$pass", "abc$ENV", or "$ENV-suffix" are never expanded — only an
exact $IDENTIFIER whole-string match qualifies. The default is False to
preserve backward compatibility.
import os
from mt5cli import AccountSpec, resolve_account_specs
os.environ["MT5_PASSWORD"] = "secret"
accounts = [AccountSpec(symbols=["EURUSD"], password="$MT5_PASSWORD")]
resolved = resolve_account_specs(accounts, allow_whole_dollar_env=True)
# resolved[0].password == "secret"
Throttled incremental history updates¶
ThrottledHistoryUpdater wraps update_history() with a minimum interval
between successful runs (using a monotonic clock), so an application loop can
call it every iteration without over-fetching.
from pdmt5 import Mt5Config, Mt5DataClient
from mt5cli import ThrottledHistoryUpdater
from mt5cli.utils import Dataset
updater = ThrottledHistoryUpdater(
output="history.db",
datasets={Dataset.rates},
timeframes=["M1"],
interval_seconds=60, # <= 0 updates on every call
)
client = Mt5DataClient(config=Mt5Config(login=12345))
client.initialize_and_login_mt5()
try:
while True:
updater.update(client, ["EURUSD", "GBPUSD"]) # no-op until 60s elapse
# ... do other work; break when shutting down ...
finally:
client.shutdown()
Pass update_backend to substitute the default update_history implementation
without monkey-patching mt5cli.sdk.update_history. The callable receives the
same keyword arguments as update_history (client, output, symbols,
datasets, timeframes, flags, lookback_hours, with_views,
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 (Mt5TradingError, Mt5RuntimeError,
sqlite3.Error, ValueError, OSError, and MT5 client capability
AttributeError / TypeError for history API methods) propagate so the caller
controls logging; pass suppress_errors=True to swallow them and return
False without advancing the throttle. Other AttributeError / TypeError
values always propagate. 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.
Trading-capable sessions¶
For order placement and trading calculations, use the dedicated
Trading module. Use mt5_session() / MT5Client for read-only
collection.