Saturday, 31 August 2024


TIKTOK SINTETICO MYM-A MODO SCALA




 import tkinter as tk

from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from bs4 import BeautifulSoup
import time
import numpy as np
import cv2
import pyttsx3
import os
import moviepy.editor as mpe
from PIL import Image, ImageTk
import io

# Function to scrape the news using Selenium and BeautifulSoup
def fetch_news():
    print("Fetching news...")
    try:
        driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()))
        driver.get("https://www.bbc.com/news")
        time.sleep(20)
        soup = BeautifulSoup(driver.page_source, "html.parser")
        articles = soup.find_all('h2', {"data-testid": "card-headline"}, limit=3)
        news = []
        for article in articles:
            title = article.text if article else "No title available."
            description = article.find_next('p').text if article.find_next('p') else "No description available."
            image_tag = article.find_previous('img')
            image_data = None
            if image_tag and 'src' in image_tag.attrs:
                image_url = image_tag['src']
                driver.get(image_url)
                image_data = driver.get_screenshot_as_png()
            news.append((title, description, image_data))
        driver.quit()
        return news
    except Exception as e:
        print(f"Failed to fetch news: {e}")
        return [("Error", f"Failed to fetch news: {e}", None)]

def data_to_image(image_data):
    try:
        img = Image.open(io.BytesIO(image_data))
        return img
    except Exception as e:
        print(f"Failed to convert image data: {e}")
        return None

def text_to_speech(news):
    engine = pyttsx3.init()
    audio_files = []
    for i, (title, description, _) in enumerate(news):
        text = f"{title}. {description}"
        audio_path = f"news_{i + 1}.wav"
        engine.save_to_file(text, audio_path)
        audio_files.append(audio_path)
    engine.runAndWait()
    return audio_files

def generate_video(news, audio_files):
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    fps = 24
    frame_size = (1080, 1920)  # Adjusted resolution for TikTok
    word_duration = 14
    num_frames_per_word = fps * word_duration
    num_frames = num_frames_per_word * len(news)
    video_path = 'news_video.mp4'
    out = cv2.VideoWriter(video_path, fourcc, fps, frame_size)

    for i in range(num_frames):
        paragraph_index = i // num_frames_per_word
        frame = np.zeros((1920, 1080, 3), dtype=np.uint8)  # Black background by default

        title, description, image_data = news[paragraph_index]
        text = f"{title}: {description}"

        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 1.5
        font_thickness = 3
        max_line_width = frame_size[0] - 40
        wrapped_text = wrap_text(text, font, font_scale, max_line_width)

        if image_data:
            img = data_to_image(image_data)
            if img:
                img = img.resize((800, 800), Image.ANTIALIAS)  # Resize image to 100x100 for debugging
                img_np = np.array(img)
                if img_np.shape[2] == 4:
                    img_np = cv2.cvtColor(img_np, cv2.COLOR_RGBA2RGB)
               
                img_y, img_x, _ = img_np.shape
                # Calculate the center position for the image
                center_x = (frame_size[0] - img_x) // 2
                center_y = (frame_size[1] - img_y) // 2
                # Place the image at the center
                frame[center_y:center_y + img_y, center_x:center_x + img_x] = img_np

        y0, dy = 1500, 60  # Adjusted y-position for high-resolution text overlay
        for j, line in enumerate(wrapped_text):
            text_size = cv2.getTextSize(line, font, font_scale, font_thickness)[0]
            text_x = int((frame_size[0] - text_size[0]) / 2)
            text_y = y0 + j * dy
            cv2.putText(frame, line, (text_x, text_y), font, font_scale, (255, 255, 255), font_thickness, lineType=cv2.LINE_AA)

        out.write(frame)

    out.release()

    video_clip = mpe.VideoFileClip(video_path)
    audio_clips = [mpe.AudioFileClip(audio) for audio in audio_files]
    audio_start_times = [i * word_duration for i in range(len(news))]
    final_audio = mpe.CompositeAudioClip([
        audio_clips[i].set_start(audio_start_times[i])
        for i in range(len(news))
    ])
    final_clip = video_clip.set_audio(final_audio)
    final_clip.write_videofile("final_news_video_with_audio.mp4", codec="libx264", fps=fps)

    for audio in audio_files:
        os.remove(audio)

    print("Video with synchronized audio saved successfully.")

def wrap_text(text, font, font_scale, max_width):
    words = text.split(' ')
    lines = []
    current_line = ''

    for word in words:
        test_line = current_line + word + ' '
        text_size = cv2.getTextSize(test_line, font, font_scale, 1)[0]
        if text_size[0] <= max_width:
            current_line = test_line
        else:
            lines.append(current_line)
            current_line = word + ' '

    lines.append(current_line.strip())
    return lines

