File size: 7,299 Bytes
fe62e1f 2d0c02a fe62e1f 63c9a20 fe62e1f 63c9a20 fe62e1f 63c9a20 fe62e1f 2d0c02a fe62e1f 2d0c02a 63c9a20 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a 63c9a20 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f 2d0c02a fe62e1f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | 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 ---
@app.post("/telegram-webhook")
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"}
@app.get("/predict")
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)}
@app.get("/")
def health():
return {"status": "Chronos Control Center Online"}
|