Skip to content

Client

The main entry point for all MetaTrader 5 operations.


MetaTrader5Client

MetaTrader5Client

MetaTrader5Client(*, debug: bool = False)

Unified client for all MetaTrader 5 operations.

Composes the individual service classes (connection, positions, orders, history, market data, etc.) behind a single interface. All methods return Result[T] β€” never raise β€” so callers always handle both the success and failure paths explicitly.

Lifecycle

  1. initialize() β€” connect to the terminal (required before anything else)
  2. login() β€” authenticate with the broker (required for trading operations)
  3. (use the client)
  4. shutdown() β€” disconnect cleanly

The client can also be used as a context manager; shutdown() is called automatically on exit regardless of whether an exception occurred.

PARAMETER DESCRIPTION
debug

When True, each operation logs its name, outcome, and elapsed time at DEBUG level via the syntiq_mt5 logger.

TYPE: bool DEFAULT: False

Initialise the client and instantiate all service objects.

PARAMETER DESCRIPTION
debug

Enable per-call DEBUG logging with timing information.

TYPE: bool DEFAULT: False

__enter__

__enter__() -> MetaTrader5Client

Support with MetaTrader5Client() as client: usage.

__exit__

__exit__(*_: object) -> None

Call shutdown() automatically when leaving the context block.

initialize

initialize(
    credentials: LoginCredential | None = None,
) -> Result[None]

Connect to the MetaTrader 5 terminal.

Must be called before any other operation. Sets the internal _initialized flag on success so subsequent calls to other methods are permitted.

PARAMETER DESCRIPTION
credentials

Optional credentials; only path is used here to locate the terminal executable.

TYPE: LoginCredential | None DEFAULT: None

RETURNS DESCRIPTION
Result[None]

Result[None]: Success if the terminal connected.

login

login(credentials: LoginCredential) -> Result[None]

Authenticate with the broker.

Requires a prior successful initialize() call.

PARAMETER DESCRIPTION
credentials

Account number, password, and server name.

TYPE: LoginCredential

RETURNS DESCRIPTION
Result[None]

Result[None]: Success if authentication succeeded.

shutdown

shutdown() -> Result[None]

Disconnect from the MetaTrader 5 terminal.

Resets _initialized and _logged_in regardless of outcome. Safe to call multiple times.

RETURNS DESCRIPTION
Result[None]

Result[None]: Success in almost all cases.

version

version() -> Result[tuple[int, int, str]]

Return the connected terminal's version information.

RETURNS DESCRIPTION
Result[tuple[int, int, str]]

Result[tuple[int, int, str]]: (build, date, version_string) on success.

positions

positions(
    symbol: str | None = None,
) -> Result[list[Position]]

Retrieve all open positions, optionally filtered by symbol.

PARAMETER DESCRIPTION
symbol

If provided, only positions for this symbol are returned.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
Result[list[Position]]

Result[list[Position]]: Open positions on success (may be empty).

positions_total

positions_total() -> Result[int]

Return the total number of open positions.

RETURNS DESCRIPTION
Result[int]

Result[int]: Count of open positions on success.

get_candles

get_candles(
    symbol: str, timeframe: int, count: int
) -> Result[list[Candle]]

Retrieve the most recent OHLCV candles for a symbol.

PARAMETER DESCRIPTION
symbol

Trading instrument name (e.g. "EURUSD").

TYPE: str

timeframe

MT5 timeframe constant (e.g. constants.TIMEFRAME_H1).

TYPE: int

count

Number of bars to retrieve.

TYPE: int

RETURNS DESCRIPTION
Result[list[Candle]]

Result[list[Candle]]: Candles in chronological order on success.

copy_rates_from

copy_rates_from(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
) -> Result[list[Candle]]

Retrieve candles starting from a specific datetime.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

timeframe

MT5 timeframe constant.

TYPE: int

date_from

Start datetime (inclusive).

TYPE: datetime

count

Number of bars to retrieve going forward.

TYPE: int

RETURNS DESCRIPTION
Result[list[Candle]]

Result[list[Candle]]: Candles in chronological order on success.

copy_rates_range

copy_rates_range(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
) -> Result[list[Candle]]

Retrieve all candles within a datetime range.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

timeframe

MT5 timeframe constant.

TYPE: int

date_from

Range start datetime (inclusive).

TYPE: datetime

date_to

Range end datetime (inclusive).

TYPE: datetime

RETURNS DESCRIPTION
Result[list[Candle]]

Result[list[Candle]]: Candles in chronological order on success.

account_info

account_info() -> Result[AccountInfo]

Retrieve the current trading account details.