def display_news():
    for widget in news_frame.winfo_children():
        widget.destroy()

    news_data = fetch_news()
    audio_files = text_to_speech(news_data)
    generate_video(news_data, audio_files)

    for i, (title, description, image_data) in enumerate(news_data):
        title_label = tk.Label(news_frame, text=title, font=("Arial", 14, "bold"))
        title_label.grid(row=i*3, column=0, sticky="w", padx=10, pady=5)

        desc_label = tk.Label(news_frame, text=description, wraplength=600, justify="left")
        desc_label.grid(row=i*3+1, column=0, sticky="w", padx=10, pady=5)

        if image_data:
            img = data_to_image(image_data)
            if img:
                img.thumbnail((300, 200))
                img_tk = ImageTk.PhotoImage(img)
                img_label = tk.Label(news_frame, image=img_tk)
                img_label.image = img_tk
                img_label.grid(row=i*3+2, column=0, sticky="w", padx=10, pady=5)

root = tk.Tk()
root.title("Top News")
root.geometry("250x100")

news_frame = tk.Frame(root)
news_frame.pack(fill="both", expand=True)

connect_button = tk.Button(root, text="Connect", command=display_news, font=("Arial", 12))
connect_button.pack(pady=20)

root.mainloop()

Friday, 30 August 2024




SYNTHETHIC TIKTOK MYM-A 


NOTA: MODIFICAR CALIDAD <>







 import tkinter as tk

from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from bs4 import BeautifulSoup
import time
import numpy as np
import cv2
import pyttsx3
import os
import moviepy.editor as mpe
from PIL import Image, ImageTk
import io

# Function to scrape the news using Selenium and BeautifulSoup
def fetch_news():
    print("Fetching news...")
    try:
        driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()))
        driver.get("https://www.bbc.com/news")
        time.sleep(20)
        soup = BeautifulSoup(driver.page_source, "html.parser")
        articles = soup.find_all('h2', {"data-testid": "card-headline"}, limit=3)
        news = []
        for article in articles:
            title = article.text if article else "No title available."
            description = article.find_next('p').text if article.find_next('p') else "No description available."
            image_tag = article.find_previous('img')
            image_data = None
            if image_tag and 'src' in image_tag.attrs:
                image_url = image_tag['src']
                driver.get(image_url)
                image_data = driver.get_screenshot_as_png()
            news.append((title, description, image_data))
        driver.quit()
        return news
    except Exception as e:
        print(f"Failed to fetch news: {e}")
        return [("Error", f"Failed to fetch news: {e}", None)]

def data_to_image(image_data):
    try:
        img = Image.open(io.BytesIO(image_data))
        return img
    except Exception as e:
        print(f"Failed to convert image data: {e}")
        return None

def text_to_speech(news):
    engine = pyttsx3.init()
    audio_files = []
    for i, (title, description, _) in enumerate(news):
        text = f"{title}. {description}"
        audio_path = f"news_{i + 1}.wav"
        engine.save_to_file(text, audio_path)
        audio_files.append(audio_path)
    engine.runAndWait()
    return audio_files

def generate_video(news, audio_files):
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    fps = 24
    frame_size = (1080, 1920)  # Adjusted resolution for TikTok
    word_duration = 14
    num_frames_per_word = fps * word_duration
    num_frames = num_frames_per_word * len(news)
    video_path = 'news_video.mp4'
    out = cv2.VideoWriter(video_path, fourcc, fps, frame_size)

    for i in range(num_frames):
        paragraph_index = i // num_frames_per_word
        frame = np.zeros((1920, 1080, 3), dtype=np.uint8)  # Black background by default

        title, description, image_data = news[paragraph_index]
        text = f"{title}: {description}"

        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 1.5
        font_thickness = 3
        max_line_width = frame_size[0] - 40
        wrapped_text = wrap_text(text, font, font_scale, max_line_width)

        if image_data:
            img = data_to_image(image_data)
            if img:
                img = img.resize(frame_size, Image.ANTIALIAS)  # Force resize to cover the entire screen (1080x1920)
                img_np = np.array(img)
                if img_np.shape[2] == 4:
                    img_np = cv2.cvtColor(img_np, cv2.COLOR_RGBA2RGB)
               
                img_y, img_x, _ = img_np.shape
                frame[:img_y, :img_x] = img_np  # Directly replace the frame with the resized image

        y0, dy = 1500, 60  # Adjusted y-position for high-resolution text overlay
        for j, line in enumerate(wrapped_text):
            text_size = cv2.getTextSize(line, font, font_scale, font_thickness)[0]
            text_x = int((frame_size[0] - text_size[0]) / 2)
            text_y = y0 + j * dy
            cv2.putText(frame, line, (text_x, text_y), font, font_scale, (255, 255, 255), font_thickness, lineType=cv2.LINE_AA)

        out.write(frame)

    out.release()

    video_clip = mpe.VideoFileClip(video_path)
    audio_clips = [mpe.AudioFileClip(audio) for audio in audio_files]
    audio_start_times = [i * word_duration for i in range(len(news))]
    final_audio = mpe.CompositeAudioClip([
        audio_clips[i].set_start(audio_start_times[i])
        for i in range(len(news))
    ])
    final_clip = video_clip.set_audio(final_audio)
    final_clip.write_videofile("final_news_video_with_audio.mp4", codec="libx264", fps=fps)

    for audio in audio_files:
        os.remove(audio)

    print("Video with synchronized audio saved successfully.")

