Client

mt5cli.client

Sole connection-lifecycle owner and stable public client abstraction.

This module owns the MT5 connection lifecycle end to end: building Mt5Config, initializing and logging in to the terminal, and shutting it down exactly once on exit. mt5_session() is the only public session factory; every other mt5cli module that needs a connection imports the private primitives defined here instead of duplicating lifecycle behavior.

T module-attribute

T = TypeVar('T')

__all__ module-attribute

__all__ = [
    "MT5Client",
    "build_config",
    "mt5_session",
    "substitute_env_placeholders",
    "substitute_mapping_values",
]

logger module-attribute

logger = logging.getLogger(__name__)

MT5Client

MT5Client(
    *,
    path: str | None = None,
    login: int | None = None,
    password: str | None = None,
    server: str | None = None,
    timeout: int | None = None,
    retry_count: int = 3,
    config: Mt5Config | None = None,
)

Bases: _BaseMT5Client

The single public connected MT5 client.

Extends the read-only data access above with optional order check/send helpers and exposes the same connection lifecycle as :func:mt5_session.

mt5cli intentionally exposes minimal execution primitives only. Trading decisions, signals, strategies, backtests, and optimization remain the responsibility of downstream applications.

Configure a client; use it as a context manager to connect.

Source code in mt5cli/client.py
def __init__(
    self,
    *,
    path: str | None = None,
    login: int | None = None,
    password: str | None = None,
    server: str | None = None,
    timeout: int | None = None,
    retry_count: int = 3,
    config: Mt5Config | None = None,
) -> None:
    """Configure a client; use it as a context manager to connect."""
    super().__init__(
        path=path,
        login=login,
        password=password,
        server=server,
        timeout=timeout,
        retry_count=retry_count,
        config=config,
    )

mt5 property

mt5: Any

MT5 constants required by operational helpers.

This intentionally exposes constants only, never the pdmt5 client.

account_info_as_dict

account_info_as_dict() -> dict[str, object]

Return the current account snapshot as a plain mapping.

Source code in mt5cli/client.py
def account_info_as_dict(self) -> dict[str, object]:
    """Return the current account snapshot as a plain mapping."""
    frame = self.account_info()
    return {} if frame.empty else cast("dict[str, object]", frame.iloc[0].to_dict())

from_connected_client classmethod

from_connected_client(client: object) -> Self

Bind the public facade to an externally owned connection.

Returns:

Type Description
Self

Public facade that never initializes or shuts down client.

Source code in mt5cli/client.py
@classmethod
def from_connected_client(cls, client: object) -> Self:
    """Bind the public facade to an externally owned connection.

    Returns:
        Public facade that never initializes or shuts down ``client``.
    """
    return cls._from_connected_client(client)

order_calc_margin

order_calc_margin(
    action: int, symbol: str, volume: float, price: float
) -> object

Calculate broker margin for an order candidate.

Returns:

Type Description
object

Broker-calculated margin value.

Source code in mt5cli/client.py
def order_calc_margin(
    self, action: int, symbol: str, volume: float, price: float
) -> object:
    """Calculate broker margin for an order candidate.

    Returns:
        Broker-calculated margin value.
    """
    return self._fetch_value(
        lambda client: client.order_calc_margin(action, symbol, volume, price)
    )

order_check

order_check(request: dict[str, Any]) -> DataFrame

Check funds sufficiency for a trade request.

Parameters:

Name Type Description Default
request dict[str, Any]

MT5 order request dictionary.

required

Returns:

Type Description
DataFrame

One-row DataFrame with the order-check result.

Source code in mt5cli/client.py
def order_check(self, request: dict[str, Any]) -> pd.DataFrame:
    """Check funds sufficiency for a trade request.

    Args:
        request: MT5 order request dictionary.

    Returns:
        One-row DataFrame with the order-check result.
    """
    return self._fetch(lambda client: client.order_check_as_df(request=request))

order_send

order_send(request: dict[str, Any]) -> DataFrame

Send a live trade request to the MT5 trade server.

Warning

This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing.

Parameters:

Name Type Description Default
request dict[str, Any]

