# 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`

    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454

    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`

    63
    64
    65
    66
    67
    68
    69
    70

    @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`

    34
    35
    36
    37
    38
    39
    40
    41
    42
    43

    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`

    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61

    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`

    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358

    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`

    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86

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

#### Search

From here you can search these documents. Enter your search terms below.

#### Keyboard Shortcuts

Keys | Action
--- | ---
`?` | Open this help
`n` | Next page
`p` | Previous page
`s` | Search