def wrap_text(text, font, font_scale, max_width):
    words = text.split(' ')
    lines = []
    current_line = ''

    for word in words:
        test_line = current_line + word + ' '
        text_size = cv2.getTextSize(test_line, font, font_scale, 1)[0]
        if text_size[0] <= max_width:
            current_line = test_line
        else:
            lines.append(current_line)
            current_line = word + ' '

    lines.append(current_line.strip())
    return lines

def display_news():
    for widget in news_frame.winfo_children():
        widget.destroy()

    news_data = fetch_news()
    audio_files = text_to_speech(news_data)
    generate_video(news_data, audio_files)

    for i, (title, description, image_data) in enumerate(news_data):
        title_label = tk.Label(news_frame, text=title, font=("Arial", 14, "bold"))
        title_label.grid(row=i*3, column=0, sticky="w", padx=10, pady=5)

        desc_label = tk.Label(news_frame, text=description, wraplength=600, justify="left")
        desc_label.grid(row=i*3+1, column=0, sticky="w", padx=10, pady=5)

        if image_data:
            img = data_to_image(image_data)
            if img:
                img.thumbnail((300, 200))
                img_tk = ImageTk.PhotoImage(img)
                img_label = tk.Label(news_frame, image=img_tk)
                img_label.image = img_tk
                img_label.grid(row=i*3+2, column=0, sticky="w", padx=10, pady=5)

root = tk.Tk()
root.title("Top News")
root.geometry("250x100")

news_frame = tk.Frame(root)
news_frame.pack(fill="both", expand=True)

connect_button = tk.Button(root, text="Connect", command=display_news, font=("Arial", 12))
connect_button.pack(pady=20)

root.mainloop()

Monday, 26 August 2024

Magnifier Icon
Magnifier Icon

 SEEK JOB NOTES:


LA. SD. 

https://www.sandiego.edu/cas/art-architecture-art-history/architecture/careers-and-internships.php




https://yulys.com/jobs/entry-level-architectural-designer-f659a8de-4385-44bc-9a86-b6ad510e9dee?utm_campaign=google_jobs_apply&utm_source=google_jobs_apply&utm_medium=organic



Project Architect / Senior Job Captain - SD in San Diego, CA for SGPA Architecture and Planning (aia.org)



https://www.linkedin.com/jobs/view/3940578479




https://www.linkedin.com/jobs/view/3964813346




https://www.linkedin.com/jobs/view/3994015885




https://www.linkedin.com/jobs/view/3945894574



https://www.linkedin.com/jobs/view/3976090095 ++++IR




https://swccd.joinhandshake.com/stu/employers/17918




Rough Carpentry Estimator/ Project Manager - skilled trades / artisan - job employment - craigslist




Civil Engineering Drafting/Design - architect / engineer / cad - job employment - craigslist





Estimating Coordinator - admin / office - administrative job employment - craigslist






Portfolio Expansion: Continue building on your projects like the "Tiny House" prototype​ (itch.io). Document and showcase your progress on platforms like GitHub or Itch.io to attract collaborators and users.









Thursday, 15 August 2024

 MYM-A    (!)


COLISEO
___________________________________________________________________________________

 I suggest you focus on the probability of whether the price will be higher or lower at the close. This approach allows you to handle uncertainty more pragmatically and better capture the random nature of markets.


developed a hidden markov model, to tell you in a nutshell the hidden regimes of the market.


UNCENSORED GPT 

cryptojacking


How to Backtest a Trading Strategy on Tradingview


RSI, MACD, moving averages, and price volatility. Define states such as “Strong Bull,” “Weak Bull,” “Neutral,” “Weak Bear,” and “Strong Bear.” Each state corresponds to distinct market dynamics, allowing the Q-learning algorithm 

Buy low, sell high, and manage risks with discipline.




-INPUT TABLES: data tables. for machine learning or API 


  1. I made two beautiful trades just because of a fucking news from a telegram channel regarding Lebanon


