blind-monkeys / modules /market_data.py
deanpowers's picture
Binance geo-block fallback via scanner proxy (HTTP 451 on US egress) + Nov 2 UI polish (nav fonts, page tweaks)
4333e4e
Raw History Blame Contribute Delete
16.3 kB
import os
import requests
import numpy as np
import time
from datetime import datetime
from config import TREASURY_SYMBOLS
# ---------- Binance API (Free, High Rate Limit) ----------
BINANCE_BASE_URL = "https://api.binance.com"
COINBASE_BASE_URL = "https://api.exchange.coinbase.com"
# ---------- Dynamic Binance Symbol Cache ----------
_binance_symbols_cache = {"symbols": {}, "last_updated": None}
def _get_binance_symbols():
"""Fetch all available Binance trading symbols (cached for 1 hour)"""
global _binance_symbols_cache
if _binance_symbols_cache["symbols"] and _binance_symbols_cache["last_updated"]:
age = (datetime.now() - _binance_symbols_cache["last_updated"]).total_seconds()
if age < 3600:
return _binance_symbols_cache["symbols"]
try:
url = f"{BINANCE_BASE_URL}/api/v3/exchangeInfo"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
else:
# Binance geo-blocks US egress (HTTP 451). Fall back to the
# scanner-service proxy in europe-west1.
pr = requests.get(f"{SCANNER_BASE_URL}/binance/exchange-info",
timeout=25)
if pr.status_code != 200:
return {}
data = {"_symbols": pr.json()}
symbols = {}
if "_symbols" in data:
symbols = dict(data["_symbols"])
else:
for s in data.get("symbols", []):
if s.get("status") == "TRADING" and s["symbol"].endswith("USDT"):
base = s["baseAsset"].upper()
symbols[base] = s["symbol"]
_binance_symbols_cache["symbols"] = symbols
_binance_symbols_cache["last_updated"] = datetime.now()
print(f"✅ Loaded {len(symbols)} Binance symbols")
return symbols
except Exception as e:
print(f"⚠️ Failed to fetch Binance symbols: {e}")
return {}
# ---------- Known Overrides (CoinGecko ID → Binance Base) ----------
COINGECKO_OVERRIDES = {
"bitcoin": "BTC", "ethereum": "ETH", "solana": "SOL", "cardano": "ADA",
"ripple": "XRP", "binancecoin": "BNB", "dogecoin": "DOGE", "polkadot": "DOT",
"chainlink": "LINK", "litecoin": "LTC", "bitcoin-cash": "BCH", "stellar": "XLM",
"tron": "TRX", "uniswap": "UNI", "aave": "AAVE", "cosmos": "ATOM",
"algorand": "ALGO", "avalanche-2": "AVAX", "vechain": "VET", "filecoin": "FIL",
"near": "NEAR", "monero": "XMR", "tezos": "XTZ", "eos": "EOS",
"internet-computer": "ICP", "the-graph": "GRT", "decentraland": "MANA",
"sandbox": "SAND", "axie-infinity": "AXS", "basic-attention-token": "BAT",
"zilliqa": "ZIL", "harmony": "ONE", "matic-network": "MATIC",
"shiba-inu": "SHIB", "pepe": "PEPE", "aptos": "APT", "arbitrum": "ARB",
"optimism": "OP", "injective-protocol": "INJ", "sei-network": "SEI",
"sui": "SUI", "celestia": "TIA", "render-token": "RENDER", "fetch-ai": "FET",
"kaspa": "KAS", "thorchain": "RUNE", "gala": "GALA", "floki": "FLOKI",
"bonk": "BONK", "dogwifcoin": "WIF", "ethereum-classic": "ETC",
"hedera-hashgraph": "HBAR", "quant-network": "QNT", "aptos": "APT",
"sei-network": "SEI", "starknet": "STRK", "worldcoin-wld": "WLD",
"jupiter-exchange-solana": "JUP", "pyth-network": "PYTH", "jito-governance-token": "JTO",
"ethereum-name-service": "ENS", "curve-dao-token": "CRV", "compound-governance-token": "COMP",
"lido-dao": "LDO", "pendle": "PENDLE", "ondo-finance": "ONDO",
"ethena": "ENA", "jasmycoin": "JASMY", "iota": "IOTA", "arweave": "AR",
"the-open-network": "TON", "kaspa": "KAS", "mantle": "MNT",
"immutable-x": "IMX", "flow": "FLOW", "mina-protocol": "MINA",
"oasis-network": "ROSE", "kava": "KAVA", "band-protocol": "BAND",
"ankr": "ANKR", "1inch": "1INCH", "sushi": "SUSHI", "yearn-finance": "YFI"
}
def _map_to_binance(coin_id, coin_symbol=None):
"""Map a CoinGecko coin ID to a Binance USDT trading symbol"""
binance_symbols = _get_binance_symbols()
# Try override first
if coin_id in COINGECKO_OVERRIDES:
base = COINGECKO_OVERRIDES[coin_id]
if base in binance_symbols:
return binance_symbols[base]
# Fallback: use the coin symbol from registry
if coin_symbol:
base = coin_symbol.upper()
if base in binance_symbols:
return binance_symbols[base]
# Last resort: try the coin_id uppercased (e.g. "bitcoin" → "BITCOIN" won't work, but just in case)
if coin_id.upper() in binance_symbols:
return binance_symbols[coin_id.upper()]
return None
# ---------- Crypto Prices ----------
def get_market_data():
"""Fetch real crypto prices from Binance (fast, no rate limits)"""
try:
key_map = {"BTCUSDT": "BTC", "ETHUSDT": "ETH", "SOLUSDT": "SOL", "ADAUSDT": "ADA", "XRPUSDT": "XRP"}
results = {}
for symbol, key in key_map.items():
url = f"{BINANCE_BASE_URL}/api/v3/ticker/price"
response = requests.get(url, params={"symbol": symbol}, timeout=5)
if response.status_code == 200:
data = response.json()
results[key] = float(data["price"])
results["timestamp"] = datetime.now().isoformat()
return results
except Exception as e:
return {"error": str(e), "timestamp": datetime.now().isoformat()}
# ---------- Historical Prices (Binance Klines) ----------
def fetch_coin_data(coin_id, days=30):
"""Fetch historical price data. Tries Binance first, falls back to Coinbase."""
result = _fetch_coin_data_binance(coin_id, days)
if result and len(result) >= 7:
return result
print("Binance unavailable for " + coin_id + " - trying Coinbase")
return _fetch_coin_data_coinbase(coin_id, days)
def _fetch_coin_data_coinbase(coin_id, days=30):
"""Fallback: fetch daily close prices from Coinbase Exchange."""
try:
base = COINGECKO_OVERRIDES.get(coin_id)
if not base:
return []
pair = base.upper() + "-USD"
url = f"{COINBASE_BASE_URL}/products/{pair}/candles?granularity=86400"
r = requests.get(url, timeout=10)
if r.status_code != 200:
return []
candles = r.json()
if not candles:
return []
candles = list(reversed(candles))
closes = [float(c[4]) for c in candles]
return closes[-days:] if days else closes
except Exception as e:
print("Coinbase fetch failed for " + coin_id + ": " + str(e))
return []
SCANNER_BASE_URL = os.environ.get("SCANNER_BASE_URL",
"https://blind-monkeys-scanner-353804379600.europe-west1.run.app")
def _fetch_klines_via_scanner(symbol, limit):
"""Fetch Binance klines through the scanner-service proxy (europe-west1).
Used as a fallback when Binance geo-blocks the caller (HTTP 451)."""
try:
url = (f"{SCANNER_BASE_URL}/binance/klines"
f"?symbol={symbol}&interval=1d&limit={limit}")
r = requests.get(url, timeout=15)
if r.status_code == 200:
return r.json()
except Exception as e:
print(f"Scanner kline proxy failed for {symbol}: {e}")
return None
def _fetch_coin_data_binance(coin_id, days=30):
"""Fetch historical price data from Binance (fast, no rate limits)"""
from modules.coin_registry import get_coin_symbols
symbols_map = get_coin_symbols()
coin_symbol = symbols_map.get(coin_id)
binance_symbol = _map_to_binance(coin_id, coin_symbol)
if not binance_symbol:
return None
try:
url = f"{BINANCE_BASE_URL}/api/v3/klines"
limit = min(days, 1000)
params = {"symbol": binance_symbol, "interval": "1d", "limit": limit}
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
klines = response.json()
return [float(k[4]) for k in klines] # Close prices
# Binance returns HTTP 451 (geo-blocked) to US egress IPs such as
# us-central1 Cloud Run. Fall back to the scanner-service proxy in
# europe-west1, which can still reach Binance.
klines = _fetch_klines_via_scanner(binance_symbol, limit)
if klines:
return [float(k[4]) for k in klines]
return None
except Exception as e:
print(f"Error fetching {coin_id}: {e}")
return None
# ---------- ATR Calculation ----------
def calculate_atr(coin_id, period=14):
"""Calculate ATR using Binance klines"""
from modules.coin_registry import get_coin_symbols
symbols_map = get_coin_symbols()
coin_symbol = symbols_map.get(coin_id)
binance_symbol = _map_to_binance(coin_id, coin_symbol)
if not binance_symbol:
return None
try:
url = f"{BINANCE_BASE_URL}/api/v3/klines"
params = {"symbol": binance_symbol, "interval": "1d", "limit": 30}
response = requests.get(url, params=params, timeout=10)
if response.status_code != 200:
return None
klines = response.json()
if len(klines) < period + 1:
return None
true_ranges = []
for i in range(1, len(klines)):
high = float(klines[i][2])
low = float(klines[i][3])
prev_close = float(klines[i-1][4])
tr = max(high - low, abs(high - prev_close), abs(low - prev_close))
true_ranges.append(tr)
atr = np.mean(true_ranges[-period:])
current_price = float(klines[-1][4])
atr_percent = (atr / current_price) * 100
return {
"atr": round(float(atr), 4),
"atr_percent": round(float(atr_percent), 2),
"current_price": round(float(current_price), 4)
}
except Exception as e:
print(f"Error calculating ATR for {coin_id}: {e}")
return None
def get_atr_for_coins(coin_ids, period=14):
"""Get ATR for multiple coins"""
results = {}
for coin_id in coin_ids:
atr_data = calculate_atr(coin_id, period)
if atr_data:
results[coin_id.upper()] = atr_data
return results
# ---------- Treasury Yields (FRED API) ----------
def get_treasury_yields():
"""Fetch US Treasury yields from FRED API"""
from config import FRED_API_KEY
results = {}
if not FRED_API_KEY:
return {
"yields": {"3M": 5.25, "6M": 5.10, "1Y": 4.85, "2Y": 4.50, "5Y": 4.25, "10Y": 4.35, "30Y": 4.50},
"timestamp": datetime.now().isoformat(),
"source": "fallback"
}
try:
for label, symbol in TREASURY_SYMBOLS.items():
url = "https://api.stlouisfed.org/fred/series/observations"
params = {"series_id": symbol, "api_key": FRED_API_KEY, "file_type": "json", "sort_order": "desc", "limit": 1}
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
if 'observations' in data and len(data['observations']) > 0:
value = data['observations'][0]['value']
if value != '.':
results[label] = float(value)
if not results:
return {
"yields": {"3M": 5.25, "6M": 5.10, "1Y": 4.85, "2Y": 4.50, "5Y": 4.25, "10Y": 4.35, "30Y": 4.50},
"timestamp": datetime.now().isoformat(),
"source": "fallback"
}
return {"yields": results, "timestamp": datetime.now().isoformat(), "source": "FRED"}
except Exception as e:
return {"error": str(e), "timestamp": datetime.now().isoformat()}
def get_yield_curve_spread():
"""Calculate the 10Y-2Y Treasury spread (recession indicator)"""
yields = get_treasury_yields()
if 'yields' in yields:
y10 = yields['yields'].get('10Y', 0)
y2 = yields['yields'].get('2Y', 0)
spread = y10 - y2
return {"10Y": y10, "2Y": y2, "spread": round(spread, 3), "inverted": spread < 0, "timestamp": datetime.now().isoformat()}
return yields
# ---------- Market Regime Panel (Phase 2) ----------
# 10Y Treasury (FRED DGS10) + Fear & Greed (alternative.me) + VIX (FRED VIXCLS)
# All three have in-memory caches and return None on failure so the scan
# page can render "unavailable" without crashing.
_regime_cache = {
"fng": None, "fng_at": 0,
"vix": None, "vix_at": 0,
"dgs10": None, "dgs10_at": 0,
}
def get_fear_greed():
"""Crypto Fear & Greed Index from alternative.me. Cache 1 hour."""
now = time.time()
if _regime_cache["fng"] and now - _regime_cache["fng_at"] < 3600:
return _regime_cache["fng"]
try:
url = "https://api.alternative.me/fng/"
params = {"limit": 1}
r = requests.get(url, params=params, timeout=10)
if r.status_code != 200:
return None
data = r.json()
entry = (data.get("data") or [None])[0]
if not entry:
return None
result = {
"value": int(entry.get("value", 0)),
"classification": entry.get("value_classification", "Unknown"),
"timestamp": int(entry.get("timestamp", 0)),
}
_regime_cache["fng"] = result
_regime_cache["fng_at"] = now
return result
except Exception as e:
print(f"⚠️ Fear & Greed fetch failed: {e}")
return None
def _fred_latest(series_id):
"""Fetch the latest observation for a FRED series. Returns (value, date) or None."""
from config import FRED_API_KEY
if not FRED_API_KEY:
return None
try:
url = "https://api.stlouisfed.org/fred/series/observations"
params = {
"series_id": series_id,
"api_key": FRED_API_KEY,
"file_type": "json",
"sort_order": "desc",
"limit": 5,
}
r = requests.get(url, params=params, timeout=10)
if r.status_code != 200:
return None
for obs in r.json().get("observations", []):
val = obs.get("value", ".")
if val != ".":
return (float(val), obs.get("date"))
return None
except Exception as e:
print(f"⚠️ FRED {series_id} fetch failed: {e}")
return None
def get_vix():
"""VIX volatility index from FRED VIXCLS. Cache 6 hours."""
now = time.time()
if _regime_cache["vix"] and now - _regime_cache["vix_at"] < 21600:
return _regime_cache["vix"]
latest = _fred_latest("VIXCLS")
if not latest:
return None
value, date = latest
result = {"value": round(value, 2), "date": date}
_regime_cache["vix"] = result
_regime_cache["vix_at"] = now
return result
def get_treasury_history():
"""10Y Treasury yield (FRED DGS10), ~1 year of history. Cache 6 hours."""
now = time.time()
if _regime_cache["dgs10"] and now - _regime_cache["dgs10_at"] < 21600:
return _regime_cache["dgs10"]
from config import FRED_API_KEY
if not FRED_API_KEY:
return None
try:
url = "https://api.stlouisfed.org/fred/series/observations"
params = {
"series_id": "DGS10",
"api_key": FRED_API_KEY,
"file_type": "json",
"sort_order": "desc",
"limit": 400,
}
r = requests.get(url, params=params, timeout=15)
if r.status_code != 200:
return None
obs = r.json().get("observations", [])
series = []
for o in obs:
v = o.get("value", ".")
if v != ".":
series.append([o.get("date"), float(v)])
if not series:
return None
series.reverse() # oldest -> newest for charting
current = series[-1]
result = {
"current": round(current[1], 2),
"date": current[0],
"series": series,
}
_regime_cache["dgs10"] = result
_regime_cache["dgs10_at"] = now
return result
except Exception as e:
print(f"⚠️ FRED DGS10 fetch failed: {e}")
return None