Fix: Switch to Tokocrypto endpoint to bypass US IP restriction
Browse files3 unmodified lines456789101112132 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697983 unmodified linesfrom sklearn.preprocessing import MinMaxScalerfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, LSTM, Inputfrom binance.client import Clientimport requestsimport osimport timeapp = FastAPI()2 unmodified linesSUPA_KEY = os.getenv("SUPABASE_KEY")TG_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")TG_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")BIN_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: return1 unmodified linetry: requests.post(f"{SUPA_URL}/rest/v1/signals", json=payload, headers=headers, timeout=5)except: pass# --- 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))])X = X.reshape(-1, lookback, 1)model = Sequential([Input(shape=(lookback, 1)), LSTM(16), Dense(1)])model.compile(optimizer='adam', loss='mse')model.fit(X, scaled_data[lookback:], epochs=2, verbose=0)pred_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"}3 unmodified lines45678910112 unmodified lines1415161718192021222324252627282930313233343536373839404142434445461 unmodified line4849505152535455565758596061626364656667686970717273747576777879808182838485868788899091923 unmodified linesfrom sklearn.preprocessing import MinMaxScalerfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, LSTM, Inputimport requestsimport osapp = FastAPI()2 unmodified linesSUPA_KEY = os.getenv("SUPABASE_KEY")TG_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")TG_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")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}, timeout=5)except: passdef get_crypto_data_global():"""Menggunakan public API Tokocrypto (Binance Cloud) yang bebas blokir wilayah di HF"""try:# Mengambil data candlestick/kline BTCUSDT interval 1 hari (1d) sebanyak 60 barisurl = "https://api.tokocrypto.com/open/v1/market/klines?symbol=BTC_USDT&intervals=1d&limit=60"res = requests.get(url, timeout=10).json()if res.get("code") != 0 or not res.get("data"):return None, f"API Error: {res.get('msg', 'Unknown')}"# Format data dari Tokocrypto: [openTime, open, high, low, close, volume, ...]raw_data = res["data"]# Ambil harga close (index ke-4)closes = [float(item[4]) for item in raw_data]df = pd.DataFrame(closes, columns=['close'])return df, Noneexcept Exception as e:return None, str(e)def save_to_supabase(payload):if not SUPA_KEY: return1 unmodified linetry: requests.post(f"{SUPA_URL}/rest/v1/signals", json=payload, headers=headers, timeout=5)except: pass@app.get("/predict")def get_prediction():try:df, err = get_crypto_data_global()if err:return {"error": "Gagal mengambil data market", "detail": err}current_price = float(df['close'].iloc[-1])# Scaling data untuk LSTMscaler = 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))])X = X.reshape(-1, lookback, 1)# AI Modeling kilatmodel = Sequential([Input(shape=(lookback, 1)), LSTM(16), Dense(1)])model.compile(optimizer='adam', loss='mse')model.fit(X, scaled_data[lookback:], epochs=2, verbose=0)pred_scaled = model.predict(scaled_data[-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 🔴"# Catat ke Databasepayload = {"price": current_price, "prediction": final_pred, "fng_index": 50, "signal_type": signal}save_to_supabase(payload)# Kirim Laporan ke Telegrammsg = f"🛡️ CHRONOS AI REPORT\n\nPrice: ${current_price:,.2f}\nPred: ${final_pred:,.2f}\nSignal: {signal}\n\n🤖 Server Status: Stable"send_telegram(msg)return {**payload, "telegram_status": "Pesan dikirim"}except Exception as e:return {"error": "System Busy", "detail": str(e)}@app.get("/")def health():return {"status": "Chronos Online", "engine": "Tokocrypto Data Stream"}
app.py+45-51