MT5 order request dictionary.

required

Returns:

Type Description
DataFrame

One-row DataFrame with the order-send result.

Source code in mt5cli/client.py
def order_send(self, request: dict[str, Any]) -> pd.DataFrame:
    """Send a live trade request to the MT5 trade server.

    Warning:
        This is a live execution primitive. A successful call can place,
        modify, or close real trades on the connected account. Downstream
        applications must gate usage explicitly (for example behind manual
        confirmation or application-specific risk controls). mt5cli does
        not implement strategy logic, signal generation, or trade sizing.

    Args:
        request: MT5 order request dictionary.

    Returns:
        One-row DataFrame with the order-send result.
    """
    return self._fetch(lambda client: client.order_send_as_df(request=request))

positions_get_as_df

positions_get_as_df(symbol: str | None = None) -> DataFrame

Return open positions in the canonical DataFrame schema.

Source code in mt5cli/client.py
def positions_get_as_df(self, symbol: str | None = None) -> pd.DataFrame:
    """Return open positions in the canonical DataFrame schema."""
    return self.positions(symbol=symbol)

symbol_info_as_dict

symbol_info_as_dict(symbol: str) -> dict[str, object]

Return one symbol snapshot as a plain mapping.

Source code in mt5cli/client.py
def symbol_info_as_dict(self, symbol: str) -> dict[str, object]:
    """Return one symbol snapshot as a plain mapping."""
    frame = self.symbol_info(symbol)
    return {} if frame.empty else cast("dict[str, object]", frame.iloc[0].to_dict())

symbol_select

symbol_select(symbol: str, enable: bool = True) -> bool

Select or deselect a symbol in Market Watch.

Returns:

Type Description
bool

Whether MT5 accepted the selection operation.

Source code in mt5cli/client.py
def symbol_select(self, symbol: str, enable: bool = True) -> bool:
    """Select or deselect a symbol in Market Watch.

    Returns:
        Whether MT5 accepted the selection operation.
    """
    return bool(
        self._fetch_value(
            lambda client: client.symbol_select(symbol, enable=enable)
        )
    )

build_config

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

Build an Mt5Config from optional connection parameters.

Parameters:

Name Type Description Default
path str | None

Optional terminal executable path.

None
login int | str | None

Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None; numeric strings such as "12345" are converted to int; non-numeric strings raise ValueError. When allow_whole_dollar_env=True, $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion.

None
password str | None

Optional trading account password.

None
server str | None

Optional trading server name.

None
timeout int | None

Optional connection timeout in milliseconds.

None
allow_whole_dollar_env bool

When True, string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path, login, password, and server. Default False preserves existing behavior.

False

Returns:

Type Description
Mt5Config

Configured Mt5Config instance.

Source code in mt5cli/client.py
def build_config(
    *,
    path: str | None = None,
    login: int | str | None = None,
    password: str | None = None,
    server: str | None = None,
    timeout: int | None = None,
    allow_whole_dollar_env: bool = False,
) -> Mt5Config:
    """Build an ``Mt5Config`` from optional connection parameters.

    Args:
        path: Optional terminal executable path.
        login: Optional trading account login. Integers are preserved. String
            values are coerced: empty or whitespace-only strings become
            ``None``; numeric strings such as ``"12345"`` are converted to
            ``int``; non-numeric strings raise ``ValueError``. When
            ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and
            ``${ENV_NAME}`` placeholders are expanded before coercion.
        password: Optional trading account password.
        server: Optional trading server name.
        timeout: Optional connection timeout in milliseconds.
        allow_whole_dollar_env: When ``True``, string parameters that are
            exactly ``$ENV_NAME`` are expanded from the environment. Applies
            to ``path``, ``login``, ``password``, and ``server``. Default
            ``False`` preserves existing behavior.

    Returns:
        Configured ``Mt5Config`` instance.
    """
    if allow_whole_dollar_env:
        if path is not None:
            path = substitute_env_placeholders(path, allow_whole_dollar_env=True)
        if isinstance(login, str):
            login = substitute_env_placeholders(login, allow_whole_dollar_env=True)
        if password is not None:
            password = substitute_env_placeholders(
                password, allow_whole_dollar_env=True
            )
        if server is not None:
            server = substitute_env_placeholders(server, allow_whole_dollar_env=True)
    return Mt5Config(
        path=path,
        login=_coerce_login(login),
        password=password,
        server=server,
        timeout=timeout,
    )

