Trading¶
pdmt5.trading ¶
Trading operations module with advanced MetaTrader5 functionality.
Mt5TradingClient ¶
Bases: Mt5DataClient
MetaTrader5 trading client with advanced trading operations.
This class extends Mt5DataClient to provide specialized trading functionality including position management, order analysis, and trading performance metrics.
mt5_failed_trade_retcodes
cached
property
¶
Set of failed trade return codes.
Returns:
| Type | Description |
|---|---|
set[int]
|
Set of failed trade return codes. |
mt5_successful_trade_retcodes
cached
property
¶
Set of successful trade return codes.
Returns:
| Type | Description |
|---|---|
set[int]
|
Set of successful trade return codes. |
calculate_minimum_order_margin ¶
calculate_minimum_order_margin(
symbol: str, order_side: Literal["BUY", "SELL"]
) -> dict[str, float]
Calculate the minimum order margins for a given symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the minimum order margins. |
required |
order_side
|
Literal['BUY', 'SELL']
|
Optional side of the order, either "BUY" or "SELL". |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with minimum volume and margin for the specified order side. |
Source code in pdmt5/trading.py
calculate_new_position_margin_ratio ¶
calculate_new_position_margin_ratio(
symbol: str,
new_position_side: Literal["BUY", "SELL"] | None = None,
new_position_volume: float = 0,
) -> float
Calculate the margin ratio for a new position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the margin ratio. |
required |
new_position_side
|
Literal['BUY', 'SELL'] | None
|
Side of the new position, either "BUY" or "SELL". |
None
|
new_position_volume
|
float
|
Volume of the new position. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Margin ratio for the new position as a fraction of account equity. |
Source code in pdmt5/trading.py
calculate_spread_ratio ¶
Calculate the spread ratio for a given symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the spread ratio. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Spread ratio as a float. |
Source code in pdmt5/trading.py
calculate_volume_by_margin ¶
calculate_volume_by_margin(
symbol: str,
margin: float,
order_side: Literal["BUY", "SELL"],
) -> float
Calculate volume based on margin for a given symbol and order side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the volume. |
required |
margin
|
float
|
Margin amount to use for the calculation. |
required |
order_side
|
Literal['BUY', 'SELL']
|
Side of the order, either "BUY" or "SELL". |
required |
Returns:
| Type | Description |
|---|---|
float
|
Calculated volume as a float. |
Source code in pdmt5/trading.py
close_open_positions ¶
close_open_positions(
symbols: str
| list[str]
| tuple[str, ...]
| None = None,
order_filling_mode: Literal[
"IOC", "FOK", "RETURN"
] = "IOC",
dry_run: bool = False,
**kwargs: Any,
) -> dict[str, list[dict[str, Any]]]
Close all open positions for specified symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
str | list[str] | tuple[str, ...] | None
|
Optional symbol or list of symbols to filter positions. If None, all symbols will be considered. |
None
|
order_filling_mode
|
Literal['IOC', 'FOK', 'RETURN']
|
Order filling mode, either "IOC", "FOK", or "RETURN". |
'IOC'
|
dry_run
|
bool
|
If True, only check the order without sending it. |
False
|
**kwargs
|
Any
|
Additional keyword arguments for request parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, list[dict[str, Any]]]
|
Dictionary with symbols as keys and lists of dictionaries containing operation results for each closed position as values. |
Source code in pdmt5/trading.py
collect_entry_deals_as_df ¶
collect_entry_deals_as_df(
symbol: str,
history_seconds: int = 3600,
index_keys: str | None = "ticket",
) -> DataFrame
Collect entry deals as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to collect entry deals for. |
required |
history_seconds
|
int
|
Time range in seconds to fetch deals around the last tick. |
3600
|
index_keys
|
str | None
|
Optional index keys for the DataFrame. |
'ticket'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Entry deals with time index. |
Source code in pdmt5/trading.py
fetch_latest_rates_as_df ¶
fetch_latest_rates_as_df(
symbol: str,
granularity: str = "M1",
count: int = 1440,
index_keys: str | None = "time",
) -> DataFrame
Fetch rate (OHLC) data as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch data for. |
required |
granularity
|
str
|
Time granularity as a timeframe suffix (e.g., "M1", "H1"). |
'M1'
|
count
|
int
|
Number of bars to fetch. |
1440
|
index_keys
|
str | None
|
Optional index keys for the DataFrame. |
'time'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: OHLC data with time index. |
Raises:
| Type | Description |
|---|---|
Mt5TradingError
|
If the granularity is not supported by MetaTrader5. |
Source code in pdmt5/trading.py
fetch_latest_ticks_as_df ¶
fetch_latest_ticks_as_df(
symbol: str,
seconds: int = 300,
index_keys: str | None = "time_msc",
) -> DataFrame
Fetch tick data as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch tick data for. |
required |
seconds
|
int
|
Time range in seconds to fetch ticks around the last tick time. |
300
|
index_keys
|
str | None
|
Optional index keys for the DataFrame. |
'time_msc'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Tick data with time index. |
Source code in pdmt5/trading.py
fetch_positions_with_metrics_as_df ¶
Fetch open positions as a DataFrame with additional metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch positions for. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame containing open positions with additional metrics. |
Source code in pdmt5/trading.py
place_market_order ¶
place_market_order(
symbol: str,
volume: float,
order_side: Literal["BUY", "SELL"],
order_filling_mode: Literal[
"IOC", "FOK", "RETURN"
] = "IOC",
order_time_mode: Literal[
"GTC", "DAY", "SPECIFIED", "SPECIFIED_DAY"
] = "GTC",
raise_on_error: bool = False,
dry_run: bool = False,
**kwargs: Any,
) -> dict[str, Any]
Send or check an order request to place a market order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for the order. |
required |
volume
|
float
|
Volume of the order. |
required |
order_side
|
Literal['BUY', 'SELL']
|
Side of the order, either "BUY" or "SELL". |
required |
order_filling_mode
|
Literal['IOC', 'FOK', 'RETURN']
|
Order filling mode, either "IOC", "FOK", or "RETURN". |
'IOC'
|
order_time_mode
|
Literal['GTC', 'DAY', 'SPECIFIED', 'SPECIFIED_DAY']
|
Order time mode, either "GTC", "DAY", "SPECIFIED", or "SPECIFIED_DAY". |
'GTC'
|
raise_on_error
|
bool
|
If True, raise an error on operation failure. |
False
|
dry_run
|
bool
|
If True, only check the order without sending it. |
False
|
**kwargs
|
Any
|
Additional keyword arguments for request parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with operation result. |
Source code in pdmt5/trading.py
update_sltp_for_open_positions ¶
update_sltp_for_open_positions(
symbol: str,
stop_loss: float | None = None,
take_profit: float | None = None,
tickets: list[int] | None = None,
raise_on_error: bool = False,
dry_run: bool = False,
**kwargs: Any,
) -> list[dict[str, Any]]
Change Stop Loss and Take Profit for open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for the position. |
required |
stop_loss
|
float | None
|
New Stop Loss price. If None, it will not be changed. |
None
|
take_profit
|
float | None
|
New Take Profit price. If None, it will not be changed. |
None
|
tickets
|
list[int] | None
|
List of position tickets to filter positions. If None, all open positions for the symbol will be considered. |
None
|
raise_on_error
|
bool
|
If True, raise an error on operation failure. |
False
|
dry_run
|
bool
|
If True, only check the order without sending it. |
False
|
**kwargs
|
Any
|
Additional keyword arguments for request parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of dictionaries with operation results for each updated position. |
Source code in pdmt5/trading.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
Mt5TradingError ¶
Bases: Mt5RuntimeError
MetaTrader5 trading error.
Overview¶
The trading module extends Mt5DataClient with advanced trading operations including position management, order execution, and dry run support for testing trading strategies without actual execution.
Classes¶
Mt5TradingClient¶
pdmt5.trading.Mt5TradingClient ¶
Bases: Mt5DataClient
MetaTrader5 trading client with advanced trading operations.
This class extends Mt5DataClient to provide specialized trading functionality including position management, order analysis, and trading performance metrics.
mt5_failed_trade_retcodes
cached
property
¶
Set of failed trade return codes.
Returns:
| Type | Description |
|---|---|
set[int]
|
Set of failed trade return codes. |
mt5_successful_trade_retcodes
cached
property
¶
Set of successful trade return codes.
Returns:
| Type | Description |
|---|---|
set[int]
|
Set of successful trade return codes. |
calculate_minimum_order_margin ¶
calculate_minimum_order_margin(
symbol: str, order_side: Literal["BUY", "SELL"]
) -> dict[str, float]
Calculate the minimum order margins for a given symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the minimum order margins. |
required |
order_side
|
Literal['BUY', 'SELL']
|
Optional side of the order, either "BUY" or "SELL". |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with minimum volume and margin for the specified order side. |
Source code in pdmt5/trading.py
calculate_new_position_margin_ratio ¶
calculate_new_position_margin_ratio(
symbol: str,
new_position_side: Literal["BUY", "SELL"] | None = None,
new_position_volume: float = 0,
) -> float
Calculate the margin ratio for a new position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the margin ratio. |
required |
new_position_side
|
Literal['BUY', 'SELL'] | None
|
Side of the new position, either "BUY" or "SELL". |
None
|
new_position_volume
|
float
|
Volume of the new position. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Margin ratio for the new position as a fraction of account equity. |
Source code in pdmt5/trading.py
calculate_spread_ratio ¶
Calculate the spread ratio for a given symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the spread ratio. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Spread ratio as a float. |
Source code in pdmt5/trading.py
calculate_volume_by_margin ¶
calculate_volume_by_margin(
symbol: str,
margin: float,
order_side: Literal["BUY", "SELL"],
) -> float
Calculate volume based on margin for a given symbol and order side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for which to calculate the volume. |
required |
margin
|
float
|
Margin amount to use for the calculation. |
required |
order_side
|
Literal['BUY', 'SELL']
|
Side of the order, either "BUY" or "SELL". |
required |
Returns:
| Type | Description |
|---|---|
float
|
Calculated volume as a float. |
Source code in pdmt5/trading.py
close_open_positions ¶
close_open_positions(
symbols: str
| list[str]
| tuple[str, ...]
| None = None,
order_filling_mode: Literal[
"IOC", "FOK", "RETURN"
] = "IOC",
dry_run: bool = False,
**kwargs: Any,
) -> dict[str, list[dict[str, Any]]]
Close all open positions for specified symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
str | list[str] | tuple[str, ...] | None
|
Optional symbol or list of symbols to filter positions. If None, all symbols will be considered. |
None
|
order_filling_mode
|
Literal['IOC', 'FOK', 'RETURN']
|
Order filling mode, either "IOC", "FOK", or "RETURN". |
'IOC'
|
dry_run
|
bool
|
If True, only check the order without sending it. |
False
|
**kwargs
|
Any
|
Additional keyword arguments for request parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, list[dict[str, Any]]]
|
Dictionary with symbols as keys and lists of dictionaries containing operation results for each closed position as values. |
Source code in pdmt5/trading.py
collect_entry_deals_as_df ¶
collect_entry_deals_as_df(
symbol: str,
history_seconds: int = 3600,
index_keys: str | None = "ticket",
) -> DataFrame
Collect entry deals as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to collect entry deals for. |
required |
history_seconds
|
int
|
Time range in seconds to fetch deals around the last tick. |
3600
|
index_keys
|
str | None
|
Optional index keys for the DataFrame. |
'ticket'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Entry deals with time index. |
Source code in pdmt5/trading.py
fetch_latest_rates_as_df ¶
fetch_latest_rates_as_df(
symbol: str,
granularity: str = "M1",
count: int = 1440,
index_keys: str | None = "time",
) -> DataFrame
Fetch rate (OHLC) data as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch data for. |
required |
granularity
|
str
|
Time granularity as a timeframe suffix (e.g., "M1", "H1"). |
'M1'
|
count
|
int
|
Number of bars to fetch. |
1440
|
index_keys
|
str | None
|
Optional index keys for the DataFrame. |
'time'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: OHLC data with time index. |
Raises:
| Type | Description |
|---|---|
Mt5TradingError
|
If the granularity is not supported by MetaTrader5. |
Source code in pdmt5/trading.py
fetch_latest_ticks_as_df ¶
fetch_latest_ticks_as_df(
symbol: str,
seconds: int = 300,
index_keys: str | None = "time_msc",
) -> DataFrame
Fetch tick data as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch tick data for. |
required |
seconds
|
int
|
Time range in seconds to fetch ticks around the last tick time. |
300
|
index_keys
|
str | None
|
Optional index keys for the DataFrame. |
'time_msc'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Tick data with time index. |
Source code in pdmt5/trading.py
fetch_positions_with_metrics_as_df ¶
Fetch open positions as a DataFrame with additional metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch positions for. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame containing open positions with additional metrics. |
Source code in pdmt5/trading.py
place_market_order ¶
place_market_order(
symbol: str,
volume: float,
order_side: Literal["BUY", "SELL"],
order_filling_mode: Literal[
"IOC", "FOK", "RETURN"
] = "IOC",
order_time_mode: Literal[
"GTC", "DAY", "SPECIFIED", "SPECIFIED_DAY"
] = "GTC",
raise_on_error: bool = False,
dry_run: bool = False,
**kwargs: Any,
) -> dict[str, Any]
Send or check an order request to place a market order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for the order. |
required |
volume
|
float
|
Volume of the order. |
required |
order_side
|
Literal['BUY', 'SELL']
|
Side of the order, either "BUY" or "SELL". |
required |
order_filling_mode
|
Literal['IOC', 'FOK', 'RETURN']
|
Order filling mode, either "IOC", "FOK", or "RETURN". |
'IOC'
|
order_time_mode
|
Literal['GTC', 'DAY', 'SPECIFIED', 'SPECIFIED_DAY']
|
Order time mode, either "GTC", "DAY", "SPECIFIED", or "SPECIFIED_DAY". |
'GTC'
|
raise_on_error
|
bool
|
If True, raise an error on operation failure. |
False
|
dry_run
|
bool
|
If True, only check the order without sending it. |
False
|
**kwargs
|
Any
|
Additional keyword arguments for request parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with operation result. |
Source code in pdmt5/trading.py
update_sltp_for_open_positions ¶
update_sltp_for_open_positions(
symbol: str,
stop_loss: float | None = None,
take_profit: float | None = None,
tickets: list[int] | None = None,
raise_on_error: bool = False,
dry_run: bool = False,
**kwargs: Any,
) -> list[dict[str, Any]]
Change Stop Loss and Take Profit for open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol for the position. |
required |
stop_loss
|
float | None
|
New Stop Loss price. If None, it will not be changed. |
None
|
take_profit
|
float | None
|
New Take Profit price. If None, it will not be changed. |
None
|
tickets
|
list[int] | None
|
List of position tickets to filter positions. If None, all open positions for the symbol will be considered. |
None
|
raise_on_error
|
bool
|
If True, raise an error on operation failure. |
False
|
dry_run
|
bool
|
If True, only check the order without sending it. |
False
|
**kwargs
|
Any
|
Additional keyword arguments for request parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of dictionaries with operation results for each updated position. |
Source code in pdmt5/trading.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
options: show_bases: false
Advanced trading client class that inherits from Mt5DataClient and provides specialized trading functionality.
Mt5TradingError¶
pdmt5.trading.Mt5TradingError ¶
Bases: Mt5RuntimeError
MetaTrader5 trading error.
options: show_bases: false
Custom runtime exception for trading-specific errors.
Usage Examples¶
Basic Trading Operations¶
import MetaTrader5 as mt5
from pdmt5 import Mt5TradingClient, Mt5Config
# Create configuration
config = Mt5Config(
login=123456,
password="your_password",
server="broker_server",
timeout=60000,
portable=False
)
# Create client with dry run mode for testing
client = Mt5TradingClient(config=config, dry_run=True)
# Use as context manager
with client:
# Get current positions as DataFrame
positions_df = client.get_positions_as_df()
print(f"Open positions: {len(positions_df)}")
# Close positions for specific symbol
results = client.close_open_positions("EURUSD")
print(f"Closed positions: {results}")
Production Trading¶
# Create client for live trading (dry_run=False)
client = Mt5TradingClient(config=config, dry_run=False)
with client:
# Close all positions for multiple symbols
results = client.close_open_positions(["EURUSD", "GBPUSD", "USDJPY"])
# Close all positions (all symbols)
all_results = client.close_open_positions()
Order Filling Modes¶
with Mt5TradingClient(config=config) as client:
# Use IOC (Immediate or Cancel) - default
results_ioc = client.close_open_positions(
symbols="EURUSD",
order_filling_mode="IOC"
)
# Use FOK (Fill or Kill)
results_fok = client.close_open_positions(
symbols="GBPUSD",
order_filling_mode="FOK"
)
# Use RETURN (Return if not filled)
results_return = client.close_open_positions(
symbols="USDJPY",
order_filling_mode="RETURN"
)
Custom Order Parameters¶
with client:
# Close positions with custom parameters and order filling mode
results = client.close_open_positions(
"EURUSD",
order_filling_mode="IOC", # Specify per method call
comment="Closing all EURUSD positions",
deviation=10 # Maximum price deviation
)
Error Handling¶
from pdmt5.trading import Mt5TradingError
try:
with client:
results = client.close_open_positions("EURUSD")
except Mt5TradingError as e:
print(f"Trading error: {e}")
# Handle specific trading errors
Checking Order Status¶
with client:
# Check order (note: send_or_check_order is an internal method)
# For trading operations, use the provided methods like close_open_positions
# Example: Check if we can close a position
positions = client.get_positions_as_df()
if not positions.empty:
# Close specific position
results = client.close_open_positions("EURUSD")
Position Management Features¶
The Mt5TradingClient provides intelligent position management:
- Automatic Position Reversal: Automatically determines the correct order type to close positions
- Batch Operations: Close multiple positions for one or more symbols
- Dry Run Support: Test trading logic without executing real trades
- Flexible Filtering: Close positions by symbol, group, or all positions
- Custom Parameters: Support for additional order parameters like comment, deviation, etc.
Dry Run Mode¶
Dry run mode is essential for testing trading strategies:
# Test mode - validates orders without execution
test_client = Mt5TradingClient(config=config, dry_run=True)
# Production mode - executes real orders
prod_client = Mt5TradingClient(config=config, dry_run=False)
In dry run mode:
- Orders are validated using
order_check()instead oforder_send() - No actual trades are executed
- Full validation of margin requirements and order parameters
- Same return structure as live trading for easy testing
Return Values¶
The close_open_positions() method returns a dictionary with symbols as keys:
{
"EURUSD": [
{
"retcode": 10009, # Trade done
"deal": 123456,
"order": 789012,
"volume": 1.0,
"price": 1.1000,
"comment": "Request executed",
...
}
],
"GBPUSD": [...]
}
Best Practices¶
- Always use dry run mode first to test your trading logic
- Handle Mt5TradingError exceptions for proper error management
- Check return codes to verify successful execution
- Use context managers for automatic connection handling
- Log trading operations for audit trails
- Validate positions exist before attempting to close them
- Consider market hours and trading session times
Common Return Codes¶
TRADE_RETCODE_DONE(10009): Trade operation completed successfullyTRADE_RETCODE_TRADE_DISABLED: Trading disabled for the accountTRADE_RETCODE_MARKET_CLOSED: Market is closedTRADE_RETCODE_NO_MONEY: Insufficient fundsTRADE_RETCODE_INVALID_VOLUME: Invalid trade volume
Margin Calculation Methods¶
The trading client provides advanced margin calculation capabilities:
Calculate Minimum Order Margin¶
with client:
# Calculate minimum margin required for BUY order
min_margin_buy = client.calculate_minimum_order_margin("EURUSD", "BUY")
print(f"Minimum volume: {min_margin_buy['volume']}")
print(f"Minimum margin: {min_margin_buy['margin']}")
# Calculate minimum margin required for SELL order
min_margin_sell = client.calculate_minimum_order_margin("EURUSD", "SELL")
Calculate Volume by Margin¶
with client:
# Calculate maximum volume for given margin amount
available_margin = 1000.0 # USD
max_volume_buy = client.calculate_volume_by_margin("EURUSD", available_margin, "BUY")
max_volume_sell = client.calculate_volume_by_margin("EURUSD", available_margin, "SELL")
print(f"Max BUY volume for ${available_margin}: {max_volume_buy}")
print(f"Max SELL volume for ${available_margin}: {max_volume_sell}")
Calculate New Position Margin Ratio¶
with client:
# Calculate margin ratio for potential new position
margin_ratio = client.calculate_new_position_margin_ratio(
symbol="EURUSD",
new_position_side="BUY",
new_position_volume=1.0
)
print(f"New position would use {margin_ratio:.2%} of account equity")
# Check if adding position would exceed risk limits
if margin_ratio > 0.1: # 10% risk limit
print("Position size too large for risk management")
Market Order Placement¶
Place market orders with flexible configuration:
with client:
# Place a BUY market order
result = client.place_market_order(
symbol="EURUSD",
volume=1.0,
order_side="BUY",
order_filling_mode="IOC", # Immediate or Cancel
order_time_mode="GTC", # Good Till Cancelled
dry_run=False, # Set to True for testing
comment="My buy order"
)
# Place a SELL market order with FOK filling
result = client.place_market_order(
symbol="EURUSD",
volume=0.5,
order_side="SELL",
order_filling_mode="FOK", # Fill or Kill
dry_run=True # Test mode
)
print(f"Order result: {result}")
Stop Loss and Take Profit Management¶
Update SL/TP for existing positions:
with client:
# Update SL/TP for all EURUSD positions
results = client.update_sltp_for_open_positions(
symbol="EURUSD",
stop_loss=1.0950,
take_profit=1.1100,
dry_run=False
)
# Update only specific positions by ticket
results = client.update_sltp_for_open_positions(
symbol="EURUSD",
stop_loss=1.0950,
tickets=[123456, 789012], # Specific position tickets
dry_run=True
)
Market Data and Analysis Methods¶
Spread Analysis¶
with client:
# Calculate spread ratio for symbol
spread_ratio = client.calculate_spread_ratio("EURUSD")
print(f"EURUSD spread ratio: {spread_ratio:.6f}")
OHLC Data Retrieval¶
with client:
# Fetch latest rate data as DataFrame
rates_df = client.fetch_latest_rates_as_df(
symbol="EURUSD",
granularity="M1", # 1-minute bars
count=1440, # Last 24 hours
index_keys="time"
)
print(f"Latest rates: {rates_df.tail()}")
Tick Data Analysis¶
with client:
# Fetch recent tick data
ticks_df = client.fetch_latest_ticks_as_df(
symbol="EURUSD",
seconds=300, # Last 5 minutes
index_keys="time_msc"
)
print(f"Tick count: {len(ticks_df)}")
Position Analytics with Enhanced Metrics¶
with client:
# Get positions with additional calculated metrics
positions_df = client.fetch_positions_with_metrics_as_df("EURUSD")
if not positions_df.empty:
print("Position metrics:")
print(f"Total signed volume: {positions_df['signed_volume'].sum()}")
print(f"Total signed margin: {positions_df['signed_margin'].sum()}")
print(f"Average profit ratio: {positions_df['underlier_profit_ratio'].mean():.4f}")
Deal History Analysis¶
with client:
# Collect entry deals for analysis
deals_df = client.collect_entry_deals_as_df(
symbol="EURUSD",
history_seconds=3600, # Last hour
index_keys="ticket"
)
if not deals_df.empty:
print(f"Entry deals found: {len(deals_df)}")
print(f"Deal types: {deals_df['type'].value_counts()}")
Integration with Mt5DataClient¶
Since Mt5TradingClient inherits from Mt5DataClient, all data retrieval methods are available:
with Mt5TradingClient(config=config) as client:
# Get current positions as DataFrame
positions_df = client.get_positions_as_df()
# Analyze positions
if not positions_df.empty:
# Calculate total exposure
total_volume = positions_df['volume'].sum()
# Close losing positions
losing_positions = positions_df[positions_df['profit'] < 0]
for symbol in losing_positions['symbol'].unique():
client.close_open_positions(symbol)
# Risk management with margin calculations
for symbol in ["EURUSD", "GBPUSD", "USDJPY"]:
# Calculate current margin usage
current_ratio = client.calculate_new_position_margin_ratio(symbol)
print(f"{symbol} current margin ratio: {current_ratio:.2%}")
# Calculate maximum safe position size
safe_margin = 500.0 # USD
max_safe_volume = client.calculate_volume_by_margin(symbol, safe_margin, "BUY")
print(f"{symbol} max safe volume: {max_safe_volume}")