Market Data Module

mt5cli.marketdata

Market-data facade and multi-account rate collection helpers.

These are stateless convenience wrappers around :class:~mt5cli.client.MT5Client for one-off reads. Downstream applications that need a persistent connection across multiple calls should use :func:mt5cli.mt5_session instead.

__all__ module-attribute

__all__ = [
    "AccountSpec",
    "account_info",
    "collect_latest_closed_rates_by_granularity",
    "collect_latest_closed_rates_for_accounts",
    "collect_latest_rates",
    "collect_latest_rates_for_accounts",
    "collect_latest_rates_for_accounts_with_retries",
    "copy_rates_from",
    "copy_rates_from_pos",
    "copy_rates_range",
    "copy_ticks_from",
    "copy_ticks_range",
    "fetch_latest_closed_rates",
    "history_deals",
    "history_orders",
    "last_error",
    "latest_rates",
    "market_book",
    "minimum_margins",
    "mt5_summary",
    "mt5_summary_as_df",
    "orders",
    "positions",
    "recent_history_deals",
    "recent_ticks",
    "resolve_account_spec",
    "resolve_account_specs",
    "symbol_info",
    "symbol_info_tick",
    "symbols",
    "terminal_info",
    "version",
]

AccountSpec dataclass

AccountSpec(
    symbols: Sequence[str],
    login: int | str | None = None,
    password: str | None = None,
    server: str | None = None,
    path: str | None = None,
    timeout: int | None = None,
)

Connection parameters and symbols for one MT5 account group.

Attributes:

Name Type Description
symbols Sequence[str]

Symbols to load latest rates for under this account.

login int | str | None

Trading account login. String values are coerced to int when non-empty.

password str | None

Trading account password.

server str | None

Trading server name.

path str | None

Path to the MetaTrader5 terminal EXE file.

timeout int | None

Connection timeout in milliseconds.

login class-attribute instance-attribute

login: int | str | None = field(default=None, repr=False)

password class-attribute instance-attribute

password: str | None = field(default=None, repr=False)

path class-attribute instance-attribute

path: str | None = None

server class-attribute instance-attribute

server: str | None = None

symbols instance-attribute

symbols: Sequence[str]

timeout class-attribute instance-attribute

timeout: int | None = None

account_info

account_info(
    *, config: Mt5Config | None = None
) -> DataFrame

Return account information.

Source code in mt5cli/marketdata.py
def account_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    """Return account information."""
    return _make_client(config=config).account_info()

collect_latest_closed_rates_by_granularity

collect_latest_closed_rates_by_granularity(
    accounts: Sequence[AccountSpec],
    granularities: Sequence[int | str],
    count: int,
    *,
    start_pos: int = 0,
    base_config: Mt5Config | None = None,
    retry_count: int = 0,
    backoff_base: float = 2.0,
) -> dict[tuple[str, str], DataFrame]

Collect latest closed rate bars keyed by symbol and granularity name.

Thin wrapper around :func:collect_latest_closed_rates_for_accounts that rekeys the result by granularity name (for example M1) instead of the integer timeframe.

Parameters:

Name Type Description Default
accounts Sequence[AccountSpec]

Account groups to read. Each must define at least one symbol.

required
granularities Sequence[int | str]

MT5 timeframes as integers or names (for example M1).

required
count int

Number of closed bars to return per symbol/timeframe.

required
start_pos int

Initial bar position offset passed to the underlying collector.

0
base_config Mt5Config | None

Optional base configuration whose fields fill any value not set on an individual account.

None
retry_count int

Maximum number of retries after the first attempt. 0 disables retries.

0
backoff_base float

Base for exponential backoff between retry attempts.

2.0

Returns:

Type Description
dict[tuple[str, str], DataFrame]

Mapping keyed by (symbol, granularity_name). Propagates

dict[tuple[str, str], DataFrame]

ValueError from :func:collect_latest_closed_rates_for_accounts.

Source code in mt5cli/marketdata.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()
    }

collect_latest_closed_rates_for_accounts

collect_latest_closed_rates_for_accounts(
    accounts: Sequence[AccountSpec],
    timeframes: Sequence[int | str],
    count: int,
    *,
    start_pos: int = 0,
    base_config: Mt5Config | None = None,
    retry_count: int = 0,
    backoff_base: float = 2.0,
) -> dict[tuple[str, int], DataFrame]

