zainulabedin949 commited on
Commit
91e7f66
Β·
verified Β·
1 Parent(s): fdf52b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -80
app.py CHANGED
@@ -3,116 +3,125 @@ import time
3
  import gradio as gr
4
  from datetime import datetime
5
  import pytz
 
 
6
  from quotexpy import Quotex
7
  from quotexpy.utils.candles_period import CandlesPeriod
8
  from quotexpy.utils.account_type import AccountType
9
 
10
- # Initialize state and trade recommendations
11
  state = []
12
  trade_recommendations = []
13
  client = Quotex(email="your_email@example.com", password="your_password", headless=True)
 
14
 
15
- def analyze_candle_pattern(candles):
16
- """Analyze candle patterns and return a recommendation."""
17
- if not candles or len(candles) < 3:
18
- return "Waiting for more data..."
 
 
 
19
 
20
- latest_candle = max(candles.values(), key=lambda x: x["time"])
21
- prev_candle = sorted(candles.values(), key=lambda x: x["time"])[-2]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Basic bullish/bearish detection
24
- if latest_candle["close"] > latest_candle["open"] and latest_candle["close"] > prev_candle["close"]:
25
- return "πŸ”₯ STRONG UPTREND - BUY Signal (Bullish Candle + Higher Close)"
26
- elif latest_candle["close"] < latest_candle["open"] and latest_candle["close"] < prev_candle["close"]:
27
- return "πŸ“‰ STRONG DOWNTREND - SELL Signal (Bearish Candle + Lower Close)"
28
- elif latest_candle["close"] > latest_candle["open"]:
29
- return "🟒 Mild Bullish - Consider BUY"
 
 
 
 
 
 
30
  else:
31
- return "πŸ”΄ Mild Bearish - Consider SELL"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  def background_worker(pair: str, timeframe: str):
34
  try:
35
- if not client.connect():
36
- print("[ERROR] Failed to connect to Quotex")
37
- return
38
-
39
- client.change_account(AccountType.PRACTICE)
40
-
41
- period_map = {
42
- "5s": CandlesPeriod.SEC_5,
43
- "15s": CandlesPeriod.SEC_15,
44
- "1m": CandlesPeriod.ONE_MINUTE,
45
- "5m": CandlesPeriod.FIVE_MINUTES,
46
- }
47
- period = period_map[timeframe]
48
- client.start_candles_stream(pair, 10, period)
49
-
50
  while True:
51
  candles = client.get_realtime_candles(pair)
52
  if candles:
53
- latest_ts = max(candles.keys())
54
- candle_data = candles[latest_ts]
55
- direction = "↑ (Bullish)" if candle_data["close"] > candle_data["open"] else "↓ (Bearish)"
56
- timestamp = datetime.fromtimestamp(latest_ts / 1000).strftime("%H:%M:%S")
57
-
58
- entry = f"{timestamp} | {direction} | Close: {candle_data['close']:.5f}"
59
- state.append(entry)
60
-
61
- # Generate new recommendation every 5 candles
62
- if len(state) % 5 == 0:
63
- recommendation = analyze_candle_pattern(candles)
64
- trade_recommendations.append(f"⏱️ {timestamp} | {recommendation}")
65
-
66
- if len(state) > 100:
67
- state.pop(0)
68
- time.sleep(1)
69
  except Exception as e:
70
- print(f"[ERROR] Worker crashed: {e}")
71
 
72
  def start(pair, timeframe):
73
- global state, trade_recommendations
74
  state.clear()
75
  trade_recommendations.clear()
76
- threading.Thread(target=background_worker, args=(pair, timeframe), daemon=True).start()
77
- return "βœ… Bot is now analyzing market data..."
78
-
79
- def get_latest_candles():
80
- """Display last 5 candles."""
81
- return "\n".join(state[-5:][::-1]) or "No data yet."
82
-
83
- def get_latest_recommendations():
84
- """Display last 3 trade recommendations."""
85
- return "\n".join(trade_recommendations[-3:][::-1]) or "Waiting for recommendations..."
86
 
87
- with gr.Blocks(title="Quotex Trading Bot") as demo:
88
- gr.Markdown("## πŸ“Š Quotex Trading Bot")
 
89
 
90
  with gr.Row():
91
- pair = gr.Dropdown(["EURUSD", "USDJPY", "BTCUSD"], label="Select Currency Pair")
92
- timeframe = gr.Dropdown(["5s", "15s", "1m", "5m"], label="Select Timeframe")
93
- start_btn = gr.Button("Start Bot")
94
- refresh_btn = gr.Button("Refresh Data")
95
 
96
- status = gr.Textbox(label="Status")
97
- gr.Markdown("### πŸ•―οΈ Latest Candles")
98
- candle_output = gr.Textbox(label="Market Data")
99
- gr.Markdown("### πŸ€– Trade Recommendations")
100
- recommendation_output = gr.Textbox(label="AI Recommendations")
 
 
 
101
 
102
  start_btn.click(
103
- fn=start,
104
  inputs=[pair, timeframe],
105
- outputs=status
106
  )