mt5_session

mt5_session(
    config: Mt5Config | None = None,
    *,
    client: MT5Client | None = None,
) -> Generator[MT5Client, None, None]

Open an MT5 terminal session and yield a connected :class:MT5Client.

This is the sole public MT5 session factory. It is the only supported way to obtain a connected :class:MT5Client for market data, history, observability, and execution workflows.

Parameters:

Name Type Description Default
config Mt5Config | None

MT5 connection configuration. Defaults to an empty config that attaches to a running terminal.

None
client MT5Client | None

A caller-owned connected public client. It is yielded as-is and is never initialized or shut down by this context manager.

None

Yields:

Name Type Description
Connected MT5Client

class:MT5Client bound to the session.

Source code in mt5cli/client.py
@contextmanager
def mt5_session(
    config: Mt5Config | None = None, *, client: MT5Client | None = None
) -> Generator[MT5Client, None, None]:
    """Open an MT5 terminal session and yield a connected :class:`MT5Client`.

    This is the sole public MT5 session factory. It is the only supported way
    to obtain a connected :class:`MT5Client` for market data, history,
    observability, and execution workflows.

    Args:
        config: MT5 connection configuration. Defaults to an empty config that
            attaches to a running terminal.
        client: A caller-owned connected public client. It is yielded as-is and
            is never initialized or shut down by this context manager.

    Yields:
        Connected :class:`MT5Client` bound to the session.
    """
    if client is not None:
        yield client
        return
    mt5_config = config or build_config()
    with _connected_client(mt5_config) as raw_client:
        yield MT5Client._from_connected_client(  # pyright: ignore[reportPrivateUsage]  # ruff: ignore[private-member-access]
            raw_client
        )

substitute_env_placeholders

substitute_env_placeholders(
    value: str, *, allow_whole_dollar_env: bool = False
) -> str

Replace ${ENV_VAR} placeholders in a string with environment values.

Parameters:

Name Type Description Default
value str

String that may contain one or more ${ENV_VAR} placeholders.

required
allow_whole_dollar_env bool