Collect latest closed rate bars across multiple MT5 account groups.

When start_pos is 0 (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches count + 1 bars, drops that bar with :func:drop_forming_rate_bar, and validates that each resulting frame is non-empty. When start_pos is greater than zero the forming bar is not in range, so only count bars are fetched and no row is dropped.

Wraps :func:collect_latest_rates_for_accounts_with_retries for transient MT5 error handling.

Parameters:

Name Type Description Default
accounts Sequence[AccountSpec]

Account groups to read. Each must define at least one symbol.

required
timeframes Sequence[int | str]

MT5 timeframes as integers or names (for example M1).

required
count int

Number of closed bars to return per symbol/timeframe.

required
start_pos int

Initial bar position offset passed to the underlying collector.

0
base_config Mt5Config | None

Optional base configuration whose fields fill any value not set on an individual account.

None
retry_count int

Maximum number of retries after the first attempt. 0 disables retries.

0
backoff_base float

Base for exponential backoff between retry attempts.

2.0

Returns:

Type Description
dict[tuple[str, int], DataFrame]

Mapping keyed by (symbol, timeframe_int).

Raises:

Type Description
ValueError

If inputs are invalid, or any series is empty (after dropping the still-forming bar when start_pos is 0).

Source code in mt5cli/marketdata.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

collect_latest_rates

collect_latest_rates(
    symbols: Sequence[str],
    timeframes: Sequence[int | str],
    *,
    count: int,
    start_pos: int = 0,
    config: Mt5Config | None = None,
) -> dict[tuple[str, int], DataFrame]

Return latest rates for each symbol/timeframe pair.

Source code in mt5cli/marketdata.py
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,
    )

collect_latest_rates_for_accounts

collect_latest_rates_for_accounts(
    accounts: Sequence[AccountSpec],
    timeframes: Sequence[int | str],
    count: int,
    *,
    start_pos: int = 0,
    base_config: Mt5Config | None = None,
) -> dict[tuple[str, int], DataFrame]

Collect latest rates across multiple MT5 account groups.

Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping.

Parameters:

Name Type Description Default
accounts Sequence[AccountSpec]

Account groups to read. Each must define at least one symbol.

required
timeframes Sequence[int | str]

MT5 timeframes as integers or names (for example M1).

required
count int

Number of most recent bars to read per symbol/timeframe.

required
start_pos int

Initial bar position offset.

0
base_config Mt5Config | None

Optional base configuration whose fields fill any value not set on an individual account.

None

Returns:

Type Description
dict[tuple[str, int], DataFrame]

Mapping keyed by (symbol, timeframe_int). When accounts share a

dict[tuple[str, int], DataFrame]

symbol/timeframe pair, the last account processed wins.

Raises:

Type Description
ValueError

If accounts, timeframes, or any account's symbols are empty, or count is not positive.

Source code in mt5cli/marketdata.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 MT5Client(config=config) as client:
            result.update(
                client.collect_latest_rates(
                    account.symbols,
                    timeframes,
                    count=count,
                    start_pos=start_pos,
                ),
            )
    return result

collect_latest_rates_for_accounts_with_retries

collect_latest_rates_for_accounts_with_retries(
    accounts: Sequence[AccountSpec],
    timeframes: Sequence[int | str],
    count: int,
    *,
    start_pos: int = 0,
    base_config: Mt5Config | None = None,
    retry_count: int = 0,
    backoff_base: float = 2.0,
) -> dict[tuple[str, int], DataFrame]

Collect latest rates across accounts, retrying transient MT5 failures.

Wraps :func:collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5RuntimeError and its normalized Mt5ConnectionError form are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted.

Parameters:

Name Type Description Default
accounts Sequence[AccountSpec]

Account groups to read. Each must define at least one symbol.

required
timeframes Sequence[int | str]

MT5 timeframes as integers or names (for example M1).

required
count int

Number of most recent bars to read per symbol/timeframe.

required
start_pos int

Initial bar position offset.

0
base_config Mt5Config | None

Optional base configuration whose fields fill any value not set on an individual account.

None
retry_count int

Maximum number of retries after the first attempt. 0 disables retries.

0
backoff_base float

Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds.

2.0

Returns:

