MYM-A MODO UNO
import tkinter as tk
from tkinter import messagebox
import MetaTrader5 as mt5
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.dates as mdates
import threading
import time
def main():
root = tk.Tk()
root.title("MT5MYM-A")
root.geometry("1270x600")
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=400, height=600)
main_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
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(), root, main_frame))
connect_button.pack(pady=20)
root.mainloop()
def connect_to_mt5(login, password, server, root, main_frame):
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")
display_account_info(root)
fetch_and_display_chart(main_frame)
add_trade_buttons(root)
start_automation()
else:
messagebox.showerror("Error", "Failed to connect to MetaTrader 5")
def display_account_info(root):
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)
fetch_live_trades(root)
def fetch_live_trades(root):
trades = mt5.positions_get()
if trades is None:
messagebox.showerror("Error", "Failed to get live trades")
return
for trade in trades:
trade_info = f"Symbol: {trade.symbol}, Volume: {trade.volume}, Profit: {trade.profit}"
label = tk.Label(root, text=trade_info, font=("Helvetica", 14))
label.pack(pady=2)
# Schedule the next update
root.after(10000, lambda: refresh_live_trades(root))
def refresh_live_trades(root):
# Clear existing trade info
for widget in root.pack_slaves():
if isinstance(widget, tk.Label) and "Symbol" in widget.cget("text"):
widget.destroy()
# Fetch and display live trades again
fetch_live_trades(root)
def fetch_and_display_chart(main_frame):
symbol = "BTCUSD"
timeframe = mt5.TIMEFRAME_M30
bars = 48
data = fetch_historical_data(symbol, timeframe, bars)
plot_chart(data, main_frame)
def fetch_historical_data(symbol, timeframe, bars):
rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, bars)
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 plot_chart(data, main_frame):
fig, ax = plt.subplots(figsize=(5, 5))
ax.plot(data['time'], data['close'], label="BTC/USD")
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.set_title("BTC/USD 30-Minute Chart")
ax.legend()
# Format the date labels to show only hour and minute
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
plt.tight_layout()
for widget in main_frame.winfo_children():
widget.destroy()
canvas = FigureCanvasTkAgg(fig, master=main_frame)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
def add_trade_buttons(root):
buy_button = tk.Button(root, text="Buy", font=("Helvetica", 14), command=place_buy_trade)
buy_button.pack(pady=10)
sell_button = tk.Button(root, text="Sell", font=("Helvetica", 14), command=place_sell_trade)
sell_button.pack(pady=10)
def place_buy_trade():
symbol = "BTCUSD"
lot_size = 0.1
price = mt5.symbol_info_tick(symbol).ask
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot_size,
"type": mt5.ORDER_TYPE_BUY,
"price": price,
"deviation": 10,
"magic": 234000,
"comment": "Python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
messagebox.showerror("Trade Error", f"Failed to place trade: {result.retcode}")
else:
print("Trade successfully placed")
threading.Timer(2, close_trade, args=[result.order, mt5.ORDER_TYPE_BUY]).start()
def place_sell_trade():
symbol = "BTCUSD"
lot_size = 0.1
price = mt5.symbol_info_tick(symbol).bid
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot_size,
"type": mt5.ORDER_TYPE_SELL,
"price": price,
"deviation": 10,
"magic": 234000,
"comment": "Python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
messagebox.showerror("Trade Error", f"Failed to place trade: {result.retcode}")
else:
print("Trade successfully placed")
threading.Timer(2, close_trade, args=[result.order, mt5.ORDER_TYPE_SELL]).start()
def close_trade(order, order_type):
symbol = "BTCUSD"
position_id = order
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": position_id,
"price": price,
"deviation": 10,
"magic": 234000,
"comment": "Python script 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:
messagebox.showerror("Trade Error", f"Failed to close trade: {result.retcode}")
else:
print("Trade successfully closed")
def start_automation():
def automation_loop():
for i in range(1000):
place_buy_trade()
time.sleep(2)
place_sell_trade()
time.sleep(2)
threading.Thread(target=automation_loop).start()
if __name__ == "__main__":
main()
No comments:
Post a Comment