406
-407
-408
-409
-410
-411
-412
-413
-414
+ | 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
+441
+442
+443
+444
+445
+446
+447
+448
+449
| 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
|
@@ -636,7 +636,7 @@ not implement strategy logic, signal generation, or trade sizing.
build_config(
*,
path: str | None = None,
- login: int | None = None,
+ login: int | str | None = None,
password: str | None = None,
server: str | None = None,
timeout: int | None = None,
@@ -681,11 +681,16 @@ not implement strategy logic, signal generation, or trade sizing.
login
|
- int | None
+ int | str | None
|
- Optional trading account login.
+ Optional trading account login. Integers are preserved. String
+values are coerced: empty or whitespace-only strings become
+None; numeric strings such as "12345" are converted to
+int; non-numeric strings raise ValueError. When
+allow_whole_dollar_env=True, $ENV_NAME and
+${ENV_NAME} placeholders are expanded before coercion.
|
@@ -751,8 +756,8 @@ not implement strategy logic, signal generation, or trade sizing.
When True, string parameters that are
exactly $ENV_NAME are expanded from the environment. Applies
-to path, password, and server. Default False
-preserves existing behavior.
+to path, login, password, and server. Default
+ False preserves existing behavior.
|
@@ -788,8 +793,7 @@ preserves existing behavior.
Source code in mt5cli/sdk.py
- 305
-306
+ | def build_config(
- *,
- path: str | None = None,
- login: int | 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.
-
- Args:
- path: Optional terminal executable path.
- login: Optional trading account login.
- password: Optional trading account password.
- server: Optional trading server name.
- timeout: Optional connection timeout in milliseconds.
- allow_whole_dollar_env: When ``True``, string parameters that are
- exactly ``$ENV_NAME`` are expanded from the environment. Applies
- to ``path``, ``password``, and ``server``. Default ``False``
- preserves existing behavior.
-
- Returns:
- Configured ``Mt5Config`` instance.
- """
- if allow_whole_dollar_env:
- if path is not None:
- path = substitute_env_placeholders(path, allow_whole_dollar_env=True)
- if password is not None:
- password = substitute_env_placeholders(
- password, allow_whole_dollar_env=True
- )
- if server is not None:
- server = substitute_env_placeholders(server, allow_whole_dollar_env=True)
- return Mt5Config(
- path=path,
- login=login,
- password=password,
- server=server,
- timeout=timeout,
- )
+345
+346
+347
+348
+349
+350
+351
+352
+353
| def 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.
+
+ Args:
+ path: Optional terminal executable path.
+ login: Optional trading account login. Integers are preserved. String
+ values are coerced: empty or whitespace-only strings become
+ ``None``; numeric strings such as ``"12345"`` are converted to
+ ``int``; non-numeric strings raise ``ValueError``. When
+ ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and
+ ``${ENV_NAME}`` placeholders are expanded before coercion.
+ password: Optional trading account password.
+ server: Optional trading server name.
+ timeout: Optional connection timeout in milliseconds.
+ allow_whole_dollar_env: When ``True``, string parameters that are
+ exactly ``$ENV_NAME`` are expanded from the environment. Applies
+ to ``path``, ``login``, ``password``, and ``server``. Default
+ ``False`` preserves existing behavior.
+
+ Returns:
+ Configured ``Mt5Config`` instance.
+ """
+ if allow_whole_dollar_env:
+ if path is not None:
+ path = substitute_env_placeholders(path, allow_whole_dollar_env=True)
+ if isinstance(login, str):
+ login = substitute_env_placeholders(login, allow_whole_dollar_env=True)
+ if password is not None:
+ password = substitute_env_placeholders(
+ password, allow_whole_dollar_env=True
+ )
+ if server is not None:
+ server = substitute_env_placeholders(server, allow_whole_dollar_env=True)
+ return Mt5Config(
+ path=path,
+ login=_coerce_login(login),
+ password=password,
+ server=server,
+ timeout=timeout,
+ )
|
diff --git a/api/public-contract/index.html b/api/public-contract/index.html
index a79d975..9af736d 100644
--- a/api/public-contract/index.html
+++ b/api/public-contract/index.html
@@ -218,7 +218,7 @@ APIs.
|
build_config |
-Build pdmt5.Mt5Config from connection fields |
+Build pdmt5.Mt5Config from connection fields; login accepts int \| str \| None — numeric strings are coerced to int, blank strings are treated as unset, and ${ENV_VAR} / $ENV_NAME placeholders in string parameters are expanded when allow_whole_dollar_env=True |
mt5_session |
@@ -240,14 +240,19 @@ APIs.
substitute_env_placeholders |
Replace ${NAME} substrings from the environment; opt-in allow_whole_dollar_env for whole-value $NAME |
+
+substitute_mapping_values |
+Recursively traverse a dict/list/scalar structure and substitute ${ENV_VAR} placeholders for caller-selected mapping keys only; optionally normalise blank strings to None for a separate caller-selected key set; does not hard-code any application-specific key names |
+
Credential resolution is generic: any environment variable name may appear inside
${...}. mt5cli does not hard-code application-specific keys such as
mt5_login or mt5_exe.
Pass allow_whole_dollar_env=True to substitute_env_placeholders(),
-resolve_account_spec(), resolve_account_specs(), and build_config() to
-additionally expand strings whose entire value is a bare $ENV_NAME identifier.
+substitute_mapping_values(), resolve_account_spec(), resolve_account_specs(),
+and build_config() to additionally expand strings whose entire value is a bare
+$ENV_NAME identifier.
Partial strings such as "plan$pass", "abc$ENV", or "$ENV-suffix" are
never expanded — only an exact $IDENTIFIER whole-string match qualifies.
Default is False to preserve backward compatibility.
diff --git a/api/sdk/index.html b/api/sdk/index.html
index 5b4f844..6678729 100644
--- a/api/sdk/index.html
+++ b/api/sdk/index.html
@@ -278,14 +278,15 @@
"resolve_account_spec",
"resolve_account_specs",
"substitute_env_placeholders",
- "symbol_info",
- "symbol_info_tick",
- "symbols",
- "terminal_info",
- "update_history",
- "update_history_with_config",
- "version",
- ]
+ "substitute_mapping_values",
+ "symbol_info",
+ "symbol_info_tick",
+ "symbols",
+ "terminal_info",
+ "update_history",
+ "update_history_with_config",
+ "version",
+ ]
@@ -813,15 +814,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 406
-407
-408
-409
-410
-411
-412
-413
-414
+ | 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
+441
+442
+443
+444
+445
+446
+447
+448
+449
| 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
|
@@ -965,15 +966,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 460
-461
-462
-463
-464
-465
-466
-467
-468
+ | 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
+476
+477
+478
+479
+480
+481
+482
+483
+484
| 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
|
@@ -1026,25 +1027,25 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- | def __exit__(
- self,
- exc_type: type[BaseException] | None,
- exc: BaseException | None,
- tb: object,
-) -> None:
- """Shut down the persistent MT5 connection."""
- if self._client is not None and self._owns_client:
- self._client.shutdown()
- self._client = None
+ | def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: object,
+) -> None:
+ """Shut down the persistent MT5 connection."""
+ if self._client is not None and self._owns_client:
+ self._client.shutdown()
+ self._client = None
|
@@ -1069,11 +1070,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())
|
@@ -1150,15 +1151,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 545
-546
-547
-548
-549
-550
-551
-552
-553
+ | 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
- },
- )
+580
+581
+582
+583
+584
+585
+586
+587
+588
| 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
+ },
+ )
|
@@ -1250,15 +1251,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 497
-498
-499
-500
-501
-502
-503
-504
-505
+ | 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,
- ),
- )
+514
+515
+516
+517
+518
+519
+520
+521
+522
| 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,
+ ),
+ )
|
@@ -1314,15 +1315,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 516
-517
-518
-519
-520
-521
-522
-523
-524
+ | 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,
- ),
- )
+532
+533
+534
+535
+536
+537
+538
+539
+540
| 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,
+ ),
+ )
|
@@ -1376,15 +1377,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 582
-583
-584
-585
-586
-587
-588
-589
-590
+ | 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,
- ),
- )
+600
+601
+602
+603
+604
+605
+606
+607
+608
| 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,
+ ),
+ )
|
@@ -1442,15 +1443,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 602
-603
-604
-605
-606
-607
-608
-609
-610
+ | 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,
- ),
- )
+619
+620
+621
+622
+623
+624
+625
+626
+627
| 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,
+ ),
+ )
|
@@ -1506,15 +1507,7 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 621
-622
-623
-624
-625
-626
-627
-628
-629
+ | 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,
- ),
- )
+639
+640
+641
+642
+643
+644
+645
+646
+647
| 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,
+ ),
+ )
|
@@ -1596,27 +1597,27 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 443
-444
-445
-446
-447
-448
-449
-450
-451
+ | @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)
+453
+454
+455
+456
+457
+458
+459
+460
+461
| @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)
|
@@ -1648,15 +1649,7 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 710
-711
-712
-713
-714
-715
-716
-717
-718
+ | def history_deals(
- self,
- date_from: datetime | str | None = None,
- date_to: datetime | str | None = None,
- group: str | None = None,
- symbol: str | None = None,
- ticket: int | None = None,
- position: int | None = None,
-) -> pd.DataFrame:
- """Return historical deals."""
- start = _coerce_datetime(date_from)
- end = _coerce_datetime(date_to)
- return self._fetch(
- lambda c: c.history_deals_get_as_df(
- date_from=start,
- date_to=end,
- group=group,
- symbol=symbol,
- ticket=ticket,
- position=position,
- ),
- )
+731
+732
+733
+734
+735
+736
+737
+738
+739
| def history_deals(
+ self,
+ date_from: datetime | str | None = None,
+ date_to: datetime | str | None = None,
+ group: str | None = None,
+ symbol: str | None = None,
+ ticket: int | None = None,
+ position: int | None = None,
+) -> pd.DataFrame:
+ """Return historical deals."""
+ start = _coerce_datetime(date_from)
+ end = _coerce_datetime(date_to)
+ return self._fetch(
+ lambda c: c.history_deals_get_as_df(
+ date_from=start,
+ date_to=end,
+ group=group,
+ symbol=symbol,
+ ticket=ticket,
+ position=position,
+ ),
+ )
|
@@ -1722,15 +1723,7 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 687
-688
-689
-690
-691
-692
-693
-694
-695
+ | def history_orders(
- self,
- date_from: datetime | str | None = None,
- date_to: datetime | str | None = None,
- group: str | None = None,
- symbol: str | None = None,
- ticket: int | None = None,
- position: int | None = None,
-) -> pd.DataFrame:
- """Return historical orders."""
- start = _coerce_datetime(date_from)
- end = _coerce_datetime(date_to)
- return self._fetch(
- lambda c: c.history_orders_get_as_df(
- date_from=start,
- date_to=end,
- group=group,
- symbol=symbol,
- ticket=ticket,
- position=position,
- ),
- )
+708
+709
+710
+711
+712
+713
+714
+715
+716
| def history_orders(
+ self,
+ date_from: datetime | str | None = None,
+ date_to: datetime | str | None = None,
+ group: str | None = None,
+ symbol: str | None = None,
+ ticket: int | None = None,
+ position: int | None = None,
+) -> pd.DataFrame:
+ """Return historical orders."""
+ start = _coerce_datetime(date_from)
+ end = _coerce_datetime(date_to)
+ return self._fetch(
+ lambda c: c.history_orders_get_as_df(
+ date_from=start,
+ date_to=end,
+ group=group,
+ symbol=symbol,
+ ticket=ticket,
+ position=position,
+ ),
+ )
|
@@ -1789,11 +1790,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- | def last_error(self) -> pd.DataFrame:
- """Return the last error information."""
- return self._fetch(lambda c: c.last_error_as_df())
+ | def last_error(self) -> pd.DataFrame:
+ """Return the last error information."""
+ return self._fetch(lambda c: c.last_error_as_df())
|
@@ -1823,25 +1824,25 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- | def latest_rates(
- self,
- symbol: str,
- timeframe: int | str,
- count: int,
- start_pos: int = 0,
-) -> pd.DataFrame:
- """Return the latest rates from a bar position."""
- _require_positive(count, "count")
- return self.copy_rates_from_pos(symbol, timeframe, start_pos, count)
+ | def latest_rates(
+ self,
+ symbol: str,
+ timeframe: int | str,
+ count: int,
+ start_pos: int = 0,
+) -> pd.DataFrame:
+ """Return the latest rates from a bar position."""
+ _require_positive(count, "count")
+ return self.copy_rates_from_pos(symbol, timeframe, start_pos, count)
|
@@ -1866,11 +1867,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- | def market_book(self, symbol: str) -> pd.DataFrame:
- """Return market depth for a symbol."""
- return self._fetch(lambda c: c.market_book_get_as_df(symbol=symbol))
+ | def market_book(self, symbol: str) -> pd.DataFrame:
+ """Return market depth for a symbol."""
+ return self._fetch(lambda c: c.market_book_get_as_df(symbol=symbol))
|
@@ -1959,27 +1960,27 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 806
-807
-808
-809
-810
-811
-812
-813
-814
+ | def minimum_margins(self, symbol: str) -> pd.DataFrame:
- """Return minimum-volume buy and sell margin requirements.
-
- Args:
- symbol: Symbol name.
-
- Returns:
- One-row DataFrame with columns ``symbol``, ``account_currency``,
- ``volume_min``, ``buy_margin``, and ``sell_margin``.
- """
- return self._fetch(lambda c: _fetch_minimum_margins(c, symbol))
+816
+817
+818
+819
+820
+821
+822
+823
+824
| def minimum_margins(self, symbol: str) -> pd.DataFrame:
+ """Return minimum-volume buy and sell margin requirements.
+
+ Args:
+ symbol: Symbol name.
+
+ Returns:
+ One-row DataFrame with columns ``symbol``, ``account_currency``,
+ ``volume_min``, ``buy_margin``, and ``sell_margin``.
+ """
+ return self._fetch(lambda c: _fetch_minimum_margins(c, symbol))
|
@@ -2004,15 +2005,7 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 818
-819
-820
-821
-822
-823
-824
-825
-826
+ | def mt5_summary(self) -> dict[str, object]:
- """Return a compact terminal/account status summary."""
-
- def _summary(client: Mt5DataClient) -> dict[str, object]:
- return {
- "version": _plain_mt5_value(
- _call_required_client_method(client, "version"),
- ),
- "terminal_info": _plain_mt5_value(
- _call_required_client_method(client, "terminal_info"),
- ),
- "account_info": _plain_mt5_value(
- _call_required_client_method(client, "account_info"),
- ),
- "symbols_total": _plain_mt5_value(
- _call_required_client_method(client, "symbols_total"),
- ),
- }
-
- return self._fetch_value(_summary)
+837
+838
+839
+840
+841
+842
+843
+844
+845
| def mt5_summary(self) -> dict[str, object]:
+ """Return a compact terminal/account status summary."""
+
+ def _summary(client: Mt5DataClient) -> dict[str, object]:
+ return {
+ "version": _plain_mt5_value(
+ _call_required_client_method(client, "version"),
+ ),
+ "terminal_info": _plain_mt5_value(
+ _call_required_client_method(client, "terminal_info"),
+ ),
+ "account_info": _plain_mt5_value(
+ _call_required_client_method(client, "account_info"),
+ ),
+ "symbols_total": _plain_mt5_value(
+ _call_required_client_method(client, "symbols_total"),
+ ),
+ }
+
+ return self._fetch_value(_summary)
|
@@ -2067,27 +2068,27 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 839
-840
-841
-842
-843
-844
-845
-846
-847
+ | def mt5_summary_as_df(self) -> pd.DataFrame:
- """Return an export-safe one-row terminal/account summary DataFrame."""
- summary = self.mt5_summary()
- return pd.DataFrame(
- [
- {
- key: _mt5_summary_export_value(value)
- for key, value in summary.items()
- },
- ],
- )
+849
+850
+851
+852
+853
+854
+855
+856
+857
| def mt5_summary_as_df(self) -> pd.DataFrame:
+ """Return an export-safe one-row terminal/account summary DataFrame."""
+ summary = self.mt5_summary()
+ return pd.DataFrame(
+ [
+ {
+ key: _mt5_summary_export_value(value)
+ for key, value in summary.items()
+ },
+ ],
+ )
|
@@ -2116,33 +2117,33 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 657
-658
-659
-660
-661
-662
-663
-664
-665
+ | def orders(
- self,
- symbol: str | None = None,
- group: str | None = None,
- ticket: int | None = None,
-) -> pd.DataFrame:
- """Return active orders."""
- return self._fetch(
- lambda c: c.orders_get_as_df(
- symbol=symbol,
- group=group,
- ticket=ticket,
- ),
- )
+670
+671
+672
+673
+674
+675
+676
+677
+678
| def orders(
+ self,
+ symbol: str | None = None,
+ group: str | None = None,
+ ticket: int | None = None,
+) -> pd.DataFrame:
+ """Return active orders."""
+ return self._fetch(
+ lambda c: c.orders_get_as_df(
+ symbol=symbol,
+ group=group,
+ ticket=ticket,
+ ),
+ )
|
@@ -2171,33 +2172,33 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 672
-673
-674
-675
-676
-677
-678
-679
-680
+ | def positions(
- self,
- symbol: str | None = None,
- group: str | None = None,
- ticket: int | None = None,
-) -> pd.DataFrame:
- """Return open positions."""
- return self._fetch(
- lambda c: c.positions_get_as_df(
- symbol=symbol,
- group=group,
- ticket=ticket,
- ),
- )
+685
+686
+687
+688
+689
+690
+691
+692
+693
| def positions(
+ self,
+ symbol: str | None = None,
+ group: str | None = None,
+ ticket: int | None = None,
+) -> pd.DataFrame:
+ """Return open positions."""
+ return self._fetch(
+ lambda c: c.positions_get_as_df(
+ symbol=symbol,
+ group=group,
+ ticket=ticket,
+ ),
+ )
|
@@ -2227,15 +2228,7 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 733
-734
-735
-736
-737
-738
-739
-740
-741
+ | def recent_history_deals(
- self,
- hours: float,
- date_to: datetime | str | None = None,
- group: str | None = None,
- symbol: str | None = None,
-) -> pd.DataFrame:
- """Return historical deals from a recent trailing window."""
- _require_positive(hours, "hours")
- end = _require_datetime(date_to) if date_to is not None else datetime.now(UTC)
- start = end - timedelta(hours=hours)
- return self.history_deals(
- date_from=start,
- date_to=end,
- group=group,
- symbol=symbol,
- )
+749
+750
+751
+752
+753
+754
+755
+756
+757
| def recent_history_deals(
+ self,
+ hours: float,
+ date_to: datetime | str | None = None,
+ group: str | None = None,
+ symbol: str | None = None,
+) -> pd.DataFrame:
+ """Return historical deals from a recent trailing window."""
+ _require_positive(hours, "hours")
+ end = _require_datetime(date_to) if date_to is not None else datetime.now(UTC)
+ start = end - timedelta(hours=hours)
+ return self.history_deals(
+ date_from=start,
+ date_to=end,
+ group=group,
+ symbol=symbol,
+ )
|
@@ -2423,15 +2424,7 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- 767
-768
-769
-770
-771
-772
-773
-774
-775
+ | def recent_ticks(
- self,
- symbol: str,
- seconds: float,
- *,
- date_to: datetime | str | None = None,
- count: int = 10000,
- flags: int | str = "ALL",
-) -> pd.DataFrame:
- """Return ticks from a recent time window.
-
- Args:
- symbol: Symbol name.
- seconds: Lookback window in seconds ending at ``date_to``.
- date_to: Window end time. When ``None``, uses the latest
- ``symbol_info_tick().time`` rather than wall-clock now.
- count: Maximum ticks to return. Values ``<= 0`` return the full
- window without trimming. Positive values keep the most recent
- ticks; when the window is sparse, ``copy_ticks_from`` avoids
- fetching the entire range.
- flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer.
-
- Returns:
- Tick DataFrame with MT5 tick columns such as ``time``, ``bid``,
- ``ask``, ``last``, and ``volume``.
- """
- tick_flags = _coerce_tick_flags(flags)
- end = _coerce_datetime(date_to)
- return self._fetch(
- lambda c: _fetch_recent_ticks(
- c,
- symbol,
- seconds,
- end,
- count,
- tick_flags,
- ),
- )
+804
+805
+806
+807
+808
+809
+810
+811
+812
| def recent_ticks(
+ self,
+ symbol: str,
+ seconds: float,
+ *,
+ date_to: datetime | str | None = None,
+ count: int = 10000,
+ flags: int | str = "ALL",
+) -> pd.DataFrame:
+ """Return ticks from a recent time window.
+
+ Args:
+ symbol: Symbol name.
+ seconds: Lookback window in seconds ending at ``date_to``.
+ date_to: Window end time. When ``None``, uses the latest
+ ``symbol_info_tick().time`` rather than wall-clock now.
+ count: Maximum ticks to return. Values ``<= 0`` return the full
+ window without trimming. Positive values keep the most recent
+ ticks; when the window is sparse, ``copy_ticks_from`` avoids
+ fetching the entire range.
+ flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer.
+
+ Returns:
+ Tick DataFrame with MT5 tick columns such as ``time``, ``bid``,
+ ``ask``, ``last``, and ``volume``.
+ """
+ tick_flags = _coerce_tick_flags(flags)
+ end = _coerce_datetime(date_to)
+ return self._fetch(
+ lambda c: _fetch_recent_ticks(
+ c,
+ symbol,
+ seconds,
+ end,
+ count,
+ tick_flags,
+ ),
+ )
|
@@ -2522,11 +2523,11 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- | def symbol_info(self, symbol: str) -> pd.DataFrame:
- """Return details for one symbol."""
- return self._fetch(lambda c: c.symbol_info_as_df(symbol=symbol))
+ | def symbol_info(self, symbol: str) -> pd.DataFrame:
+ """Return details for one symbol."""
+ return self._fetch(lambda c: c.symbol_info_as_df(symbol=symbol))
|
@@ -2551,11 +2552,11 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- | def symbol_info_tick(self, symbol: str) -> pd.DataFrame:
- """Return the last tick for a symbol."""
- return self._fetch(lambda c: c.symbol_info_tick_as_df(symbol=symbol))
+ | def symbol_info_tick(self, symbol: str) -> pd.DataFrame:
+ """Return the last tick for a symbol."""
+ return self._fetch(lambda c: c.symbol_info_tick_as_df(symbol=symbol))
|
@@ -2580,11 +2581,11 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- | def symbols(self, group: str | None = None) -> pd.DataFrame:
- """Return the symbol list."""
- return self._fetch(lambda c: c.symbols_get_as_df(group=group))
+ | def symbols(self, group: str | None = None) -> pd.DataFrame:
+ """Return the symbol list."""
+ return self._fetch(lambda c: c.symbols_get_as_df(group=group))
|
@@ -2609,11 +2610,11 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- | def terminal_info(self) -> pd.DataFrame:
- """Return terminal information."""
- return self._fetch(lambda c: c.terminal_info_as_df())
+ | def terminal_info(self) -> pd.DataFrame:
+ """Return terminal information."""
+ return self._fetch(lambda c: c.terminal_info_as_df())
|
@@ -2638,11 +2639,11 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- | def version(self) -> pd.DataFrame:
- """Return MetaTrader5 version information."""
- return self._fetch(lambda c: c.version_as_df())
+ | def version(self) -> pd.DataFrame:
+ """Return MetaTrader5 version information."""
+ return self._fetch(lambda c: c.version_as_df())
|
@@ -2907,15 +2908,7 @@ when :meth:update runs. Receives the same keyword arguments as
Source code in mt5cli/sdk.py
- 1082
-1083
-1084
-1085
-1086
-1087
-1088
-1089
-1090
+ | def __init__(
- self,
- *,
- output: Path | str,
- datasets: set[Dataset] | None = None,
- timeframes: Sequence[int | str] | None = None,
- flags: int | str = "ALL",
- lookback_hours: float = 24.0,
- with_views: bool = False,
- include_account_events: bool = True,
- interval_seconds: float = 0.0,
- suppress_errors: bool = False,
- update_backend: UpdateHistoryBackend | None = None,
-) -> None:
- """Initialize the throttled updater.
-
- Args:
- output: SQLite database path.
- datasets: Datasets to include (defaults to all).
- timeframes: Rate timeframes to update (defaults to all fixed MT5
- timeframes).
- flags: Tick copy flags as integer or name (e.g. ``ALL``).
- lookback_hours: First-run lookback when a table has no prior rows.
- with_views: Create ``cash_events`` and ``positions_reconstructed``
- views.
- include_account_events: Include account-level cash events.
- interval_seconds: Minimum seconds between successful updates. Values
- ``<= 0`` update on every call.
- suppress_errors: When True, recoverable errors (``Mt5TradingError``,
- ``Mt5RuntimeError``, ``sqlite3.Error``, ``ValueError``,
- ``OSError``, and MT5 client capability ``AttributeError`` /
- ``TypeError`` for history API methods) raised during an update
- are swallowed and :meth:`update` returns False without advancing
- the throttle. Other ``AttributeError`` / ``TypeError`` values
- always propagate. When False (default), recoverable errors
- propagate so callers control logging.
- update_backend: Callable invoked instead of :func:`update_history`
- when :meth:`update` runs. Receives the same keyword arguments as
- :func:`update_history` (``client``, ``output``, ``symbols``,
- ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``,
- ``with_views``, ``include_account_events``). Defaults to
- :func:`update_history`.
- """
- self.output = output
- self.datasets = datasets
- self.timeframes = timeframes
- self.flags = flags
- self.lookback_hours = lookback_hours
- self.with_views = with_views
- self.include_account_events = include_account_events
- self.interval_seconds = interval_seconds
- self.suppress_errors = suppress_errors
- self.update_backend = (
- update_history if update_backend is None else update_backend
- )
- self._last_update_monotonic: float | None = None
+1137
+1138
+1139
+1140
+1141
+1142
+1143
+1144
+1145
| def __init__(
+ self,
+ *,
+ output: Path | str,
+ datasets: set[Dataset] | None = None,
+ timeframes: Sequence[int | str] | None = None,
+ flags: int | str = "ALL",
+ lookback_hours: float = 24.0,
+ with_views: bool = False,
+ include_account_events: bool = True,
+ interval_seconds: float = 0.0,
+ suppress_errors: bool = False,
+ update_backend: UpdateHistoryBackend | None = None,
+) -> None:
+ """Initialize the throttled updater.
+
+ Args:
+ output: SQLite database path.
+ datasets: Datasets to include (defaults to all).
+ timeframes: Rate timeframes to update (defaults to all fixed MT5
+ timeframes).
+ flags: Tick copy flags as integer or name (e.g. ``ALL``).
+ lookback_hours: First-run lookback when a table has no prior rows.
+ with_views: Create ``cash_events`` and ``positions_reconstructed``
+ views.
+ include_account_events: Include account-level cash events.
+ interval_seconds: Minimum seconds between successful updates. Values
+ ``<= 0`` update on every call.
+ suppress_errors: When True, recoverable errors (``Mt5TradingError``,
+ ``Mt5RuntimeError``, ``sqlite3.Error``, ``ValueError``,
+ ``OSError``, and MT5 client capability ``AttributeError`` /
+ ``TypeError`` for history API methods) raised during an update
+ are swallowed and :meth:`update` returns False without advancing
+ the throttle. Other ``AttributeError`` / ``TypeError`` values
+ always propagate. When False (default), recoverable errors
+ propagate so callers control logging.
+ update_backend: Callable invoked instead of :func:`update_history`
+ when :meth:`update` runs. Receives the same keyword arguments as
+ :func:`update_history` (``client``, ``output``, ``symbols``,
+ ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``,
+ ``with_views``, ``include_account_events``). Defaults to
+ :func:`update_history`.
+ """
+ self.output = output
+ self.datasets = datasets
+ self.timeframes = timeframes
+ self.flags = flags
+ self.lookback_hours = lookback_hours
+ self.with_views = with_views
+ self.include_account_events = include_account_events
+ self.interval_seconds = interval_seconds
+ self.suppress_errors = suppress_errors
+ self.update_backend = (
+ update_history if update_backend is None else update_backend
+ )
+ self._last_update_monotonic: float | None = None
|
@@ -3343,27 +3344,27 @@ when :meth:update runs. Receives the same keyword arguments as
Source code in mt5cli/sdk.py
- 1144
-1145
-1146
-1147
-1148
-1149
-1150
-1151
-1152
+ | def should_update(self) -> bool:
- """Return whether enough time has elapsed to run another update.
-
- Returns:
- True when ``interval_seconds <= 0``, when no update has succeeded
- yet, or when at least ``interval_seconds`` have elapsed since the
- last successful update.
- """
- if self.interval_seconds <= 0 or self._last_update_monotonic is None:
- return True
- return (time.monotonic() - self._last_update_monotonic) >= self.interval_seconds
+1154
+1155
+1156
+1157
+1158
+1159
+1160
+1161
+1162
| def should_update(self) -> bool:
+ """Return whether enough time has elapsed to run another update.
+
+ Returns:
+ True when ``interval_seconds <= 0``, when no update has succeeded
+ yet, or when at least ``interval_seconds`` have elapsed since the
+ last successful update.
+ """
+ if self.interval_seconds <= 0 or self._last_update_monotonic is None:
+ return True
+ return (time.monotonic() - self._last_update_monotonic) >= self.interval_seconds
|
@@ -3525,15 +3526,7 @@ is False, or any other type error.
Source code in mt5cli/sdk.py
- 1156
-1157
-1158
-1159
-1160
-1161
-1162
-1163
-1164
+ | def update(self, client: Mt5DataClient, symbols: Sequence[str]) -> bool:
- """Run a throttled incremental history update.
-
- Args:
- client: Connected MT5 data client.
- symbols: Symbols to update.
-
- Returns:
- True if an update ran successfully, False if it was throttled or
- (when ``suppress_errors`` is True) failed with a recoverable error.
- When ``suppress_errors`` is False, recoverable update failures
- propagate to the caller.
-
- Raises:
- AttributeError: MT5 client capability mismatch when
- ``suppress_errors`` is False, or any other attribute error.
- TypeError: MT5 client capability mismatch when ``suppress_errors``
- is False, or any other type error.
- """
- if not self.should_update():
- return False
- try:
- _resolve_update_history_request(
- output=self.output,
- symbols=symbols,
- datasets=self.datasets,
- timeframes=self.timeframes,
- flags=self.flags,
- lookback_hours=self.lookback_hours,
- date_to=None,
- )
- self.update_backend(
- client=client,
- output=self.output,
- symbols=symbols,
- datasets=self.datasets,
- timeframes=self.timeframes,
- flags=self.flags,
- lookback_hours=self.lookback_hours,
- with_views=self.with_views,
- include_account_events=self.include_account_events,
- )
- except _RECOVERABLE_HISTORY_UPDATE_ERRORS:
- if self.suppress_errors:
- logger.warning("Suppressed history update error", exc_info=True)
- return False
- raise
- except (AttributeError, TypeError) as exc:
- if self.suppress_errors and _is_mt5_client_capability_error(exc):
- logger.warning("Suppressed history update error", exc_info=True)
- return False
- raise
- self._last_update_monotonic = time.monotonic()
- return True
+1209
+1210
+1211
+1212
+1213
+1214
+1215
+1216
+1217
| def update(self, client: Mt5DataClient, symbols: Sequence[str]) -> bool:
+ """Run a throttled incremental history update.
+
+ Args:
+ client: Connected MT5 data client.
+ symbols: Symbols to update.
+
+ Returns:
+ True if an update ran successfully, False if it was throttled or
+ (when ``suppress_errors`` is True) failed with a recoverable error.
+ When ``suppress_errors`` is False, recoverable update failures
+ propagate to the caller.
+
+ Raises:
+ AttributeError: MT5 client capability mismatch when
+ ``suppress_errors`` is False, or any other attribute error.
+ TypeError: MT5 client capability mismatch when ``suppress_errors``
+ is False, or any other type error.
+ """
+ if not self.should_update():
+ return False
+ try:
+ _resolve_update_history_request(
+ output=self.output,
+ symbols=symbols,
+ datasets=self.datasets,
+ timeframes=self.timeframes,
+ flags=self.flags,
+ lookback_hours=self.lookback_hours,
+ date_to=None,
+ )
+ self.update_backend(
+ client=client,
+ output=self.output,
+ symbols=symbols,
+ datasets=self.datasets,
+ timeframes=self.timeframes,
+ flags=self.flags,
+ lookback_hours=self.lookback_hours,
+ with_views=self.with_views,
+ include_account_events=self.include_account_events,
+ )
+ except _RECOVERABLE_HISTORY_UPDATE_ERRORS:
+ if self.suppress_errors:
+ logger.warning("Suppressed history update error", exc_info=True)
+ return False
+ raise
+ except (AttributeError, TypeError) as exc:
+ if self.suppress_errors and _is_mt5_client_capability_error(exc):
+ logger.warning("Suppressed history update error", exc_info=True)
+ return False
+ raise
+ self._last_update_monotonic = time.monotonic()
+ return True
|
@@ -3667,11 +3668,11 @@ is False, or any other type error.
Source code in mt5cli/sdk.py
- | def account_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
- """Return account information."""
- return _make_client(config=config).account_info()
+ | def account_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
+ """Return account information."""
+ return _make_client(config=config).account_info()
|
@@ -3689,7 +3690,7 @@ is False, or any other type error.
build_config(
*,
path: str | None = None,
- login: int | None = None,
+ login: int | str | None = None,
password: str | None = None,
server: str | None = None,
timeout: int | None = None,
@@ -3734,11 +3735,16 @@ is False, or any other type error.
login
|
- int | None
+ int | str | None
|
- Optional trading account login.
+ Optional trading account login. Integers are preserved. String
+values are coerced: empty or whitespace-only strings become
+None; numeric strings such as "12345" are converted to
+int; non-numeric strings raise ValueError. When
+allow_whole_dollar_env=True, $ENV_NAME and
+${ENV_NAME} placeholders are expanded before coercion.
|
@@ -3804,8 +3810,8 @@ is False, or any other type error.
When True, string parameters that are
exactly $ENV_NAME are expanded from the environment. Applies
-to path, password, and server. Default False
-preserves existing behavior.
+to path, login, password, and server. Default
+ False preserves existing behavior.
|
@@ -3841,8 +3847,7 @@ preserves existing behavior.
Source code in mt5cli/sdk.py
- 305
-306
+ | def build_config(
- *,
- path: str | None = None,
- login: int | 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.
-
- Args:
- path: Optional terminal executable path.
- login: Optional trading account login.
- password: Optional trading account password.
- server: Optional trading server name.
- timeout: Optional connection timeout in milliseconds.
- allow_whole_dollar_env: When ``True``, string parameters that are
- exactly ``$ENV_NAME`` are expanded from the environment. Applies
- to ``path``, ``password``, and ``server``. Default ``False``
- preserves existing behavior.
-
- Returns:
- Configured ``Mt5Config`` instance.
- """
- if allow_whole_dollar_env:
- if path is not None:
- path = substitute_env_placeholders(path, allow_whole_dollar_env=True)
- if password is not None:
- password = substitute_env_placeholders(
- password, allow_whole_dollar_env=True
- )
- if server is not None:
- server = substitute_env_placeholders(server, allow_whole_dollar_env=True)
- return Mt5Config(
- path=path,
- login=login,
- password=password,
- server=server,
- timeout=timeout,
- )
+345
+346
+347
+348
+349
+350
+351
+352
+353
| def 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.
+
+ Args:
+ path: Optional terminal executable path.
+ login: Optional trading account login. Integers are preserved. String
+ values are coerced: empty or whitespace-only strings become
+ ``None``; numeric strings such as ``"12345"`` are converted to
+ ``int``; non-numeric strings raise ``ValueError``. When
+ ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and
+ ``${ENV_NAME}`` placeholders are expanded before coercion.
+ password: Optional trading account password.
+ server: Optional trading server name.
+ timeout: Optional connection timeout in milliseconds.
+ allow_whole_dollar_env: When ``True``, string parameters that are
+ exactly ``$ENV_NAME`` are expanded from the environment. Applies
+ to ``path``, ``login``, ``password``, and ``server``. Default
+ ``False`` preserves existing behavior.
+
+ Returns:
+ Configured ``Mt5Config`` instance.
+ """
+ if allow_whole_dollar_env:
+ if path is not None:
+ path = substitute_env_placeholders(path, allow_whole_dollar_env=True)
+ if isinstance(login, str):
+ login = substitute_env_placeholders(login, allow_whole_dollar_env=True)
+ if password is not None:
+ password = substitute_env_placeholders(
+ password, allow_whole_dollar_env=True
+ )
+ if server is not None:
+ server = substitute_env_placeholders(server, allow_whole_dollar_env=True)
+ return Mt5Config(
+ path=path,
+ login=_coerce_login(login),
+ password=password,
+ server=server,
+ timeout=timeout,
+ )
|
@@ -4145,15 +4165,7 @@ preserves existing behavior.
Source code in mt5cli/sdk.py
- 1212
-1213
-1214
-1215
-1216
-1217
-1218
-1219
-1220
+ | def collect_history(
- output: Path,
- symbols: list[str],
- date_from: datetime | str,
- date_to: datetime | str,
- *,
- datasets: set[Dataset] | None = None,
- timeframe: int | str = 1,
- flags: int | str = "ALL",
- if_exists: IfExists = IfExists.FAIL,
- with_views: bool = False,
- config: Mt5Config | None = None,
-) -> None:
- """Collect historical datasets into a single SQLite database.
-
- Args:
- output: SQLite database path.
- symbols: Symbols to collect.
- date_from: Start date.
- date_to: End date.
- datasets: Datasets to include (defaults to all).
- timeframe: Rates timeframe as integer or name (e.g. ``M1``).
- flags: Tick copy flags as integer or name (e.g. ``ALL``).
- if_exists: Behavior when a target table already exists.
- with_views: Create ``cash_events`` and ``positions_reconstructed`` views.
- config: MT5 connection configuration.
- """
- start = _require_datetime(date_from)
- end = _require_datetime(date_to)
- selected = datasets if datasets is not None else set(Dataset)
- tf = _coerce_timeframe(timeframe)
- tick_flags = _coerce_tick_flags(flags)
- mt5_config = config or build_config()
- with connected_client(mt5_config) as client, sqlite3.connect(output) as conn:
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA synchronous=NORMAL")
- written_tables, written_columns = write_collected_datasets(
- conn,
- client,
- symbols,
- selected,
- tf,
- tick_flags,
- start,
- end,
- if_exists,
- )
- create_history_indexes(conn, written_columns)
- if with_views and Dataset.history_deals in written_tables:
- create_cash_events_view(conn, written_columns[Dataset.history_deals])
- create_positions_reconstructed_view(
- conn,
- written_columns[Dataset.history_deals],
- )
- elif with_views:
- logger.warning(
- "--with-views ignored: history_deals table was not written",
- )
- logger.info(
- "Collected %s for %d symbol(s) into %s",
- ", ".join(sorted(ds.value for ds in selected)),
- len(symbols),
- output,
- )
+1275
+1276
+1277
+1278
+1279
+1280
+1281
+1282
+1283
| def collect_history(
+ output: Path,
+ symbols: list[str],
+ date_from: datetime | str,
+ date_to: datetime | str,
+ *,
+ datasets: set[Dataset] | None = None,
+ timeframe: int | str = 1,
+ flags: int | str = "ALL",
+ if_exists: IfExists = IfExists.FAIL,
+ with_views: bool = False,
+ config: Mt5Config | None = None,
+) -> None:
+ """Collect historical datasets into a single SQLite database.
+
+ Args:
+ output: SQLite database path.
+ symbols: Symbols to collect.
+ date_from: Start date.
+ date_to: End date.
+ datasets: Datasets to include (defaults to all).
+ timeframe: Rates timeframe as integer or name (e.g. ``M1``).
+ flags: Tick copy flags as integer or name (e.g. ``ALL``).
+ if_exists: Behavior when a target table already exists.
+ with_views: Create ``cash_events`` and ``positions_reconstructed`` views.
+ config: MT5 connection configuration.
+ """
+ start = _require_datetime(date_from)
+ end = _require_datetime(date_to)
+ selected = datasets if datasets is not None else set(Dataset)
+ tf = _coerce_timeframe(timeframe)
+ tick_flags = _coerce_tick_flags(flags)
+ mt5_config = config or build_config()
+ with connected_client(mt5_config) as client, sqlite3.connect(output) as conn:
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA synchronous=NORMAL")
+ written_tables, written_columns = write_collected_datasets(
+ conn,
+ client,
+ symbols,
+ selected,
+ tf,
+ tick_flags,
+ start,
+ end,
+ if_exists,
+ )
+ create_history_indexes(conn, written_columns)
+ if with_views and Dataset.history_deals in written_tables:
+ create_cash_events_view(conn, written_columns[Dataset.history_deals])
+ create_positions_reconstructed_view(
+ conn,
+ written_columns[Dataset.history_deals],
+ )
+ elif with_views:
+ logger.warning(
+ "--with-views ignored: history_deals table was not written",
+ )
+ logger.info(
+ "Collected %s for %d symbol(s) into %s",
+ ", ".join(sorted(ds.value for ds in selected)),
+ len(symbols),
+ output,
+ )
|
@@ -4480,93 +4500,93 @@ disables retries.
Source code in mt5cli/sdk.py
- | def 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], pd.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.
-
- Args:
- accounts: Account groups to read. Each must define at least one symbol.
- granularities: MT5 timeframes as integers or names (for example ``M1``).
- count: Number of closed bars to return per symbol/timeframe.
- start_pos: Initial bar position offset passed to the underlying collector.
- base_config: Optional base configuration whose fields fill any value not
- set on an individual account.
- retry_count: Maximum number of retries after the first attempt. ``0``
- disables retries.
- backoff_base: Base for exponential backoff between retry attempts.
-
- Returns:
- Mapping keyed by ``(symbol, granularity_name)``. Propagates
- ``ValueError`` from :func:`collect_latest_closed_rates_for_accounts`.
- """
- loaded = collect_latest_closed_rates_for_accounts(
- accounts,
- granularities,
- count,
- start_pos=start_pos,
- base_config=base_config,
- retry_count=retry_count,
- backoff_base=backoff_base,
- )
- return {
- (symbol, resolve_granularity_name(timeframe)): frame
- for (symbol, timeframe), frame in loaded.items()
- }
+ | def 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], pd.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.
+
+ Args:
+ accounts: Account groups to read. Each must define at least one symbol.
+ granularities: MT5 timeframes as integers or names (for example ``M1``).
+ count: Number of closed bars to return per symbol/timeframe.
+ start_pos: Initial bar position offset passed to the underlying collector.
+ base_config: Optional base configuration whose fields fill any value not
+ set on an individual account.
+ retry_count: Maximum number of retries after the first attempt. ``0``
+ disables retries.
+ backoff_base: Base for exponential backoff between retry attempts.
+
+ Returns:
+ Mapping keyed by ``(symbol, granularity_name)``. Propagates
+ ``ValueError`` from :func:`collect_latest_closed_rates_for_accounts`.
+ """
+ loaded = collect_latest_closed_rates_for_accounts(
+ accounts,
+ granularities,
+ count,
+ start_pos=start_pos,
+ base_config=base_config,
+ retry_count=retry_count,
+ backoff_base=backoff_base,
+ )
+ return {
+ (symbol, resolve_granularity_name(timeframe)): frame
+ for (symbol, timeframe), frame in loaded.items()
+ }
|
@@ -4794,127 +4814,127 @@ dropping the still-forming bar when start_pos is 0).
Source code in mt5cli/sdk.py
- | def 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], pd.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.
-
- Args:
- accounts: Account groups to read. Each must define at least one symbol.
- timeframes: MT5 timeframes as integers or names (for example ``M1``).
- count: Number of closed bars to return per symbol/timeframe.
- start_pos: Initial bar position offset passed to the underlying collector.
- base_config: Optional base configuration whose fields fill any value not
- set on an individual account.
- retry_count: Maximum number of retries after the first attempt. ``0``
- disables retries.
- backoff_base: Base for exponential backoff between retry attempts.
-
- Returns:
- Mapping keyed by ``(symbol, timeframe_int)``.
-
- Raises:
- ValueError: If inputs are invalid, or any series is empty (after
- dropping the still-forming bar when ``start_pos`` is ``0``).
- """
- _require_positive(count, "count")
- _require_non_negative(start_pos, "start_pos")
- fetch_count = count + 1 if start_pos == 0 else count
- loaded = collect_latest_rates_for_accounts_with_retries(
- accounts,
- timeframes,
- fetch_count,
- start_pos=start_pos,
- base_config=base_config,
- retry_count=retry_count,
- backoff_base=backoff_base,
- )
- result: dict[tuple[str, int], pd.DataFrame] = {}
- for key, df_rate in loaded.items():
- closed = drop_forming_rate_bar(df_rate) if start_pos == 0 else df_rate
- if closed.empty:
- symbol, timeframe = key
- msg = f"Rate data is empty for {symbol!r} at timeframe {timeframe}."
- raise ValueError(msg)
- result[key] = closed
- return result
+ | def 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], pd.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.
+
+ Args:
+ accounts: Account groups to read. Each must define at least one symbol.
+ timeframes: MT5 timeframes as integers or names (for example ``M1``).
+ count: Number of closed bars to return per symbol/timeframe.
+ start_pos: Initial bar position offset passed to the underlying collector.
+ base_config: Optional base configuration whose fields fill any value not
+ set on an individual account.
+ retry_count: Maximum number of retries after the first attempt. ``0``
+ disables retries.
+ backoff_base: Base for exponential backoff between retry attempts.
+
+ Returns:
+ Mapping keyed by ``(symbol, timeframe_int)``.
+
+ Raises:
+ ValueError: If inputs are invalid, or any series is empty (after
+ dropping the still-forming bar when ``start_pos`` is ``0``).
+ """
+ _require_positive(count, "count")
+ _require_non_negative(start_pos, "start_pos")
+ fetch_count = count + 1 if start_pos == 0 else count
+ loaded = collect_latest_rates_for_accounts_with_retries(
+ accounts,
+ timeframes,
+ fetch_count,
+ start_pos=start_pos,
+ base_config=base_config,
+ retry_count=retry_count,
+ backoff_base=backoff_base,
+ )
+ result: dict[tuple[str, int], pd.DataFrame] = {}
+ for key, df_rate in loaded.items():
+ closed = drop_forming_rate_bar(df_rate) if start_pos == 0 else df_rate
+ if closed.empty:
+ symbol, timeframe = key
+ msg = f"Rate data is empty for {symbol!r} at timeframe {timeframe}."
+ raise ValueError(msg)
+ result[key] = closed
+ return result
|
@@ -4946,35 +4966,35 @@ dropping the still-forming bar when start_pos is 0).
Source code in mt5cli/sdk.py
- 1360
-1361
-1362
-1363
-1364
-1365
-1366
-1367
-1368
+ | def collect_latest_rates(
- symbols: Sequence[str],
- timeframes: Sequence[int | str],
- *,
- count: int,
- start_pos: int = 0,
- config: Mt5Config | None = None,
-) -> dict[tuple[str, int], pd.DataFrame]:
- """Return latest rates for each symbol/timeframe pair."""
- return _make_client(config=config).collect_latest_rates(
- symbols,
- timeframes,
- count=count,
- start_pos=start_pos,
- )
+1374
+1375
+1376
+1377
+1378
+1379
+1380
+1381
+1382
| def collect_latest_rates(
+ symbols: Sequence[str],
+ timeframes: Sequence[int | str],
+ *,
+ count: int,
+ start_pos: int = 0,
+ config: Mt5Config | None = None,
+) -> dict[tuple[str, int], pd.DataFrame]:
+ """Return latest rates for each symbol/timeframe pair."""
+ return _make_client(config=config).collect_latest_rates(
+ symbols,
+ timeframes,
+ count=count,
+ start_pos=start_pos,
+ )
|
@@ -5171,111 +5191,111 @@ empty, or count is not positive.
Source code in mt5cli/sdk.py
- | def collect_latest_rates_for_accounts(
- accounts: Sequence[AccountSpec],
- timeframes: Sequence[int | str],
- count: int,
- *,
- start_pos: int = 0,
- base_config: Mt5Config | None = None,
-) -> dict[tuple[str, int], pd.DataFrame]:
- """Collect latest rates across multiple MT5 account groups.
-
- Each account is connected in turn, its symbols are read for every
- timeframe, and the resulting frames are merged into a single mapping.
-
- Args:
- accounts: Account groups to read. Each must define at least one symbol.
- timeframes: MT5 timeframes as integers or names (for example ``M1``).
- count: Number of most recent bars to read per symbol/timeframe.
- start_pos: Initial bar position offset.
- base_config: Optional base configuration whose fields fill any value not
- set on an individual account.
-
- Returns:
- Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a
- symbol/timeframe pair, the last account processed wins.
-
- Raises:
- ValueError: If ``accounts``, ``timeframes``, or any account's symbols are
- empty, or ``count`` is not positive.
- """
- account_list = list(accounts)
- if not account_list:
- msg = "At least one account is required."
- raise ValueError(msg)
- if not timeframes:
- msg = "At least one timeframe is required."
- raise ValueError(msg)
- if any(not account.symbols for account in account_list):
- msg = "Each account requires at least one symbol."
- raise ValueError(msg)
- _require_positive(count, "count")
- result: dict[tuple[str, int], pd.DataFrame] = {}
- for account in account_list:
- config = _build_account_config(account, base_config)
- with Mt5CliClient(config=config) as client:
- result.update(
- client.collect_latest_rates(
- account.symbols,
- timeframes,
- count=count,
- start_pos=start_pos,
- ),
- )
- return result
+ | def collect_latest_rates_for_accounts(
+ accounts: Sequence[AccountSpec],
+ timeframes: Sequence[int | str],
+ count: int,
+ *,
+ start_pos: int = 0,
+ base_config: Mt5Config | None = None,
+) -> dict[tuple[str, int], pd.DataFrame]:
+ """Collect latest rates across multiple MT5 account groups.
+
+ Each account is connected in turn, its symbols are read for every
+ timeframe, and the resulting frames are merged into a single mapping.
+
+ Args:
+ accounts: Account groups to read. Each must define at least one symbol.
+ timeframes: MT5 timeframes as integers or names (for example ``M1``).
+ count: Number of most recent bars to read per symbol/timeframe.
+ start_pos: Initial bar position offset.
+ base_config: Optional base configuration whose fields fill any value not
+ set on an individual account.
+
+ Returns:
+ Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a
+ symbol/timeframe pair, the last account processed wins.
+
+ Raises:
+ ValueError: If ``accounts``, ``timeframes``, or any account's symbols are
+ empty, or ``count`` is not positive.
+ """
+ account_list = list(accounts)
+ if not account_list:
+ msg = "At least one account is required."
+ raise ValueError(msg)
+ if not timeframes:
+ msg = "At least one timeframe is required."
+ raise ValueError(msg)
+ if any(not account.symbols for account in account_list):
+ msg = "Each account requires at least one symbol."
+ raise ValueError(msg)
+ _require_positive(count, "count")
+ result: dict[tuple[str, int], pd.DataFrame] = {}
+ for account in account_list:
+ config = _build_account_config(account, base_config)
+ with Mt5CliClient(config=config) as client:
+ result.update(
+ client.collect_latest_rates(
+ account.symbols,
+ timeframes,
+ count=count,
+ start_pos=start_pos,
+ ),
+ )
+ return result
|
@@ -5506,107 +5526,107 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def collect_latest_rates_for_accounts_with_retries(
- accounts: Sequence[AccountSpec],
- timeframes: Sequence[int | str],
- count: int,
- *,
- start_pos: int = 0,
- base_config: Mt5Config | None = None,
- retry_count: int = 0,
- backoff_base: float = 2.0,
-) -> dict[tuple[str, int], pd.DataFrame]:
- """Collect latest rates across accounts, retrying transient MT5 failures.
-
- Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential
- backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are
- retried; other exceptions propagate immediately. The final failure is
- re-raised once retries are exhausted.
-
- Args:
- accounts: Account groups to read. Each must define at least one symbol.
- timeframes: MT5 timeframes as integers or names (for example ``M1``).
- count: Number of most recent bars to read per symbol/timeframe.
- start_pos: Initial bar position offset.
- base_config: Optional base configuration whose fields fill any value not
- set on an individual account.
- retry_count: Maximum number of retries after the first attempt. ``0``
- disables retries.
- backoff_base: Base for exponential backoff. The delay before retry
- attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds.
-
- Returns:
- Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError``
- for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and
- re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError``
- once retries are exhausted.
- """
-
- def _collect() -> dict[tuple[str, int], pd.DataFrame]:
- return collect_latest_rates_for_accounts(
- accounts,
- timeframes,
- count,
- start_pos=start_pos,
- base_config=base_config,
- )
-
- return retry_with_backoff(
- _collect,
- retry_count=retry_count,
- backoff_base=backoff_base,
- operation="Rate collection",
- )
+ | def collect_latest_rates_for_accounts_with_retries(
+ accounts: Sequence[AccountSpec],
+ timeframes: Sequence[int | str],
+ count: int,
+ *,
+ start_pos: int = 0,
+ base_config: Mt5Config | None = None,
+ retry_count: int = 0,
+ backoff_base: float = 2.0,
+) -> dict[tuple[str, int], pd.DataFrame]:
+ """Collect latest rates across accounts, retrying transient MT5 failures.
+
+ Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential
+ backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are
+ retried; other exceptions propagate immediately. The final failure is
+ re-raised once retries are exhausted.
+
+ Args:
+ accounts: Account groups to read. Each must define at least one symbol.
+ timeframes: MT5 timeframes as integers or names (for example ``M1``).
+ count: Number of most recent bars to read per symbol/timeframe.
+ start_pos: Initial bar position offset.
+ base_config: Optional base configuration whose fields fill any value not
+ set on an individual account.
+ retry_count: Maximum number of retries after the first attempt. ``0``
+ disables retries.
+ backoff_base: Base for exponential backoff. The delay before retry
+ attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds.
+
+ Returns:
+ Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError``
+ for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and
+ re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError``
+ once retries are exhausted.
+ """
+
+ def _collect() -> dict[tuple[str, int], pd.DataFrame]:
+ return collect_latest_rates_for_accounts(
+ accounts,
+ timeframes,
+ count,
+ start_pos=start_pos,
+ base_config=base_config,
+ )
+
+ return retry_with_backoff(
+ _collect,
+ retry_count=retry_count,
+ backoff_base=backoff_base,
+ operation="Rate collection",
+ )
|
@@ -5687,37 +5707,37 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 348
-349
-350
-351
-352
-353
-354
-355
-356
+ | @contextmanager
-def connected_client(config: Mt5Config) -> Iterator[Mt5DataClient]:
- """Initialize MT5, yield a connected client, and always shut down.
-
- Args:
- config: MT5 connection configuration.
-
- Yields:
- Connected ``Mt5DataClient`` instance.
- """
- client = Mt5DataClient(config=config)
- try:
- client.initialize_and_login_mt5()
- yield client
- finally:
- client.shutdown()
+363
+364
+365
+366
+367
+368
+369
+370
+371
| @contextmanager
+def connected_client(config: Mt5Config) -> Iterator[Mt5DataClient]:
+ """Initialize MT5, yield a connected client, and always shut down.
+
+ Args:
+ config: MT5 connection configuration.
+
+ Yields:
+ Connected ``Mt5DataClient`` instance.
+ """
+ client = Mt5DataClient(config=config)
+ try:
+ client.initialize_and_login_mt5()
+ yield client
+ finally:
+ client.shutdown()
|
@@ -5749,35 +5769,35 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1282
-1283
-1284
-1285
-1286
-1287
-1288
-1289
-1290
+ | def copy_rates_from(
- symbol: str,
- timeframe: int | str,
- date_from: datetime | str,
- count: int,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return rates starting from a date."""
- return _make_client(config=config).copy_rates_from(
- symbol,
- timeframe,
- date_from,
- count,
- )
+1296
+1297
+1298
+1299
+1300
+1301
+1302
+1303
+1304
| def copy_rates_from(
+ symbol: str,
+ timeframe: int | str,
+ date_from: datetime | str,
+ count: int,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return rates starting from a date."""
+ return _make_client(config=config).copy_rates_from(
+ symbol,
+ timeframe,
+ date_from,
+ count,
+ )
|
@@ -5809,35 +5829,35 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1299
-1300
-1301
-1302
-1303
-1304
-1305
-1306
-1307
+ | def copy_rates_from_pos(
- symbol: str,
- timeframe: int | str,
- start_pos: int,
- count: int,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return rates starting from a bar position."""
- return _make_client(config=config).copy_rates_from_pos(
- symbol,
- timeframe,
- start_pos,
- count,
- )
+1313
+1314
+1315
+1316
+1317
+1318
+1319
+1320
+1321
| def copy_rates_from_pos(
+ symbol: str,
+ timeframe: int | str,
+ start_pos: int,
+ count: int,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return rates starting from a bar position."""
+ return _make_client(config=config).copy_rates_from_pos(
+ symbol,
+ timeframe,
+ start_pos,
+ count,
+ )
|
@@ -5869,35 +5889,35 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def copy_rates_range(
- symbol: str,
- timeframe: int | str,
- date_from: datetime | str,
- date_to: datetime | str,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return rates for a date range."""
- return _make_client(config=config).copy_rates_range(
- symbol,
- timeframe,
- date_from,
- date_to,
- )
+ | def copy_rates_range(
+ symbol: str,
+ timeframe: int | str,
+ date_from: datetime | str,
+ date_to: datetime | str,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return rates for a date range."""
+ return _make_client(config=config).copy_rates_range(
+ symbol,
+ timeframe,
+ date_from,
+ date_to,
+ )
|
@@ -5929,35 +5949,35 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def copy_ticks_from(
- symbol: str,
- date_from: datetime | str,
- count: int,
- flags: int | str,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return ticks starting from a date."""
- return _make_client(config=config).copy_ticks_from(
- symbol,
- date_from,
- count,
- flags,
- )
+ | def copy_ticks_from(
+ symbol: str,
+ date_from: datetime | str,
+ count: int,
+ flags: int | str,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return ticks starting from a date."""
+ return _make_client(config=config).copy_ticks_from(
+ symbol,
+ date_from,
+ count,
+ flags,
+ )
|
@@ -5989,35 +6009,35 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def copy_ticks_range(
- symbol: str,
- date_from: datetime | str,
- date_to: datetime | str,
- flags: int | str,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return ticks for a date range."""
- return _make_client(config=config).copy_ticks_range(
- symbol,
- date_from,
- date_to,
- flags,
- )
+ | def copy_ticks_range(
+ symbol: str,
+ date_from: datetime | str,
+ date_to: datetime | str,
+ flags: int | str,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return ticks for a date range."""
+ return _make_client(config=config).copy_ticks_range(
+ symbol,
+ date_from,
+ date_to,
+ flags,
+ )
|
@@ -6094,15 +6114,7 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1333
-1334
-1335
-1336
-1337
-1338
-1339
-1340
-1341
+ | def fetch_latest_closed_rates(
- client: Mt5CliClient,
- *,
- symbol: str,
- granularity: str,
- count: int,
-) -> pd.DataFrame:
- """Fetch up to ``count`` most recent closed bars, oldest to newest.
-
- Returns:
- Closed rate bars ordered oldest to newest.
-
- Raises:
- ValueError: If ``count`` is not positive or no closed bars are returned.
- """
- _require_positive(count, "count")
- frame = client.latest_rates(symbol, granularity, count + 1, start_pos=0)
- closed = drop_forming_rate_bar(frame)
- if closed.empty:
- msg = (
- f"Rate data is empty for {symbol!r} at granularity {granularity!r} "
- f"with count {count}."
- )
- raise ValueError(msg)
- return closed.tail(count).reset_index(drop=True)
+1357
+1358
+1359
+1360
+1361
+1362
+1363
+1364
+1365
| def fetch_latest_closed_rates(
+ client: Mt5CliClient,
+ *,
+ symbol: str,
+ granularity: str,
+ count: int,
+) -> pd.DataFrame:
+ """Fetch up to ``count`` most recent closed bars, oldest to newest.
+
+ Returns:
+ Closed rate bars ordered oldest to newest.
+
+ Raises:
+ ValueError: If ``count`` is not positive or no closed bars are returned.
+ """
+ _require_positive(count, "count")
+ frame = client.latest_rates(symbol, granularity, count + 1, start_pos=0)
+ closed = drop_forming_rate_bar(frame)
+ if closed.empty:
+ msg = (
+ f"Rate data is empty for {symbol!r} at granularity {granularity!r} "
+ f"with count {count}."
+ )
+ raise ValueError(msg)
+ return closed.tail(count).reset_index(drop=True)
|
@@ -6176,43 +6196,43 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def history_deals(
- date_from: datetime | str | None = None,
- date_to: datetime | str | None = None,
- group: str | None = None,
- symbol: str | None = None,
- ticket: int | None = None,
- position: int | None = None,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return historical deals."""
- return _make_client(config=config).history_deals(
- date_from=date_from,
- date_to=date_to,
- group=group,
- symbol=symbol,
- ticket=ticket,
- position=position,
- )
+ | def history_deals(
+ date_from: datetime | str | None = None,
+ date_to: datetime | str | None = None,
+ group: str | None = None,
+ symbol: str | None = None,
+ ticket: int | None = None,
+ position: int | None = None,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return historical deals."""
+ return _make_client(config=config).history_deals(
+ date_from=date_from,
+ date_to=date_to,
+ group=group,
+ symbol=symbol,
+ ticket=ticket,
+ position=position,
+ )
|
@@ -6246,43 +6266,43 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def history_orders(
- date_from: datetime | str | None = None,
- date_to: datetime | str | None = None,
- group: str | None = None,
- symbol: str | None = None,
- ticket: int | None = None,
- position: int | None = None,
- *,
- config: Mt5Config | None = None,
-) -> pd.DataFrame:
- """Return historical orders."""
- return _make_client(config=config).history_orders(
- date_from=date_from,
- date_to=date_to,
- group=group,
- symbol=symbol,
- ticket=ticket,
- position=position,
- )
+ | def history_orders(
+ date_from: datetime | str | None = None,
+ date_to: datetime | str | None = None,
+ group: str | None = None,
+ symbol: str | None = None,
+ ticket: int | None = None,
+ position: int | None = None,
+ *,
+ config: Mt5Config | None = None,
+) -> pd.DataFrame:
+ """Return historical orders."""
+ return _make_client(config=config).history_orders(
+ date_from=date_from,
+ date_to=date_to,
+ group=group,
+ symbol=symbol,
+ ticket=ticket,
+ position=position,
+ )
|
@@ -6307,11 +6327,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- | def last_error(*, config: Mt5Config | None = None) -> pd.DataFrame:
- """Return the last error information."""
- return _make_client(config=config).last_error()
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|