Go directly to td365. Do your research man. I won't spoon feed u
You're trading with prime market terminal. I have a Bloomberg

  1. Intake the bias from NOVASCALPER and have someone trading with an EA with them



I know shitty mm brokers wich pays for losses up to 40%, deposit 1k in an ecn and 1k in mm and hedge those accounts, you earn 200 dollars everytime you do that

Start following Tom Hougaard and copy his trades 1:1


  1. GRU: Predict time series trends with memory of past data.
  2. LSTM: Capture long-term dependencies in stock price movements.
  3. Gradient Boosting: Enhance predictions by combining weak models iteratively.
  4. Hyperopt: Optimize model parameters for better trading strategy performance.
  5. ARIMA: Model and forecast future prices using past price data.
  6. SVR: Predict stock prices by finding optimal hyperplane for regression.
  7. Random Forest: Aggregate multiple decision trees for robust market predictions.
  8. MLP: Neural network for non-linear stock price prediction.
  9. Transformer: Capture relationships between different time series data.
  10. Monte Carlo Methods: Simulate and assess risk in trading strategies. -Louis Bachelier's: primal formula


Trading Software | New Hope Inc. - Trading Systems Provider


Tuesday, 6 August 2024

THE MAN:


(SR):








UP TO DATE TASK "LIST":






1. Hack METATRADER (brute force)

2. COMPLETE THE GAME

3. YOU HAVE MATH CLASS

4. HACK INSTAGRAM AUTOMATION

5. VIDEO GENERATOR AUTOMATION

6. ARCHITECTURE PORTFOLIO/JOB (HACK)

7. SENTRI STATUS

8. FULL "FAFSA" ANALYSIS

9. ESCAPE TIJUANA "ESTIMATION DATE"

10. SAN DIEGO RECOURSES FOR MINIMAL RENTAL

______________________________________________________________

                                                     "Q"





 MYM-A MODO CHISTE


import tkinter as tk
from tkinter import messagebox
import MetaTrader5 as mt5
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, GRU, Dense
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.svm import SVR
from sklearn.neural_network import MLPRegressor
from hyperopt import hp, tpe, fmin, Trials
from hyperopt.pyll.base import scope
from statsmodels.tsa.arima.model import ARIMA
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import threading
import time
import random

# Variables to track the winning rate
total_trades = 0
profitable_trades = 0

def main():
    global root, display_var, click_button, message_label, connect_button, win_rate_var
    root = tk.Tk()
    root.title("MYM-A MODO CHEZ")
    root.geometry("600x400")

    # Create frames
    dice_frame = tk.Frame(root, width=300, height=400)
    dice_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
   
    login_frame = tk.Frame(root, width=300, height=400)
    login_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

    # Dice UI
    title_label = tk.Label(dice_frame, text="3 FACE DICE", font=("Helvetica", 16))
    title_label.pack(pady=10)

    display_var = tk.StringVar()
    display_label = tk.Label(dice_frame, textvariable=display_var, font=("Helvetica", 24), width=5, height=2, relief="solid")
    display_label.pack(pady=20)

    click_button = tk.Button(dice_frame, text="Click", font=("Helvetica", 14), command=on_button_click)
    click_button.pack(pady=10)

    message_label = tk.Label(dice_frame, text="", font=("Helvetica", 14), fg="green")
    message_label.pack(pady=10)

    win_rate_var = tk.StringVar()
    win_rate_label = tk.Label(dice_frame, textvariable=win_rate_var, font=("Helvetica", 14))
    win_rate_label.pack(pady=10)
    update_win_rate()  # Initialize the win rate display

    # Login UI
    login_title = tk.Label(login_frame, text="🏧MYM-A", font=("Helvetica", 20))
    login_title.pack(pady=20)

    login_label = tk.Label(login_frame, text="Login:", font=("Helvetica", 14))
    login_label.pack(pady=5)
    login_entry = tk.Entry(login_frame, font=("Helvetica", 14))
    login_entry.pack(pady=5)
    login_entry.insert(0, "312128713")

    password_label = tk.Label(login_frame, text="Password:", font=("Helvetica", 14))
    password_label.pack(pady=5)
    password_entry = tk.Entry(login_frame, show="*", font=("Helvetica", 14))
    password_entry.pack(pady=5)
    password_entry.insert(0, "Sexo247420@")

    server_label = tk.Label(login_frame, text="Server:", font=("Helvetica", 14))
    server_label.pack(pady=5)
    server_entry = tk.Entry(login_frame, font=("Helvetica", 14))
    server_entry.pack(pady=5)
    server_entry.insert(0, "XMGlobal-MT5 7")

    connect_button = tk.Button(login_frame, text="Connect", font=("Helvetica", 14),
                               command=lambda: connect_to_mt5(login_entry.get(), password_entry.get(), server_entry.get()))
    connect_button.pack(pady=20)

    # Start the automatic dice rolling in a separate thread
    threading.Thread(target=auto_roll, daemon=True).start()

    root.mainloop()