107
-
108
- refresh_btn.click(
109
- fn=get_latest_candles,
110
- outputs=candle_output
111
- )
112
-
113
- refresh_btn.click(
114
- fn=get_latest_recommendations,
115
- outputs=recommendation_output
116
  )
117
 
118
  if __name__ == "__main__":
 
3
  import gradio as gr
4
  from datetime import datetime
5
  import pytz
6
+ import requests
7
+ from groq import Groq
8
  from quotexpy import Quotex
9
  from quotexpy.utils.candles_period import CandlesPeriod
10
  from quotexpy.utils.account_type import AccountType
11
 
12
+ # Initialize
13
  state = []
14
  trade_recommendations = []
15
  client = Quotex(email="your_email@example.com", password="your_password", headless=True)
16
+ groq_client = Groq(api_key="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")
17
 
18
+ def get_ai_recommendation(market_data):
19
+ """Get AI-powered recommendation using Groq API"""
20
+ try:
21
+ prompt = f"""
22
+ Analyze the latest candlestick patterns and market data:
23
+
24
+ {market_data}
25
 
26
+ Provide:
27
+ 1. Trading Signal (BUY/SELL/HOLD)
28
+ 2. Confidence (High/Medium/Low)
29
+ 3. RSI Level
30
+ 4. Key Price Levels
31
+ """
32
+
33
+ chat_completion = groq_client.chat.completions.create(
34
+ messages=[{"role": "user", "content": prompt}],
35
+ model="mixtral-8x7b-32768",
36
+ temperature=0.3,
37
+ max_tokens=150
38
+ )
39
+ return chat_completion.choices[0].message.content
40
+ except Exception as e:
41
+ return f"AI analysis failed: {e}"
42
 
43
+ def analyze_candles(candles):
44
+ """AI + Technical Analysis"""
45
+ if not candles or len(candles) < 3:
46
+ return "Waiting for more data..."
47
+
48
+ # Technical analysis
49
+ last_close = candles[max(candles.keys())]["close"]
50
+ prev_close = candles[sorted(candles.keys())[-2]]["close"]
51
+
52
+ if last_close > prev_close * 1.005: # Strong bullish
53
+ tech_signal = "πŸ”₯ STRONG UPTREND - BUY"
54
+ elif last_close < prev_close * 0.995: # Strong bearish
55
+ tech_signal = "πŸ“‰ STRONG DOWNTREND - SELL"
56
  else:
57
+ tech_signal = "🟑 WEAK TREND - HOLD"
58
+
59
+ # AI Input
60
+ market_data = f"""
61
+ Latest Candle:
62
+ - Open: {last_candle["open"]}
63
+ - Close: {last_candle["close"]}
64
+ - High: {last_candle["high"]}
65
+ - Low: {last_candle["low"]}
66
+ - Volume: {last_candle["vol"]}
67
+ """
68
+ ai_signal = get_ai_recommendation(market_data)
69
+
70
+ return f"""\n
71
+ πŸ“Š **TECHNICAL ANALYSIS:**
72
+ {tech_signal}
73
+ πŸ€– **AI RECOMMENDATION:**
74
+ {ai_signal}"""
75
 
76
  def background_worker(pair: str, timeframe: str):
77
  try:
78
+ client.start_candles_stream(pair, 10, period_map[timeframe])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  while True:
80
  candles = client.get_realtime_candles(pair)
81
  if candles:
82
+ analysis = analyze_candles(candles)
83
+ trade_recommendations.append(analysis)
84
+ time.sleep(5) # Refresh every 5 sec
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  except Exception as e:
86
+ print(f"❌ Worker error: {e}")
87
 
88
  def start(pair, timeframe):
 
89
  state.clear()
90
  trade_recommendations.clear()
91
+ threading.Thread(
92
+ target=background_worker,
93
+ args=(pair, timeframe),
94
+ daemon=True
95
+ ).start()
96
+ return "πŸ”„ Analyzing market..."
 
 
 
 
97
 
98
+ with gr.Blocks() as demo:
99
+ gr.Markdown("## πŸ€– AI Trading Assistant")
100
+ gr.Markdown("### Real-time Candle Analysis")
101
 
102
  with gr.Row():
103
+ pair = gr.Dropdown(choices=["EURUSD", "USDJPY", "BTCUSD"], label="Pair")
104
+ timeframe = gr.Dropdown(choices=["5s", "15s", "1m", "5m"], label="Timeframe")
105
+ start_btn = gr.Button("Start AI Analysis")
 
106
 
107
+ gr.Markdown("---")
108
+
109
+ with gr.Column():
110
+ gr.Markdown("### πŸ“œ Last 10 Candles")
111
+ candle_output = gr.Textbox()
112
+
113
+ gr.Markdown("### πŸ—ƒοΈ Trading Signals")
114
+ ai_output = gr.Textbox(label="AI + Technical Signals")
115
 
116
  start_btn.click(
117
+ start,
118
  inputs=[pair, timeframe],
119
+ outputs=[candle_output, ai_output]
120
  )
121
+ demo.load(
122
+ get_latest_recommendations,
123
+ outputs=ai_output,
124
+ every=5 # Refresh signals every 5 seconds
 
 
 
 
 
125
  )
126
 
127
  if __name__ == "__main__":