When True, a string that is exactly $ENV_NAME (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as "plan$pass" or "$ENV-suffix" are left unchanged.

False

Returns:

Type Description
str

The string with every placeholder replaced by its environment value.

Raises:

Type Description
ValueError

If a referenced environment variable is not set.

Source code in mt5cli/client.py
def substitute_env_placeholders(
    value: str,
    *,
    allow_whole_dollar_env: bool = False,
) -> str:
    """Replace ``${ENV_VAR}`` placeholders in a string with environment values.

    Args:
        value: String that may contain one or more ``${ENV_VAR}`` placeholders.
        allow_whole_dollar_env: When ``True``, a string that is exactly
            ``$ENV_NAME`` (the whole value and nothing else) is also expanded
            from the environment. Partial occurrences such as ``"plan$pass"``
            or ``"$ENV-suffix"`` are left unchanged.

    Returns:
        The string with every placeholder replaced by its environment value.

    Raises:
        ValueError: If a referenced environment variable is not set.
    """
    if allow_whole_dollar_env:
        m = _WHOLE_DOLLAR_PATTERN.match(value)
        if m:
            name = m.group("name")
            if name not in os.environ:
                msg = f"Environment variable {name!r} is not set."
                raise ValueError(msg)
            return os.environ[name]
    parts: list[str] = []
    last_end = 0
    for match in _ENV_PLACEHOLDER_PATTERN.finditer(value):
        parts.append(value[last_end : match.start()])
        name = match.group("name")
        if name not in os.environ:
            msg = f"Environment variable {name!r} is not set."
            raise ValueError(msg)
        parts.append(os.environ[name])
        last_end = match.end()
    parts.append(value[last_end:])
    return "".join(parts)

substitute_mapping_values

substitute_mapping_values(
    data: object,
    *,
    keys: Collection[str],
    allow_whole_dollar_env: bool = False,
    blank_string_keys_as_none: Collection[str] = (),
) -> object

Recursively substitute environment placeholders for selected mapping keys.

Traverses nested dicts and lists, expanding ${ENV_VAR} (and $ENV_NAME when allow_whole_dollar_env=True) in string values whose immediate parent dict key is in keys. Fields whose key is not in keys are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values.

This is a generic downstream config utility. Key names such as mt5_login or mt5_password must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring data has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit.

Parameters:

Name Type Description Default
data object

Arbitrarily nested dict/list/scalar value to process.

required
keys Collection[str]

Mapping keys whose string values receive placeholder substitution.

required
allow_whole_dollar_env bool

When True, a string that is exactly $ENV_NAME (whole value) is also expanded from the environment in addition to ${ENV_NAME} placeholders. Default False expands ${ENV_NAME} only.

False
blank_string_keys_as_none Collection[str]

Mapping keys for which blank strings (after any substitution) are normalised to None. A key may appear in blank_string_keys_as_none without also appearing in keys.

()

Returns:

Type Description
object

The processed value. Dicts and lists are rebuilt into new

object

containers with selected string values substituted and

object

blank-normalised. Scalar inputs (non-dict, non-list) are

object

returned as-is.

Source code in mt5cli/client.py
def substitute_mapping_values(
    data: object,
    *,
    keys: Collection[str],
    allow_whole_dollar_env: bool = False,
    blank_string_keys_as_none: Collection[str] = (),
) -> object:
    """Recursively substitute environment placeholders for selected mapping keys.

    Traverses nested dicts and lists, expanding ``${ENV_VAR}`` (and
    ``$ENV_NAME`` when ``allow_whole_dollar_env=True``) in string values
    whose immediate parent dict key is in ``keys``.  Fields whose key is
    not in ``keys`` are preserved exactly, including literal dollar signs.
    Strings that are direct elements of a list are never substituted;
    substitution only applies to strings that are immediate dict values.

    This is a generic downstream config utility.  Key names such as
    ``mt5_login`` or ``mt5_password`` must be supplied by the caller;
    mt5cli does not hard-code any application-specific key names.
    Callers are responsible for ensuring ``data`` has bounded nesting depth;
    deeply nested or self-referential structures will hit Python's recursion
    limit.

    Args:
        data: Arbitrarily nested dict/list/scalar value to process.
        keys: Mapping keys whose string values receive placeholder
            substitution.
        allow_whole_dollar_env: When ``True``, a string that is exactly
            ``$ENV_NAME`` (whole value) is also expanded from the
            environment in addition to ``${ENV_NAME}`` placeholders.
            Default ``False`` expands ``${ENV_NAME}`` only.
        blank_string_keys_as_none: Mapping keys for which blank strings
            (after any substitution) are normalised to ``None``.  A key
            may appear in ``blank_string_keys_as_none`` without also
            appearing in ``keys``.

    Returns:
        The processed value.  Dicts and lists are rebuilt into new
        containers with selected string values substituted and
        blank-normalised.  Scalar inputs (non-dict, non-list) are
        returned as-is.
    """
    keys_set: frozenset[str] = frozenset(keys)
    blank_keys_set: frozenset[str] = frozenset(blank_string_keys_as_none)

    def _visit(node: object, current_key: str | None) -> object:
        if isinstance(node, dict):
            typed = cast("dict[object, object]", node)
            return {
                k: _visit(v, k if isinstance(k, str) else None)
                for k, v in typed.items()
            }
        if isinstance(node, list):
            typed_list = cast("list[object]", node)
            return [_visit(item, None) for item in typed_list]
        if not isinstance(node, str):
            return node
        text = node
        if current_key in keys_set:
            text = substitute_env_placeholders(
                node, allow_whole_dollar_env=allow_whole_dollar_env
            )
        if current_key in blank_keys_set and not text.strip():
            return None
        return text

    return _visit(data, None)