Certainly! Below is a complete, modular Python implementation of your intraday trading bot using the MetaTrader 5 (MT5) Python API. The code follows your provided specifications closely, ensuring only print statements are enhanced for better visibility. The structure is organized into classes and functions for clarity and maintainability.
Prerequisites
-
Install MetaTrader5 Package:
Ensure you have the MetaTrader5 package installed. If not, install it using pip:
pip install MetaTrader5
-
MT5 Terminal:
Make sure the MT5 terminal is installed and logged in with the appropriate trading account.
Complete Code
import MetaTrader5 as mt5
import time
from datetime import datetime, time as dtime
import sys
# Configuration Parameters
class Config:
# Operation Hours (Server Time)
OPERATION_START = dtime(hour=1, minute=15)
OPERATION_END = dtime(hour=21, minute=0)
# Main Order Parameters
MAIN_ORDER_DIRECTION = "BUY" # "BUY" or "SELL"
MAIN_ORDER_DIRECTION_VALUE = -1 if "BUY" == "BUY" else 1 # BUY=-1, SELL=1
MAIN_ORDER_LOTS = 0.01
MAIN_ORDER_THRESHOLD = -50 # in points
STRATEGY_POS_TYPE = "mainorder"
MULTIPLIER_MAINORDER = 5 # Multiplier for next main order's lot size
# Sleep Intervals (in seconds)
SLEEP_INTERVAL = 1 # General sleep interval to avoid excessive usage
CHECK_SERVER_TIME_INTERVAL = 10
CHECK_OPERATIONAL_STATE_INTERVAL = 60
POSITION_TRACKING_FLAG = 1
MAINORDER_TRACKING_FLAG = 1
# Symbol to Trade
SYMBOL = "EURUSD" # Change as needed
# Trading Bot Class
class IntradayBot:
def __init__(self, config):
self.config = config
self.loop_count = 0
self.operational_state = "off"
self.strategy_pos_type = self.config.STRATEGY_POS_TYPE
self.last_server_time_check = 0
self.last_operational_state_check = 0
self.symbol = self.config.SYMBOL
self.point = 0.0
self.initialize_mt5()
self.on_init()
def initialize_mt5(self):
if not mt5.initialize():
print("initialize() failed, error code =", mt5.last_error())
sys.exit(1)
else:
print("MT5 initialized successfully.")
# Retrieve symbol information
symbol_info = mt5.symbol_info(self.symbol)
if symbol_info is None:
print(f"Symbol {self.symbol} not found.")
mt5.shutdown()
sys.exit(1)
if not symbol_info.visible:
print(f"Symbol {self.symbol} is not visible, trying to activate.")
if not mt5.symbol_select(self.symbol, True):
print(f"Failed to select symbol {self.symbol}.")
mt5.shutdown()
sys.exit(1)
self.point = symbol_info.point
print(f"Trading symbol: {self.symbol}, Point size: {self.point}")
def on_init(self):
self.loop_count = 0
print("Initialization complete. LoopCount set to 0.")
self.operational_state = "off"
print("Operational_State set to 'off'.")
def check_server_time(self):
current_time = datetime.now().time()
start = self.config.OPERATION_START
end = self.config.OPERATION_END
in_operational_hours = start <= current_time <= end
print(f"[{datetime.now()}] Checking server time...")
if in_operational_hours:
if self.operational_state != "on":
self.operational_state = "on"
print("Set Operational_State to 'on'.")
else:
print("Server Time not in operational Hours.")
self.close_all_positions()
self.delete_all_orders()
self.kill_all_outstanding_tasks()
self.loop_count = 0
print("Set LoopCount to 0.")
self.operational_state = "off"
print("Set Operational_State to 'off'.")
def check_operational_state(self):
print(f"[{datetime.now()}] Checking Operational_State...")
if self.operational_state == "off":
print("Operational_State is 'off'. Doing nothing.")
return
elif self.operational_state == "on":
print("Operational_State is 'on'.")
if self.loop_count == 0:
self.loop_cycle()
else:
print(f"LoopCount is {self.loop_count}. Doing nothing.")
def loop_cycle(self):
print(f"[{datetime.now()}] Starting Loop_Cycle...")
success = self.open_main_order()
if success:
self.loop_count = 1
print("Set LoopCount to 1.")
self.position_tracking()
else:
print("Failed to open MainOrder.")
def position_tracking(self):
print(f"[{datetime.now()}] Starting Position_Tracking loop...")
if self.strategy_pos_type == "mainorder":
self.mainorder_tracking()
else:
print(f"Strategy_Pos_Type '{self.strategy_pos_type}' not recognized.")
def mainorder_tracking(self):
print(f"[{datetime.now()}] Starting mainorder_tracking loop...")
while self.operational_state == "on":
positions = mt5.positions_get(symbol=self.symbol)
if positions is None or len(positions) == 0:
print("No open positions to track.")
self.loop_count = 0
break
for pos in positions:
if pos.type == mt5.ORDER_TYPE_BUY and self.config.MAIN_ORDER_DIRECTION != "BUY":
continue
if pos.type == mt5.ORDER_TYPE_SELL and self.config.MAIN_ORDER_DIRECTION != "SELL":
continue
opening_price = pos.price_open
current_price = pos.price_current
direction = self.config.MAIN_ORDER_DIRECTION_VALUE
pnl = (opening_price - current_price) * direction / self.point
print(f"Position ID: {pos.ticket}, Opening Price: {opening_price}, Current Price: {current_price}, PnL: {pnl} points.")
if pnl <= self.config.MAIN_ORDER_THRESHOLD:
print(f"PnL {pnl} <= Threshold {self.config.MAIN_ORDER_THRESHOLD}. Opening next MainOrder in reverse direction.")
success = self.open_main_order_reversed()
if success:
self.loop_count += 1
print(f"Set LoopCount to {self.loop_count}.")
else:
print("Failed to open reversed MainOrder.")
else:
print(f"PnL {pnl} > Threshold {self.config.MAIN_ORDER_THRESHOLD}. Continuing tracking.")
time.sleep(self.config.SLEEP_INTERVAL)
def open_main_order(self):
print(f"[{datetime.now()}] Opening MainOrder: {self.config.MAIN_ORDER_DIRECTION}, Lots: {self.config.MAIN_ORDER_LOTS}")
order_type = mt5.ORDER_TYPE_BUY if self.config.MAIN_ORDER_DIRECTION == "BUY" else mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(self.symbol).ask if order_type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(self.symbol).bid
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": self.symbol,
"volume": self.config.MAIN_ORDER_LOTS,
"type": order_type,
"price": price,
"sl": 0, # Set to 0 if not using Stop Loss
"tp": 0, # Set to 0 if not using Take Profit
"deviation": 10,
"magic": 234000,
"comment": "MainOrder",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_FOK,
}
result = mt5.order_send(request)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print(f"MainOrder successfully opened. Ticket: {result.order}")
return True
else:
print(f"Failed to open MainOrder. Retcode: {result.retcode}")
return False
def open_main_order_reversed(self):
reversed_direction = "SELL" if self.config.MAIN_ORDER_DIRECTION == "BUY" else "BUY"
lot_size = self.config.MAIN_ORDER_LOTS * self.config.MULTIPLIER_MAINORDER
print(f"[{datetime.now()}] Opening Reversed MainOrder: {reversed_direction}, Lots: {lot_size}")
order_type = mt5.ORDER_TYPE_BUY if reversed_direction == "BUY" else mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(self.symbol).ask if order_type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(self.symbol).bid
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": self.symbol,
"volume": lot_size,
"type": order_type,
"price": price,
"sl": 0,
"tp": 0,
"deviation": 10,
"magic": 234000,
"comment": "Reversed_MainOrder",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_FOK,
}
result = mt5.order_send(request)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print(f"Reversed MainOrder successfully opened. Ticket: {result.order}")
return True
else:
print(f"Failed to open Reversed MainOrder. Retcode: {result.retcode}")
return False
def close_all_positions(self):
print(f"[{datetime.now()}] Closing all positions for symbol {self.symbol}...")
positions = mt5.positions_get(symbol=self.symbol)
if positions is None or len(positions) == 0:
print("No positions to close.")
return
for pos in positions:
close_type = mt5.ORDER_TYPE_SELL if pos.type == mt5.ORDER_TYPE_BUY else mt5.ORDER_TYPE_BUY
price = mt5.symbol_info_tick(self.symbol).bid if close_type == mt5.ORDER_TYPE_SELL else mt5.symbol_info_tick(self.symbol).ask
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": self.symbol,
"volume": pos.volume,
"type": close_type,
"position": pos.ticket,
"price": price,
"deviation": 10,
"magic": pos.magic,
"comment": "Close_Position",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_FOK,
}
result = mt5.order_send(request)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print(f"Position {pos.ticket} closed successfully.")
else:
print(f"Failed to close Position {pos.ticket}. Retcode: {result.retcode}")
def delete_all_orders(self):
print(f"[{datetime.now()}] Deleting all pending orders for symbol {self.symbol}...")
pending_orders = mt5.orders_get(symbol=self.symbol)
if pending_orders is None or len(pending_orders) == 0:
print("No pending orders to delete.")
return
for order in pending_orders:
request = {
"action": mt5.TRADE_ACTION_REMOVE,
"order": order.ticket,
"symbol": self.symbol,
"magic": order.magic,
"comment": "Delete_Pending_Order",
}
result = mt5.order_send(request)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print(f"Pending Order {order.ticket} deleted successfully.")
else:
print(f"Failed to delete Pending Order {order.ticket}. Retcode: {result.retcode}")
def kill_all_outstanding_tasks(self):
print(f"[{datetime.now()}] Killing all outstanding tasks...")
# Since this is a synchronous script, there's no outstanding tasks to kill.
# If using threading or asyncio, implement task cancellation here.
print("All outstanding tasks killed (if any).")
def run(self):
print("Trading Bot started.")
try:
while True:
current_time = time.time()
# Check Server Time
if current_time - self.last_server_time_check >= self.config.CHECK_SERVER_TIME_INTERVAL:
self.check_server_time()
self.last_server_time_check = current_time
# Check Operational State
if current_time - self.last_operational_state_check >= self.config.CHECK_OPERATIONAL_STATE_INTERVAL:
self.check_operational_state()
self.last_operational_state_check = current_time
time.sleep(self.config.SLEEP_INTERVAL)
except KeyboardInterrupt:
print("Interrupted by user. Shutting down.")
finally:
mt5.shutdown()
print("MT5 connection closed.")
# Main Execution
if __name__ == "__main__":
config = Config()
bot = IntradayBot(config)
bot.run()
Explanation of the Code
-
Configuration (Config Class):
- Defines all the configurable parameters such as operation hours, main order settings, sleep intervals, and the symbol to trade.
- The
MAIN_ORDER_DIRECTION_VALUE is set to -1 for "BUY" and 1 for "SELL" to align with your PnL calculation.
-
IntradayBot Class:
-
Initialization (__init__ and initialize_mt5):
- Initializes the MT5 connection and checks if the specified symbol is available and visible.
- Retrieves the point size for the symbol, which is essential for PnL calculations.
-
on_init Method:
- Sets the initial state of
loop_count and operational_state.
-
check_server_time Method:
- Checks if the current server time falls within the defined operation hours.
- If within hours, sets the operational state to "on"; otherwise, it closes all positions, deletes all orders, kills any outstanding tasks, resets the loop count, and sets the operational state to "off".
-
check_operational_state Method:
- If the operational state is "on" and
loop_count is 0, it initiates the loop_cycle.
- Otherwise, it does nothing.
-
loop_cycle Method:
- Attempts to open a main order.
- If successful, increments the
loop_count and starts position tracking.
-
position_tracking Method:
- Checks the
strategy_pos_type. If it's "mainorder", it proceeds to mainorder_tracking.
-
mainorder_tracking Method:
- Continuously monitors open positions.
- Calculates the PnL based on the current price and opening price.
- If PnL falls below the threshold, it opens a reversed main order with an increased lot size and increments the
loop_count.
- Continues tracking as long as the operational state is "on".
Usage Instructions
-
Adjust Configuration:
- Modify the
Config class as needed, especially the SYMBOL to trade and operation hours.
-
Run the Script:
-
Monitoring:
- The bot will print detailed logs to the console, showing its actions and state changes.
- To stop the bot, press
Ctrl+C.
Notes
-
Error Handling:
The script includes basic error handling for MT5 operations. It prints error codes if any operation fails. For a production environment, consider implementing more robust error handling and logging mechanisms.
-
PnL Calculation:
The PnL is calculated in points as per your specifications. Ensure that this aligns with your trading strategy and adjust if necessary.
-
Concurrency:
This implementation is synchronous. If you plan to extend it with asynchronous tasks or threading, ensure thread safety, especially when interacting with the MT5 API.
-
Testing:
Before deploying the bot on a live account, thoroughly test it in a demo environment to ensure it behaves as expected.
This implementation adheres strictly to your requirements, focusing on modularity and comprehensive print statements for monitoring. It serves as a solid foundation for further enhancements and strategy testing.