Mt5Client¶
pdmt5.mt5 ¶
MetaTrader5 client wrapper class.
Mt5Client ¶
Bases: BaseModel
MetaTrader5 client class.
This class provides a wrapper interface to all MetaTrader5 functions, delegating calls to the underlying MetaTrader5 module while providing error handling and logging capabilities.
model_config
class-attribute
instance-attribute
¶
mt5
class-attribute
instance-attribute
¶
mt5: ModuleType = Field(
default_factory=lambda: import_module("MetaTrader5"),
description="MetaTrader5 module instance",
)
__enter__ ¶
__exit__ ¶
account_info ¶
Get info on the current trading account.
Returns:
| Type | Description |
|---|---|
Any
|
AccountInfo structure. |
Source code in pdmt5/mt5.py
copy_rates_from ¶
Get bars from the terminal starting from the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
timeframe
|
int
|
Timeframe constant. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
count
|
int
|
Number of bars to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of rates. |
Source code in pdmt5/mt5.py
copy_rates_from_pos ¶
Get bars from the terminal starting from the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
timeframe
|
int
|
Timeframe constant. |
required |
start_pos
|
int
|
Starting position. |
required |
count
|
int
|
Number of bars to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of rates. |
Source code in pdmt5/mt5.py
copy_rates_range ¶
copy_rates_range(
symbol: str,
timeframe: int,
date_from: datetime | int,
date_to: datetime | int,
) -> Any
Get bars in the specified date range from the terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
timeframe
|
int
|
Timeframe constant. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of rates. |
Source code in pdmt5/mt5.py
copy_ticks_from ¶
Get ticks from the terminal starting from the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
count
|
int
|
Number of ticks to retrieve. |
required |
flags
|
int
|
Tick flags. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of ticks. |
Source code in pdmt5/mt5.py
copy_ticks_range ¶
copy_ticks_range(
symbol: str,
date_from: datetime | int,
date_to: datetime | int,
flags: int,
) -> Any
Get ticks for the specified date range from the terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
flags
|
int
|
Tick flags. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of ticks. |
Source code in pdmt5/mt5.py
history_deals_get ¶
history_deals_get(
date_from: datetime | int | None = None,
date_to: datetime | int | None = None,
group: str | None = None,
ticket: int | None = None,
position: int | None = None,
) -> tuple[Any, ...]
Get deals from trading history within the specified interval with the ability to filter by ticket, position, or group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int | None
|
Start date or timestamp in trade-server time (not UTC). |
None
|
date_to
|
datetime | int | None
|
End date or timestamp in trade-server time (not UTC). |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with ticket and position. |
None
|
ticket
|
int | None
|
Order ticket filter. Mutually exclusive with other filters. |
None
|
position
|
int | None
|
Position ticket filter. Mutually exclusive with other filters. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of historical deal info structures. |
Source code in pdmt5/mt5.py
history_deals_total ¶
Get the number of deals in trading history within the specified interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of historical deals. |
Source code in pdmt5/mt5.py
history_orders_get ¶
history_orders_get(
date_from: datetime | int | None = None,
date_to: datetime | int | None = None,
group: str | None = None,
ticket: int | None = None,
position: int | None = None,
) -> tuple[Any, ...]
Get orders from trading history with the ability to filter by ticket, position, or group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int | None
|
Start date or timestamp in trade-server time (not UTC). |
None
|
date_to
|
datetime | int | None
|
End date or timestamp in trade-server time (not UTC). |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with ticket and position. |
None
|
ticket
|
int | None
|
Order ticket filter. Mutually exclusive with other filters. |
None
|
position
|
int | None
|
Position ticket filter. Mutually exclusive with other filters. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of historical order info structures. |
Source code in pdmt5/mt5.py
history_orders_total ¶
Get the number of orders in trading history within the specified interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of historical orders. |
Source code in pdmt5/mt5.py
initialize ¶
initialize(
path: str | None = None,
login: int | None = None,
password: str | SecretStr | None = None,
server: str | None = None,
timeout: int | None = None,
) -> bool
Establish a connection with the MetaTrader 5 terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to the MetaTrader 5 terminal EXE file. |
None
|
login
|
int | None
|
Trading account number. |
None
|
password
|
str | SecretStr | None
|
Trading account password. |
None
|
server
|
str | None
|
Trade server address. |
None
|
timeout
|
int | None
|
Connection timeout in milliseconds. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
last_error ¶
Return data on the last error.
Returns:
| Type | Description |
|---|---|
tuple[int, str]
|
Tuple of (error_code, error_description). |
login ¶
login(
login: int,
password: str | SecretStr | None = None,
server: str | None = None,
timeout: int | None = None,
) -> bool
Connect to a trading account using specified parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
login
|
int
|
Trading account number. |
required |
password
|
str | SecretStr | None
|
Trading account password. |
None
|
server
|
str | None
|
Trade server address. |
None
|
timeout
|
int | None
|
Connection timeout in milliseconds. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
market_book_add ¶
Subscribe the terminal to the Market Depth change events for a specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
market_book_get ¶
Return a tuple from BookInfo featuring Market Depth entries for the specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of BookInfo structures. |
Source code in pdmt5/mt5.py
market_book_release ¶
Cancels subscription of the terminal to the Market Depth change events for a specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
order_calc_margin ¶
Return margin in the account currency to perform a specified trading operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
int
|
Order type (ORDER_TYPE_BUY or ORDER_TYPE_SELL). |
required |
symbol
|
str
|
Symbol name. |
required |
volume
|
float
|
Volume in lots. |
required |
price
|
float
|
Open price. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Required margin amount. |
Source code in pdmt5/mt5.py
order_calc_profit ¶
order_calc_profit(
action: int,
symbol: str,
volume: float,
price_open: float,
price_close: float,
) -> float
Return profit in the account currency for a specified trading operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
int
|
Order type (ORDER_TYPE_BUY or ORDER_TYPE_SELL). |
required |
symbol
|
str
|
Symbol name. |
required |
volume
|
float
|
Volume in lots. |
required |
price_open
|
float
|
Open price. |
required |
price_close
|
float
|
Close price. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Calculated profit. |
Source code in pdmt5/mt5.py
order_check ¶
Check funds sufficiency for performing a required trading operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
dict[str, Any]
|
Trade request dictionary. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
OrderCheckResult structure. |
Source code in pdmt5/mt5.py
order_send ¶
Send a request to perform a trading operation from the terminal to the trade server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
dict[str, Any]
|
Trade request dictionary. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
OrderSendResult structure. |
Source code in pdmt5/mt5.py
orders_get ¶
orders_get(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
) -> tuple[Any, ...]
Get active orders with the ability to filter by symbol, group, or ticket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str | None
|
Symbol name filter. Mutually exclusive with group and ticket. |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with symbol and ticket. |
None
|
ticket
|
int | None
|
Order ticket filter. Mutually exclusive with symbol and group. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of order info structures. |
Source code in pdmt5/mt5.py
orders_total ¶
Get the number of active orders.
Returns:
| Type | Description |
|---|---|
int
|
Number of active orders. |
Source code in pdmt5/mt5.py
positions_get ¶
positions_get(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
) -> tuple[Any, ...]
Get open positions with the ability to filter by symbol, group, or ticket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str | None
|
Symbol name filter. Mutually exclusive with group and ticket. |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with symbol and ticket. |
None
|
ticket
|
int | None
|
Position ticket filter. Mutually exclusive with symbol and group. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of position info structures. |
Source code in pdmt5/mt5.py
positions_total ¶
Get the number of open positions.
Returns:
| Type | Description |
|---|---|
int
|
Number of open positions. |
Source code in pdmt5/mt5.py
shutdown ¶
Close the previously established connection to the MetaTrader 5 terminal.
Source code in pdmt5/mt5.py
symbol_info ¶
Get data on the specified financial instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Symbol info structure. |
Source code in pdmt5/mt5.py
symbol_info_tick ¶
Get the last tick for the specified financial instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Tick info structure. |
Source code in pdmt5/mt5.py
symbol_select ¶
Select a symbol in the MarketWatch window or remove a symbol from the window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
enable
|
bool
|
True to show, False to hide. |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
symbols_get ¶
Get all financial instruments from the terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str | None
|
Symbol group filter. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of symbol info structures. |
Source code in pdmt5/mt5.py
symbols_total ¶
Get the number of all financial instruments in the terminal.
Returns:
| Type | Description |
|---|---|
int
|
Total number of symbols. |
Source code in pdmt5/mt5.py
terminal_info ¶
Get the connected MetaTrader 5 client terminal status and settings.
Returns:
| Type | Description |
|---|---|
Any
|
TerminalInfo structure. |
Source code in pdmt5/mt5.py
version ¶
Return the MetaTrader 5 terminal version.
Returns:
| Type | Description |
|---|---|
tuple[int, int, str]
|
Tuple of (terminal_version, build, release_date). |
Source code in pdmt5/mt5.py
Mt5RuntimeError ¶
Bases: RuntimeError
MetaTrader5 specific runtime error.
Raised when MetaTrader5 operations fail or when the client is used incorrectly (e.g., calling methods before initialization).
Overview¶
The Mt5Client module provides the base client class for connecting to MetaTrader 5 and performing core operations. This is the foundation class that handles the low-level MT5 API interactions and provides basic error handling and connection management.
Classes¶
Mt5Client¶
pdmt5.mt5.Mt5Client ¶
Bases: BaseModel
MetaTrader5 client class.
This class provides a wrapper interface to all MetaTrader5 functions, delegating calls to the underlying MetaTrader5 module while providing error handling and logging capabilities.
model_config
class-attribute
instance-attribute
¶
mt5
class-attribute
instance-attribute
¶
mt5: ModuleType = Field(
default_factory=lambda: import_module("MetaTrader5"),
description="MetaTrader5 module instance",
)
__enter__ ¶
__exit__ ¶
account_info ¶
Get info on the current trading account.
Returns:
| Type | Description |
|---|---|
Any
|
AccountInfo structure. |
Source code in pdmt5/mt5.py
copy_rates_from ¶
Get bars from the terminal starting from the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
timeframe
|
int
|
Timeframe constant. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
count
|
int
|
Number of bars to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of rates. |
Source code in pdmt5/mt5.py
copy_rates_from_pos ¶
Get bars from the terminal starting from the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
timeframe
|
int
|
Timeframe constant. |
required |
start_pos
|
int
|
Starting position. |
required |
count
|
int
|
Number of bars to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of rates. |
Source code in pdmt5/mt5.py
copy_rates_range ¶
copy_rates_range(
symbol: str,
timeframe: int,
date_from: datetime | int,
date_to: datetime | int,
) -> Any
Get bars in the specified date range from the terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
timeframe
|
int
|
Timeframe constant. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of rates. |
Source code in pdmt5/mt5.py
copy_ticks_from ¶
Get ticks from the terminal starting from the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
count
|
int
|
Number of ticks to retrieve. |
required |
flags
|
int
|
Tick flags. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of ticks. |
Source code in pdmt5/mt5.py
copy_ticks_range ¶
copy_ticks_range(
symbol: str,
date_from: datetime | int,
date_to: datetime | int,
flags: int,
) -> Any
Get ticks for the specified date range from the terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
flags
|
int
|
Tick flags. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Array of ticks. |
Source code in pdmt5/mt5.py
history_deals_get ¶
history_deals_get(
date_from: datetime | int | None = None,
date_to: datetime | int | None = None,
group: str | None = None,
ticket: int | None = None,
position: int | None = None,
) -> tuple[Any, ...]
Get deals from trading history within the specified interval with the ability to filter by ticket, position, or group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int | None
|
Start date or timestamp in trade-server time (not UTC). |
None
|
date_to
|
datetime | int | None
|
End date or timestamp in trade-server time (not UTC). |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with ticket and position. |
None
|
ticket
|
int | None
|
Order ticket filter. Mutually exclusive with other filters. |
None
|
position
|
int | None
|
Position ticket filter. Mutually exclusive with other filters. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of historical deal info structures. |
Source code in pdmt5/mt5.py
history_deals_total ¶
Get the number of deals in trading history within the specified interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of historical deals. |
Source code in pdmt5/mt5.py
history_orders_get ¶
history_orders_get(
date_from: datetime | int | None = None,
date_to: datetime | int | None = None,
group: str | None = None,
ticket: int | None = None,
position: int | None = None,
) -> tuple[Any, ...]
Get orders from trading history with the ability to filter by ticket, position, or group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int | None
|
Start date or timestamp in trade-server time (not UTC). |
None
|
date_to
|
datetime | int | None
|
End date or timestamp in trade-server time (not UTC). |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with ticket and position. |
None
|
ticket
|
int | None
|
Order ticket filter. Mutually exclusive with other filters. |
None
|
position
|
int | None
|
Position ticket filter. Mutually exclusive with other filters. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of historical order info structures. |
Source code in pdmt5/mt5.py
history_orders_total ¶
Get the number of orders in trading history within the specified interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime | int
|
Start date or timestamp in trade-server time (not UTC). |
required |
date_to
|
datetime | int
|
End date or timestamp in trade-server time (not UTC). |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of historical orders. |
Source code in pdmt5/mt5.py
initialize ¶
initialize(
path: str | None = None,
login: int | None = None,
password: str | SecretStr | None = None,
server: str | None = None,
timeout: int | None = None,
) -> bool
Establish a connection with the MetaTrader 5 terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to the MetaTrader 5 terminal EXE file. |
None
|
login
|
int | None
|
Trading account number. |
None
|
password
|
str | SecretStr | None
|
Trading account password. |
None
|
server
|
str | None
|
Trade server address. |
None
|
timeout
|
int | None
|
Connection timeout in milliseconds. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
last_error ¶
Return data on the last error.
Returns:
| Type | Description |
|---|---|
tuple[int, str]
|
Tuple of (error_code, error_description). |
login ¶
login(
login: int,
password: str | SecretStr | None = None,
server: str | None = None,
timeout: int | None = None,
) -> bool
Connect to a trading account using specified parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
login
|
int
|
Trading account number. |
required |
password
|
str | SecretStr | None
|
Trading account password. |
None
|
server
|
str | None
|
Trade server address. |
None
|
timeout
|
int | None
|
Connection timeout in milliseconds. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
market_book_add ¶
Subscribe the terminal to the Market Depth change events for a specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
market_book_get ¶
Return a tuple from BookInfo featuring Market Depth entries for the specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of BookInfo structures. |
Source code in pdmt5/mt5.py
market_book_release ¶
Cancels subscription of the terminal to the Market Depth change events for a specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
order_calc_margin ¶
Return margin in the account currency to perform a specified trading operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
int
|
Order type (ORDER_TYPE_BUY or ORDER_TYPE_SELL). |
required |
symbol
|
str
|
Symbol name. |
required |
volume
|
float
|
Volume in lots. |
required |
price
|
float
|
Open price. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Required margin amount. |
Source code in pdmt5/mt5.py
order_calc_profit ¶
order_calc_profit(
action: int,
symbol: str,
volume: float,
price_open: float,
price_close: float,
) -> float
Return profit in the account currency for a specified trading operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
int
|
Order type (ORDER_TYPE_BUY or ORDER_TYPE_SELL). |
required |
symbol
|
str
|
Symbol name. |
required |
volume
|
float
|
Volume in lots. |
required |
price_open
|
float
|
Open price. |
required |
price_close
|
float
|
Close price. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Calculated profit. |
Source code in pdmt5/mt5.py
order_check ¶
Check funds sufficiency for performing a required trading operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
dict[str, Any]
|
Trade request dictionary. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
OrderCheckResult structure. |
Source code in pdmt5/mt5.py
order_send ¶
Send a request to perform a trading operation from the terminal to the trade server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
dict[str, Any]
|
Trade request dictionary. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
OrderSendResult structure. |
Source code in pdmt5/mt5.py
orders_get ¶
orders_get(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
) -> tuple[Any, ...]
Get active orders with the ability to filter by symbol, group, or ticket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str | None
|
Symbol name filter. Mutually exclusive with group and ticket. |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with symbol and ticket. |
None
|
ticket
|
int | None
|
Order ticket filter. Mutually exclusive with symbol and group. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of order info structures. |
Source code in pdmt5/mt5.py
orders_total ¶
Get the number of active orders.
Returns:
| Type | Description |
|---|---|
int
|
Number of active orders. |
Source code in pdmt5/mt5.py
positions_get ¶
positions_get(
symbol: str | None = None,
group: str | None = None,
ticket: int | None = None,
) -> tuple[Any, ...]
Get open positions with the ability to filter by symbol, group, or ticket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str | None
|
Symbol name filter. Mutually exclusive with group and ticket. |
None
|
group
|
str | None
|
Group filter. Mutually exclusive with symbol and ticket. |
None
|
ticket
|
int | None
|
Position ticket filter. Mutually exclusive with symbol and group. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of position info structures. |
Source code in pdmt5/mt5.py
positions_total ¶
Get the number of open positions.
Returns:
| Type | Description |
|---|---|
int
|
Number of open positions. |
Source code in pdmt5/mt5.py
shutdown ¶
Close the previously established connection to the MetaTrader 5 terminal.
Source code in pdmt5/mt5.py
symbol_info ¶
Get data on the specified financial instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Symbol info structure. |
Source code in pdmt5/mt5.py
symbol_info_tick ¶
Get the last tick for the specified financial instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Tick info structure. |
Source code in pdmt5/mt5.py
symbol_select ¶
Select a symbol in the MarketWatch window or remove a symbol from the window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name. |
required |
enable
|
bool
|
True to show, False to hide. |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise. |
Source code in pdmt5/mt5.py
symbols_get ¶
Get all financial instruments from the terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str | None
|
Symbol group filter. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of symbol info structures. |
Source code in pdmt5/mt5.py
symbols_total ¶
Get the number of all financial instruments in the terminal.
Returns:
| Type | Description |
|---|---|
int
|
Total number of symbols. |
Source code in pdmt5/mt5.py
terminal_info ¶
Get the connected MetaTrader 5 client terminal status and settings.
Returns:
| Type | Description |
|---|---|
Any
|
TerminalInfo structure. |
Source code in pdmt5/mt5.py
version ¶
Return the MetaTrader 5 terminal version.
Returns:
| Type | Description |
|---|---|
tuple[int, int, str]
|
Tuple of (terminal_version, build, release_date). |
Source code in pdmt5/mt5.py
options: show_bases: false
Base client class for MetaTrader 5 operations with connection management and error handling.
Mt5RuntimeError¶
pdmt5.mt5.Mt5RuntimeError ¶
Bases: RuntimeError
MetaTrader5 specific runtime error.
Raised when MetaTrader5 operations fail or when the client is used incorrectly (e.g., calling methods before initialization).
options: show_bases: false
Custom runtime exception for MetaTrader 5 specific errors.
Usage Examples¶
Basic Connection¶
import MetaTrader5 as mt5
from pdmt5.mt5 import Mt5Client
# Create client
client = Mt5Client(mt5=mt5)
# Use as context manager: entering the block initializes the connection
# and raises Mt5RuntimeError if initialization fails
with client:
print("Connected to MetaTrader 5")
# Get version info
version = client.version()
print(f"MT5 Version: {version}")
# Get account info
account = client.account_info()
print(f"Account: {account}")
Connection with Login¶
with client:
# The context manager already initialized the connection;
# log in to a specific account
success = client.login(
login=12345, password="your_password", server="broker_server"
)
if success:
print("Logged in successfully")
# To initialize with custom arguments (e.g. a terminal path), call
# initialize() explicitly instead of relying on the context manager entry
client.initialize(path="C:\\Program Files\\MetaTrader 5\\terminal64.exe")
try:
...
finally:
client.shutdown()
Symbol Operations¶
with client:
# Get total number of symbols
total = client.symbols_total()
print(f"Total symbols: {total}")
# Get all symbols
symbols = client.symbols_get()
print(f"First 5 symbols: {symbols[:5]}")
# Get symbols by group
forex_symbols = client.symbols_get(group="*USD*")
# Get specific symbol info
symbol_info = client.symbol_info("EURUSD")
print(f"EURUSD info: {symbol_info}")
# Get current tick
tick = client.symbol_info_tick("EURUSD")
print(f"Current EURUSD tick: {tick}")
Market Data Retrieval¶
from datetime import datetime
import MetaTrader5 as mt5
with client:
# Get OHLCV rates from specific date
rates = client.copy_rates_from(
symbol="EURUSD",
timeframe=mt5.TIMEFRAME_H1,
date_from=datetime(2024, 1, 1),
count=100,
)
# Get rates within date range
rates_range = client.copy_rates_range(
symbol="EURUSD",
timeframe=mt5.TIMEFRAME_D1,
date_from=datetime(2024, 1, 1),
date_to=datetime(2024, 1, 31),
)
# Get tick data
ticks = client.copy_ticks_from(
symbol="EURUSD",
date_from=datetime(2024, 1, 1),
count=1000,
flags=mt5.COPY_TICKS_ALL,
)
Trading Operations¶
with client:
client.login(12345, "password", "server")
# Get current positions
positions = client.positions_get()
print(f"Open positions: {len(positions) if positions else 0}")
# Get current orders
orders = client.orders_get()
print(f"Pending orders: {len(orders) if orders else 0}")
# Calculate margin requirement
margin = client.order_calc_margin(
action=mt5.ORDER_TYPE_BUY, symbol="EURUSD", volume=1.0, price=1.1000
)
print(f"Required margin: {margin}")
# Calculate profit
profit = client.order_calc_profit(
action=mt5.ORDER_TYPE_BUY,
symbol="EURUSD",
volume=1.0,
price_open=1.1000,
price_close=1.1050,
)
print(f"Calculated profit: {profit}")
Historical Data¶
from datetime import datetime
with client:
# Get historical orders
history_orders = client.history_orders_get(
date_from=datetime(2024, 1, 1), date_to=datetime(2024, 1, 31)
)
# Get historical deals
history_deals = client.history_deals_get(
date_from=datetime(2024, 1, 1), date_to=datetime(2024, 1, 31)
)
# Get specific order by ticket
order = client.history_orders_get(ticket=123456)
Market Book Operations¶
with client:
# Subscribe to market depth
success = client.market_book_add("EURUSD")
if success:
print("Subscribed to EURUSD market depth")
# Get market book
book = client.market_book_get("EURUSD")
print(f"Market book: {book}")
# Unsubscribe
client.market_book_release("EURUSD")
Connection Management¶
The Mt5Client supports both explicit and context manager usage:
# Explicit initialization
client = Mt5Client(mt5=mt5)
client.initialize()
try:
# Your trading operations
account = client.account_info()
finally:
client.shutdown()
# Context manager (recommended): initializes on entry, shuts down on exit,
# and raises Mt5RuntimeError if initialization fails
with Mt5Client(mt5=mt5) as client:
# Your trading operations
account = client.account_info()
Error Handling¶
Data-retrieval and trading methods raise Mt5RuntimeError with detailed information when the terminal reports a failure (for example, a None response or a failed initialization):
from pdmt5.mt5 import Mt5RuntimeError
try:
with client:
rates = client.copy_rates_from("INVALID", mt5.TIMEFRAME_H1, datetime.now(), 100)
except Mt5RuntimeError as e:
print(f"MetaTrader 5 error: {e}")
Entering the context manager also raises Mt5RuntimeError when the terminal
cannot be initialized, and invalid argument combinations (e.g. mutually
exclusive filters) raise ValueError.
Logging¶
The client includes comprehensive logging for all operations. Operations are logged at INFO level, and non-OK MT5 status codes at WARNING level:
import logging
# Enable INFO logging to see all MT5 operations
logging.basicConfig(level=logging.INFO)
with client: # Entry logs the initialization details
account = client.account_info() # Will log account retrieval
Method Categories¶
Connection Management¶
initialize()- Initialize MT5 connectionlogin()- Login to trading accountshutdown()- Close connectionversion()- Get MT5 versionlast_error()- Get last error details
Account & Terminal¶
account_info()- Get account informationterminal_info()- Get terminal status and settings
Symbol Management¶
symbols_total()- Get total number of symbolssymbols_get()- Get symbol listsymbol_info()- Get symbol informationsymbol_info_tick()- Get current ticksymbol_select()- Add/remove symbol from Market Watch
Market Data¶
copy_rates_from()- Get OHLCV rates from datecopy_rates_from_pos()- Get OHLCV rates from positioncopy_rates_range()- Get OHLCV rates in date rangecopy_ticks_from()- Get ticks from datecopy_ticks_range()- Get ticks in date range
Market Book¶
market_book_add()- Subscribe to market depthmarket_book_release()- Unsubscribe from market depthmarket_book_get()- Get market book data
Trading¶
orders_total()- Get number of pending ordersorders_get()- Get pending orderspositions_total()- Get number of open positionspositions_get()- Get open positionsorder_calc_margin()- Calculate required marginorder_calc_profit()- Calculate profitorder_check()- Validate order requestorder_send()- Send trading order
History¶
history_orders_total()- Get historical orders counthistory_orders_get()- Get historical ordershistory_deals_total()- Get historical deals counthistory_deals_get()- Get historical deals
Best Practices¶
- Always use context manager for automatic connection management -
entering the
withblock initializes the connection and raisesMt5RuntimeErroron failure - Handle errors gracefully with try-except blocks
- Call
initialize()explicitly only outside the context manager - for example to pass a terminal path; pair it withshutdown() - Use logging (INFO level) to debug connection and operation issues
- Expect exceptions on failure - data accessors raise
Mt5RuntimeErrorwhen MT5 returns None, and conflicting filter arguments raiseValueError - Use appropriate timeframes and date ranges for data requests
- Subscribe/unsubscribe to market book properly to avoid resource leaks