Skip to content

History

Historical orders and deals retrieval.


Models

Deal

Deal

Bases: BaseModel

A completed transaction in the MT5 trade history.

Wraps the raw TradeDeal struct returned by mt5.history_deals_get(). A deal is created whenever a position is opened, modified, or closed. Non-trade operations (balance adjustments, commissions, swaps) also appear as deals with non-BUY/SELL type values.

ATTRIBUTE DESCRIPTION
ticket

Unique deal identifier.

TYPE: int

order

Ticket of the order that generated this deal.

TYPE: int

time

Deal execution time as a Unix timestamp (seconds).

TYPE: int

time_msc

Deal execution time in milliseconds.

TYPE: int

type

Nature of the transaction (BUY, SELL, BALANCE, COMMISSION, etc.).

TYPE: DealType

entry

How this deal relates to the affected position (IN, OUT, INOUT, OUT_BY).

TYPE: DealEntry

magic

Expert Advisor identifier; 0 for manual trades.

TYPE: int

position_id

Ticket of the position this deal belongs to.

TYPE: int

reason

What triggered the deal.

TYPE: DealReason

volume

Executed volume in lots.

TYPE: float

price

Execution price.

TYPE: float

commission

Commission charged for this deal.

TYPE: float

swap

Swap charged at the time of this deal.

TYPE: float

profit

Realised profit/loss in account currency.

TYPE: float

fee

Additional fee charged for this deal.

TYPE: float

symbol

Trading instrument name.

TYPE: str

comment

Arbitrary comment attached to the deal.

TYPE: str

external_id

Deal identifier in an external system.

TYPE: str

net_profit property

net_profit: float

Realised profit after deducting commission, swap, and fees.

RETURNS DESCRIPTION
float

Net profit in account currency.

is_entry property

is_entry: bool

Whether this deal opened a new position (DEAL_ENTRY_IN).

is_exit property

is_exit: bool

Whether this deal closed an existing position (DEAL_ENTRY_OUT).

is_reversal property

is_reversal: bool

Whether this deal reversed the direction of a position (DEAL_ENTRY_INOUT).

is_close_by property

is_close_by: bool

Whether this deal closed a position by an opposite position (DEAL_ENTRY_OUT_BY).

is_buy property

is_buy: bool

Whether this is a buy deal (DEAL_TYPE_BUY).

is_sell property

is_sell: bool

Whether this is a sell deal (DEAL_TYPE_SELL).


Service

HistoryService

HistoryService

Retrieves historical orders and deals from the MT5 trade history.

Wraps mt5.history_orders_total(), mt5.history_orders_get(), mt5.history_deals_total(), and mt5.history_deals_get() via call_mt5, parses raw structs into HistoricalOrder and Deal models, and returns Result[T].


Usage

from datetime import datetime, timezone

date_from = datetime(2024, 1, 1, tzinfo=timezone.utc)
date_to = datetime(2024, 1, 31, tzinfo=timezone.utc)

# Get historical orders
res = mt5.history_orders_get(date_from, date_to)

# Get historical deals
res = mt5.history_deals_get(date_from, date_to)

# Filter by position
res = mt5.history_deals_get(position=123456)