Wednesday, 31 July 2024

 MYM-A MODO CICLOPE





import tkinter as tk
from tkinter import messagebox
import MetaTrader5 as mt5
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

def main():
    # Create the main window
    root = tk.Tk()
    root.title("MT5MYM-A")
    root.geometry("1200x800")

    # Create a frame for the login UI
    login_frame = tk.Frame(root, width=400, height=600, bg="lightgrey")
    login_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    # Title for the login UI
    login_title = tk.Label(login_frame, text="🏧MYM-A", font=("Helvetica", 20), bg="lightgrey")
    login_title.pack(pady=20)

    # Login fields
    login_label = tk.Label(login_frame, text="Login:", font=("Helvetica", 14), bg="lightgrey")
    login_label.pack(pady=5)

    login_entry = tk.Entry(login_frame, font=("Helvetica", 14))
    login_entry.pack(pady=5)
    login_entry.insert(0, "5027341082")  # Pre-fill with your login

    password_label = tk.Label(login_frame, text="Password:", font=("Helvetica", 14), bg="lightgrey")
    password_label.pack(pady=5)

    password_entry = tk.Entry(login_frame, show="*", font=("Helvetica", 14))
    password_entry.pack(pady=5)
    password_entry.insert(0, "IxS@Po1b")  # Pre-fill with your password

    server_label = tk.Label(login_frame, text="Server:", font=("Helvetica", 14), bg="lightgrey")
    server_label.pack(pady=5)

    server_entry = tk.Entry(login_frame, font=("Helvetica", 14))
    server_entry.pack(pady=5)
    server_entry.insert(0, "MetaQuotes-Demo")  # Pre-fill with your server

    # Connect button
    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(), root, trend_label))
    connect_button.pack(pady=20)

    # Create a frame for the main content
    main_frame = tk.Frame(root, width=800, height=600)
    main_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

    # Create a label with the text "USD/MXN"
    label = tk.Label(main_frame, text="USD/MXN", font=("Helvetica", 24))
    label.pack(expand=True)

    # Create a label to display the market trend
    trend_label = tk.Label(main_frame, text="", font=("Helvetica", 18))
    trend_label.pack(expand=True)

    # Create a label with the text "Loading..." at the bottom
    loading_label = tk.Label(main_frame, text="Loading...", font=("Helvetica", 14))
    loading_label.pack(side=tk.BOTTOM, pady=10)

    # Start the Tkinter event loop
    root.mainloop()

def connect_to_mt5(login, password, server, root, trend_label):
    # Initialize MetaTrader 5
    if not mt5.initialize():
        messagebox.showerror("Error", "initialize() failed")
        mt5.shutdown()
        return

    # Log in to the MetaTrader 5 account
    authorized = mt5.login(login=int(login), password=password, server=server)
    if authorized:
        print("Connected to MetaTrader 5")
        display_account_info(root)
        fetch_and_display_chart(root, trend_label)
    else:
        messagebox.showerror("Error", "Failed to connect to MetaTrader 5")

def display_account_info(root):
    # Get account info
    account_info = mt5.account_info()
    if account_info is None:
        messagebox.showerror("Error", "Failed to get account info")
        return

    # Create a new window for account information
    info_window = tk.Toplevel(root)
    info_window.title("Account Information")
    info_window.geometry("400x300")

    # Display account information
    info_labels = [
        f"Account ID: {account_info.login}",
        f"Balance: {account_info.balance}",
        f"Equity: {account_info.equity}",
        f"Margin: {account_info.margin}",
        f"Free Margin: {account_info.margin_free}",
        f"Leverage: {account_info.leverage}"
    ]

    for info in info_labels:
        label = tk.Label(info_window, text=info, font=("Helvetica", 14))
        label.pack(pady=5)

def fetch_and_display_chart(root, trend_label):
    symbol = "USDMXN"
    timeframe = mt5.TIMEFRAME_D1
    days = 600  # Fetch 600 days of data

    data = fetch_historical_data(symbol, timeframe, days)
    scaled_data, scaler = preprocess_data(data)

    # Train the LSTM model
    model = train_lstm_model(scaled_data)

    # Predict the future prices
    future_days = 60
    predicted_prices = predict_future(model, scaled_data, future_days)
    predicted_prices = scaler.inverse_transform(np.array(predicted_prices).reshape(-1, 1))

    # Append predicted prices to the original data
    predicted_dates = pd.date_range(start=data['time'].iloc[-1], periods=future_days + 1, closed='right')
    predicted_df = pd.DataFrame({'time': predicted_dates, 'close': predicted_prices.flatten()})

    # Plot and display the chart with peaks and predictions
    plot_predictions(data, predicted_df, root)

    # Determine and display the trend
    trend = determine_trend(predicted_prices)
    display_trend(trend_label, trend)

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', 'close']]