def roll_dice():
    def loading_animation():
        loading_text = ["", ".", "..", "..."]
        for _ in range(3):
            for text in loading_text:
                display_var.set(text)
                time.sleep(0.5)

    loading_animation()
    dice_result = random.randint(1, 3)
    display_var.set(dice_result)

    if dice_result == 3:
        message_label.config(text="Click Connect")
        root.after(0, connect_button.invoke)
    else:
        root.after(500, enable_button)

def reset():
    message_label.config(text="")
    display_var.set("")
    enable_button()

def on_button_click():
    threading.Thread(target=roll_dice).start()
    click_button.config(state="disabled")

def enable_button():
    click_button.config(state="normal")

def auto_roll():
    while True:
        time.sleep(10)
        if click_button["state"] == "normal":
            root.after(0, on_button_click)

def connect_to_mt5(login, password, server):
    if not mt5.initialize():
        messagebox.showerror("Error", "initialize() failed")
        mt5.shutdown()
        return

    authorized = mt5.login(login=int(login), password=password, server=server)
    if authorized:
        print("Connected to MetaTrader 5")
        start_automation()
    else:
        messagebox.showerror("Error", "Failed to connect to MetaTrader 5")

def start_automation():
    def automation_loop():
        while True:
            symbol = "BTCUSD"
            timeframe = mt5.TIMEFRAME_D1
            days = 600
            data = fetch_historical_data(symbol, timeframe, days)
            scaled_data, scaler = preprocess_data(data)
           
            # Train models
            lstm_model = train_lstm_model(scaled_data)
            gb_model = train_gb_model(scaled_data)
            hyperopt_model = train_hyperopt_model(scaled_data)
            arima_model = train_arima_model(data['close'])
            svr_model = train_svr_model(scaled_data)
            rf_model = train_rf_model(scaled_data)
            mlp_model = train_mlp_model(scaled_data)
            transformer_model = train_transformer_model(scaled_data)
            gru_model = train_gru_model(scaled_data)

            # Predict future prices
            future_days = 60
            lstm_predictions = predict_future_lstm(lstm_model, scaled_data, future_days)
            gb_predictions = predict_future_gb(gb_model, scaled_data, future_days)
            hyperopt_predictions = predict_future_hyperopt(hyperopt_model, scaled_data, future_days)
            arima_predictions = predict_future_arima(arima_model, len(data), future_days)
            svr_predictions = predict_future_svr(svr_model, scaled_data, future_days)
            rf_predictions = predict_future_rf(rf_model, scaled_data, future_days)
            mlp_predictions = predict_future_mlp(mlp_model, scaled_data, future_days)
            transformer_predictions = predict_future_transformer(transformer_model, scaled_data, future_days)
            gru_predictions = predict_future_gru(gru_model, scaled_data, future_days)

            # Combine predictions
            combined_predictions = (np.array(lstm_predictions) +
                                    np.array(gb_predictions) +
                                    np.array(hyperopt_predictions) +
                                    np.array(arima_predictions) +
                                    np.array(svr_predictions) +
                                    np.array(rf_predictions) +
                                    np.array(mlp_predictions) +
                                    np.array(transformer_predictions) +
                                    np.array(gru_predictions)) / 9
            combined_predictions = scaler.inverse_transform(np.array(combined_predictions).reshape(-1, 1))

            # Determine trend
            trend = determine_trend(combined_predictions)
            if trend == "Bull":
                virtual_trade(mt5.ORDER_TYPE_BUY, combined_predictions)
            elif trend == "Bear":
                virtual_trade(mt5.ORDER_TYPE_SELL, combined_predictions)
            time.sleep(3600)  # Run the prediction and trading every hour

    threading.Thread(target=automation_loop, daemon=True).start()

def fetch_historical_data(symbol, timeframe, days):
    rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, days)
    if rates is None or len(rates) == 0:
        raise Exception("Failed to retrieve rates")
    df = pd.DataFrame(rates)
    df['time'] = pd.to_datetime(df['time'], unit='s')
    return df[['time', 'open', 'high', 'low', 'close', 'tick_volume']]

def preprocess_data(data):
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data[['open', 'high', 'low', 'close', 'tick_volume']])
    return scaled_data, scaler

