GoshawkVortexAI commited on
Commit
92e88cb
·
verified ·
1 Parent(s): 6148521

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -46
app.py CHANGED
@@ -18,64 +18,65 @@ if api_key:
18
  client = Groq(api_key=api_key)
19
 
20
  # ==========================================
21
- # 📡 2. MEXC PUBLIC API
22
  # ==========================================
23
- MEXC_BASE = "https://api.mexc.com"
 
24
 
25
- # Akamai WAF'ın Python varsayılan UA'sını engellemesini aşmak için
26
- MEXC_HEADERS = {
27
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
28
  "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
29
  "Accept": "application/json",
30
  "Accept-Language": "en-US,en;q=0.9",
31
  }
32
 
33
- def fetch_mexc_ticker(symbol="BTCUSDT"):
34
- """MEXC spot son fiyat. 3 kez dener."""
35
  for attempt in range(3):
36
  try:
37
  r = requests.get(
38
- f"{MEXC_BASE}/api/v3/ticker/24hr",
39
- params={"symbol": symbol},
40
- headers=MEXC_HEADERS,
41
  timeout=15
42
  )
43
  r.raise_for_status()
44
- d = r.json()
45
  return {
46
- "last": float(d["lastPrice"]),
47
- "open24h": float(d["openPrice"]),
48
- "high24h": float(d["highPrice"]),
49
- "low24h": float(d["lowPrice"]),
50
- "vol24h": float(d["volume"]),
51
- "change_pct": float(d["priceChangePercent"]),
52
  }
53
  except Exception as e:
54
- print(f"MEXC ticker attempt {attempt+1} failed: {e}")
55
  if attempt < 2:
56
  time.sleep(2)
57
  return None
58
 
59
- def fetch_mexc_klines(symbol="BTCUSDT", interval="1h", limit=100):
60
- """MEXC spot K-line. 3 kez dener."""
61
  for attempt in range(3):
62
  try:
63
  r = requests.get(
64
- f"{MEXC_BASE}/api/v3/klines",
65
- params={"symbol": symbol, "interval": interval, "limit": limit},
66
- headers=MEXC_HEADERS,
67
  timeout=15
68
  )
69
  r.raise_for_status()
70
- raw = r.json()
71
- cols = ["ts","open","high","low","close","vol","close_time","qvol","trades","tb","tq","ignore"]
72
- df = pd.DataFrame(raw, columns=cols)
73
- for c in ["open","high","low","close","vol"]:
74
- df[c] = df[c].astype(float)
75
  df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
76
- return df[["ts","open","high","low","close","vol"]].sort_values("ts").reset_index(drop=True)
77
  except Exception as e:
78
- print(f"MEXC klines attempt {attempt+1} failed: {e}")
79
  if attempt < 2:
80
  time.sleep(2)
81
  return None
@@ -90,9 +91,9 @@ def compute_rsi(series, period=14):
90
  rs = gain / loss
91
  return 100 - (100 / (1 + rs))
92
 
93
- def train_models_from_mexc():
94
- """MEXC'ten çekilen mum verisiyle XGBoost ve KNN eğitir."""
95
- df = fetch_mexc_klines(limit=500)
96
  if df is None or len(df) < 50:
97
  return None, None, None, None
98
 
@@ -123,11 +124,11 @@ def train_models_from_mexc():
123
 
124
  return xgb_model, knn_model, scaler, features
125
 
126
- # Başlangıçta modelleri MEXC verisiyle eğit
127
- xgb_model, knn_model, scaler, feature_cols = train_models_from_mexc()
128
 
129
  if xgb_model is None:
130
- print("MEXC erişilemedi, dummy modeller kullanılıyor.")
131
  dummy_X = np.random.rand(50, 5)
132
  dummy_y = np.random.randint(0, 2, 50)
133
  xgb_model = xgb.XGBClassifier(n_estimators=10, max_depth=2)
@@ -135,17 +136,17 @@ if xgb_model is None:
135
  scaler = StandardScaler()
136
  knn_model = KNeighborsClassifier(n_neighbors=5)
137
  knn_model.fit(scaler.fit_transform(dummy_X), dummy_y)
138
- feature_cols = ["ma_5","ma_20","rsi","macd","vol"]
139
 
140
  # ==========================================
141
  # 🧠 4. ANALİZ MOTORU (XGB + KNN Ensemble)
142
  # ==========================================
143
  def predict_and_analyze():
144
- ticker = fetch_mexc_ticker()
145
- candles = fetch_mexc_klines(limit=30)
146
 