Type Description
dict[tuple[str, int], DataFrame]

Mapping keyed by (symbol, timeframe_int). Propagates ValueError

dict[tuple[str, int], DataFrame]

for invalid inputs (see :func:collect_latest_rates_for_accounts) and

dict[tuple[str, int], DataFrame]

re-raises the last recoverable MT5 error once retries are exhausted.

Source code in mt5cli/marketdata.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.Mt5RuntimeError`` and its normalized
    ``Mt5ConnectionError`` form 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 recoverable MT5 error 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",
    )

copy_rates_from

copy_rates_from(
    symbol: str,
    timeframe: int | str,
    date_from: datetime | str,
    count: int,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return rates starting from a date.

Source code in mt5cli/marketdata.py
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,
    )

copy_rates_from_pos

copy_rates_from_pos(
    symbol: str,
    timeframe: int | str,
    start_pos: int,
    count: int,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return rates starting from a bar position.

Source code in mt5cli/marketdata.py
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,
    )

copy_rates_range

copy_rates_range(
    symbol: str,
    timeframe: int | str,
    date_from: datetime | str,
    date_to: datetime | str,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return rates for a date range.

Source code in mt5cli/marketdata.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,
    )

copy_ticks_from

copy_ticks_from(
    symbol: str,
    date_from: datetime | str,
    count: int,
    flags: int | str,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return ticks starting from a date.

Source code in mt5cli/marketdata.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,
    )

copy_ticks_range

copy_ticks_range(
    symbol: str,
    date_from: datetime | str,
    date_to: datetime | str,
    flags: int | str,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return ticks for a date range.

Source code in mt5cli/marketdata.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,
    )

fetch_latest_closed_rates

fetch_latest_closed_rates(
    client: MT5Client,
    *,
    symbol: str,
    granularity: str,
    count: int,
) -> DataFrame

Fetch up to count most recent closed bars, oldest to newest.

Returns:

Type Description
DataFrame

Closed rate bars ordered oldest to newest.

Raises:

Type Description
ValueError

If count is not positive or no closed bars are returned.

Source code in mt5cli/marketdata.py
def fetch_latest_closed_rates(
    client: MT5Client,
    *,
    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)

history_deals

history_deals(
    date_from: datetime | str | None = None,
    date_to: datetime | str | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return historical deals.

Source code in mt5cli/marketdata.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,
    )

history_orders

history_orders(
    date_from: datetime | str | None = None,
    date_to: datetime | str | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return historical orders.

Source code in mt5cli/marketdata.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,
    )

last_error

last_error(*, config: Mt5Config | None = None) -> DataFrame

Return the last error information.

Source code in mt5cli/marketdata.py
def last_error(*, config: Mt5Config | None = None) -> pd.DataFrame:
    """Return the last error information."""
    return _make_client(config=config).last_error()

latest_rates

