| def quote_sqlite_identifier(identifier: str) -> str:
- """Return a safely quoted SQLite identifier using double quotes."""
- return '"' + identifier.replace('"', '""') + '"'
+ | def quote_sqlite_identifier(identifier: str) -> str:
+ """Return a safely quoted SQLite identifier using double quotes."""
+ return '"' + identifier.replace('"', '""') + '"'
|
@@ -3591,17 +3591,19 @@ fails.
Source code in mt5cli/history.py
- 101
+ | def resolve_granularity_name(timeframe: int) -> str:
- """Return a granularity name for a timeframe integer when known."""
- for name, value in TIMEFRAME_MAP.items():
- if value == timeframe:
- return name
- return str(timeframe)
+106
| def resolve_granularity_name(timeframe: int) -> str:
+ """Return a granularity name for a timeframe integer when known."""
+ try:
+ name = _get_timeframe_name(timeframe)
+ except ValueError:
+ return str(timeframe)
+ return name.removeprefix("TIMEFRAME_")
|
@@ -3661,8 +3663,7 @@ fails.
Source code in mt5cli/history.py
- 59
-60
+ | def resolve_history_datasets(datasets: set[Dataset] | None) -> set[Dataset]:
- """Resolve configured history datasets.
-
- Returns:
- All supported datasets when ``datasets`` is None, otherwise the
- configured selection (which may be empty).
- """
- if datasets is None:
- return set(Dataset)
- return set(datasets)
+68
+69
| def resolve_history_datasets(datasets: set[Dataset] | None) -> set[Dataset]:
+ """Resolve configured history datasets.
+
+ Returns:
+ All supported datasets when ``datasets`` is None, otherwise the
+ configured selection (which may be empty).
+ """
+ if datasets is None:
+ return set(Dataset)
+ return set(datasets)
|
@@ -3727,23 +3729,19 @@ fails.
Source code in mt5cli/history.py
- 90
-91
+ | def resolve_history_tick_flags(flags: int | str) -> int:
- """Resolve tick copy flags from an integer or name.
-
- Returns:
- Integer tick flag value.
- """
- if isinstance(flags, int):
- return flags
- return parse_tick_flags(flags)
+97
| def resolve_history_tick_flags(flags: int | str) -> int:
+ """Resolve tick copy flags from an integer or name.
+
+ Returns:
+ Integer tick flag value.
+ """
+ return parse_tick_flags(flags)
|
@@ -3793,8 +3791,7 @@ fails.
Source code in mt5cli/history.py
- 71
-72
+ | def resolve_history_timeframes(
- timeframes: Sequence[int | str] | None,
-) -> list[int]:
- """Resolve rate timeframes, deduplicating aliases for the same integer.
-
- Returns:
- Ordered list of unique timeframe integers.
- """
- raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES
- seen: set[int] = set()
- resolved: list[int] = []
- for value in raw:
- tf = value if isinstance(value, int) else parse_timeframe(str(value))
- if tf not in seen:
- seen.add(tf)
- resolved.append(tf)
- return resolved
+87
+88
| def resolve_history_timeframes(
+ timeframes: Sequence[int | str] | None,
+) -> list[int]:
+ """Resolve rate timeframes, deduplicating aliases for the same integer.
+
+ Returns:
+ Ordered list of unique timeframe integers.
+ """
+ raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES
+ seen: set[int] = set()
+ resolved: list[int] = []
+ for value in raw:
+ tf = parse_timeframe(value)
+ if tf not in seen:
+ seen.add(tf)
+ resolved.append(tf)
+ return resolved
|
diff --git a/api/sdk/index.html b/api/sdk/index.html
index d9e1859..eafd8e1 100644
--- a/api/sdk/index.html
+++ b/api/sdk/index.html
@@ -747,7 +747,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 380
+ | def __init__(
- self,
- *,
- path: str | None = None,
- login: int | None = None,
- password: str | None = None,
- server: str | None = None,
- timeout: int | None = None,
- config: Mt5Config | None = None,
- client: Mt5DataClient | None = None,
-) -> None:
- """Initialize the SDK client.
-
- Args:
- path: Path to MetaTrader5 terminal EXE file.
- login: Trading account login.
- password: Trading account password.
- server: Trading server name.
- timeout: Connection timeout in milliseconds.
- config: Optional pre-built ``Mt5Config`` (overrides other args).
- client: Optional already-connected ``Mt5DataClient``. Injected
- clients are reused as-is and are not initialized or shut down.
- """
- self._config = config or build_config(
- path=path,
- login=login,
- password=password,
- server=server,
- timeout=timeout,
- )
- self._client = client
- self._owns_client = client is None
+407
| def __init__(
+ self,
+ *,
+ path: str | None = None,
+ login: int | None = None,
+ password: str | None = None,
+ server: str | None = None,
+ timeout: int | None = None,
+ config: Mt5Config | None = None,
+ client: Mt5DataClient | None = None,
+) -> None:
+ """Initialize the SDK client.
+
+ Args:
+ path: Path to MetaTrader5 terminal EXE file.
+ login: Trading account login.
+ password: Trading account password.
+ server: Trading server name.
+ timeout: Connection timeout in milliseconds.
+ config: Optional pre-built ``Mt5Config`` (overrides other args).
+ client: Optional already-connected ``Mt5DataClient``. Injected
+ clients are reused as-is and are not initialized or shut down.
+ """
+ self._config = config or build_config(
+ path=path,
+ login=login,
+ password=password,
+ server=server,
+ timeout=timeout,
+ )
+ self._client = client
+ self._owns_client = client is None
|
@@ -891,7 +891,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 430
+ | def __enter__(self) -> Self:
- """Open a persistent MT5 connection for multiple calls.
-
- Returns:
- This client instance.
- """
- if self._client is not None:
- return self
- client = Mt5DataClient(config=self._config)
- try:
- client.initialize_and_login_mt5()
- except Exception:
- client.shutdown()
- raise
- self._client = client
- self._owns_client = True # only set when this method created the client
- return self
+442
| def __enter__(self) -> Self:
+ """Open a persistent MT5 connection for multiple calls.
+
+ Returns:
+ This client instance.
+ """
+ if self._client is not None:
+ return self
+ client = Mt5DataClient(config=self._config)
+ try:
+ client.initialize_and_login_mt5()
+ except Exception:
+ client.shutdown()
+ raise
+ self._client = client
+ self._owns_client = True # only set when this method created the client
+ return self
|
@@ -952,25 +952,25 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 448
+ | 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
+453
| 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
|
@@ -995,11 +995,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())
|
@@ -1076,7 +1076,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 515
+ | 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
- },
- )
+546
| 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
+ },
+ )
|
@@ -1176,7 +1176,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 467
+ | 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,
- ),
- )
+480
| 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,
+ ),
+ )
|
@@ -1240,7 +1240,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 486
+ | 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,
- ),
- )
+498
| 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,
+ ),
+ )
|
@@ -1302,7 +1302,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 552
+ | 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,
- ),
- )
+566
| 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,
+ ),
+ )
|
@@ -1368,7 +1368,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 572
+ | 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,
- ),
- )
+585
| 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,
+ ),
+ )
|
@@ -1432,7 +1432,11 @@ clients are reused as-is and are not initialized or shut down.
Source code in mt5cli/sdk.py
- 591
+ | 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,
- ),
- )
+605
| 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,
+ ),
+ )
|
@@ -1522,27 +1522,27 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 413
+ | @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)
+419
| @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)
|
@@ -1574,7 +1574,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 680
+ | 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,
- ),
- )
+697
| 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,
+ ),
+ )
|
@@ -1648,7 +1648,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 657
+ | 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,
- ),
- )
+674
| 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,
+ ),
+ )
|
@@ -1715,11 +1715,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())
|
@@ -1749,25 +1749,25 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 504
+ | 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)
+509
| 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)
|
@@ -1792,11 +1792,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))
|
@@ -1885,27 +1885,27 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 776
+ | 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))
+782
| 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))
|
@@ -1930,7 +1930,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 788
+ | 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)
+803
| 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)
|
@@ -1993,27 +1993,27 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 809
+ | 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()
- },
- ],
- )
+815
| 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()
+ },
+ ],
+ )
|
@@ -2042,7 +2042,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 627
+ | 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,
- ),
- )
+636
| 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,
+ ),
+ )
|
@@ -2097,7 +2097,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 642
+ | 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,
- ),
- )
+651
| 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,
+ ),
+ )
|
@@ -2153,7 +2153,11 @@ injected client, including when used as a context manager.
Source code in mt5cli/sdk.py
- 703
+ | 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,
- )
+715
| 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,
+ )
|
@@ -2349,7 +2349,11 @@ fetching the entire range.
Source code in mt5cli/sdk.py
- 737
+ | 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,
- ),
- )
+770
| 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,
+ ),
+ )
|
@@ -2448,11 +2448,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))
|
@@ -2477,11 +2477,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))
|
@@ -2506,11 +2506,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))
|
@@ -2535,11 +2535,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())
|
@@ -2564,11 +2564,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())
|
@@ -2796,7 +2796,11 @@ propagate so callers control logging.
Source code in mt5cli/sdk.py
- 1046
+ | def __init__(
- self,
- *,
- output: Path | str,
- datasets: set[Dataset] | None = None,
- timeframes: Sequence[int | str] | None = None,
- flags: int | str = "ALL",
- lookback_hours: float = 24.0,
- with_views: bool = False,
- include_account_events: bool = True,
- interval_seconds: float = 0.0,
- suppress_errors: bool = False,
-) -> None:
- """Initialize the throttled updater.
-
- Args:
- output: SQLite database path.
- datasets: Datasets to include (defaults to all).
- timeframes: Rate timeframes to update (defaults to all fixed MT5
- timeframes).
- flags: Tick copy flags as integer or name (e.g. ``ALL``).
- lookback_hours: First-run lookback when a table has no prior rows.
- with_views: Create ``cash_events`` and ``positions_reconstructed``
- views.
- include_account_events: Include account-level cash events.
- interval_seconds: Minimum seconds between successful updates. Values
- ``<= 0`` update on every call.
- suppress_errors: When True, 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.
- """
- self.output = output
- self.datasets = datasets
- self.timeframes = timeframes
- self.flags = flags
- self.lookback_hours = lookback_hours
- self.with_views = with_views
- self.include_account_events = include_account_events
- self.interval_seconds = interval_seconds
- self.suppress_errors = suppress_errors
- self._last_update_monotonic: float | None = None
+1087
| def __init__(
+ self,
+ *,
+ output: Path | str,
+ datasets: set[Dataset] | None = None,
+ timeframes: Sequence[int | str] | None = None,
+ flags: int | str = "ALL",
+ lookback_hours: float = 24.0,
+ with_views: bool = False,
+ include_account_events: bool = True,
+ interval_seconds: float = 0.0,
+ suppress_errors: bool = False,
+) -> None:
+ """Initialize the throttled updater.
+
+ Args:
+ output: SQLite database path.
+ datasets: Datasets to include (defaults to all).
+ timeframes: Rate timeframes to update (defaults to all fixed MT5
+ timeframes).
+ flags: Tick copy flags as integer or name (e.g. ``ALL``).
+ lookback_hours: First-run lookback when a table has no prior rows.
+ with_views: Create ``cash_events`` and ``positions_reconstructed``
+ views.
+ include_account_events: Include account-level cash events.
+ interval_seconds: Minimum seconds between successful updates. Values
+ ``<= 0`` update on every call.
+ suppress_errors: When True, 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.
+ """
+ self.output = output
+ self.datasets = datasets
+ self.timeframes = timeframes
+ self.flags = flags
+ self.lookback_hours = lookback_hours
+ self.with_views = with_views
+ self.include_account_events = include_account_events
+ self.interval_seconds = interval_seconds
+ self.suppress_errors = suppress_errors
+ self._last_update_monotonic: float | None = None
|
@@ -3186,27 +3186,27 @@ propagate so callers control logging.
Source code in mt5cli/sdk.py
- 1098
+ | 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
+1104
| 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
|
@@ -3368,7 +3368,11 @@ is False, or any other type error.
Source code in mt5cli/sdk.py
- 1110
+ | def update(self, client: Mt5DataClient, symbols: Sequence[str]) -> bool:
- """Run a throttled incremental history update.
+1159
| 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.
- 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,
- )
- update_history(
- client=client,
- output=self.output,
- symbols=symbols,
- datasets=self.datasets,
- timeframes=self.timeframes,
- flags=self.flags,
- lookback_hours=self.lookback_hours,
- with_views=self.with_views,
- include_account_events=self.include_account_events,
- )
- except _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
+ 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,
+ )
+ update_history(
+ client=client,
+ output=self.output,
+ symbols=symbols,
+ datasets=self.datasets,
+ timeframes=self.timeframes,
+ flags=self.flags,
+ lookback_hours=self.lookback_hours,
+ with_views=self.with_views,
+ include_account_events=self.include_account_events,
+ )
+ except _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
|
@@ -3510,11 +3510,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()
|
@@ -3569,7 +3569,11 @@ is False, or any other type error.
Source code in mt5cli/sdk.py
- 300
+ | def build_config(
- *,
- path: str | None = None,
- login: int | None = None,
- password: str | None = None,
- server: str | None = None,
- timeout: int | None = None,
-) -> Mt5Config:
- """Build an ``Mt5Config`` from optional connection parameters.
-
- Returns:
- Configured ``Mt5Config`` instance.
- """
- return Mt5Config(
- path=path,
- login=login,
- password=password,
- server=server,
- timeout=timeout,
- )
+315
| def build_config(
+ *,
+ path: str | None = None,
+ login: int | None = None,
+ password: str | None = None,
+ server: str | None = None,
+ timeout: int | None = None,
+) -> Mt5Config:
+ """Build an ``Mt5Config`` from optional connection parameters.
+
+ Returns:
+ Configured ``Mt5Config`` instance.
+ """
+ return Mt5Config(
+ path=path,
+ login=login,
+ password=password,
+ server=server,
+ timeout=timeout,
+ )
|
@@ -3630,7 +3630,7 @@ is False, or any other type error.
*,
datasets: set[Dataset] | None = None,
timeframe: int | str = 1,
- flags: int | str = 1,
+ flags: int | str = "ALL",
if_exists: IfExists =
@@ -3831,7 +3831,11 @@ is False, or any other type error.
Source code in mt5cli/sdk.py
- 1166
+ | def collect_history(
- output: Path,
- symbols: list[str],
- date_from: datetime | str,
- date_to: datetime | str,
- *,
- datasets: set[Dataset] | None = None,
- timeframe: int | str = 1,
- flags: int | str = 1,
- if_exists: IfExists = IfExists.FAIL,
- with_views: bool = False,
- config: Mt5Config | None = None,
-) -> None:
- """Collect historical datasets into a single SQLite database.
-
- Args:
- output: SQLite database path.
- symbols: Symbols to collect.
- date_from: Start date.
- date_to: End date.
- datasets: Datasets to include (defaults to all).
- timeframe: Rates timeframe as integer or name (e.g. ``M1``).
- flags: Tick copy flags as integer or name (e.g. ``ALL``).
- if_exists: Behavior when a target table already exists.
- with_views: Create ``cash_events`` and ``positions_reconstructed`` views.
- config: MT5 connection configuration.
- """
- start = _require_datetime(date_from)
- end = _require_datetime(date_to)
- selected = datasets if datasets is not None else set(Dataset)
- tf = _coerce_timeframe(timeframe)
- tick_flags = _coerce_tick_flags(flags)
- mt5_config = config or build_config()
- with _connected_client(mt5_config) as client, sqlite3.connect(output) as conn:
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA synchronous=NORMAL")
- written_tables, written_columns = write_collected_datasets(
- conn,
- client,
- symbols,
- selected,
- tf,
- tick_flags,
- start,
- end,
- if_exists,
- )
- create_history_indexes(conn, written_columns)
- if with_views and Dataset.history_deals in written_tables:
- create_cash_events_view(conn, written_columns[Dataset.history_deals])
- create_positions_reconstructed_view(
- conn,
- written_columns[Dataset.history_deals],
+1225
| 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",
)
- 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,
- )
+ logger.info(
+ "Collected %s for %d symbol(s) into %s",
+ ", ".join(sorted(ds.value for ds in selected)),
+ len(symbols),
+ output,
+ )
|
@@ -4166,7 +4166,11 @@ disables retries.
Source code in mt5cli/sdk.py
- 1685
+ | 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.
+1724
| 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.
- 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()
- }
+ 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()
+ }
|
@@ -4480,7 +4480,11 @@ dropping the still-forming bar when start_pos is 0).
Source code in mt5cli/sdk.py
- 1622
+ | 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
+1678
| 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
|
@@ -4632,7 +4632,11 @@ dropping the still-forming bar when start_pos is 0).
Source code in mt5cli/sdk.py
- 1287
+ | 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,
- )
+1297
| 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,
+ )
|
@@ -4857,7 +4857,11 @@ empty, or count is not positive.
Source code in mt5cli/sdk.py
- 1505
+ | 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.
+1553
| 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.
- 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
+ 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
|
@@ -5192,7 +5192,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1560
+ | def collect_latest_rates_for_accounts_with_retries(
- accounts: Sequence[AccountSpec],
- timeframes: Sequence[int | str],
- count: int,
- *,
- start_pos: int = 0,
- base_config: Mt5Config | None = None,
- retry_count: int = 0,
- backoff_base: float = 2.0,
-) -> dict[tuple[str, int], pd.DataFrame]:
- """Collect latest rates across accounts, retrying transient MT5 failures.
-
- Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential
- backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are
- retried; other exceptions propagate immediately. The final failure is
- re-raised once retries are exhausted.
-
- Args:
- accounts: Account groups to read. Each must define at least one symbol.
- timeframes: MT5 timeframes as integers or names (for example ``M1``).
- count: Number of most recent bars to read per symbol/timeframe.
- start_pos: Initial bar position offset.
- base_config: Optional base configuration whose fields fill any value not
- set on an individual account.
- retry_count: Maximum number of retries after the first attempt. ``0``
- disables retries.
- backoff_base: Base for exponential backoff. The delay before retry
- attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds.
-
- Returns:
- Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError``
- for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and
- re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError``
- once retries are exhausted.
- """
- attempts = max(retry_count, 0) + 1
-
- def _collect() -> dict[tuple[str, int], pd.DataFrame]:
- return collect_latest_rates_for_accounts(
- accounts,
- timeframes,
- count,
- start_pos=start_pos,
- base_config=base_config,
- )
-
- for attempt in range(attempts - 1):
- try:
- return _collect()
- except (Mt5TradingError, Mt5RuntimeError) as exc:
- delay = backoff_base ** (attempt + 1)
- logger.warning(
- "Rate collection failed (attempt %d/%d): %s; retrying in %.1fs",
- attempt + 1,
- attempts,
- exc,
- delay,
- )
- time.sleep(delay)
- return _collect()
+1615
| def collect_latest_rates_for_accounts_with_retries(
+ accounts: Sequence[AccountSpec],
+ timeframes: Sequence[int | str],
+ count: int,
+ *,
+ start_pos: int = 0,
+ base_config: Mt5Config | None = None,
+ retry_count: int = 0,
+ backoff_base: float = 2.0,
+) -> dict[tuple[str, int], pd.DataFrame]:
+ """Collect latest rates across accounts, retrying transient MT5 failures.
+
+ Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential
+ backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are
+ retried; other exceptions propagate immediately. The final failure is
+ re-raised once retries are exhausted.
+
+ Args:
+ accounts: Account groups to read. Each must define at least one symbol.
+ timeframes: MT5 timeframes as integers or names (for example ``M1``).
+ count: Number of most recent bars to read per symbol/timeframe.
+ start_pos: Initial bar position offset.
+ base_config: Optional base configuration whose fields fill any value not
+ set on an individual account.
+ retry_count: Maximum number of retries after the first attempt. ``0``
+ disables retries.
+ backoff_base: Base for exponential backoff. The delay before retry
+ attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds.
+
+ Returns:
+ Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError``
+ for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and
+ re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError``
+ once retries are exhausted.
+ """
+ attempts = max(retry_count, 0) + 1
+
+ def _collect() -> dict[tuple[str, int], pd.DataFrame]:
+ return collect_latest_rates_for_accounts(
+ accounts,
+ timeframes,
+ count,
+ start_pos=start_pos,
+ base_config=base_config,
+ )
+
+ for attempt in range(attempts - 1):
+ try:
+ return _collect()
+ except (Mt5TradingError, Mt5RuntimeError) as exc:
+ delay = backoff_base ** (attempt + 1)
+ logger.warning(
+ "Rate collection failed (attempt %d/%d): %s; retrying in %.1fs",
+ attempt + 1,
+ attempts,
+ exc,
+ delay,
+ )
+ time.sleep(delay)
+ return _collect()
|
@@ -5342,7 +5342,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1236
+ | 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,
- )
+1246
| 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,
+ )
|
@@ -5402,7 +5402,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1253
+ | 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,
- )
+1263
| 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,
+ )
|
@@ -5462,7 +5462,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1731
+ | 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,
- )
+1741
| 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,
+ )
|
@@ -5522,7 +5522,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1748
+ | 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,
- )
+1758
| 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,
+ )
|
@@ -5582,7 +5582,11 @@ attempt n (1-indexed) is backoff_base ** n seconds.
Source code in mt5cli/sdk.py
- 1765
+ | 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,
- )
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|