147
  if ticker is None or candles is None:
148
- return "❌ MEXC API'sine erişilemedi (Akamai WAF veya Hugging Face ağ kısıtlaması). Lütfen sonra tekrar deneyin.", {}
149
 
150
  last_price = ticker["last"]
151
  change_pct = ticker["change_pct"]
@@ -176,7 +177,7 @@ def predict_and_analyze():
176
  prompt = f"""
177
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
178
 
179
- 📡 MEXC Canlı Verileri (BTC/USDT):
180
  - Son Fiyat: ${last_price:,.2f}
181
  - 24s Değişim: %{change_pct:+.2f}
182
  - 24s Hacim: {vol24h:,.0f} BTC
@@ -216,7 +217,7 @@ def predict_and_analyze():
216
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
217
 
218
  header = (
219
- f"**MEXC Canlı: ${last_price:,.2f}** (%{change_pct:+.2f}) | RSI: {rsi:.1f} | "
220
  f"MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n"
221
  f"**XGB:** %{xgb_prob_up*100:.1f} | **KNN:** %{knn_prob_up*100:.1f} | "
222
  f"**Ensemble:** %{ensemble_prob_up*100:.1f}\n\n---\n\n"
@@ -229,17 +230,17 @@ def predict_and_analyze():
229
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
230
  gr.Markdown(
231
  """
232
- # ₿ BTC/USD XGBoost + KNN & Groq AI Tahmin Radarı (MEXC Canlı)
233
- Fiyat ve mum verileri **MEXC halka açık API**'sinden otomatik çekilir. **XGBoost + KNN** ensemble tahmini yapar, **Groq** analiz raporu üretir.
234
  """
235
  )
236
  with gr.Row():
237
  with gr.Column():
238
- analyze_btn = gr.Button("🔄 MEXC'ten Veri Çek ve Analiz Et", variant="primary", size="lg")
239
- gr.Markdown("**Not**: MEXC API'si Akamai WAF koruması altındadır; kod tarayıcı UA ve 3 deneme içerir.")
240
  with gr.Column():
241
  prob_output = gr.Label(label="Model Tahminleri (XGB + KNN)")
242
- analysis_output = gr.Markdown(value="Butona basarak MEXC'ten canlı veri çekip analizi başlatın.")
243
  analyze_btn.click(fn=predict_and_analyze, inputs=[], outputs=[analysis_output, prob_output])
244
  gr.Markdown("---\n⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır.")
245
 
 
18
  client = Groq(api_key=api_key)
19
 
20
  # ==========================================
21
+ # 📡 2. OKX PUBLIC API (openapi alan adı)
22
  # ==========================================
23
+ # HF'de www.okx.com engellenmiş olabilir; openapi.okx.com küresel REST alan adıdır
24
+ OKX_BASE = "https://openapi.okx.com"
25
 
26
+ # Cloudflare istemci imzası engellemesini aşmak için tarayıcı benzeri başlıklar
27
+ OKX_HEADERS = {
28
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
29
  "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
30
  "Accept": "application/json",
31
  "Accept-Language": "en-US,en;q=0.9",
32
  }
33
 
34
+ def fetch_okx_ticker(inst_id="BTC-USDT"):
35
+ """OKX anlık fiyat. 3 kez dener."""
36
  for attempt in range(3):
37
  try:
38
  r = requests.get(
39
+ f"{OKX_BASE}/api/v5/market/ticker",
40
+ params={"instId": inst_id},
41
+ headers=OKX_HEADERS,
42
  timeout=15
43
  )
44
  r.raise_for_status()
45
+ d = r.json()["data"][0]
46
  return {
47
+ "last": float(d["last"]),
48
+ "open24h": float(d["open24h"]),
49
+ "high24h": float(d["high24h"]),
50
+ "low24h": float(d["low24h"]),
51
+ "vol24h": float(d["vol24h"]),
52
+ "change_pct": (float(d["last"]) / float(d["open24h"]) - 1) * 100,
53
  }
54
  except Exception as e:
55
+ print(f"OKX ticker attempt {attempt+1} failed: {e}")
56
  if attempt < 2:
57
  time.sleep(2)
58
  return None
59
 
60
+ def fetch_okx_candles(inst_id="BTC-USDT", bar="1H", limit=100):
61
+ """OKX mum verisi. 3 kez dener."""
62
  for attempt in range(3):
63
  try:
64
  r = requests.get(
65
+ f"{OKX_BASE}/api/v5/market/candles",
66
+ params={"instId": inst_id, "bar": bar, "limit": limit},
67
+ headers=OKX_HEADERS,
68
  timeout=15
69
  )
70
  r.raise_for_status()
71
+ raw = r.json()["data"]
72
+ # OKX formatı: [ts, open, high, low, close, vol, ...]
73
+ df = pd.DataFrame(raw, columns=["ts", "open", "high", "low", "close", "vol"])
74
+ for col in ["open", "high", "low", "close", "vol"]:
75
+ df[col] = df[col].astype(float)
76
  df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
77
+ return df.sort_values("ts").reset_index(drop=True)
78
  except Exception as e:
79
+ print(f"OKX candles attempt {attempt+1} failed: {e}")
80
  if attempt < 2:
81
  time.sleep(2)
82
  return None
 
91
  rs = gain / loss
92
  return 100 - (100 / (1 + rs))
93
 
94
+ def train_models_from_okx():
95
+ """OKX mum verisiyle XGBoost ve KNN eğitir."""
96
+ df = fetch_okx_candles(limit=500)
97
  if df is None or len(df) < 50:
98
  return None, None, None, None
99
 
 
124
 
125
  return xgb_model, knn_model, scaler, features
126
 
127
+ # Başlangıçta modelleri OKX verisiyle eğit
128
+ xgb_model, knn_model, scaler, feature_cols = train_models_from_okx()
129
 
130
  if xgb_model is None:
131
+ print("OKX erişilemedi, dummy modeller kullan��lıyor.")
132
  dummy_X = np.random.rand(50, 5)
133
  dummy_y = np.random.randint(0, 2, 50)
134
  xgb_model = xgb.XGBClassifier(n_estimators=10, max_depth=2)
 
136
  scaler = StandardScaler()
137
  knn_model = KNeighborsClassifier(n_neighbors=5)
138
  knn_model.fit(scaler.fit_transform(dummy_X), dummy_y)
139
+ feature_cols = ["ma_5", "ma_20", "rsi", "macd", "vol"]
140
 
141
  # ==========================================
142
  # 🧠 4. ANALİZ MOTORU (XGB + KNN Ensemble)
143
  # ==========================================
144
  def predict_and_analyze():
145
+ ticker = fetch_okx_ticker()
146
+ candles = fetch_okx_candles(limit=30)
147
 
148
  if ticker is None or candles is None:
149
+ return "❌ OKX API'sine erişilemedi (openapi alan adı + tarayıcı UA denendi). Lütfen sonra tekrar deneyin.", {}
150
 
151
  last_price = ticker["last"]
152
  change_pct = ticker["change_pct"]
 
177
  prompt = f"""
