import MetaTrader5 as mt5
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
mt5.initialize()
def load_data(symbol, timeframe, start_date, end_date):
rates = mt5.copy_rates_from(symbol, timeframe, start_date, end_date)
rates_df = pd.DataFrame(rates)
rates_df['time'] = pd.to_datetime(rates_df['time'], unit='s')
rates_df.set_index('time', inplace=True)
return rates_df
def prepare_data(df, lookback):
data = df.Close.values
data = data.reshape(-1, 1)
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
X = []
y = []
for i in range(lookback, len(data)):
X.append(data[i-lookback:i, 0])
y.append(data[i, 0])
X = np.array(X)
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
y = np.array(y)
return X, y, scaler
def build_model(lookback, neurons):
model = keras.Sequential()
model.add(keras.layers.LSTM(neurons, input_shape=(lookback, 1)))
model.add(keras.layers.Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, epochs):
history = model.fit(X_train, y_train, epochs=epochs, batch_size=32)
return history
def make_predictions(model, X_test, scaler):
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
return predictions
def visualize_results(df, predictions, title):
plt.plot(df.Close, label='Actual')
plt.plot(predictions, label='Predicted')
plt.title(title)
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()
def place_order(symbol, volume, sl, tp, direction):
result = mt5.order_send(symbol, direction, volume, sl, tp)
return result
def main(symbol, timeframe, start_date, end_date, lookback, neurons, epochs, volume, sl, tp, direction):
df = load_data(symbol, timeframe, start_date, end_date)
X_train, y_train, scaler = prepare_data(df[:-1000], lookback)
X_test, y_test, _ = prepare
# Adding Take Profit and Stop Loss to the Model
# Define the Take Profit and Stop Loss levels
take_profit = 50
stop_loss = -100
# Update the order management logic to include Take Profit and Stop Loss
for i in range(len(predictions)):
# If prediction is bullish (price will increase)
if predictions[i] > close_prices[i]:
# Place a Buy Order with the specified Take Profit and Stop Loss levels
mt5.order_send(symbol=symbol, cmd=mt5.ORDER_TYPE_BUY, volume=1, price=close_prices[i], sl=close_prices[i]+stop_loss, tp=close_prices[i]+take_profit)
# If prediction is bearish (price will decrease)
elif predictions[i] < close_prices[i]:
# Place a Sell Order with the specified Take Profit and Stop Loss levels
mt5.order_send(symbol=symbol, cmd=mt5.ORDER_TYPE_SELL, volume=1, price=close_prices[i], sl=close_prices[i]+take_profit, tp=close_prices[i]+stop_loss)
# Visualizing the results on historical data
import matplotlib.pyplot as plt
# Plot the actual close prices
plt.plot(close_prices, label='Actual Close Price')
# Plot the predicted close prices
plt.plot(predictions, label='Predicted Close Price')
# Add the title and labels to the plot
plt.title('Actual vs Predicted Close Price')
plt.xlabel('Time (in bars)')
plt.ylabel('Price')
# Show the legend
plt.legend()
# Display the plot
plt.show()