latest_rates(
    symbol: str,
    timeframe: int | str,
    count: int,
    start_pos: int = 0,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return the latest rates from a bar position.

Source code in mt5cli/marketdata.py
def latest_rates(
    symbol: str,
    timeframe: int | str,
    count: int,
    start_pos: int = 0,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return the latest rates from a bar position."""
    return _make_client(config=config).latest_rates(
        symbol,
        timeframe,
        count,
        start_pos=start_pos,
    )

market_book

market_book(
    symbol: str, *, config: Mt5Config | None = None
) -> DataFrame

Return market depth for a symbol.

Source code in mt5cli/marketdata.py
def market_book(
    symbol: str,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return market depth for a symbol."""
    return _make_client(config=config).market_book(symbol)

minimum_margins

minimum_margins(
    symbol: str, *, config: Mt5Config | None = None
) -> DataFrame

Return minimum-volume buy and sell margin requirements.

See MT5Client.minimum_margins for return details.

Source code in mt5cli/marketdata.py
def minimum_margins(
    symbol: str,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return minimum-volume buy and sell margin requirements.

    See ``MT5Client.minimum_margins`` for return details.
    """
    return _make_client(config=config).minimum_margins(symbol)

mt5_summary

mt5_summary(
    *, config: Mt5Config | None = None
) -> dict[str, object]

Return a compact terminal/account status summary.

Source code in mt5cli/marketdata.py
def mt5_summary(*, config: Mt5Config | None = None) -> dict[str, object]:
    """Return a compact terminal/account status summary."""
    return _make_client(config=config).mt5_summary()

mt5_summary_as_df

mt5_summary_as_df(
    *, config: Mt5Config | None = None
) -> DataFrame

Return an export-safe terminal/account status summary DataFrame.

Source code in mt5cli/marketdata.py
def mt5_summary_as_df(*, config: Mt5Config | None = None) -> pd.DataFrame:
    """Return an export-safe terminal/account status summary DataFrame."""
    return _make_client(config=config).mt5_summary_as_df()

orders

orders(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return active orders.

Source code in mt5cli/marketdata.py
def orders(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return active orders."""
    return _make_client(config=config).orders(
        symbol=symbol,
        group=group,
        ticket=ticket,
    )

positions

positions(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return open positions.

Source code in mt5cli/marketdata.py
def positions(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return open positions."""
    return _make_client(config=config).positions(
        symbol=symbol,
        group=group,
        ticket=ticket,
    )

recent_history_deals

recent_history_deals(
    hours: float,
    date_to: datetime | str | None = None,
    group: str | None = None,
    symbol: str | None = None,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return deals from a trailing window ending at explicit server time.

Source code in mt5cli/marketdata.py
def recent_history_deals(
    hours: float,
    date_to: datetime | str | None = None,
    group: str | None = None,
    symbol: str | None = None,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return deals from a trailing window ending at explicit server time."""
    return _make_client(config=config).recent_history_deals(
        hours,
        date_to=date_to,
        group=group,
        symbol=symbol,
    )

recent_ticks

recent_ticks(
    symbol: str,
    seconds: float,
    *,
    date_to: datetime | str | None = None,
    count: int = 10000,
    flags: int | str = "ALL",
    config: Mt5Config | None = None,
) -> DataFrame

Return ticks from a recent time window ending at date_to or now.

See MT5Client.recent_ticks for parameter and return details.

Source code in mt5cli/marketdata.py
def recent_ticks(
    symbol: str,
    seconds: float,
    *,
    date_to: datetime | str | None = None,
    count: int = 10000,
    flags: int | str = "ALL",
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return ticks from a recent time window ending at ``date_to`` or now.

    See ``MT5Client.recent_ticks`` for parameter and return details.
    """
    return _make_client(config=config).recent_ticks(
        symbol,
        seconds,
        date_to=date_to,
        count=count,
        flags=flags,
    )

resolve_account_spec

resolve_account_spec(
    account: AccountSpec,
    *,
    login: int | str | None = None,
    password: str | None = None,
    server: str | None = None,
    path: str | None = None,
    timeout: int | None = None,
    allow_whole_dollar_env: bool = False,
) -> AccountSpec

Resolve an account's credentials from overrides and ${ENV_VAR} values.

Explicit override arguments take precedence over the corresponding :class:AccountSpec fields. The resolved string fields (login, password, server, path) have any ${ENV_VAR} placeholders substituted from the environment.

Parameters:

Name Type Description Default
account AccountSpec

Source account specification.

required
login int | str | None

Optional explicit login override.

None
password str | None

Optional explicit password override.

None
server str | None

Optional explicit server override.

None
path str | None

Optional explicit terminal path override.

None
timeout int | None

Optional explicit connection timeout override.

None
allow_whole_dollar_env bool

When True, string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior.

False

Returns:

Type Description
AccountSpec

A new :class:AccountSpec with resolved credentials and the original

AccountSpec

symbols preserved. Raises ValueError (via

AccountSpec

func:~mt5cli.client.substitute_env_placeholders) if a referenced

AccountSpec

environment variable is not set.

Source code in mt5cli/marketdata.py
def resolve_account_spec(
    account: AccountSpec,
    *,
    login: int | str | None = None,
    password: str | None = None,
    server: str | None = None,
    path: str | None = None,
    timeout: int | None = None,
    allow_whole_dollar_env: bool = False,
) -> AccountSpec:
    """Resolve an account's credentials from overrides and ``${ENV_VAR}`` values.

    Explicit override arguments take precedence over the corresponding
    :class:`AccountSpec` fields. The resolved string fields (``login``,
    ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders
    substituted from the environment.

    Args:
        account: Source account specification.
        login: Optional explicit login override.
        password: Optional explicit password override.
        server: Optional explicit server override.
        path: Optional explicit terminal path override.
        timeout: Optional explicit connection timeout override.
        allow_whole_dollar_env: When ``True``, string fields that are exactly
            ``$ENV_NAME`` are also expanded from the environment. Default
            ``False`` preserves existing behavior.

    Returns:
        A new :class:`AccountSpec` with resolved credentials and the original
        symbols preserved. Raises ``ValueError`` (via
        :func:`~mt5cli.client.substitute_env_placeholders`) if a referenced
        environment variable is not set.
    """
    return AccountSpec(
        symbols=account.symbols,
        login=_resolve_login(
            login, account.login, allow_whole_dollar_env=allow_whole_dollar_env
        ),
        password=_resolve_field(
            password, account.password, allow_whole_dollar_env=allow_whole_dollar_env
        ),
        server=_resolve_field(
            server, account.server, allow_whole_dollar_env=allow_whole_dollar_env
        ),
        path=_resolve_field(
            path, account.path, allow_whole_dollar_env=allow_whole_dollar_env
        ),
        timeout=timeout if timeout is not None else account.timeout,
    )

resolve_account_specs

resolve_account_specs(
    accounts: Sequence[AccountSpec],
    *,
    login: int | str | None = None,
    password: str | None = None,
    server: str | None = None,
    path: str | None = None,
    timeout: int | None = None,
    allow_whole_dollar_env: bool = False,
) -> list[AccountSpec]

Resolve credentials for multiple accounts.

Applies the same overrides and ${ENV_VAR} substitution as :func:resolve_account_spec to every account.

Parameters:

Name Type Description Default
accounts Sequence[AccountSpec]

Source account specifications.

required
login int | str | None

Optional explicit login override applied to each account.

None
password str | None

Optional explicit password override applied to each account.

None
server str | None

Optional explicit server override applied to each account.

None
path str | None

Optional explicit terminal path override applied to each account.

None
timeout int | None

Optional explicit timeout override applied to each account.

None
allow_whole_dollar_env bool

When True, string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior.

False

Returns:

Type Description
list[AccountSpec]

Resolved account specifications in the original order. Raises

list[AccountSpec]

ValueError (via :func:~mt5cli.client.substitute_env_placeholders)

list[AccountSpec]

if a referenced environment variable is not set.

Source code in mt5cli/marketdata.py
def resolve_account_specs(
    accounts: Sequence[AccountSpec],
    *,
    login: int | str | None = None,
    password: str | None = None,
    server: str | None = None,
    path: str | None = None,
    timeout: int | None = None,
    allow_whole_dollar_env: bool = False,
) -> list[AccountSpec]:
    """Resolve credentials for multiple accounts.

    Applies the same overrides and ``${ENV_VAR}`` substitution as
    :func:`resolve_account_spec` to every account.

    Args:
        accounts: Source account specifications.
        login: Optional explicit login override applied to each account.
        password: Optional explicit password override applied to each account.
        server: Optional explicit server override applied to each account.
        path: Optional explicit terminal path override applied to each account.
        timeout: Optional explicit timeout override applied to each account.
        allow_whole_dollar_env: When ``True``, string fields that are exactly
            ``$ENV_NAME`` are also expanded from the environment. Default
            ``False`` preserves existing behavior.

    Returns:
        Resolved account specifications in the original order. Raises
        ``ValueError`` (via :func:`~mt5cli.client.substitute_env_placeholders`)
        if a referenced environment variable is not set.
    """
    return [
        resolve_account_spec(
            account,
            login=login,
            password=password,
            server=server,
            path=path,
            timeout=timeout,
            allow_whole_dollar_env=allow_whole_dollar_env,
        )
        for account in accounts
    ]

symbol_info

symbol_info(
    symbol: str, *, config: Mt5Config | None = None
) -> DataFrame

Return details for one symbol.

Source code in mt5cli/marketdata.py
def symbol_info(
    symbol: str,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return details for one symbol."""
    return _make_client(config=config).symbol_info(symbol)

symbol_info_tick

symbol_info_tick(
    symbol: str, *, config: Mt5Config | None = None
) -> DataFrame

Return the last tick for a symbol.

Source code in mt5cli/marketdata.py
def symbol_info_tick(
    symbol: str,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return the last tick for a symbol."""
    return _make_client(config=config).symbol_info_tick(symbol)

symbols

symbols(
    group: str | None = None,
    *,
    config: Mt5Config | None = None,
) -> DataFrame

Return the symbol list.

Source code in mt5cli/marketdata.py
def symbols(
    group: str | None = None,
    *,
    config: Mt5Config | None = None,
) -> pd.DataFrame:
    """Return the symbol list."""
    return _make_client(config=config).symbols(group=group)

terminal_info

terminal_info(
    *, config: Mt5Config | None = None
) -> DataFrame

Return terminal information.

Source code in mt5cli/marketdata.py
def terminal_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    """Return terminal information."""
    return _make_client(config=config).terminal_info()

version

version(*, config: Mt5Config | None = None) -> DataFrame

Return MetaTrader5 version information.

Source code in mt5cli/marketdata.py
def version(*, config: Mt5Config | None = None) -> pd.DataFrame:
    """Return MetaTrader5 version information."""
    return _make_client(config=config).version()

Resilient multi-account orchestration

This module ships strategy-agnostic helpers for building long-running collectors on top of MT5Client. None of them depend on a particular trading application.

Retrying transient rate collection

collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5RuntimeError is retried; the final failure is re-raised once retry_count is exhausted.

from mt5cli import AccountSpec, collect_latest_rates_for_accounts_with_retries

accounts = [AccountSpec(symbols=["EURUSD"], login=12345)]
rates = collect_latest_rates_for_accounts_with_retries(
    accounts,
    ["M1", "H1"],
    count=500,
    retry_count=3,
    backoff_base=2,  # sleeps 2s, 4s, 8s between attempts
)

Latest closed rate bars

MetaTrader 5 start_pos=0 includes the still-forming current bar as the last row. fetch_latest_closed_rates() handles one connected MT5Client. Multi-account helpers fetch count + 1 bars, drop that row with drop_forming_rate_bar(), and validate each series is non-empty. Returned frames are ordered oldest-to-newest and may contain fewer than count rows only when MT5 returns fewer closed bars.

from mt5cli import (
    AccountSpec,
    collect_latest_closed_rates_by_granularity,
    fetch_latest_closed_rates,
)

closed = fetch_latest_closed_rates(
    client,
    symbol="EURUSD",
    granularity="M1",
    count=500,
)

rates = collect_latest_closed_rates_by_granularity(
    [AccountSpec(symbols=["EURUSD"], login=12345)],
    ["M1", "H1"],
    count=500,
    retry_count=3,
)
closed_m1 = rates["EURUSD", "M1"]

Use collect_latest_closed_rates_by_granularity() when callers prefer keys such as ("EURUSD", "M1") instead of integer timeframes.

Resolving credentials and ${ENV_VAR} placeholders

resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError.

import os

from mt5cli import AccountSpec, resolve_account_specs

os.environ["MT5_LOGIN"] = "12345"
os.environ["MT5_PASSWORD"] = "secret"
accounts = [
    AccountSpec(symbols=["EURUSD"], login="${MT5_LOGIN}", password="${MT5_PASSWORD}")
]

resolved = resolve_account_specs(accounts, server="Broker-Demo")
# resolved[0].login == "12345", resolved[0].server == "Broker-Demo"

Pass allow_whole_dollar_env=True to also expand strings whose entire value is a bare $ENV_NAME identifier (no braces). This opt-in covers substitute_env_placeholders(), resolve_account_spec(), resolve_account_specs(), and build_config(). Note: build_config cannot expand login because that parameter is int | None; use resolve_account_spec for a string login placeholder. Partial strings such as "plan$pass", "abc$ENV", or "$ENV-suffix" are never expanded — only an exact $IDENTIFIER whole-string match qualifies. The default is False to preserve backward compatibility.

import os

from mt5cli import AccountSpec, resolve_account_specs

os.environ["MT5_PASSWORD"] = "secret"
accounts = [AccountSpec(symbols=["EURUSD"], password="$MT5_PASSWORD")]

resolved = resolve_account_specs(accounts, allow_whole_dollar_env=True)
# resolved[0].password == "secret"

Trading-capable sessions

For order placement and trading calculations, use the dedicated Trading module. Use mt5_session() / MT5Client for read-only collection.