RETURNS DESCRIPTION
Result[AccountInfo]

Result[AccountInfo]: Account state including balance, equity,

Result[AccountInfo]

and margin on success.

terminal_info

terminal_info() -> Result[TerminalInfo]

Retrieve the connected terminal's configuration and state.

RETURNS DESCRIPTION
Result[TerminalInfo]

Result[TerminalInfo]: Terminal details including connection

Result[TerminalInfo]

status and trading permissions on success.

symbols_total

symbols_total() -> Result[int]

Return the total number of symbols available in the terminal.

RETURNS DESCRIPTION
Result[int]

Result[int]: Symbol count on success.

symbols_get

symbols_get(group: str | None = None) -> Result[list[str]]

Retrieve symbol names, optionally filtered by group pattern.

PARAMETER DESCRIPTION
group

Wildcard filter pattern (e.g. "*USD*"). When None, all available symbols are returned.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
Result[list[str]]

Result[list[str]]: List of symbol names on success.

symbol_select

symbol_select(symbol: str, enable: bool) -> Result[bool]

Add or remove a symbol from the Market Watch window.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

enable

True to add the symbol; False to remove it.

TYPE: bool

RETURNS DESCRIPTION
Result[bool]

Result[bool]: True on success.

symbol_info

symbol_info(symbol: str) -> Result[SymbolInfo]

Retrieve full specification data for a symbol.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

RETURNS DESCRIPTION
Result[SymbolInfo]

Result[SymbolInfo]: Symbol specification on success.

symbol_info_tick

symbol_info_tick(symbol: str) -> Result[SymbolTick]

Retrieve the latest tick for a symbol.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

RETURNS DESCRIPTION
Result[SymbolTick]

Result[SymbolTick]: The most recent bid/ask/last prices on success.

market_book_add

market_book_add(symbol: str) -> Result[bool]

Subscribe to market depth (DOM) updates for a symbol.

Must be called before market_book_get() for the same symbol.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

RETURNS DESCRIPTION
Result[bool]

Result[bool]: True if the subscription was accepted.

market_book_get

market_book_get(symbol: str) -> Result[list[BookEntry]]

Retrieve the current market depth snapshot for a symbol.

Requires a prior market_book_add() call for the same symbol.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

RETURNS DESCRIPTION
Result[list[BookEntry]]

Result[list[BookEntry]]: All DOM entries on success.

market_book_release

market_book_release(symbol: str) -> Result[bool]

Unsubscribe from market depth updates for a symbol.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

RETURNS DESCRIPTION
Result[bool]

Result[bool]: True if the subscription was released.

copy_ticks_from

copy_ticks_from(
    symbol: str, date_from: datetime, count: int, flags: int
) -> Result[list[Tick]]

Retrieve ticks starting from a specific datetime.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

date_from

Start datetime (inclusive).

TYPE: datetime

count

Maximum number of ticks to retrieve.

TYPE: int

flags

COPY_TICKS_* constant controlling which ticks to include.

TYPE: int

RETURNS DESCRIPTION
Result[list[Tick]]

Result[list[Tick]]: Ticks in chronological order on success.

copy_ticks_range

copy_ticks_range(
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
) -> Result[list[Tick]]

Retrieve all ticks within a datetime range.

PARAMETER DESCRIPTION
symbol

Trading instrument name.

TYPE: str

date_from

Range start datetime (inclusive).

TYPE: datetime

date_to

Range end datetime (inclusive).

TYPE: datetime

flags

COPY_TICKS_* constant controlling which ticks to include.

TYPE: int

RETURNS DESCRIPTION
Result[list[Tick]]

Result[list[Tick]]: Ticks in chronological order on success.

orders_total

orders_total() -> Result[int]

Return the total number of active pending orders.

RETURNS DESCRIPTION
Result[int]

Result[int]: Count of pending orders on success.

orders_get

orders_get(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
) -> Result[list[Order]]

Retrieve active pending orders with optional filtering.

At most one filter argument should be provided. When none are given, all active orders are returned.

PARAMETER DESCRIPTION
symbol

Filter by trading instrument name.

TYPE: str | None DEFAULT: None

group

Filter by symbol group wildcard pattern.

TYPE: str | None DEFAULT: None

ticket

Filter by order ticket number.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Result[list[Order]]

Result[list[Order]]: Active orders on success (may be empty).

order_calc_margin

order_calc_margin(
    action: int, symbol: str, volume: float, price: float
) -> Result[float]

Calculate the margin required for a hypothetical order.

PARAMETER DESCRIPTION
action

Trade action type (TRADE_ACTION_DEAL or TRADE_ACTION_PENDING).

TYPE: int

symbol

