In this blog post, we’ll explore a Python script that connects to MetaTrader 5 (MT5), retrieves ticker information, historical data, and executes trades with a simple trading bot. This example script demonstrates the power of MT5's Python API, offering a blend of real-time trading and data analysis, which is essential for developing automated trading systems.
Prerequisites
Before we dive into the code, make sure you have the following:
- MetaTrader 5 Installed: MT5 should be installed on your system.
- MetaTrader 5 Python API (MetaTrader5 module): You can install it via pip: pip install MetaTrader5
- A Demo Account on MetaTrader 5: This is required for trading simulations.
- Pandas Library: To handle the historical data in a DataFrame.
Script Breakdown
1. Initialize the MT5 Connection
To begin with, we need to establish a connection with MetaTrader 5. The script initializes the connection using login credentials, password, and the server name. If the connection fails, the script prints the error and exits.
2. Account Information and Symbol Selection
Next, the script retrieves and prints the account balance. It then checks if the specified symbol (in this case, TSLA) is available on the selected server. If the symbol is not available, the script shuts down the connection.
3. Retrieving Current Price
The script then retrieves the current price of the symbol. This information is essential for calculating the lot size for our trade request.
4. Trade Execution
Now that we have the current price, the script calculates the lot size based on the amount we wish to invest. The symbol_info.volume_min
and symbol_info.volume_step
are used to ensure that the lot size conforms to the broker’s requirements. A buy order is then created and sent.
5. Retrieving Historical Data
The script retrieves historical data for the given symbol within a defined date range. The data is then converted into a Pandas DataFrame, which allows for easy manipulation and analysis.
6. Shutdown MT5 Connection
Finally, after completing the data retrieval and trade, the script shuts down the MetaTrader 5 connection.
How This Script Works
- Initialize Connection: Establishes a connection to MT5 with your demo account credentials.
- Retrieve Ticker Info: Fetches the current price of the TSLA stock.
- Calculate Lot Size: Based on the current price and the desired investment, the script calculates the appropriate lot size for the trade.
- Execute Trade: A buy order for TSLA is placed with a specified lot size and price.
- Historical Data Retrieval: It fetches daily historical data from 2022 to the present.
- Shutdown: Cleanly shuts down the connection to MT5.
1. Run MT5 Without GUI (Headless Mode)
By default, when you run MetaTrader 5, the application window opens. However, you can prevent this window from opening by using a special configuration or by running MT5 in a detached or background mode.
To run MetaTrader 5 in headless mode:
- MetaTrader 5 on Windows: You can start MT5 in headless mode by running the terminal with specific command-line arguments. The MT5 terminal itself does not need to be visible for the API (Python) to connect and interact with it.
Steps:
Launch MT5 in Headless Mode:
Windows: You can start the MetaTrader 5 terminal with the
-silent
argument in the command line to suppress the GUI. Command: terminal.exe -silentConnecting from Python: Once the terminal is running in the background (in headless mode), your Python script can connect to the MetaTrader 5 application just like it would in normal mode, and it will not open the MT5 application window.
Conclusion
This Python script provides a solid foundation for interacting with MetaTrader 5. It allows you to execute trades, retrieve real-time ticker information, and analyze historical market data using the MT5 Python API. You can expand this framework to include more advanced trading strategies, risk management features, and data analysis tools, making it a versatile tool for developing automated trading systems.
By combining Python's power with MetaTrader 5's trading capabilities, you open the door to fully automated trading, where your algorithm can handle trading decisions in real time. Happy coding, and may your trades be profitable!
Here is the complete program listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | import MetaTrader5 as mt5 import time import pandas as pd from datetime import datetime # Account details account = nnn #your username password = "xxx"#password server = "MetaQuotes-Demo" #server SYMBOL = "TSLA" AMOUNT = 1 start_date = datetime(2022, 1, 1) # Start date for data end_date = datetime.now() # End date is the current date # Initialize MetaTrader 5 if not mt5.initialize(login=account, password=password, server=server): print(f"Failed to initialize MetaTrader 5: {mt5.last_error()}") quit() # Check account information account_info = mt5.account_info() if account_info: print(f"Account balance: {account_info.balance} USD") else: print(f"Failed to retrieve account info: {mt5.last_error()}") mt5.shutdown() quit() # Check and select symbol if not mt5.symbol_select(SYMBOL, True): print(f"Symbol {SYMBOL} not available or not selected.") mt5.shutdown() quit() # Get symbol info symbol_info = mt5.symbol_info(SYMBOL) if not symbol_info: print(f"Failed to retrieve symbol info for {SYMBOL}") mt5.shutdown() quit() # Get current price tick = mt5.symbol_info_tick(SYMBOL) if not tick: print(f"Failed to get price info for {SYMBOL}") mt5.shutdown() quit() price = tick.ask # Calculate lot size lot_size = max(symbol_info.volume_min, round((AMOUNT / price) / symbol_info.volume_step) * symbol_info.volume_step) # Create trade request trade_request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": SYMBOL, "volume": lot_size, "type": mt5.ORDER_TYPE_BUY, "price": price, "deviation": 20, # "magic": 123456, "comment": "Buy TSLA $500 trade", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_FOK, # Changed to IOC } # Optional: Wait for 1 second before sending the order time.sleep(1) # Send trade request result = mt5.order_send(trade_request) # Check trade result if result.retcode == mt5.TRADE_RETCODE_DONE: print(f"Trade executed successfully. Ticket={result.order}") else: print(f"Trade execution failed. Retcode={result.retcode}") print(f"Error details: {mt5.last_error()}") # Retrieve historical data for the specified date range rates = mt5.copy_rates_range(SYMBOL, mt5.TIMEFRAME_D1, start_date, end_date) # Check if data was retrieved if rates is None: print(f"Failed to retrieve data for {symbol}") mt5.shutdown() quit() # Convert the data to a pandas DataFrame data = pd.DataFrame(rates) # Convert timestamps to datetime data['time'] = pd.to_datetime(data['time'], unit='s') # Set the time column as the index data.set_index('time', inplace=True) # Print the first few rows of the data print(data.head()) # Shutdown MT5 mt5.shutdown() |
No comments:
Post a Comment