def train_lstm_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)

    model = Sequential()
    model.add(LSTM(100, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
    model.add(LSTM(100, return_sequences=False))
    model.add(Dense(50))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mean_squared_error')

    model.fit(X_train, y_train, batch_size=32, epochs=50)
    return model

def train_gb_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)
    X_train = X_train.reshape(X_train.shape[0], -1)

    def objective(params):
        model = GradientBoostingRegressor(
            n_estimators=int(params['n_estimators']),
            learning_rate=params['learning_rate'],
            max_depth=int(params['max_depth']),
            min_samples_split=int(params['min_samples_split']),
            min_samples_leaf=int(params['min_samples_leaf'])
        )
        X_train_split, X_val_split, y_train_split, y_val_split = train_test_split(X_train, y_train, test_size=0.2)
        model.fit(X_train_split, y_train_split)
        y_pred = model.predict(X_val_split)
        return mean_squared_error(y_val_split, y_pred)

    space = {
        'n_estimators': scope.int(hp.quniform('n_estimators', 50, 200, 10)),
        'learning_rate': hp.loguniform('learning_rate', -4, 0),
        'max_depth': scope.int(hp.quniform('max_depth', 1, 9, 1)),
        'min_samples_split': scope.int(hp.quniform('min_samples_split', 2, 10, 1)),
        'min_samples_leaf': scope.int(hp.quniform('min_samples_leaf', 1, 10, 1))
    }

    trials = Trials()
    best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=50, trials=trials)
    model = GradientBoostingRegressor(
        n_estimators=int(best['n_estimators']),
        learning_rate=best['learning_rate'],
        max_depth=int(best['max_depth']),
        min_samples_split=int(best['min_samples_split']),
        min_samples_leaf=int(best['min_samples_leaf'])
    )
    model.fit(X_train, y_train)
    return model

def train_hyperopt_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)
    X_train = X_train.reshape(X_train.shape[0], -1)

    def objective(params):
        model = GradientBoostingRegressor(
            n_estimators=int(params['n_estimators']),
            learning_rate=params['learning_rate'],
            max_depth=int(params['max_depth']),
            min_samples_split=int(params['min_samples_split']),
            min_samples_leaf=int(params['min_samples_leaf'])
        )
        X_train_split, X_val_split, y_train_split, y_val_split = train_test_split(X_train, y_train, test_size=0.2)
        model.fit(X_train_split, y_train_split)
        y_pred = model.predict(X_val_split)
        return mean_squared_error(y_val_split, y_pred)

    space = {
        'n_estimators': scope.int(hp.quniform('n_estimators', 50, 200, 10)),
        'learning_rate': hp.loguniform('learning_rate', -4, 0),
        'max_depth': scope.int(hp.quniform('max_depth', 1, 9, 1)),
        'min_samples_split': scope.int(hp.quniform('min_samples_split', 2, 10, 1)),
        'min_samples_leaf': scope.int(hp.quniform('min_samples_leaf', 1, 10, 1))
    }

    trials = Trials()
    best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=50, trials=trials)
    model = GradientBoostingRegressor(
        n_estimators=int(best['n_estimators']),
        learning_rate=best['learning_rate'],
        max_depth=int(best['max_depth']),
        min_samples_split=int(best['min_samples_split']),
        min_samples_leaf=int(best['min_samples_leaf'])
    )
    model.fit(X_train, y_train)
    return model

def train_arima_model(data):
    model = ARIMA(data, order=(5, 1, 0))
    model_fit = model.fit()
    return model_fit

def train_svr_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)
    X_train = X_train.reshape(X_train.shape[0], -1)
   
    def objective(params):
        model = SVR(**params)
        X_train_split, X_val_split, y_train_split, y_val_split = train_test_split(X_train, y_train, test_size=0.2)
        model.fit(X_train_split, y_train_split)
        y_pred = model.predict(X_val_split)
        return mean_squared_error(y_val_split, y_pred)

    space = {
        'C': hp.loguniform('C', -1, 3),
        'epsilon': hp.loguniform('epsilon', -3, 0),
        'gamma': hp.loguniform('gamma', -3, 0)
    }

    trials = Trials()
    best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=50, trials=trials)
    model = SVR(**best)
    model.fit(X_train, y_train)
    return model

