Made improvements to overall functionality

This commit is contained in:
Mike
2023-12-01 15:49:45 +02:00
parent f53fcb7dc3
commit 9f3d469f14
7 changed files with 300 additions and 105 deletions
+55 -22
View File
@@ -7,28 +7,32 @@ Author: Mike Kiwalabye
"""
import time
from flask import Flask, render_template, request, redirect, globals
from flask import Flask, render_template, request, redirect, json, Response
from src.connectors import mt5_connector
from src.models import neural_network_model
from src.strategies.trading_strategy import get_historical_data, calculate_indicators_and_detect_patterns, generate_trade_signals, execute_trade
from src.utils.visualization import plot_trade_signals
import threading
import pandas as pd
app = Flask(__name__)
# Define input shape for the neural network
input_shape = (10,) # Adjust the input shape based on your features and data
input_shape = (11,) # Adjust the input shape based on your features and data
# Create the neural network model
neural_network_model = neural_network_model.create_neural_network_model(input_shape)
# Global state to track whether MT5 is initialized
globals.mt5_initialized = False
mt5_initialized = False
latest_trade_signals = []
# Web Interface Routes
@app.route('/')
def index():
"""Render the main page with login form."""
"""Render the main page with the login form."""
return render_template('index.html')
@app.route('/login', methods=['POST'])
@@ -41,6 +45,7 @@ def login():
Returns:
- str: HTML response.
"""
global mt5_initialized
if request.method == 'POST':
credentials = {
'username': request.form['username'],
@@ -50,7 +55,7 @@ def login():
}
if mt5_connector.connect_to_mt5(credentials):
# Set MT5 initialization state to True
globals.mt5_initialized = True
mt5_initialized = True
# Redirect to the main dashboard or another page
return redirect('/dashboard')
else:
@@ -73,45 +78,68 @@ def dashboard():
def start_ml_bot():
"""
Handle the request to start the ML bot.
"""
# Start the ML bot
run_trading_bot_web_interface()
threading.Thread(target=run_trading_bot_web_interface).start()
# Return an empty response
return Response(status=200)
# Main Trading Bot Logic
@app.route("/stop_ml_bot", methods=['GET'])
def stop_ml_bot():
mt5_connector.stop_mt5_ml_bot()
redirect('/dashboard')
def map_signal_priority(signal_priority):
# Define a mapping for string values to integers
signal_mapping = {
'Both': 1,
'Pattern': 2,
'RSI': 3
# Add more mappings as needed
}
# Use the mapping, default to 0 if not found
return signal_mapping.get(signal_priority, 0)
# Main Trading Bot Logic
def run_trading_bot_web_interface():
"""
Run the trading bot using MetaTrader 5 credentials from the web interface.
"""
global latest_trade_signals
historical_data_df = pd.DataFrame()
while True:
try:
symbol = 'EURUSD'
lot_size = 0.01
stop_loss = 100
take_profit = 150
take_profit = 200
# Get the latest historical data
latest_data = get_historical_data(symbol).iloc[-1:]
historical_data_df = get_historical_data(symbol, historical_data_df)
# Calculate indicators and detect patterns for the latest data
df = calculate_indicators_and_detect_patterns(latest_data)
df = calculate_indicators_and_detect_patterns(historical_data_df)
# Generate trade signals for the latest data
df = generate_trade_signals(df)
print(df)
# Execute trades
for i in range(len(latest_data)):
signal = df['signal'].iloc[i]
if signal != 'None':
print(df['signal'].array)
execute_trade(signal, df, symbol, lot_size, stop_loss, take_profit)
df.to_csv('your_file.csv', sep='\t', index=False)
# Visualize data
# plot_trade_signals(df)
# Inside the run_trading_bot_web_interface function
latest_trade_signals = df.replace({pd.NA: 'null'}).to_json(orient='records')
# Execute trades
for i in range(len(df)):
signal_priority = df['signal'].iloc[i] # Replace with your actual value
mapped_priority = map_signal_priority(signal_priority)
if mapped_priority != 0:
execute_trade(mapped_priority, df, symbol, lot_size, stop_loss, take_profit)
except Exception as e:
print(f"Error running trading bot: {str(e)}")
@@ -119,6 +147,11 @@ def run_trading_bot_web_interface():
# Wait for the next iteration
time.sleep(60) # Adjust the time interval as needed
@app.route('/get_latest_trade_signals', methods=['GET'])
def get_latest_trade_signals():
global latest_trade_signals
return json.dumps(latest_trade_signals)
# Start the Flask app
if __name__ == '__main__':
app.run(debug=True)