178
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
179
 
180
+ 📡 OKX Canlı Verileri (BTC/USDT):
181
  - Son Fiyat: ${last_price:,.2f}
182
  - 24s Değişim: %{change_pct:+.2f}
183
  - 24s Hacim: {vol24h:,.0f} BTC
 
217
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
218
 
219
  header = (
220
+ f"**OKX Canlı: ${last_price:,.2f}** (%{change_pct:+.2f}) | RSI: {rsi:.1f} | "
221
  f"MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n"
222
  f"**XGB:** %{xgb_prob_up*100:.1f} | **KNN:** %{knn_prob_up*100:.1f} | "
223
  f"**Ensemble:** %{ensemble_prob_up*100:.1f}\n\n---\n\n"
 
230
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
231
  gr.Markdown(
232
  """
233
+ # ₿ BTC/USD XGBoost + KNN & Groq AI Tahmin Radarı (OKX Canlı)
234
+ Fiyat ve mum verileri **OKX halka açık API**'sinden (`openapi.okx.com`) otomatik çekilir. **XGBoost + KNN** ensemble tahmini yapar, **Groq** analiz raporu üretir.
235
  """
236
  )
237
  with gr.Row():
238
  with gr.Column():
239
+ analyze_btn = gr.Button("🔄 OKX'ten Veri Çek ve Analiz Et", variant="primary", size="lg")
240
+ gr.Markdown("**Not**: `openapi.okx.com` + tarayıcı UA + 3 deneme kullanılıyor.")
241
  with gr.Column():
242
  prob_output = gr.Label(label="Model Tahminleri (XGB + KNN)")
243
+ analysis_output = gr.Markdown(value="Butona basarak OKX'ten canlı veri çekip analizi başlatın.")
244
  analyze_btn.click(fn=predict_and_analyze, inputs=[], outputs=[analysis_output, prob_output])
245
  gr.Markdown("---\n⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır.")
246