Riy777 commited on
Commit
56d514f
·
verified ·
1 Parent(s): 7ec406d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import time
3
+ import threading
4
+ import pandas as pd
5
+ import plotly.graph_objects as go
6
+ from datetime import datetime
7
+ from r2 import R2Manager
8
+ from llm import MarketBrain
9
+
10
+ # تهيئة الكائنات
11
+ r2 = R2Manager()
12
+ brain = MarketBrain()
13
+
14
+ # متغيرات عالمية للتحكم في البوت
15
+ bot_active = False
16
+ target_symbol = "ETH/USDT" # الافتراضي
17
+ stop_event = threading.Event()
18
+
19
+ def trading_loop():
20
+ """الحلقة الخلفية التي تعمل كل 15 دقيقة"""
21
+ global bot_active, target_symbol
22
+
23
+ while not stop_event.is_set():
24
+ if bot_active:
25
+ print(f"--- Running Analysis for {target_symbol} at {datetime.now()} ---")
26
+
27
+ # 1. جلب بيانات المحفظة
28
+ portfolio = r2.get_data()
29
+ current_pos = portfolio.get("active_position")
30
+
31
+ # 2. استشارة الذكاء الاصطناعي
32
+ decision, _ = brain.analyze_and_decide(target_symbol, current_pos)
33
+ print(f"AI Decision: {decision}")
34
+
35
+ current_price = brain.get_market_data(target_symbol)[0]['close']
36
+
37
+ # 3. تنفيذ المنطق
38
+ # حالة الشراء (لا توجد صفقة + إشارة شراء + ثقة عالية)
39
+ if not current_pos and decision.get('action') == "BUY" and decision.get('confidence', 0) > 70:
40
+ # منطق التحجيم (10$ ثم 20$)
41
+ trade_size = 10.0
42
+ if portfolio['balance'] > 1050: # مثال بسيط لزيادة الحجم عند الربح
43
+ trade_size = 20.0
44
+
45
+ new_pos = {
46
+ "symbol": target_symbol,
47
+ "entry_price": current_price,
48
+ "amount": trade_size / current_price,
49
+ "cost": trade_size,
50
+ "tp": decision.get('tp_target'),
51
+ "sl": decision.get('sl_target'),
52
+ "timestamp": str(datetime.now())
53
+ }
54
+ portfolio['active_position'] = new_pos
55
+ portfolio['balance'] -= trade_size
56
+ print(f"OPENED BUY POSITION: {new_pos}")
57
+
58
+ # حالة البيع (يوجد صفقة + إشارة بيع أو ضرب الأهداف)
59
+ elif current_pos:
60
+ # التحقق من الأهداف المحددة مسبقاً (إدارة مخاطر صارمة)
61
+ hit_tp = current_price >= current_pos['tp'] if current_pos['tp'] else False
62
+ hit_sl = current_price <= current_pos['sl'] if current_pos['sl'] else False
63
+ ai_exit = decision.get('action') == "SELL"
64
+
65
+ if hit_tp or hit_sl or ai_exit:
66
+ revenue = current_pos['amount'] * current_price
67
+ pnl = revenue - current_pos['cost']
68
+
69
+ # تحديث السجلات
70
+ portfolio['active_position'] = None
71
+ portfolio['balance'] += revenue
72
+ portfolio['stats']['total_pnl'] += pnl
73
+ if pnl > 0:
74
+ portfolio['stats']['wins'] += 1
75
+ else:
76
+ portfolio['stats']['losses'] += 1
77
+
78
+ history_record = {
79
+ "symbol": target_symbol,
80
+ "entry": current_pos['entry_price'],
81
+ "exit": current_price,
82
+ "pnl": pnl,
83
+ "reason": "TP" if hit_tp else ("SL" if hit_sl else "AI_DECISION"),
84
+ "time": str(datetime.now())
85
+ }
86
+ portfolio['history'].append(history_record)
87
+ print(f"CLOSED POSITION: {history_record}")
88
+
89
+ # 4. حفظ البيانات في Cloudflare R2
90
+ r2.save_data(portfolio)
91
+
92
+ # الانتظار 15 دقيقة (900 ثانية)
93
+ time.sleep(900)
94
+
95
+ # تشغيل الخيط الخلفي
96
+ t = threading.Thread(target=trading_loop, daemon=True)
97
+ t.start()
98
+
99
+ # --- دوال الواجهة ---
100
+
101
+ def start_bot(symbol):
102
+ global bot_active, target_symbol
103
+ target_symbol = symbol
104
+ bot_active = True
105
+ return f"Bot Started on {symbol}. Scanning every 15 mins..."
106
+
107
+ def stop_bot():
108
+ global bot_active
109
+ bot_active = False
110
+ return "Bot Stopped."
111
+
112
+ def get_dashboard_data():
113
+ portfolio = r2.get_data()
114
+ market_info, df = brain.get_market_data(target_symbol)
115
+
116
+ # 1. الرسم البياني
117
+ fig = go.Figure(data=[go.Candlestick(
118
+ x=df['timestamp'],
119
+ open=df['open'], high=df['high'],
120
+ low=df['low'], close=df['close']
121
+ )])
122
+ fig.update_layout(title=f"{target_symbol} Live Chart", height=400)
123
+
124
+ # 2. معلومات الصفقة الحالية
125
+ pos = portfolio.get('active_position')
126
+ pos_str = "No Active Position"
127
+ if pos:
128
+ pnl_pct = ((market_info['close'] - pos['entry_price']) / pos['entry_price']) * 100
129
+ pos_str = f"""
130
+ Symbol: {pos['symbol']}
131
+ Entry: {pos['entry_price']}
132
+ Current: {market_info['close']}
133
+ PnL: {pnl_pct:.2f}%
134
+ TP: {pos['tp']} | SL: {pos['sl']}
135
+ """
136
+
137
+ # 3. السجلات
138
+ stats = f"""
139
+ Balance: ${portfolio['balance']:.2f}
140
+ Wins: {portfolio['stats']['wins']} | Losses: {portfolio['stats']['losses']}
141
+ Total PnL: ${portfolio['stats']['total_pnl']:.2f}
142
+ """
143
+
144
+ history_df = pd.DataFrame(portfolio.get('history', []))
145
+ if not history_df.empty:
146
+ history_table = history_df[['time', 'symbol', 'pnl', 'reason']].tail(5).values.tolist()
147
+ else:
148
+ history_table = []
149
+
150
+ return fig, pos_str, stats, history_table
151
+
152
+ # --- بناء واجهة Gradio ---
153
+
154
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
155
+ gr.Markdown("# 🤖 GEM-Architect AI Trading Agent (Qwen-80B + OKX)")
156
+
157
+ with gr.Row():
158
+ with gr.Column(scale=1):
159
+ symbol_input = gr.Textbox(value="BTC/USDT", label="Symbol to Trade")
160
+ start_btn = gr.Button("▶ Start Bot", variant="primary")
161
+ stop_btn = gr.Button("⏹ Stop Bot", variant="stop")
162
+ status_output = gr.Markdown("Status: Idle")
163
+
164
+ with gr.Column(scale=2):
165
+ stats_display = gr.Markdown("### Wallet Stats")
166
+
167
+ with gr.Row():
168
+ chart_output = gr.Plot(label="Price Chart")
169
+
170
+ with gr.Row():
171
+ with gr.Column():
172
+ position_display = gr.Markdown("### Active Position")
173
+ with gr.Column():
174
+ history_display = gr.Dataframe(headers=["Time", "Symbol", "PnL", "Reason"], label="Recent Trade History")
175
+
176
+ # أحداث الأزرار
177
+ start_btn.click(start_bot, inputs=[symbol_input], outputs=[status_output])
178
+ stop_btn.click(stop_bot, outputs=[status_output])
179
+
180
+ # تحديث الواجهة تلقائياً كل 30 ثانية للقراءة فقط
181
+ demo.load(get_dashboard_data, outputs=[chart_output, position_display, stats_display, history_display], every=30)
182
+
183
+ if __name__ == "__main__":
184
+ demo.launch()