Trading Module¶
mt5cli.trading ¶
Trading-capable MetaTrader 5 session helpers and operational utilities.
__all__
module-attribute
¶
__all__ = [
"OrderSide",
"PositionSide",
"calculate_margin_and_volume",
"detect_position_side",
"determine_order_limits",
"mt5_trading_session",
]
calculate_margin_and_volume ¶
calculate_margin_and_volume(
client: Mt5TradingClient,
symbol: str,
unit_margin_ratio: float,
preserved_margin_ratio: float,
) -> dict[str, float]
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 volume sizing on both buy and sell sides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Mt5TradingClient
|
Connected |
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 |
|---|---|
dict[str, float]
|
Dictionary with |
dict[str, float]
|
|
dict[str, float]
|
clamped to |
Source code in mt5cli/trading.py
detect_position_side ¶
detect_position_side(
client: Mt5TradingClient, symbol: str
) -> PositionSide | None
Detect the net open position side for a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Mt5TradingClient
|
Connected |
required |
symbol
|
str
|
Symbol to inspect. |
required |
Returns:
| Type | Description |
|---|---|
PositionSide | None
|
|
PositionSide | None
|
net sell volume exceeds buy volume, or |
PositionSide | None
|
or buy/sell volumes are exactly balanced. |
Source code in mt5cli/trading.py
determine_order_limits ¶
determine_order_limits(
client: Mt5TradingClient,
symbol: str,
side: OrderSide | str,
stop_loss_limit_ratio: float,
take_profit_limit_ratio: float,
) -> dict[str, float | None]
Derive entry and protective order prices from current market quotes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Mt5TradingClient
|
Connected |
required |
symbol
|
str
|
Symbol used for the quote lookup. |
required |
side
|
OrderSide | str
|
Position side as |
required |
stop_loss_limit_ratio
|
float
|
Relative distance from entry for stop loss in
|
required |
take_profit_limit_ratio
|
float
|
Relative distance from entry for take profit in
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, float | None]
|
Dictionary with |
dict[str, float | None]
|
Omitted protective levels are returned as |
Source code in mt5cli/trading.py
mt5_trading_session ¶
mt5_trading_session(
config: Mt5Config | None = None, retry_count: int = 0
) -> Iterator[Mt5TradingClient]
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 :class:~pdmt5.Mt5TradingClient, 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
|
retry_count
|
int
|
Number of initialization retries passed to
|
0
|
Yields:
| Type | Description |
|---|---|
Mt5TradingClient
|
Connected |
Source code in mt5cli/trading.py
Trading-capable MT5 sessions¶
mt5_trading_session() complements the read-only mt5_session() helper in
sdk.py. It yields a connected pdmt5.Mt5TradingClient, uses
Mt5Config.path to launch the terminal when configured, and always calls
shutdown() on exit.
from pdmt5 import Mt5Config
from mt5cli import mt5_trading_session
with mt5_trading_session(
Mt5Config(path=r"C:\Program Files\MetaTrader 5\terminal64.exe", login=12345),
retry_count=2,
) as client:
positions = client.positions_get_as_df(symbol="EURUSD")
The read-only Mt5CliClient / mt5_session() API is unchanged.
Operational trading 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_margin_and_volume,
detect_position_side,
determine_order_limits,
)
side = detect_position_side(client, "EURUSD")
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,
)
Protective ratios must satisfy 0 <= ratio < 1; 0 omits that level.
calculate_margin_and_volume() clamps negative margin_free to 0.0
before sizing.
Migration from mteor-local helpers¶
| mteor-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 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() / Mt5CliClient; use
mt5_trading_session() only where order placement or trading calculations are
required.