def train_rf_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)
    X_train = X_train.reshape(X_train.shape[0], -1)

    def objective(params):
        model = RandomForestRegressor(
            n_estimators=int(params['n_estimators']),
            max_depth=int(params['max_depth']),
            min_samples_split=int(params['min_samples_split']),
            min_samples_leaf=int(params['min_samples_leaf'])
        )
        X_train_split, X_val_split, y_train_split, y_val_split = train_test_split(X_train, y_train, test_size=0.2)
        model.fit(X_train_split, y_train_split)
        y_pred = model.predict(X_val_split)
        return mean_squared_error(y_val_split, y_pred)

    space = {
        'n_estimators': scope.int(hp.quniform('n_estimators', 50, 200, 10)),
        'max_depth': scope.int(hp.quniform('max_depth', 1, 20, 1)),
        'min_samples_split': scope.int(hp.quniform('min_samples_split', 2, 10, 1)),
        'min_samples_leaf': scope.int(hp.quniform('min_samples_leaf', 1, 10, 1))
    }

    trials = Trials()
    best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=50, trials=trials)
    model = RandomForestRegressor(
        n_estimators=int(best['n_estimators']),
        max_depth=int(best['max_depth']),
        min_samples_split=int(best['min_samples_split']),
        min_samples_leaf=int(best['min_samples_leaf'])
    )
    model.fit(X_train, y_train)
    return model

def train_mlp_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)
    X_train = X_train.reshape(X_train.shape[0], -1)

    def objective(params):
        model = MLPRegressor(
            hidden_layer_sizes=params['hidden_layer_sizes'],
            alpha=params['alpha'],
            learning_rate_init=params['learning_rate_init'],
            max_iter=int(params['max_iter'])
        )
        X_train_split, X_val_split, y_train_split, y_val_split = train_test_split(X_train, y_train, test_size=0.2)
        model.fit(X_train_split, y_train_split)
        y_pred = model.predict(X_val_split)
        return mean_squared_error(y_val_split, y_pred)

    space = {
        'hidden_layer_sizes': hp.choice('hidden_layer_sizes', [(50,), (100,), (50, 50), (100, 50)]),
        'alpha': hp.loguniform('alpha', -5, 0),
        'learning_rate_init': hp.loguniform('learning_rate_init', -5, -1),
        'max_iter': scope.int(hp.quniform('max_iter', 100, 1000, 100))
    }

    trials = Trials()
    best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=50, trials=trials)

    hidden_layer_sizes = space['hidden_layer_sizes'][best['hidden_layer_sizes']]
   
    model = MLPRegressor(
        hidden_layer_sizes=hidden_layer_sizes,
        alpha=best['alpha'],
        learning_rate_init=best['learning_rate_init'],
        max_iter=int(best['max_iter'])
    )
    model.fit(X_train, y_train)
    return model

class TransformerModel(nn.Module):
    def __init__(self, feature_size=5, num_layers=1, dropout=0.1):
        super(TransformerModel, self).__init__()
        self.transformer = nn.Transformer(d_model=feature_size, nhead=1, num_encoder_layers=num_layers, num_decoder_layers=num_layers, dropout=dropout)
        self.linear = nn.Linear(feature_size, 1)

    def forward(self, src, tgt):
        output = self.transformer(src, tgt)
        return self.linear(output)

def train_transformer_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)
    X_train = torch.tensor(X_train, dtype=torch.float32)
    y_train = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1).repeat(1, time_step, 1)

    model = TransformerModel(feature_size=X_train.shape[2])
    criterion = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    for epoch in range(50):  # Number of epochs
        model.train()
        optimizer.zero_grad()
        output = model(X_train, X_train)
        loss = criterion(output, y_train)
        loss.backward()
        optimizer.step()

    return model