def preprocess_data(data):
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data['close'].values.reshape(-1, 1))
    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], 1)))
    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)  # Increased epochs for better training
    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, 0])
        y_train.append(scaled_data[i, 0])
    X_train, y_train = np.array(X_train), np.array(y_train)
    X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
    return X_train, y_train

def predict_future(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], 1))
        predicted_price = model.predict(input_seq)[0]
        predictions.append(predicted_price)
        input_seq = np.append(input_seq[:, 1:], predicted_price)
    return predictions

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 display_trend(trend_label, trend):
    trend_label.config(text=trend)

def plot_predictions(data, predicted_df, root):
    combined_df = pd.concat([data, predicted_df])

    fig, ax = plt.subplots()
    ax.plot(combined_df['time'], combined_df['close'], label="USD/MXN")
    ax.plot(predicted_df['time'], predicted_df['close'], 'r--', label="Predicted USD/MXN")

    ax.set_xlabel("Date")
    ax.set_ylabel("Price")
    ax.set_title("USD/MXN Daily Chart with Predictions")
    ax.legend()

    chart_frame = tk.Frame(root)
    chart_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

    canvas = FigureCanvasTkAgg(fig, master=chart_frame)
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

if __name__ == "__main__":
    main()

Tuesday, 30 July 2024

 MYM-A MODO DADOCASIO import tkinter as tk

import threading
import time
import random

# Function to start the loading animation and display the dice result
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)

    # Run the loading animation
    loading_animation()

    # Display the dice result
    dice_result = random.randint(1, 3)
    display_var.set(dice_result)

    if dice_result == 3:
        message_label.config(text="Click Connect")
        root.after(10000, reset)  # Re-enable after 10 seconds for celebration
    else:
        root.after(500, enable_button)  # Re-enable shortly after result display

# Function to reset the display and button after celebration
def reset():
    message_label.config(text="")
    display_var.set("")
    enable_button()

# Function to handle button click event
def on_button_click():
    threading.Thread(target=roll_dice).start()
    click_button.config(state="disabled")

# Function to enable the button
def enable_button():
    click_button.config(state="normal")

# Function to automatically click the button every 10 seconds
def auto_click():
    while True:
        time.sleep(10)
        if click_button["state"] == "normal":  # Ensure it only clicks if button is enabled
            root.after(0, on_button_click)  # Use root.after to schedule the click in the main thread

# Initialize the main window
root = tk.Tk()
root.title("3 FACE DICE")
root.geometry("300x250")

# Create the UI elements
title_label = tk.Label(root, text="3 FACE DICE", font=("Helvetica", 16))
title_label.pack(pady=10)

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

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

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

# Start the automatic clicking in a separate thread
threading.Thread(target=auto_click, daemon=True).start()

# Start the Tkinter event loop
root.mainloop()

 MYM-A MODO DADOROJO



import tkinter as tk

import threading

import time

import random


# Function to start the loading animation and display the dice result

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)


    # Run the loading animation

    loading_animation()


    # Display the dice result

    dice_result = random.randint(1, 3)

    display_var.set(dice_result)


    if dice_result == 3:

        display_confetti()

        root.after(10000, enable_button)  # Re-enable after 10 seconds for celebration

    else:

        root.after(500, enable_button)  # Re-enable shortly after result display


# Function to handle button click event

def on_button_click():

    threading.Thread(target=roll_dice).start()

    click_button.config(state="disabled")


# Function to enable the button

def enable_button():

    click_button.config(state="normal")


# Function to display confetti

def display_confetti():

    confetti = ["🎉", "🎊", "🎈"]

    for _ in range(10):  # Number of confetti flashes

        for c in confetti:

            display_var.set(c)

            time.sleep(0.1)

        display_var.set("3")

        time.sleep(0.1)


# Initialize the main window

root = tk.Tk()

root.title("3 FACE DICE")

root.geometry("300x200")


# Create the UI elements

title_label = tk.Label(root, text="3 FACE DICE", font=("Helvetica", 16))

title_label.pack(pady=10)


display_var = tk.StringVar()

display_label = tk.Label(root, textvariable=display_var, font=("Helvetica", 24), width=5, height=2, relief="solid")

display_label.pack(pady=20)


click_button = tk.Button(root, text="Click", font=("Helvetica", 14), command=on_button_click)

click_button.pack(pady=10)


# Start the Tkinter event loop

root.mainloop()


MYM-A MODO PRIMEROSPASOS






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, Dense
import threading
import time
import random

# Global variables
is_first_login = True
dice_roll_result = 0

