Client

mt5cli.client

Stable public client abstraction for MT5 data and execution operations.

__all__ module-attribute

__all__ = ['MT5Client', 'build_config', 'mt5_session']

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,
    client: Mt5DataClient | None = None,
)

Bases: Mt5CliClient

Public client for generic MT5 data access and order primitives.

Extends the read-only SDK client 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.

Source code in mt5cli/sdk.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,
    client: Mt5DataClient | None = None,
) -> None:
    """Initialize the SDK client.

    Args:
        path: Path to MetaTrader5 terminal EXE file.
        login: Trading account login.
        password: Trading account password.
        server: Trading server name.
        timeout: Connection timeout in milliseconds.
        retry_count: Number of MT5 initialization retries for sessions
            opened by this client.
        config: Optional pre-built ``Mt5Config`` (overrides other args).
        client: Optional already-connected ``Mt5DataClient``. Injected
            clients are reused as-is and are not initialized or shut down.
    """
    self._config = config or build_config(
        path=path,
        login=login,
        password=password,
        server=server,
        timeout=timeout,
    )
    self._retry_count = retry_count
    self._client = client
    self._owns_client = client is None

from_connected_client classmethod

from_connected_client(client: Mt5DataClient) -> Self

Bind to an already-connected Mt5DataClient without owning it.

Returns:

Type Description
Self

Client wrapper bound to the injected connection.

Source code in mt5cli/client.py
@classmethod
def from_connected_client(cls, client: Mt5DataClient) -> Self:
    """Bind to an already-connected ``Mt5DataClient`` without owning it.

    Returns:
        Client wrapper bound to the injected connection.
    """
    return cls(client=client)

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))

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/sdk.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,
) -> Iterator[MT5Client]

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

Parameters:

Name Type Description Default
config Mt5Config | None

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

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) -> Iterator[MT5Client]:
    """Open an MT5 terminal session and yield a connected :class:`MT5Client`.

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

    Yields:
        Connected :class:`MT5Client` bound to the session.
    """
    mt5_config = config or build_config()
    with connected_client(mt5_config) as client:
        yield MT5Client.from_connected_client(client)