def train_gru_model(scaled_data):
    time_step = 60
    X_train, y_train = create_train_data(scaled_data, time_step)

    model = Sequential()
    model.add(GRU(100, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
    model.add(GRU(100, return_sequences=False))
    model.add(Dense(50))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mean_squared_error')

    model.fit(X_train, y_train, batch_size=32, epochs=50)
    return model

def create_train_data(scaled_data, time_step):
    X_train, y_train = [], []
    for i in range(time_step, len(scaled_data)):
        X_train.append(scaled_data[i-time_step:i])
        y_train.append(scaled_data[i, 3])  # Using close price as target
    X_train, y_train = np.array(X_train), np.array(y_train)
    return X_train, y_train

def predict_future_lstm(model, data, future_days):
    predictions = []
    time_step = 60
    input_seq = data[-time_step:]

    for _ in range(future_days):
        input_seq = input_seq.reshape((1, input_seq.shape[0], input_seq.shape[1]))
        predicted_price = model.predict(input_seq)[0]
        predictions.append(predicted_price)
        new_row = np.array([predicted_price] * input_seq.shape[2]).reshape(1, -1)
        input_seq = np.vstack((input_seq[0, 1:], new_row))
    return predictions

def predict_future_gb(model, data, future_days):
    predictions = []
    time_step = 60
    input_seq = data[-time_step:].reshape(1, -1)

    for _ in range(future_days):
        predicted_price = model.predict(input_seq)[0]
        predictions.append(predicted_price)
        new_row = np.array([predicted_price] * data.shape[1]).reshape(1, -1)
        input_seq = np.hstack((input_seq[:, data.shape[1]:], new_row))
    return predictions

def predict_future_hyperopt(model, data, future_days):
    return predict_future_gb(model, data, future_days)

def predict_future_arima(model, start_index, future_days):
    forecast = model.forecast(steps=future_days)
    return forecast

def predict_future_svr(model, data, future_days):
    predictions = []
    time_step = 60
    input_seq = data[-time_step:].reshape(1, -1)

    for _ in range(future_days):
        predicted_price = model.predict(input_seq)[0]
        predictions.append(predicted_price)
        new_row = np.array([predicted_price] * data.shape[1]).reshape(1, -1)
        input_seq = np.hstack((input_seq[:, data.shape[1]:], new_row))
    return predictions

def predict_future_rf(model, data, future_days):
    return predict_future_gb(model, data, future_days)

def predict_future_mlp(model, data, future_days):
    return predict_future_gb(model, data, future_days)

def predict_future_transformer(model, data, future_days):
    model.eval()
    predictions = []
    time_step = 60
    input_seq = torch.tensor(data[-time_step:], dtype=torch.float32).unsqueeze(0)

    for _ in range(future_days):
        with torch.no_grad():
            predicted_price = model(input_seq, input_seq)[:, -1, :].item()
        predictions.append(predicted_price)
        new_row = torch.tensor([[predicted_price] * data.shape[1]], dtype=torch.float32)
        input_seq = torch.cat((input_seq[:, 1:], new_row), dim=1)
    return predictions

def predict_future_gru(model, data, future_days):
    return predict_future_lstm(model, data, future_days)

def determine_trend(predicted_prices):
    start_price = predicted_prices[0]
    end_price = predicted_prices[-1]
    if end_price > start_price:
        return "Bull"
    elif end_price < start_price:
        return "Bear"
    else:
        return "Neutral"

def virtual_trade(order_type, predicted_prices):
    global total_trades, profitable_trades
    # Simulate a virtual trade based on predictions
    initial_price = predicted_prices[0]
    final_price = predicted_prices[-1]
    profit = (final_price - initial_price) if order_type == mt5.ORDER_TYPE_BUY else (initial_price - final_price)

    print(f"Virtual trade {'BUY' if order_type == mt5.ORDER_TYPE_BUY else 'SELL'}: Initial price = {initial_price}, Final price = {final_price}, Profit = {profit}")

    total_trades += 1
    if profit > 0:
        profitable_trades += 1

    update_win_rate()  # Update the win rate display

def update_win_rate():
    if total_trades == 0:
        win_rate = 0
    else:
        win_rate = (profitable_trades / total_trades) * 100
    win_rate_var.set(f"Winning Rate: {win_rate:.2f}%")

def backtest_model(data, model_type):
    # Define the backtesting period
    train_size = int(len(data) * 0.8)
    train_data = data[:train_size]
    test_data = data[train_size:]

    # Train the model
    scaled_train_data, scaler = preprocess_data(train_data)
    if model_type == 'LSTM':
        model = train_lstm_model(scaled_train_data)
    elif model_type == 'GB':
        model = train_gb_model(scaled_train_data)
    elif model_type == 'Hyperopt':
        model = train_hyperopt_model(scaled_train_data)
    elif model_type == 'ARIMA':
        model = train_arima_model(train_data['close'])
    elif model_type == 'SVR':
        model = train_svr_model(scaled_train_data)
    elif model_type == 'RF':
        model = train_rf_model(scaled_train_data)
    elif model_type == 'MLP':
        model = train_mlp_model(scaled_train_data)
    elif model_type == 'Transformer':
        model = train_transformer_model(scaled_train_data)
    elif model_type == 'GRU':
        model = train_gru_model(scaled_train_data)

    # Perform backtesting
    scaled_test_data = scaler.transform(test_data[['open', 'high', 'low', 'close', 'tick_volume']])
    future_days = len(test_data)
    if model_type in ['LSTM', 'GB', 'Hyperopt', 'SVR', 'RF', 'MLP', 'Transformer', 'GRU']:
        predictions = predict_future_lstm(model, scaled_test_data, future_days)
    elif model_type == 'ARIMA':
        predictions = predict_future_arima(model, train_size, future_days)

    predictions = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))

    # Calculate backtest performance
    test_data['Predictions'] = predictions
    test_data['Profit'] = test_data['Predictions'] - test_data['close']
    total_profit = test_data['Profit'].sum()

    print(f"Backtesting results for {model_type} model: Total profit = {total_profit}")

if __name__ == "__main__":
    main()

https://youtu.be/jZ38C-M3tyk?si=ERjuJ8hqsQwV2vAp