def main():
    global root, connect_button, display_var
    root = tk.Tk()
    root.title("MT5MYM-A with Dice")
    root.geometry("1270x600")

    # Create frames for the UI
    login_frame = tk.Frame(root, width=400, height=600, bg="lightgrey")
    login_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
   
    main_frame = tk.Frame(root, width=800, height=600)
    main_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

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

    login_label = tk.Label(login_frame, text="Login:", font=("Helvetica", 14), bg="lightgrey")
    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), bg="lightgrey")
    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), bg="lightgrey")
    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)

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

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

    click_button = tk.Button(main_frame, text="Roll Dice", font=("Helvetica", 14), command=on_dice_button_click)
    click_button.pack(pady=10)

    root.mainloop()

def on_dice_button_click():
    threading.Thread(target=roll_dice).start()

def roll_dice():
    global dice_roll_result
    loading_animation()
    dice_roll_result = random.randint(1, 3)
    display_var.set(dice_roll_result)
    if dice_roll_result == 3:
        root.after(1000, connect_button.invoke)  # Simulate a click on the connect button

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

def connect_to_mt5(login, password, server):
    global is_first_login
    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")
        if is_first_login:
            display_account_info()
            start_automation()
            is_first_login = False
    else:
        messagebox.showerror("Error", "Failed to connect to MetaTrader 5")

def display_account_info():
    account_info = mt5.account_info()
    if account_info is None:
        messagebox.showerror("Error", "Failed to get account info")
        return

    info_labels = [
        f"Account ID: {account_info.login}",
        f"Balance: {account_info.balance}",
        f"Equity: {account_info.equity}",
        f"Margin: {account_info.margin}",
        f"Free Margin: {account_info.margin_free}",
        f"Leverage: {account_info.leverage}"
    ]

    for info in info_labels:
        label = tk.Label(root, text=info, font=("Helvetica", 14))
        label.pack(pady=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)
            model = train_lstm_model(scaled_data)
            future_days = 60
            predicted_prices = predict_future(model, scaled_data, future_days)
            predicted_prices = scaler.inverse_transform(np.array(predicted_prices).reshape(-1, 1))
            trend = determine_trend(predicted_prices)
            if trend == "Bull":
                place_trade(mt5.ORDER_TYPE_BUY)
            elif trend == "Bear":
                place_trade(mt5.ORDER_TYPE_SELL)
            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', 'close']]

def preprocess_data(data):
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data['close'].values.reshape(-1, 1))
    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], 1)))
    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 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, 0])
        y_train.append(scaled_data[i, 0])
    X_train, y_train = np.array(X_train), np.array(y_train)
    X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
    return X_train, y_train

def predict_future(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], 1))
        predicted_price = model.predict(input_seq)[0]
        predictions.append(predicted_price)
        input_seq = np.append(input_seq[:, 1:], predicted_price)
    return predictions

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 place_trade(order_type):
    symbol = "BTCUSD"
    lot_size = 0.1
    price = mt5.symbol_info_tick(symbol).ask if order_type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(symbol).bid
    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot_size,
        "type": order_type,
        "price": price,
        "deviation": 10,
        "magic": 234000,
        "comment": "Automated trade",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_IOC,
    }

    result = mt5.order_send(request)
    if result.retcode == mt5.TRADE_RETCODE_DONE:
        print("Trade successfully placed")
        monitor_trade(result.order)
    else:
        messagebox.showerror("Trade Error", f"Failed to place trade: {result.retcode}")

def monitor_trade(order_id):
    while True:
        position = mt5.positions_get(ticket=order_id)
        if position:
            position = position[0]
            profit = position.profit
            if profit >= 0.01:
                close_trade(order_id, position.type)
                break
        time.sleep(5)

def close_trade(order_id, order_type):
    symbol = "BTCUSD"
    price = mt5.symbol_info_tick(symbol).bid if order_type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(symbol).ask

    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": 0.1,
        "type": mt5.ORDER_TYPE_SELL if order_type == mt5.ORDER_TYPE_BUY else mt5.ORDER_TYPE_BUY,
        "position": order_id,
        "price": price,
        "deviation": 10,
        "magic": 234000,
        "comment": "Automated trade close",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_IOC,
    }

    result = mt5.order_send(request)
    if result.retcode == mt5.TRADE_RETCODE_DONE:
        print("Trade successfully closed")
        on_dice_button_click()  # Trigger dice roll after closing a trade
    else:
        messagebox.showerror("Trade Close Error", f"Failed to close trade: {result.retcode}")

if __name__ == "__main__":
    main()

Sunday, 28 July 2024

 MYM-A MODO DIVINIDAD





 QUE CHATGPT ADMINISTRE LA CONTABILIDAD DEL ROBOT Y SU BACKTESTING 

Saturday, 27 July 2024

 I'm about to reveal exactly how smart

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