Download app.py from babikkk/Chronos: direct link, hf CLI and curl.
- Browser
- Download file 7.3 kB
-
https://huggingface.co/spaces/babikkk/Chronos/resolve/main/app.py
- Command line
-
hf download hf://spaces/babikkk/Chronos/app.py
-
curl -L -o app.py https://huggingface.co/spaces/babikkk/Chronos/resolve/main/app.py
7.3 kB
| from fastapi import FastAPI, Request | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.preprocessing import MinMaxScaler | |
| from tensorflow.keras.models import Sequential | |
| from tensorflow.keras.layers import Dense, LSTM, Input | |
| import requests | |
| import hmac | |
| import hashlib | |
| import time | |
| import os | |
| app = FastAPI() | |
| # --- CONFIG & SECRETS --- | |
| SUPA_URL = "https://nzpzddyjcthhzkyfrjpb.supabase.co" | |
| SUPA_KEY = os.getenv("SUPABASE_KEY") | |
| TG_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") | |
| TG_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID") | |
| BINANCE_KEY = os.getenv("BINANCE_API_KEY") | |
| BINANCE_SECRET = os.getenv("BINANCE_SECRET_KEY") | |
| BINANCE_BASE_URL = "https://api.binance.com" | |
| def send_tg_message(text: str): | |
| """Pengiriman langsung menggunakan multi-route fallback (Instan & Stabil)""" | |
| if not TG_TOKEN or not TG_CHAT_ID: | |
| return | |
| # Jalur pipa cadangan terkuat | |
| urls = [ | |
| f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage", | |
| f"https://teleapi.pax.workers.dev/bot{TG_TOKEN}/sendMessage" | |
| ] | |
| payload = {"chat_id": int(TG_CHAT_ID), "text": text} | |
| for url in urls: | |
| try: | |
| res = requests.post(url, json=payload, timeout=8) | |
| if res.status_code == 200: | |
| print(f"โ Pesan Telegram terkirim via: {url}") | |
| return | |
| except Exception as e: | |
| print(f"โ ๏ธ Gagal lewat {url}: {str(e)}") | |
| continue | |
| def get_binance_balance(): | |
| if not BINANCE_KEY or not BINANCE_SECRET: | |
| return "โ ๏ธ API Key Binance belum diisi di Secrets Hugging Face." | |
| endpoint = "/api/v3/account" | |
| timestamp = int(time.time() * 1000) | |
| query = f"timestamp={timestamp}" | |
| signature = hmac.new(BINANCE_SECRET.encode(), query.encode(), hashlib.sha256).hexdigest() | |
| url = f"{BINANCE_BASE_URL}{endpoint}?{query}&signature={signature}" | |
| try: | |
| res = requests.get(url, headers={"X-MBX-APIKEY": BINANCE_KEY}, timeout=5).json() | |
| balances = {b['asset']: float(b['free']) for b in res.get('balances', []) if b['asset'] in ['USDT', 'BTC']} | |
| return f"๐ต USDT: {balances.get('USDT', 0.0)}\n๐ช BTC: {balances.get('BTC', 0.0)}" | |
| except Exception as e: | |
| return f"Gagal mengambil saldo: {str(e)}" | |
| def execute_binance_trade(side: str, amount_or_qty: float, is_quote: bool = True): | |
| if not BINANCE_KEY or not BINANCE_SECRET: | |
| return "โ ๏ธ Fitur Binance dinonaktifkan (API Key kosong)." | |
| endpoint = "/api/v3/order" | |
| timestamp = int(time.time() * 1000) | |
| params = {"symbol": "BTCUSDT", "side": side.upper(), "type": "MARKET", "timestamp": timestamp} | |
| if side.upper() == "BUY" and is_quote: | |
| params["quoteOrderQty"] = amount_or_qty | |
| else: | |
| params["quantity"] = amount_or_qty | |
| query_string = "&".join([f"{k}={v}" for k, v in params.items()]) | |
| signature = hmac.new(BINANCE_SECRET.encode(), query_string.encode(), hashlib.sha256).hexdigest() | |
| url = f"{BINANCE_BASE_URL}{endpoint}?{query_string}&signature={signature}" | |
| try: | |
| res = requests.post(url, headers={"X-MBX-APIKEY": BINANCE_KEY}, timeout=5).json() | |
| if "orderId" in res: | |
| return f"โ BERHASIL!\nOrder ID: {res['orderId']}\nStatus: {res['status']}\nSide: {side}" | |
| return f"โ Binance Reject: {res.get('msg', 'Error')}" | |
| except Exception as e: | |
| return f"โ Gagal koneksi Binance: {str(e)}" | |
| def run_ai_prediction(): | |
| url = "https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USDT&limit=60" | |
| res = requests.get(url, timeout=5).json() | |
| closes = [float(item["close"]) for item in res["Data"]["Data"]] | |
| df = pd.DataFrame(closes, columns=['close']) | |
| current_price = float(df['close'].iloc[-1]) | |
| scaler = MinMaxScaler() | |
| scaled = scaler.fit_transform(df) | |
| lookback = 15 | |
| X = np.array([scaled[i-lookback:i, 0] for i in range(lookback, len(scaled))]).reshape(-1, lookback, 1) | |
| model = Sequential([Input(shape=(lookback, 1)), LSTM(16), Dense(1)]) | |
| model.compile(optimizer='adam', loss='mse') | |
| model.fit(X, scaled[lookback:], epochs=2, verbose=0) | |
| pred_scaled = model.predict(scaled[-lookback:].reshape(1, lookback, 1), verbose=0) | |
| final_pred = float(scaler.inverse_transform(pred_scaled).flatten()[0]) | |
| signal = "BUY ๐ข" if final_pred > current_price else "HOLD/SELL ๐ด" | |
| return current_price, final_pred, signal | |
| def save_to_supabase(payload): | |
| if not SUPA_KEY: return | |
| headers = {"apikey": SUPA_KEY, "Authorization": f"Bearer {SUPA_KEY}", "Content-Type": "application/json"} | |
| try: requests.post(f"{SUPA_URL}/rest/v1/signals", json=payload, headers=headers, timeout=5) | |
| except: pass | |
| # --- WEBHOOK INTERACTIVE CENTER --- | |
| async def telegram_webhook(request: Request): | |
| try: | |
| data = await request.json() | |
| if "message" not in data or "text" not in data["message"]: | |
| return {"status": "ignored"} | |
| chat_id = data["message"]["chat"]["id"] | |
| text = data["message"]["text"].strip() | |
| if str(chat_id) != str(TG_CHAT_ID): | |
| return {"status": "unauthorized"} | |
| if text == "/status": | |
| balance = get_binance_balance() | |
| send_tg_message(f"๐ผ STATUS SPOT WALLET:\n\n{balance}") | |
| elif text == "/predict": | |
| send_tg_message("๐ค AI sedang membaca pola chart CryptoCompare...") | |
| price, pred, signal = run_ai_prediction() | |
| send_tg_message(f"๐ก๏ธ MANUAL PREDICT REPORT\n\nPrice: ${price:,.2f}\nPred: ${pred:,.2f}\nSignal: {signal}") | |
| elif text == "/buy_btc": | |
| send_tg_message("๐ Menjalankan perintah beli instan $20 USDT...") | |
| res = execute_binance_trade("BUY", 20.0, is_quote=True) | |
| send_tg_message(res) | |
| elif text == "/sell_btc": | |
| send_tg_message("๐ด Menjalankan perintah jual instan 0.0003 BTC...") | |
| res = execute_binance_trade("SELL", 0.0003, is_quote=False) | |
| send_tg_message(res) | |
| elif text == "/start": | |
| menu = ( | |
| "๐ฎ CHRONOS REMOTE CONTROLLER ๐ฎ\n\n" | |
| "Klik perintah di bawah untuk kendali instan:\n" | |
| "๐ /predict - Picu prediksi AI sekarang\n" | |
| "๐ผ /status - Cek saldo BTC & USDT\n" | |
| "๐ข /buy_btc - Eksekusi BELI BTC ($20)\n" | |
| "๐ด /sell_btc - Eksekusi JUAL BTC (0.0003)" | |
| ) | |
| send_tg_message(menu) | |
| return {"status": "success"} | |
| except Exception as e: | |
| print(f"Error webhook: {str(e)}") | |
| return {"status": "error"} | |
| def get_cron_prediction(): | |
| try: | |
| price, pred, signal = run_ai_prediction() | |
| payload = {"price": price, "prediction": pred, "fng_index": 50, "signal_type": signal} | |
| save_to_supabase(payload) | |
| msg = f"๐ก๏ธ CHRONOS CRON REPORT\n\nPrice: ${price:,.2f}\nPred: ${pred:,.2f}\nSignal: {signal}\n\n๐ค Server Status: Autopilot Active" | |
| send_tg_message(msg) | |
| return payload | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def health(): | |
| return {"status": "Chronos Control Center Online"} | |