Switch to Binance API for stability
Browse files123452 unmodified lines89101112135 unmodified lines19202122232425262728293031323334353637383940414243443 unmodified lines48495051525354555657585960616 unmodified lines686970717273747576777879808182838485868788899091929394from fastapi import FastAPIimport yfinance as yfimport pandas as pdimport numpy as npfrom sklearn.preprocessing import MinMaxScaler2 unmodified linesfrom binance.client import Clientimport requestsimport osapp = FastAPI()5 unmodified linesBIN_KEY = os.getenv("BINANCE_API_KEY")BIN_SEC = os.getenv("BINANCE_SECRET_KEY")# --- TOOLS ---def send_telegram(msg):if TG_TOKEN and TG_CHAT_ID:url = f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage"try: requests.post(url, json={"chat_id": TG_CHAT_ID, "text": msg})except: passdef get_binance_balance():if not BIN_KEY or not BIN_SEC:return "Key Missing"try:client = Client(BIN_KEY, BIN_SEC)acc = client.get_account()balances = {item['asset']: item['free'] for item in acc['balances'] if float(item['free']) > 0}# Fokus ke USDT dan BTCusdt = balances.get('USDT', '0')btc = balances.get('BTC', '0')return f"💰 Wallet: {usdt} USDT | {btc} BTC"except:return "Binance Auth Failed"def save_to_supabase(payload):if not SUPA_KEY: return3 unmodified lines# --- AI LOGIC ---def run_ai_logic():df = yf.download('BTC-USD', period='60d', interval='1d', auto_adjust=True, progress=False)if df.empty: raise ValueError("Yahoo Finance Limit")close_series = df['Close'].iloc[:, 0] if isinstance(df.columns, pd.MultiIndex) else df['Close']current_price = float(close_series.iloc[-1])scaler = MinMaxScaler()scaled_data = scaler.fit_transform(close_series.to_frame())lookback = 15X = np.array([scaled_data[i-lookback:i, 0] for i in range(lookback, len(scaled_data))])6 unmodified linespred_scaled = model.predict(scaled_data[-lookback:].reshape(1, lookback, 1), verbose=0)final_pred = float(scaler.inverse_transform(pred_scaled).flatten()[0])return current_price, final_pred# --- ENDPOINTS ---@app.get("/predict")def get_prediction():try:curr, pred = run_ai_logic()signal = "BUY 🟢" if pred > curr else "HOLD/SELL 🔴"wallet = get_binance_balance()payload = {"price": curr, "prediction": pred, "fng_index": 50, "signal_type": signal}save_to_supabase(payload)# LOG TO TELEGRAMmsg = f"🛡️ CHRONOS REPORT\n\nPrice: ${curr:,.2f}\nPred: ${pred:,.2f}\nSignal: {signal}\n\n{wallet}"send_telegram(msg)return {**payload, "wallet": wallet}except Exception as e:return {"error": str(e)}@app.get("/")def health():return {"status": "Chronos Online"}12342 unmodified lines789101112135 unmodified lines192021222324252627282930313233343536373839404142434445464748495051523 unmodified lines565758596061626364656667686 unmodified lines757677787980818283848586878889909192939495969798from fastapi import FastAPIimport pandas as pdimport numpy as npfrom sklearn.preprocessing import MinMaxScaler2 unmodified linesfrom binance.client import Clientimport requestsimport osimport timeapp = FastAPI()5 unmodified linesBIN_KEY = os.getenv("BINANCE_API_KEY")BIN_SEC = os.getenv("BINANCE_SECRET_KEY")def send_telegram(msg):if TG_TOKEN and TG_CHAT_ID:url = f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage"try: requests.post(url, json={"chat_id": TG_CHAT_ID, "text": msg})except: passdef get_binance_data_and_balance():"""Ganti Yahoo Finance dengan Binance API yang lebih stabil"""if not BIN_KEY or not BIN_SEC:return None, None, "API Key Missing"try:client = Client(BIN_KEY, BIN_SEC)# Ambil data kline (candlestick) BTCUSDT - 60 hari terakhir, interval 1 hariklines = client.get_historical_klines("BTCUSDT", Client.KLINE_INTERVAL_1DAY, "60 days ago UTC")# Format ke DataFramedf = pd.DataFrame(klines, columns=['time', 'open', 'high', 'low', 'close', 'vol', 'close_time', 'qav', 'num_trades', 'taker_base', 'taker_quote', 'ignore'])df['close'] = df['close'].astype(float)# Ambil Saldoacc = client.get_account()balances = {item['asset']: item['free'] for item in acc['balances'] if float(item['free']) > 0}wallet = f"💰 Wallet: {balances.get('USDT', '0')} USDT | {balances.get('BTC', '0')} BTC"return df[['close']], wallet, Noneexcept Exception as e:return None, None, str(e)def save_to_supabase(payload):if not SUPA_KEY: return3 unmodified lines# --- AI LOGIC ---def run_ai_logic():df, wallet, err = get_binance_data_and_balance()if err: raise ValueError(f"Binance Error: {err}")current_price = float(df['close'].iloc[-1])scaler = MinMaxScaler()scaled_data = scaler.fit_transform(df)lookback = 15X = np.array([scaled_data[i-lookback:i, 0] for i in range(lookback, len(scaled_data))])6 unmodified linespred_scaled = model.predict(scaled_data[-lookback:].reshape(1, lookback, 1), verbose=0)final_pred = float(scaler.inverse_transform(pred_scaled).flatten()[0])return current_price, final_pred, wallet@app.get("/predict")def get_prediction():try:curr, pred, wallet = run_ai_logic()signal = "BUY 🟢" if pred > curr else "HOLD/SELL 🔴"payload = {"price": curr, "prediction": pred, "fng_index": 50, "signal_type": signal}save_to_supabase(payload)msg = f"🛡️ CHRONOS REPORT (Via Binance)\n\nPrice: ${curr:,.2f}\nPred: ${pred:,.2f}\nSignal: {signal}\n\n{wallet}"send_telegram(msg)return {**payload, "wallet": wallet}except Exception as e:return {"error": "System Busy", "detail": str(e)}@app.get("/")def health():return {"status": "Chronos Online", "engine": "Binance Data Stream"}
app.py+27-23