changes made to bot execution of mt5

This commit is contained in:
Mike
2023-07-15 22:15:34 +02:00
parent 0d0c94ae99
commit 52851c97e8
4 changed files with 283 additions and 291 deletions
+102 -115
View File
@@ -1,59 +1,78 @@
import time
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import talib
import matplotlib.pyplot as plt
import pymt5 as mt5
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import Adam from keras.optimizers import Adam
import socket from keras.layers import Dense, Dropout
from keras.models import Sequential
import pymt5
import matplotlib.pyplot as plt
import talib
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import pandas as pd
import time
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
def start_mt5(username, password, server, path): def connect_to_mt5_container():
# Ensure that all variables are the correct type server = "localhost" # Change to the appropriate IP or hostname if necessary
uname = int(username) # Username must be an int port = 15555 # Change to the appropriate port if necessary
pword = str(password) # Password must be a string login = 123456 # Change to your MetaTrader login number if necessary
trading_server = str(server) # Server must be a string password = "your_password" # Change to your MetaTrader password if necessary
filepath = str(path) # Filepath must be a string
# Connect to MetaTrader 5 # Connect to MetaTrader 5
if mt5.initialize(login=uname, password=pword, server=trading_server, path=filepath): mt5 = pymt5.PyMT5()
# Login to MT5 mt5.onConnected = onConnected
if mt5.login(login=uname, password=pword, server=trading_server): mt5.onDisconnected = onDisconnected
return True mt5.onData = onData
else:
print("Login Fail")
quit()
return PermissionError
else:
print("MT5 Initialization Failed")
quit()
return ConnectionAbortedError
# Wait for the connection to be established
while not onConnected:
time.sleep(0.1)
def connect_to_mt5(username, password, server, path): # Send login request
# Start the MetaTrader 5 instance login_request = {
if start_mt5(username, password, server, path): 'ver': '3',
print("Connected to MetaTrader 5") 'type': '1',
'login': str(login),
'password': password,
'res': '0'
}
mt5.broadcast(login_request)
# Wait for the login response
while not onConnected:
time.sleep(0.1)
# Check if login was successful
if onConnected:
print(f"Connected to MetaTrader 5: {onConnected}")
else: else:
print("Failed to connect to MetaTrader 5") print("Failed to connect to MetaTrader 5")
return
# Define the symbols and timeframes def onConnected(client_info):
symbol = 'EURUSD' print(f"Connected: {client_info}")
timeframe = mt5.TIMEFRAME_H1
# Set up initial variables
lot_size = 0.01
stop_loss = 100
take_profit = 150
# Define TensorFlow neural network model
def create_neural_network_model(input_shape): def onDisconnected(client_info):
print(f"Disconnected: {client_info}")
def onData(data):
print(f"Received data: {data}")
def start_mt5_bot():
# Define the symbols and timeframes
symbol = 'EURUSD'
timeframe = 60 # H1 timeframe (1 hour)
# Set up initial variables
lot_size = 0.01
stop_loss = 100
take_profit = 150
# Define TensorFlow neural network model
def create_neural_network_model(input_shape):
model = Sequential() model = Sequential()
model.add(Dense(64, activation='relu', input_shape=input_shape)) model.add(Dense(64, activation='relu', input_shape=input_shape))
model.add(Dropout(0.2)) model.add(Dropout(0.2))
@@ -62,28 +81,26 @@ def create_neural_network_model(input_shape):
model.add(Dense(1, activation='sigmoid')) model.add(Dense(1, activation='sigmoid'))
return model return model
# Define input shape for the neural network
# Adjust the input shape based on your features and data
input_shape = (10,)
# Define input shape for the neural network # Create the neural network model
input_shape = (10,) # Adjust the input shape based on your features and data neural_network_model = create_neural_network_model(input_shape)
# Create the neural network model # Compile the model
neural_network_model = create_neural_network_model(input_shape) neural_network_model.compile(optimizer=Adam(
# Compile the model
neural_network_model.compile(optimizer=Adam(
learning_rate=0.001), loss='binary_crossentropy') learning_rate=0.001), loss='binary_crossentropy')
def get_historical_data():
def get_historical_data():
# Retrieve historical data # Retrieve historical data
rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, 1000) rates = pymt5.copy_rates_from_pos(symbol, timeframe, 0, 1000)
df = pd.DataFrame(rates) df = pd.DataFrame(rates)
df['time'] = pd.to_datetime(df['time'], unit='s') df['time'] = pd.to_datetime(df['time'], unit='s')
df.set_index('time', inplace=True) df.set_index('time', inplace=True)
return df return df
def calculate_indicators_and_detect_patterns(df):
def calculate_indicators_and_detect_patterns(df):
# Calculate RSI # Calculate RSI
rsi_period = 14 rsi_period = 14
df['rsi'] = talib.RSI(df['close'], rsi_period) df['rsi'] = talib.RSI(df['close'], rsi_period)
@@ -123,12 +140,12 @@ def calculate_indicators_and_detect_patterns(df):
(df['low'].shift(2) < df['low']) & ( (df['low'].shift(2) < df['low']) & (
df['low'].shift(-2) < df['low']), 'Double Bottom', 'None' df['low'].shift(-2) < df['low']), 'Double Bottom', 'None'
) )
df.loc[df['bottom_pattern'] != 'None', 'pattern'] = df['bottom_pattern'] df.loc[df['bottom_pattern'] != 'None',
'pattern'] = df['bottom_pattern']
return df return df
def generate_signals(df):
def generate_signals(df):
# Determine trade signals based on divergences, patterns, and trend direction # Determine trade signals based on divergences, patterns, and trend direction
df['signal'] = 'None' df['signal'] = 'None'
df['divergence_signal'] = np.where((df['rsi_divergence'] == True) & (df['pattern'] != 'None'), 'Both', df['divergence_signal'] = np.where((df['rsi_divergence'] == True) & (df['pattern'] != 'None'), 'Both',
@@ -158,8 +175,7 @@ def generate_signals(df):
return df return df
def execute_trade(signal, df):
def execute_trade(signal, df):
# Implement risk management and trade execution logic based on the signals generated # Implement risk management and trade execution logic based on the signals generated
# Update TensorFlow neural network model with trade outcome (loss or win) # Update TensorFlow neural network model with trade outcome (loss or win)
@@ -176,43 +192,15 @@ def execute_trade(signal, df):
try: try:
if signal == 'Buy': if signal == 'Buy':
# Place a buy trade # Place a buy trade
result = mt5.ORDER_RESULT_FAIL result = pymt5.order_send(symbol, pymt5.OP_BUY, lot_size, 0, stop_loss, take_profit,
request = { "Buy trade", 123456, pymt5.ORDER_TIME_GTC, 0)
"action": mt5.TRADE_ACTION_DEAL, outcome = 'Win' if result.retcode == pymt5.TRADE_RETCODE_DONE else 'Loss'
"symbol": symbol,
"volume": lot_size,
"type": mt5.ORDER_TYPE_BUY,
"price": mt5.symbol_info_tick(symbol).ask,
"sl": mt5.symbol_info_tick(symbol).ask - stop_loss * mt5.symbol_info(symbol).point,
"tp": mt5.symbol_info_tick(symbol).ask + take_profit * mt5.symbol_info(symbol).point,
"deviation": 20,
"magic": 123456,
"comment": "Buy trade",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
result = mt5.order_send(request)
outcome = 'Win' if result.retcode == mt5.TRADE_RETCODE_DONE else 'Loss'
elif signal == 'Sell': elif signal == 'Sell':
# Place a sell trade # Place a sell trade
result = mt5.ORDER_RESULT_FAIL result = pymt5.order_send(symbol, pymt5.OP_SELL, lot_size, 0, stop_loss, take_profit,
request = { "Sell trade", 123456, pymt5.ORDER_TIME_GTC, 0)
"action": mt5.TRADE_ACTION_DEAL, outcome = 'Win' if result.retcode == pymt5.TRADE_RETCODE_DONE else 'Loss'
"symbol": symbol,
"volume": lot_size,
"type": mt5.ORDER_TYPE_SELL,
"price": mt5.symbol_info_tick(symbol).bid,
"sl": mt5.symbol_info_tick(symbol).bid + stop_loss * mt5.symbol_info(symbol).point,
"tp": mt5.symbol_info_tick(symbol).bid - take_profit * mt5.symbol_info(symbol).point,
"deviation": 20,
"magic": 123456,
"comment": "Sell trade",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
result = mt5.order_send(request)
outcome = 'Win' if result.retcode == mt5.TRADE_RETCODE_DONE else 'Loss'
# Example trade outcome information # Example trade outcome information
trade_outcome = { trade_outcome = {
@@ -228,15 +216,15 @@ def execute_trade(signal, df):
update_neural_network_model(trade_outcome) update_neural_network_model(trade_outcome)
# Example print statements for debugging # Example print statements for debugging
print(f"Executed {signal} trade with position size: {position_size}") print(
f"Executed {signal} trade with position size: {position_size}")
print(f"Trade outcome: {trade_outcome}") print(f"Trade outcome: {trade_outcome}")
# Additional logic for trade management, monitoring, etc. # Additional logic for trade management, monitoring, etc.
except Exception as e: except Exception as e:
print(f"Error executing trade: {str(e)}") print(f"Error executing trade: {str(e)}")
def update_neural_network_model(trade_outcome):
def update_neural_network_model(trade_outcome):
# Implement code to update the neural network model based on trade outcome # Implement code to update the neural network model based on trade outcome
pattern = trade_outcome['pattern'] pattern = trade_outcome['pattern']
divergence_strength = trade_outcome['divergence_strength'] divergence_strength = trade_outcome['divergence_strength']
@@ -267,10 +255,9 @@ def update_neural_network_model(trade_outcome):
neural_network_model.fit(X_train, y_train, epochs=10, batch_size=32) neural_network_model.fit(X_train, y_train, epochs=10, batch_size=32)
# Save the updated model weights # Save the updated model weights
neural_network_model.save_weights('model_weights.h5') neural_network_model.save_weights('weights/model_weights.h5')
def preprocess_data(dataset):
def preprocess_data(dataset):
# Define the numerical features (if any) # Define the numerical features (if any)
numerical_features = [] # Update with the actual numerical feature column names numerical_features = [] # Update with the actual numerical feature column names
@@ -296,8 +283,7 @@ def preprocess_data(dataset):
# Return the preprocessed input features and target labels # Return the preprocessed input features and target labels
return input_features, target_labels return input_features, target_labels
def visualize_data(df):
def visualize_data(df):
plt.figure(figsize=(10, 6)) plt.figure(figsize=(10, 6))
plt.plot(df.index, df['close'], label='Close') plt.plot(df.index, df['close'], label='Close')
# Add visualizations for other indicators, levels, and patterns # Add visualizations for other indicators, levels, and patterns
@@ -308,14 +294,9 @@ def visualize_data(df):
plt.legend() plt.legend()
plt.show() plt.show()
def run_trading_bot():
def run_trading_bot(): # Connect to MetaTrader 5 container
# Connect to MetaTrader 5 connect_to_mt5_container()
connect_to_mt5(username='your_username', password='your_password',
server='your_server', path='your_mt5_installation_path')
# Load TensorFlow neural network model weights
neural_network_model.load_weights('model_weights.h5')
while True: while True:
try: try:
@@ -343,9 +324,15 @@ def run_trading_bot():
# Wait for the next iteration # Wait for the next iteration
time.sleep(60) # Adjust the time interval as needed time.sleep(60) # Adjust the time interval as needed
# Run the trading bot
run_trading_bot()
# Run the trading bot # Load TensorFlow neural network model weights
run_trading_bot() neural_network_model.load_weights('weights/model_weights.h5')
# Disconnect from MetaTrader 5 # Disconnect from MetaTrader 5
mt5.shutdown() pymt5.shutdown()
# Start the MetaTrader 5 bot
start_mt5_bot()
View File
+6 -1
View File
@@ -12,6 +12,10 @@ services:
- "15558:15558" - "15558:15558"
volumes: volumes:
- ejtraderMT:/data - ejtraderMT:/data
environment:
- DISPLAY=host.docker.internal:0
- MT5_PASSWORD=your_password
- MT5_SERVER=your_server
trading_bot: trading_bot:
container_name: trading_bot container_name: trading_bot
@@ -28,7 +32,8 @@ services:
build: build:
context: . context: .
dockerfile: docker/DockerFile.mt5_bridge dockerfile: docker/DockerFile.mt5_bridge
volumes: -./bridge:/bridge volumes:
- ./bridge:/bridge
depends_on: depends_on:
- metatrader_service - metatrader_service
- trading_bot - trading_bot
+1 -1
View File
@@ -7,6 +7,6 @@ WORKDIR /app
COPY bridge/mt5_bridge.py . COPY bridge/mt5_bridge.py .
# Install any dependencies required by the bridge script # Install any dependencies required by the bridge script
RUN pip install python-socketio python-engineio RUN pip install python-socketio python-engineio requests
CMD ["python", "mt5_bridge.py"] CMD ["python", "mt5_bridge.py"]