Trading instrument name.

TYPE: str

volume

Order volume in lots.

TYPE: float

price

Intended execution price.

TYPE: float

RETURNS DESCRIPTION
Result[float]

Result[float]: Required margin in account currency on success.

order_calc_profit

order_calc_profit(
    action: int,
    symbol: str,
    volume: float,
    price_open: float,
    price_close: float,
) -> Result[float]

Calculate the profit for a hypothetical trade.

PARAMETER DESCRIPTION
action

Trade action type (TRADE_ACTION_DEAL).

TYPE: int

symbol

Trading instrument name.

TYPE: str

volume

Trade volume in lots.

TYPE: float

price_open

Hypothetical entry price.

TYPE: float

price_close

Hypothetical exit price.

TYPE: float

RETURNS DESCRIPTION
Result[float]

Result[float]: Estimated profit in account currency on success.

order_check

order_check(request: TradeRequest) -> Result[TradeResult]

Validate a trade request without submitting it.

Useful for pre-flight checks before calling order_send().

PARAMETER DESCRIPTION
request

The trade request to validate.

TYPE: TradeRequest

RETURNS DESCRIPTION
Result[TradeResult]

Result[TradeResult]: Validation outcome including margin

Result[TradeResult]

requirements and any rejection reason on success.

order_send

order_send(request: TradeRequest) -> Result[TradeResult]

Submit a trade request to the broker.

PARAMETER DESCRIPTION
request

The trade request to execute. Use TradeRequest with typed enum fields for action, type, type_filling, and type_time.

TYPE: TradeRequest

RETURNS DESCRIPTION
Result[TradeResult]

Result[TradeResult]: Execution outcome including the deal

Result[TradeResult]

and order tickets on success. Check result.data.is_successful

Result[TradeResult]

for the broker's acceptance status.

history_orders_total

history_orders_total(
    date_from: datetime, date_to: datetime
) -> Result[int]

Return the number of historical orders in a date range.

PARAMETER DESCRIPTION
date_from

Range start (inclusive).

TYPE: datetime

date_to

Range end (inclusive).

TYPE: datetime

RETURNS DESCRIPTION
Result[int]

Result[int]: Count of historical orders on success.

history_orders_get

history_orders_get(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
) -> Result[list[HistoricalOrder]]

Retrieve historical orders with flexible filtering.

Exactly one filter strategy must be provided: either a date range (date_from + date_to), a group pattern, a ticket, or a position ticket.

PARAMETER DESCRIPTION
date_from

Range start (used with date_to).

TYPE: datetime | None DEFAULT: None

date_to

Range end (used with date_from).

TYPE: datetime | None DEFAULT: None

group

Symbol group wildcard pattern.

TYPE: str | None DEFAULT: None

ticket

Order ticket number.

TYPE: int | None DEFAULT: None

position

Position ticket to retrieve orders for.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Result[list[HistoricalOrder]]

Result[list[HistoricalOrder]]: Matching orders on success.

history_deals_total

history_deals_total(
    date_from: datetime, date_to: datetime
) -> Result[int]

Return the number of deals in a date range.

PARAMETER DESCRIPTION
date_from

Range start (inclusive).

TYPE: datetime

date_to

Range end (inclusive).

TYPE: datetime

RETURNS DESCRIPTION
Result[int]

Result[int]: Count of deals on success.

history_deals_get

history_deals_get(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
) -> Result[list[Deal]]

Retrieve deals from the trade history with flexible filtering.

Exactly one filter strategy must be provided: either a date range, a group pattern, a deal ticket, or a position ticket.

PARAMETER DESCRIPTION
date_from

Range start (used with date_to).

TYPE: datetime | None DEFAULT: None

date_to

Range end (used with date_from).

TYPE: datetime | None DEFAULT: None

group

Symbol group wildcard pattern.

TYPE: str | None DEFAULT: None

ticket

Deal ticket number.

TYPE: int | None DEFAULT: None

position

Position ticket to retrieve deals for.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Result[list[Deal]]

Result[list[Deal]]: Matching deals on success.


Usage

from pydantic import SecretStr
from syntiq_mt5 import LoginCredential, MetaTrader5Client

creds = LoginCredential(
    login=12345678,
    password=SecretStr("your-password"),
    server="Broker-Demo",
)

with MetaTrader5Client(debug=True) as mt5:
    # Initialize and login
    mt5.initialize(creds)
    mt5.login(creds)

    # Use any method
    res = mt5.positions()
    if res.success:
        for p in res.data:
            print(f"{p.symbol}: {p.pips_profit:+.1f} pips")

The client automatically calls shutdown() when the context manager exits.