import tkinter as tk
import threading
import time
from binance.client import Client
from binance.enums import SIDE_BUY, SIDE_SELL
from binance.exceptions import BinanceAPIException

# ---------------------------
# التداول بالفيوتشر (وضع الهيدج)
# ---------------------------
client = None
running = False
in_position = False
position_side = None
entry_price = 0.0
symbol = ""

# دالة لجلب السعر الحالي
def get_price():
    try:
        ticker = client.futures_symbol_ticker(symbol=symbol)
        return float(ticker['price'])
    except:
        return 0.0

# دالة لحساب الربح والخسارة
def calculate_pnl(current_price):
    if not in_position:
        return 0.0
    if position_side == "LONG":
        return current_price - entry_price
    elif position_side == "SHORT":
        return entry_price - current_price
    return 0.0

# دالة لفتح صفقة شراء (لونغ)
def open_long(amount):
    try:
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_BUY,
            type='MARKET',
            quantity=amount,
            positionSide='LONG'
        )
        return True
    except BinanceAPIException as e:
        output.insert(tk.END, f"⚠️ خطأ في فتح شراء: {e}\n")
        return False

# دالة لفتح صفقة بيع (شورت)
def open_short(amount):
    try:
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_SELL,
            type='MARKET',
            quantity=amount,
            positionSide='SHORT'
        )
        return True
    except BinanceAPIException as e:
        output.insert(tk.END, f"⚠️ خطأ في فتح بيع: {e}\n")
        return False

# الدالة الأساسية للبوت
def start_bot():
    global client, in_position, position_side, entry_price, running, symbol

    try:
        api_key = api_key_entry.get().strip()
        api_secret = api_secret_entry.get().strip()
        symbol = symbol_entry.get().strip().upper()
        max_price = float(max_price_entry.get().strip())
        percent_mode = int(percent_mode_entry.get().strip()) == 1
        amount = float(amount_entry.get().strip())

        if percent_mode:
            percent_raw = percent_below_max_entry.get().strip()
            if not percent_raw:
                raise ValueError("Percent below max is empty.")
            percent = float(percent_raw)
            min_price = max_price * (1 - (percent / 100))
        else:
            min_price_raw = min_price_entry.get().strip()
            if not min_price_raw:
                raise ValueError("Min price is empty.")
            min_price = float(min_price_raw)

    except Exception as e:
        output.insert(tk.END, f"❌ خطأ في الإدخال: {e}\n")
        return

    try:
        client = Client(api_key, api_secret)
        client.futures_change_position_mode(dualSidePosition=True)
        client.futures_account()
    except Exception as e:
        output.insert(tk.END, f"❌ خطأ في الاتصال بـ Binance: {e}\n")
        return

    running = True
    output.insert(tk.END, "🚀 البوت بدأ العمل...\n")
    output.insert(tk.END, "---------------------------------------------\n")

    while running:
        try:
            price = get_price()
            pnl = calculate_pnl(price)

            output.insert(tk.END, f"Price: {price:.5f} USDT\n")
            output.insert(tk.END, f"Range: {min_price:.5f} - {max_price:.5f}\n")
            output.insert(tk.END, f"Position: {position_side if in_position else 'None'}\n")
            output.insert(tk.END, f"PnL: {pnl:.2f} USDT\n")
            output.insert(tk.END, "\n---------------------------------------------\n")
            output.see(tk.END)

            if not in_position:
                if price > max_price:
                    if open_long(amount):
                        in_position = True
                        position_side = "LONG"
                        entry_price = price
                elif price < min_price:
                    if open_short(amount):
                        in_position = True
                        position_side = "SHORT"
                        entry_price = price
            else:
                if position_side == "LONG" and price < max_price:
                    open_short(amount)
                    in_position = False
                    position_side = None
                    entry_price = 0.0
                elif position_side == "SHORT" and price > min_price:
                    open_long(amount)
                    in_position = False
                    position_side = None
                    entry_price = 0.0

            time.sleep(0.5)

        except Exception as e:
            output.insert(tk.END, f"❗ حدث خطأ: {e}\n")
            output.see(tk.END)
            time.sleep(2)

# دالة لإيقاف البوت
def stop_bot():
    global running
    running = False
    output.insert(tk.END, "🛑 تم إيقاف البوت\n")
    output.insert(tk.END, "---------------------------------------------\n")

# تشغيل البوت في Thread
def start_bot_thread():
    thread = threading.Thread(target=start_bot)
    thread.daemon = True
    thread.start()

# ---------------------------
# واجهة المستخدم
# ---------------------------
root = tk.Tk()
root.title("Futures Trading Bot")

fields = [
    ("API Key", 40),
    ("API Secret", 40),
    ("Symbol (e.g. BTCUSDT)", 20),
    ("Max Price", 20),
    ("Min Price", 20),
    ("% below Max (if using %) mode", 20),
    ("Use % Mode? (1=yes, 0=no)", 20),
    ("Amount to Trade", 20),
]

entries = []
for label_text, width in fields:
    label = tk.Label(root, text=label_text)
    label.pack()
    entry = tk.Entry(root, width=width)
    entry.pack()
    entries.append(entry)

(api_key_entry,
 api_secret_entry,
 symbol_entry,
 max_price_entry,
 min_price_entry,
 percent_below_max_entry,
 percent_mode_entry,
 amount_entry) = entries

start_button = tk.Button(root, text="▶ Start Bot", command=start_bot_thread)
start_button.pack()

stop_button = tk.Button(root, text="■ Stop Bot", command=stop_bot)
stop_button.pack()

output = tk.Text(root, height=20)
output.pack()

root.mainloop()
