Trading Module¶
mt5cli.trading ¶
Trading-capable MetaTrader 5 session helpers and operational utilities.
ExecutionStatus
module-attribute
¶
OrderTimeMode
module-attribute
¶
POSITION_COLUMNS
module-attribute
¶
POSITION_COLUMNS = (
"ticket",
"time",
"symbol",
"type",
"volume",
"price_open",
"sl",
"tp",
"price_current",
"profit",
"swap",
"comment",
)
__all__
module-attribute
¶
__all__ = [
"POSITION_COLUMNS",
"ExecutionStatus",
"MarginVolume",
"OrderExecutionResult",
"OrderFillingMode",
"OrderLimits",
"OrderSide",
"OrderTimeMode",
"PositionSide",
"ProjectionMode",
"calculate_account_projected_margin_ratio",
"calculate_margin_and_volume",
"calculate_new_position_margin_ratio",
"calculate_positions_margin",
"calculate_positions_margin_by_symbol",
"calculate_positions_margin_safe",
"calculate_projected_margin_ratio",
"calculate_spread_ratio",
"calculate_symbol_group_margin_ratio",
"calculate_trailing_stop_updates",
"calculate_volume_by_margin",
"close_open_positions",
"create_trading_client",
"detect_position_side",
"determine_order_limits",
"ensure_symbol_selected",
"estimate_order_margin",
"extract_tick_price",
"fetch_latest_closed_rates_for_trading_client",
"fetch_latest_closed_rates_indexed",
"fetch_recent_history_deals_for_trading_client",
"get_account_snapshot",
"get_positions_frame",
"get_symbol_snapshot",
"get_tick_snapshot",
"mt5_trading_session",
"normalize_order_volume",
"place_market_order",
"update_sltp_for_open_positions",
"update_trailing_stop_loss_for_open_positions",
]
MarginVolume ¶
Bases: TypedDict
Affordable volume bounds derived from account margin and symbol constraints.
OrderExecutionResult ¶
Bases: TypedDict
Normalized result from market-order and position-management helpers.
OrderLimits ¶
calculate_account_projected_margin_ratio ¶
calculate_account_projected_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbol: str | None = None,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
) -> float
Return account-wide current plus optional new-position margin over equity.
Current exposure comes from the broker account snapshot margin field so
unrelated open positions remain in the baseline. Optional projected
exposure is added via :func:estimate_order_margin only when a symbol, side,
and positive volume are all supplied.
Source code in mt5cli/trading.py
calculate_margin_and_volume ¶
calculate_margin_and_volume(
client: _Mt5ClientProtocol,
symbol: str,
unit_margin_ratio: float,
preserved_margin_ratio: float,
) -> MarginVolume
Calculate tradable margin and volumes from account free margin.
Applies preserved_margin_ratio to keep a reserve off margin_free,
then allocates unit_margin_ratio of the remainder as the margin budget
for proportional volume sizing on both buy and sell sides. A
unit_margin_ratio of 0 requests exactly one minimum valid unit per
side when the post-reserve margin can afford it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol used for minimum-lot margin and volume calculations. |
required |
unit_margin_ratio
|
float
|
Fraction of post-reserve margin to allocate per unit. |
required |
preserved_margin_ratio
|
float
|
Fraction of |
required |
Returns:
| Type | Description |
|---|---|
MarginVolume
|
Dictionary with |
MarginVolume
|
|
MarginVolume
|
clamped to |
Source code in mt5cli/trading.py
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 | |
calculate_new_position_margin_ratio ¶
calculate_new_position_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbol: str,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
) -> float
Return total margin/equity ratio after an optional hypothetical position.
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If equity or required tick data is invalid. |
Source code in mt5cli/trading.py
calculate_positions_margin ¶
calculate_positions_margin(
client: _Mt5ClientProtocol,
*,
symbols: Sequence[str] | None = None,
) -> float
Return the sum of estimated current margin for open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbols
|
Sequence[str] | None
|
Optional symbol filter. When omitted, all open positions are included. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Total estimated margin, or |
Source code in mt5cli/trading.py
calculate_positions_margin_by_symbol ¶
calculate_positions_margin_by_symbol(
client: _Mt5ClientProtocol,
*,
symbols: Sequence[str],
suppress_errors: bool = True,
) -> dict[str, float]
Return per-symbol estimated margin for open positions.
Computes margin for each unique input symbol independently using the strict
:func:calculate_positions_margin helper. Duplicates are deduplicated in
first-seen order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbols
|
Sequence[str]
|
Symbols to compute margin for. |
required |
suppress_errors
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Mapping of symbol to margin total in first-seen unique-symbol order. |
dict[str, float]
|
Returns an empty dict when |
dict[str, float]
|
with |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
When a symbol raises |
Mt5RuntimeError
|
When a symbol raises |
AttributeError
|
When a symbol raises |
Source code in mt5cli/trading.py
calculate_positions_margin_safe ¶
Return the total estimated margin for open positions across symbols.
Internally calls :func:calculate_positions_margin_by_symbol with
suppress_errors=True. Failed symbols are silently skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbols
|
Sequence[str]
|
Symbols to include. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Sum of per-symbol margins; |
Source code in mt5cli/trading.py
calculate_projected_margin_ratio ¶
calculate_projected_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbol: str,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
) -> float
Return estimated current plus optional new-position margin over equity.
Current exposure is estimated from open positions with
:func:calculate_positions_margin. Optional projected exposure is added via
:func:estimate_order_margin. Thresholds and guard actions are intentionally
left to downstream applications.
Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller.
Source code in mt5cli/trading.py
calculate_spread_ratio ¶
Return (ask - bid) / ((ask + bid) / 2) for the latest tick.
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If bid or ask is unavailable. |
Source code in mt5cli/trading.py
calculate_symbol_group_margin_ratio ¶
calculate_symbol_group_margin_ratio(
client: _Mt5ClientProtocol,
*,
symbols: Sequence[str],
new_symbol: str | None = None,
new_position_side: OrderSide | None = None,
new_position_volume: float = 0.0,
suppress_errors: bool = True,
projection_mode: ProjectionMode = "add",
) -> float
Return estimated symbol-group margin over account equity.
Per-symbol current exposure is summed with
:func:calculate_positions_margin_by_symbol. When new_symbol is inside
the input symbol group and candidate side/volume are provided, projected order
margin is applied according to projection_mode:
"add"(default): adds candidate margin to the group total."replace_symbol": subtracts current margin fornew_symbol, then adds candidate margin. Useful for reversal-style projections where the new order is intended to replace existing exposure for that symbol.
If the candidate margin estimation fails, the subtraction is also skipped so the operation is atomic. Invalid equity always raises to fail closed.
Raises:
| Type | Description |
|---|---|
AttributeError
|
When symbol margin lookup or projected margin lookup
fails and |
Mt5RuntimeError
|
When symbol margin lookup or projected margin lookup
fails and |
Mt5OperationError
|
When account equity is invalid, or when symbol margin
lookup or projected margin lookup fails and |
Source code in mt5cli/trading.py
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 | |
calculate_trailing_stop_updates ¶
calculate_trailing_stop_updates(
client: _Mt5ClientProtocol,
*,
symbol: str,
trailing_stop_ratio: float,
) -> dict[int, float]
Return per-ticket trailing stop-loss updates for open symbol positions.
Buy positions trail from bid using bid * (1 - trailing_stop_ratio).
Sell positions trail from ask using ask * (1 + trailing_stop_ratio).
Existing stop losses are preserved when they are already more favorable.
Missing symbol metadata returns an empty update map. Positions with a
missing side-specific tick price are skipped.
Source code in mt5cli/trading.py
calculate_volume_by_margin ¶
calculate_volume_by_margin(
client: _Mt5ClientProtocol,
symbol: str,
available_margin: float,
order_side: OrderSide,
) -> float
Calculate max normalized volume affordable for one side.
Returns:
| Type | Description |
|---|---|
float
|
Largest stepped volume whose actual margin (from |
float
|
fits within |
float
|
constraints; |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If symbol volume constraints or tick data are invalid. |
Source code in mt5cli/trading.py
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 | |
close_open_positions ¶
close_open_positions(
client: _Mt5ClientProtocol,
*,
symbols: str | list[str] | None = None,
tickets: list[int] | None = None,
dry_run: bool = False,
) -> list[OrderExecutionResult]
Close matching open positions.
Returns:
| Type | Description |
|---|---|
list[OrderExecutionResult]
|
Normalized execution results for matching positions. |
Source code in mt5cli/trading.py
create_trading_client ¶
create_trading_client(
*,
config: Mt5Config | None = None,
login: int | str | None = None,
password: str | None = None,
server: str | None = None,
path: str | None = None,
timeout: int | None = None,
retry_count: int = 0,
) -> _TradingHistoryDealsClientProtocol
Return an initialized and logged-in trading client.
The returned object is a raw pdmt5.Mt5DataClient instance, not the
higher-level mt5cli.MT5Client wrapper. Use mt5_session() /
MT5Client for read-only data collection. For live trading helpers
(margin, volume, order execution, position management) pass the returned
client to the strategy-agnostic helpers in this module.
For history deal retrieval use
:func:fetch_recent_history_deals_for_trading_client; the returned client
satisfies :class:_HistoryDealsClientProtocol so no additional wrapping is
required.
Returns:
| Type | Description |
|---|---|
_TradingHistoryDealsClientProtocol
|
A |
_TradingHistoryDealsClientProtocol
|
and |
_TradingHistoryDealsClientProtocol
|
|
_TradingHistoryDealsClientProtocol
|
manage lifetime automatically. |
Source code in mt5cli/trading.py
detect_position_side ¶
detect_position_side(
client: _Mt5ClientProtocol, symbol: str
) -> PositionSide | None
Detect the net open position side for a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol to inspect. |
required |
Returns:
| Type | Description |
|---|---|
PositionSide | None
|
|
PositionSide | None
|
|
PositionSide | None
|
|
Source code in mt5cli/trading.py
determine_order_limits ¶
determine_order_limits(
client: _Mt5ClientProtocol,
symbol: str,
side: PositionSide | str,
stop_loss_limit_ratio: float | None = None,
take_profit_limit_ratio: float | None = None,
) -> OrderLimits
Derive entry and protective order prices from current market quotes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol used for the quote lookup. |
required |
side
|
PositionSide | str
|
Position side as |
required |
stop_loss_limit_ratio
|
float | None
|
Relative distance from entry for stop loss in
|
None
|
take_profit_limit_ratio
|
float | None
|
Relative distance from entry for take profit in
|
None
|
Returns:
| Type | Description |
|---|---|
OrderLimits
|
Dictionary with |
OrderLimits
|
Omitted protective levels are returned as |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If required tick data is invalid or computed SL/TP
prices violate available |
Source code in mt5cli/trading.py
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 | |
ensure_symbol_selected ¶
Ensure a symbol is visible in Market Watch before sending orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected MT5 client instance. |
required |
symbol
|
str
|
Symbol to select. |
required |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If the symbol cannot be selected in Market Watch or
|
Source code in mt5cli/trading.py
estimate_order_margin ¶
estimate_order_margin(
client: _Mt5ClientProtocol,
symbol: str,
order_side: OrderSide | str,
volume: float,
) -> float
Estimate required margin for one order at the current market price.
Returns:
| Type | Description |
|---|---|
float
|
Positive finite margin required for the order at the current quote. |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If volume, tick data, or margin estimation is invalid. |
Source code in mt5cli/trading.py
extract_tick_price ¶
Return a positive finite float from tick[key], or None if invalid.
Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None.
Source code in mt5cli/trading.py
fetch_latest_closed_rates_for_trading_client ¶
fetch_latest_closed_rates_for_trading_client(
client: _Mt5ClientProtocol,
*,
symbol: str,
granularity: str,
count: int,
) -> DataFrame
Fetch the latest closed bars from a connected trading client.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Up to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Mt5OperationError
|
If the trading client cannot fetch rate data. |
Source code in mt5cli/trading.py
fetch_latest_closed_rates_indexed ¶
fetch_latest_closed_rates_indexed(
client: _Mt5ClientProtocol,
*,
symbol: str,
granularity: str,
count: int,
) -> DataFrame
Fetch the latest closed bars with a UTC DatetimeIndex from a trading client.
Internally reuses :func:fetch_latest_closed_rates_for_trading_client for
closed-bar detection and validation, then converts the time column to a
UTC-aware :class:~pandas.DatetimeIndex named "time" and drops the
original column. Intended for downstream time-series consumers that require
a datetime index rather than a time column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_Mt5ClientProtocol
|
Connected trading client with rate-fetch capability. |
required |
symbol
|
str
|
Symbol name. |
required |
granularity
|
str
|
Timeframe string (for example |
required |
count
|
int
|
Maximum number of closed bars to return. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Up to |
DataFrame
|
UTC-aware |
DataFrame
|
column is dropped. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mt5cli/trading.py
fetch_recent_history_deals_for_trading_client ¶
fetch_recent_history_deals_for_trading_client(
client: _HistoryDealsClientProtocol,
*,
symbol: str | None = None,
group: str | None = None,
hours: float = 24.0,
date_to: datetime | None = None,
) -> DataFrame
Fetch recent history deals from an already-connected trading client.
Computes a trailing window ending at date_to (or datetime.now(UTC)
when omitted) and delegates to the client's history_deals_get_as_df
method. The object returned by :func:create_trading_client (a raw
pdmt5.Mt5DataClient) satisfies this protocol directly. Note that
mt5cli.sdk.Mt5CliClient (used via mt5_session()) exposes
history_deals(), not history_deals_get_as_df(), and therefore does
not satisfy this protocol; use this helper with trading-client sessions only.
The returned DataFrame preserves every column from the underlying client
(time, symbol, type, entry, volume, profit,
position_id, etc.). No strategy-specific transformations are applied;
downstream packages own entry/exit classification, Kelly fractions, and
any other betting or signal semantics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
_HistoryDealsClientProtocol
|
Connected |
required |
symbol
|
str | None
|
Optional symbol filter passed to the underlying client. |
None
|
group
|
str | None
|
Optional symbol group filter passed to the underlying client. |
None
|
hours
|
float
|
Trailing window length in hours. Must be positive. |
24.0
|
date_to
|
datetime | None
|
Window end timestamp. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame ordered chronologically by |
DataFrame
|
exists) with a |
DataFrame
|
(zero rows but columns present) are passed through with a reset |
DataFrame
|
index. Returns a bare empty DataFrame only when the underlying |
DataFrame
|
client returns |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example::
from mt5cli import (
create_trading_client,
fetch_recent_history_deals_for_trading_client,
)
client = create_trading_client(login=12345, server="Broker-Demo")
try:
deals_df = fetch_recent_history_deals_for_trading_client(
client,
symbol="JP225",
hours=24,
)
finally:
client.shutdown()
Source code in mt5cli/trading.py
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 | |
get_account_snapshot ¶
Return normalized account state with stable keys.
Source code in mt5cli/trading.py
get_positions_frame ¶
Return open positions as a DataFrame with stable baseline columns.
Source code in mt5cli/trading.py
get_symbol_snapshot ¶
get_symbol_snapshot(
client: _Mt5ClientProtocol, symbol: str
) -> dict[str, float | int | str | bool | None]
Return normalized symbol metadata required for trading decisions.
Source code in mt5cli/trading.py
get_tick_snapshot ¶
Return normalized latest tick data, including bid, ask, and timestamp.
Source code in mt5cli/trading.py
mt5_trading_session ¶
mt5_trading_session(
config: Mt5Config | None = None,
*,
login: int | str | None = None,
password: str | None = None,
server: str | None = None,
path: str | None = None,
timeout: int | None = None,
retry_count: int = 0,
) -> Iterator[_TradingHistoryDealsClientProtocol]
Open a trading-capable MT5 session and always shut down safely.
Launches the MetaTrader 5 terminal using Mt5Config.path when set,
initializes and logs in via initialize_and_login_mt5(), yields a
connected client supporting required MT5 methods, and calls shutdown()
on exit even when an error is raised inside the context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Mt5Config | None
|
MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. |
None
|
login
|
int | str | None
|
Optional trading account login. |
None
|
password
|
str | None
|
Optional trading account password. |
None
|
server
|
str | None
|
Optional trading server name. |
None
|
path
|
str | None
|
Optional terminal executable path. |
None
|
timeout
|
int | None
|
Optional connection timeout in milliseconds. |
None
|
retry_count
|
int
|
Number of initialization retries. |
0
|
Yields:
| Type | Description |
|---|---|
_TradingHistoryDealsClientProtocol
|
Connected client supporting required MT5 trading methods. |
Source code in mt5cli/trading.py
normalize_order_volume ¶
normalize_order_volume(
volume: float,
*,
volume_min: float,
volume_max: float,
volume_step: float,
) -> float
Normalize a requested order volume to broker volume constraints.
Returns:
| Type | Description |
|---|---|
float
|
Volume floored to the nearest valid broker step from |
float
|
capped at |
float
|
deterministically. Returns |
float
|
invalid, non-finite, or the capped request is below |
Source code in mt5cli/trading.py
place_market_order ¶
place_market_order(
client: _Mt5ClientProtocol,
*,
symbol: str,
volume: float,
order_side: OrderSide,
order_filling_mode: OrderFillingMode = "IOC",
order_time_mode: OrderTimeMode = "GTC",
sl: float | None = None,
tp: float | None = None,
position: int | None = None,
dry_run: bool = False,
) -> OrderExecutionResult
Place one normalized market order or return a dry-run result.
order_send() raises only when MT5 returns no response. When MT5 returns
a response with a known non-success retcode, this helper returns
status="failed" and keeps the normalized response details for callers
to inspect.
Returns:
| Type | Description |
|---|---|
OrderExecutionResult
|
Normalized execution result containing request and response details. |
Raises:
| Type | Description |
|---|---|
Mt5OperationError
|
If volume or required tick data is invalid. |
Source code in mt5cli/trading.py
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 | |
update_sltp_for_open_positions ¶
update_sltp_for_open_positions(
client: _Mt5ClientProtocol,
*,
symbol: str | None = None,
tickets: list[int] | None = None,
stop_loss: float | None = None,
take_profit: float | None = None,
dry_run: bool = False,
) -> list[OrderExecutionResult]
Update SL/TP for matching open positions.
Returns:
| Type | Description |
|---|---|
list[OrderExecutionResult]
|
Normalized execution results for matching positions. |
Source code in mt5cli/trading.py
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 | |
update_trailing_stop_loss_for_open_positions ¶
update_trailing_stop_loss_for_open_positions(
client: _Mt5ClientProtocol,
*,
symbol: str,
trailing_stop_ratio: float,
dry_run: bool = False,
) -> list[OrderExecutionResult]
Update open positions whose trailing stop loss should move favorably.
Returns:
| Type | Description |
|---|---|
list[OrderExecutionResult]
|
Normalized execution results for positions that need an SL update. |
Source code in mt5cli/trading.py
Trading-capable MT5 sessions¶
create_trading_client() and mt5_trading_session() complement the read-only
mt5_session() helper in sdk.py. They return or yield an initialized
client supporting order execution and account management, use Mt5Config.path
to launch the terminal when configured, and mt5_trading_session() always
calls shutdown() on exit.
create_trading_client() returns a raw pdmt5.Mt5DataClient instance, not the
higher-level MT5Client wrapper. Use mt5_session() / MT5Client for
read-only data collection; use mt5_trading_session() only where order
placement or trading calculations are required.
from mt5cli import create_trading_client, mt5_trading_session
with mt5_trading_session(
path=r"C:\Program Files\MetaTrader 5\terminal64.exe",
login="12345",
password="secret",
server="Broker-Demo",
retry_count=2,
) as client:
positions = client.positions_get_as_df(symbol="EURUSD")
client = create_trading_client(login=12345, server="Broker-Demo")
try:
account = client.account_info_as_dict()
finally:
client.shutdown()
login accepts int, numeric str, or an empty string; empty strings are
treated as unset. path, password, server, and timeout are forwarded to
pdmt5.Mt5Config, and omitted timeout values keep the lower-level default.
Use mt5_session() / MT5Client for read-only data collection.
State and order helpers¶
These helpers are strategy-agnostic and do not depend on signal detection, betting logic, or scheduling code in downstream applications.
from mt5cli import (
calculate_positions_margin,
calculate_spread_ratio,
calculate_margin_and_volume,
close_open_positions,
detect_position_side,
determine_order_limits,
estimate_order_margin,
fetch_latest_closed_rates_for_trading_client,
fetch_latest_closed_rates_indexed,
get_account_snapshot,
get_positions_frame,
get_symbol_snapshot,
get_tick_snapshot,
normalize_order_volume,
place_market_order,
)
account = get_account_snapshot(client)
symbol = get_symbol_snapshot(client, "EURUSD")
tick = get_tick_snapshot(client, "EURUSD")
positions = get_positions_frame(client, "EURUSD")
side = detect_position_side(client, "EURUSD")
spread_ratio = calculate_spread_ratio(client, "EURUSD")
volume = normalize_order_volume(
0.15,
volume_min=symbol["volume_min"],
volume_max=symbol["volume_max"],
volume_step=symbol["volume_step"],
)
buy_margin = (
estimate_order_margin(client, "EURUSD", "BUY", volume) if volume > 0 else 0.0
)
open_margin = calculate_positions_margin(client, symbols=["EURUSD"])
closed_bars = fetch_latest_closed_rates_for_trading_client(
client,
symbol="EURUSD",
granularity="M1",
count=100,
)
# Or fetch with a UTC DatetimeIndex instead of a "time" column:
indexed_bars = fetch_latest_closed_rates_indexed(
client,
symbol="EURUSD",
granularity="M1",
count=100,
)
# indexed_bars.index is a UTC-aware DatetimeIndex named "time"
sizing = calculate_margin_and_volume(
client,
"EURUSD",
unit_margin_ratio=0.5,
preserved_margin_ratio=0.2,
)
limits = determine_order_limits(
client,
"EURUSD",
side="long",
stop_loss_limit_ratio=0.01,
take_profit_limit_ratio=0.02,
)
preview = place_market_order(
client,
symbol="EURUSD",
volume=sizing["buy_volume"],
order_side="BUY",
sl=limits["stop_loss"],
tp=limits["take_profit"],
dry_run=True,
)
closed = close_open_positions(client, symbols="EURUSD", dry_run=True)
detect_position_side() returns long for buy-only exposure, short for
sell-only exposure, and None for no positions or mixed long/short exposure.
calculate_spread_ratio() uses (ask - bid) / ((ask + bid) / 2) and raises
Mt5OperationError when bid or ask is missing or non-positive.
normalize_order_volume() returns 0.0 for invalid constraints or
sub-minimum requests; check the result before calling estimate_order_margin(),
which requires a positive finite volume. calculate_positions_margin() silently
skips rows with missing symbols, non-positive volumes, non-finite volumes, or
unsupported position types, but propagates Mt5OperationError from estimate_order_margin() when a valid row
encounters invalid tick data or margin results from the broker.
SL/TP ratios for determine_order_limits() must satisfy 0 <= ratio < 1; 0
omits that level. SL/TP prices are rounded with symbol digits metadata when
available. determine_order_limits() pre-validates computed SL/TP prices against
available trade_stops_level * point metadata when present; violations raise
Mt5OperationError. This is a planning helper only: it does not guarantee broker
acceptance because live validation can still depend on price movement, bid/ask
side, freeze levels, and server-side rules, and it does not validate
trade_freeze_level. When symbol metadata cannot be loaded, protective prices
still round with digits=8 and stop-level validation is skipped.
unit_margin_ratio and preserved_margin_ratio for calculate_margin_and_volume()
accept 0 <= ratio <= 1; unit_margin_ratio=0 requests one minimum valid unit
when the post-reserve margin can afford it. Negative margin_free is clamped to
0.0 before sizing. Execution helpers return normalized OrderExecutionResult
dictionaries containing the request, response, status, retcode, and dry_run
flag; dry_run=True never sends an order or mutates Market Watch visibility.
ensure_symbol_selected() adds hidden symbols to Market Watch before live order
placement and SL/TP updates. Failed, malformed, or unknown broker retcodes are
fail-closed and returned as status="failed" while keeping the normalized
response for inspection.
Order planning return contracts¶
from mt5cli import MarginVolume, OrderLimits, OrderExecutionResult
sizing: MarginVolume = calculate_margin_and_volume(
client,
"EURUSD",
unit_margin_ratio=0.5,
preserved_margin_ratio=0.2,
)
limits: OrderLimits = determine_order_limits(
client,
"EURUSD",
side="long",
stop_loss_limit_ratio=0.01,
take_profit_limit_ratio=0.02,
)
preview: OrderExecutionResult = place_market_order(
client,
symbol="EURUSD",
volume=sizing["buy_volume"],
order_side="BUY",
sl=limits["stop_loss"],
tp=limits["take_profit"],
dry_run=True,
)
updates: list[OrderExecutionResult] = update_sltp_for_open_positions(
client,
symbol="EURUSD",
stop_loss=limits["stop_loss"],
dry_run=True,
)
Closes issue #33: strategy-neutral order planning and execution helpers exposed through the stable package root without embedding entry/exit policy.
Retrieving recent history deals¶
fetch_recent_history_deals_for_trading_client() fetches history deals from an
already-connected trading client over a trailing time window. It works directly
with the object returned by create_trading_client() (a raw
pdmt5.Mt5DataClient) without requiring any additional wrapping.
The helper returns a chronologically sorted DataFrame with a RangeIndex and
all columns from the underlying client (time, symbol, type, entry,
volume, profit, position_id, etc.). It does not apply any
strategy-specific transformations — entry/exit classification, Kelly fractions,
and betting semantics belong in downstream applications.
from mt5cli import (
create_trading_client,
fetch_recent_history_deals_for_trading_client,
)
client = create_trading_client(login=12345, server="Broker-Demo")
try:
deals_df = fetch_recent_history_deals_for_trading_client(
client,
symbol="JP225",
hours=24,
)
finally:
client.shutdown()
Or inside a managed session:
from mt5cli import fetch_recent_history_deals_for_trading_client, mt5_trading_session
with mt5_trading_session(login=12345, server="Broker-Demo") as client:
deals_df = fetch_recent_history_deals_for_trading_client(
client,
symbol="JP225",
hours=48,
)
hours must be positive; date_to defaults to datetime.now(UTC). An empty
or None result from the underlying client is normalized to an empty DataFrame.
Downstream packages own all strategy-specific transformations. mt5cli does not provide entry-deal classification, Kelly sizing, or any betting-specific helpers.
Migration from application-local helpers¶
| Application-local concern | mt5cli replacement |
|---|---|
| Manual terminal spawn/kill around trading code | mt5_trading_session() |
| Local position-side detection | detect_position_side() |
| Local margin/volume sizing | calculate_margin_and_volume() |
| Local broker volume step normalization | normalize_order_volume() |
| Local order or position margin estimation | estimate_order_margin(), calculate_positions_margin() |
| Local closed-bar fetch from a trading session | fetch_latest_closed_rates_for_trading_client(), fetch_latest_closed_rates_indexed() |
| Local recent deal history fetch from a trading session | fetch_recent_history_deals_for_trading_client() |
| Local SL/TP price derivation | determine_order_limits() |
| Throttled SQLite history loop with ad-hoc error handling | ThrottledHistoryUpdater(suppress_errors=True) |
Keep read-only data collection on mt5_session() / MT5Client; use
mt5_trading_session() only where order placement or trading calculations are
required.