from dotenv import load_dotenv load_dotenv() import os import json import re import requests import markdown as _markdown from flask import Flask, jsonify, send_file, request, send_from_directory, Response from flask_cors import CORS from datetime import datetime, timedelta, timezone import time import threading from flask import session, render_template, redirect # ---------- Import Modules ---------- from config import BINGX_API_KEY, BINGX_API_SECRET, FRED_API_KEY from modules.market_data import ( get_market_data, get_treasury_yields, get_yield_curve_spread, get_atr_for_coins ) from modules.bingx_client import ( get_bingx_balance, get_bingx_assets, get_bingx_positions, get_bingx_swap_balance, place_bingx_order, execute_batch_buy, get_spot_symbol, get_spot_price, close_batch_positions ) from modules.portfolio import get_portfolio, get_hedge from modules.scanner import _run_scan, run_scan, short_scan from modules.top20 import TOP20_COIN_IDS, get_conservative_ids, get_risk_ids from modules.auth import ( verify_login, verify_recovery, update_password, login_user, logout_user, current_user, is_admin, public_mode, require_login, require_admin, create_user, update_user_status, list_all_users, delete_user, ) from modules.registration import ( check_rate_limit, check_pending_cap, check_honeypot, check_timing, password_error, client_ip, ) from modules.telegram_alert import alert_on_buy_signals from modules.stats import log_admin_stat from modules.journal import ( get_journal_path, init_journal, get_all_trades, get_open_trades, get_journal_stats, add_trade, close_trade ) from modules.settings_manager import ( get_settings, update_settings, reset_settings, get_excluded_coins, add_excluded_coin, remove_excluded_coin, set_excluded_coins ) from modules.coin_registry import get_all_coins, get_coin_count, get_coin_ids, refresh_coins, clear_cache from modules.profile import get_profile, display_name from modules.position_tracker import ( get_all_batches, get_open_batches, get_batch, update_batch_prices, check_triggers, get_portfolio_summary, close_batch, delete_batch ) app = Flask(__name__) app.secret_key = os.environ.get("FLASK_SECRET", "dev-only-secret-change-me") CORS(app, resources={r"/*": {"origins": "*"}}) # =================================================================== # TTL cache for scanner-proxied API data (two-tier) # =================================================================== # Several /api/ endpoints are thin proxies to the scanner service, whose # live Bybit queries can take 9-15s (futures-closed, funding-summary). # Two cache tiers keep page loads fast: # 1. in-memory (per instance, TTL) # 2. a GCS snapshot (data bucket, api_cache/ prefix) that survives # cold starts and instance recycling. # A cold instance serves the last good snapshot immediately and # refreshes in the background; if the scanner is slow or down, the # most recent copy is served instead of a 502. import base64 import hashlib from modules.storage import load_bytes, save_bytes, load_json, save_json, delete_bytes, list_prefix PROXY_CACHE_TTL = 120 # seconds a fresh response is served as-is PROXY_CACHE_STALE = 6 * 3600 # max age served in-memory on upstream failure PROXY_CACHE_DISK_STALE = 24 * 3600 # max age of a GCS snapshot served cold _proxy_cache = {} # url -> (fetched_at, status, content) _proxy_refreshing = set() _proxy_lock = threading.Lock() def _cache_name(url): return "api_cache/" + hashlib.md5(url.encode("utf-8")).hexdigest() + ".json" def _snapshot_load(url): """Return (fetched_at, status, content) from the GCS snapshot, or None.""" raw = load_bytes(_cache_name(url)) if not raw: return None try: d = json.loads(raw) return (float(d.get("fetched_at") or 0), int(d.get("status") or 502), base64.b64decode(d.get("content_b64") or "")) except Exception: return None def _remember(url, status, content): """Store a response in memory and persist it to GCS for cold starts.""" fetched_at = time.time() _proxy_cache[url] = (fetched_at, status, content) try: save_bytes(_cache_name(url), json.dumps({ "url": url, "status": status, "fetched_at": fetched_at, "content_b64": base64.b64encode(content).decode("ascii"), })) except Exception: pass # snapshot write is best-effort; memory cache still works def _start_refresh(url, timeout): """Refresh a URL in the background (at most one refresh at a time).""" with _proxy_lock: if url in _proxy_refreshing: return _proxy_refreshing.add(url) def _work(): try: r = requests.get(url, timeout=timeout) r.raise_for_status() _remember(url, r.status_code, r.content) except Exception: pass finally: with _proxy_lock: _proxy_refreshing.discard(url) threading.Thread(target=_work, daemon=True).start() def proxy_cached(url, timeout, ttl=PROXY_CACHE_TTL): """GET url through the two-tier cache. Returns (status, content, cache_state) where cache_state is 'fresh' (just fetched), 'hit' (memory or snapshot) or 'stale' (last good copy served because the upstream call failed). """ now = time.time() hit = _proxy_cache.get(url) if hit and now - hit[0] < ttl: return hit[1], hit[2], 'hit' # Cold memory (new instance or expired TTL): try the GCS snapshot snap = _snapshot_load(url) if snap and now - snap[0] < PROXY_CACHE_DISK_STALE: _proxy_cache[url] = snap if now - snap[0] >= ttl: _start_refresh(url, timeout) # stale-while-revalidate return snap[1], snap[2], 'hit' # No usable snapshot: pay the upstream cost once, then persist try: r = requests.get(url, timeout=timeout) r.raise_for_status() _remember(url, r.status_code, r.content) return r.status_code, r.content, 'fresh' except Exception: if hit and now - hit[0] < PROXY_CACHE_STALE: return hit[1], hit[2], 'stale' if snap: # older than DISK_STALE but still better than an error return snap[1], snap[2], 'stale' raise def _json_response(content, status=200, max_age=60, cache_state=None): """JSON response with short browser/CDN caching and a debug header.""" resp = Response(content, status=status, mimetype='application/json') resp.headers['Cache-Control'] = f'public, max-age={max_age}' if cache_state: resp.headers['X-Cache'] = cache_state return resp # Long-cache immutable static assets (all versioned via ?v=N query). @app.after_request def _cache_static_assets(resp): p = request.path or "" if p.startswith(("/static", "/css", "/assets")): resp.headers["Cache-Control"] = "public, max-age=2592000, immutable" return resp # Share the login session with subdomains (e.g. scan.blindmonkeys.org) so # tools hosted there can recognize logged-in admins. Only widen the cookie # domain when the site is reached via a blindmonkeys.org host; on other # hosts (e.g. the raw run.app URL) keep the default host-only cookie. @app.before_request def _session_cookie_domain(): host = (request.host or "").split(":")[0].lower() if host == "blindmonkeys.org" or host.endswith(".blindmonkeys.org"): app.config["SESSION_COOKIE_DOMAIN"] = ".blindmonkeys.org" else: app.config["SESSION_COOKIE_DOMAIN"] = None # =================================================================== # GLOBAL LOGIN GATE ??? everything requires login except public endpoints # =================================================================== # ---------- Anonymous scan rate limit (3 min / IP) ---------- _ANON_SCAN_LIMIT = {} _ANON_SCAN_WINDOW = 900 PUBLIC_PATHS_EXACT = ( '/', '/home', '/home/', '/scan', '/scan/', '/login', '/logout', '/register', '/register/pending', '/terms', '/terms/', '/privacy', '/privacy/', '/about', '/about/', '/glossary', '/glossary/', '/glossary/futures_compounding', '/glossary/futures_compounding/', '/glossary/learned_weights', '/glossary/learned_weights/', '/glossary/market_regimes', '/glossary/market_regimes/', '/glossary/risk_management', '/glossary/risk_management/', '/tech_stack', '/tech_stack/', '/glossary/api', '/glossary/api/', '/telegram', '/telegram/', '/api/telegram-stats', '/regimes', '/regimes/', '/analytics', '/analytics/', '/algorithm', '/algorithm/', '/upward', '/upward/', '/downward', '/downward/', '/sideways', '/sideways/', '/financials', '/financials/', '/performance', '/performance/', '/api/bybit-balance', '/api/balance-history', '/api/funding-summary', '/api/futures-positions', '/api/futures-closed', '/robots.txt', '/sitemap.xml', '/llms.txt', '/reset', '/reset/new', '/favicon.ico', '/tonconnect-manifest.json', '/api/videos', '/api/alerts', '/api/alerts/flush-telegram', '/api/videos', '/api/alerts', '/api/alerts/flush-telegram', '/contact', '/faq', '/faq/', '/blog', '/blog/', '/api/contact', ) PUBLIC_PATHS_PREFIX = ( '/blog/', '/api/whoami', '/api/prices', '/api/bot-history', '/api/bot/', '/license', '/bot/', '/api/win-rate', '/api/bot-pnl', '/api/sp500-30d', '/api/grid-returns', '/api/grid-bots', '/api/grid-archived', '/api/grid-candidates', '/api/debug/apis', '/api/debug/users', '/api/scan', '/api/market-regime', '/api/scan/latest', '/static', '/css', '/assets', '/api/cron/', '/api/regime-panel', '/api/market-data', '/api/price-change', '/api/price/batch', '/api/price/enriched', '/api/diagnostic', '/api/btc-chart/', '/api/rising-coins', '/api/futures-weights', '/api/futures-weights-history', '/api/grid-score-weights-history', '/api/grid-config', '/api/cf-visitors', '/api/psi-scores', '/api/crawler-activity', '/api/ai-visibility', ) # Domain migration: page requests on the old domain redirect 301 to the # new domain, preserving path and query. API routes stay on the old host so # cron jobs, server-side proxies and the auto-refresh data feeds keep # working during the transition. NEW_DOMAIN = "blindmonkeys.org" OLD_HOSTS = {"blind-monkeys.com", "www.blind-monkeys.com"} @app.before_request def redirect_old_domain(): host = (request.host or "").split(":")[0].lower() if host in OLD_HOSTS and not (request.path or "").startswith("/api/"): return redirect("https://" + NEW_DOMAIN + request.full_path.rstrip("?"), code=301) @app.before_request def require_login_globally(): path = request.path or '/' if path in PUBLIC_PATHS_EXACT: return for p in PUBLIC_PATHS_PREFIX: if path.startswith(p): return if not current_user(): if path.startswith('/api/'): return jsonify({"error": "login required"}), 401 return redirect(f'/login?next={path}') # ---------- Config ---------- COINGECKO_BASE_URL = "https://api.coingecko.com/api/v3" # ---------- Startup Checks ---------- print("=" * 60) print(" Blind Monkeys - Modular Edition") print("=" * 60) if BINGX_API_KEY: print(f" BingX API Key: {BINGX_API_KEY[:10]}...") else: print(" BingX API Key: NOT SET") if BINGX_API_SECRET: print(f" BingX API Secret: {BINGX_API_SECRET[:10]}...") else: print(" BingX API Secret: NOT SET") if FRED_API_KEY: print(f" FRED API Key: {FRED_API_KEY[:10]}...") else: print(" FRED API Key: NOT SET (using fallback yields)") print("=" * 60) # =================================================================== # MARKET DATA ROUTES # =================================================================== # ---------- LIVE PRICE (BTC/ETH/etc + user lookups) ---------- _SYMBOL_MAP = { "BTC": "bitcoin", "ETH": "ethereum", "SOL": "solana", "ADA": "cardano", "XRP": "ripple", "DOGE": "dogecoin", "MATIC": "matic-network", "DOT": "polkadot", "LINK": "chainlink", "AVAX": "avalanche-2", "LTC": "litecoin", "BCH": "bitcoin-cash", "ATOM": "cosmos", "UNI": "uniswap", "AAVE": "aave", "TRX": "tron", "TRON": "tron", "TON": "the-open-network", "SHIB": "shiba-inu", "PEPE": "pepe", "NEAR": "near", "APT": "aptos", "ARB": "arbitrum", "OP": "optimism", "INJ": "injective-protocol", "SUI": "sui", "SEI": "sei-network", "TIA": "celestia", "FIL": "filecoin", "ETC": "ethereum-classic", "XLM": "stellar", "ALGO": "algorand", "VET": "vechain", "ICP": "internet-computer", "RNDR": "render-token", "IMX": "immutable-x", "GRT": "the-graph", } _COINBASE_MAP = { "BTC": "BTC-USD", "ETH": "ETH-USD", "SOL": "SOL-USD", "ADA": "ADA-USD", "XRP": "XRP-USD", "DOGE": "DOGE-USD", "MATIC": "MATIC-USD", "DOT": "DOT-USD", "LINK": "LINK-USD", "AVAX": "AVAX-USD", "LTC": "LTC-USD", "BCH": "BCH-USD", } _PRICE_CACHE = {} _PRICE_TTL = 60 def _price_cache_get(sym, now): e = _PRICE_CACHE.get(sym) if e and (now - e.get("at", 0) < _PRICE_TTL): return e return None def _resolve_symbol(sym): sym = (sym or "").strip().upper() if not sym: return None if sym in _SYMBOL_MAP: return _SYMBOL_MAP[sym] try: r = requests.get("https://api.coingecko.com/api/v3/search", params={"query": sym}, timeout=8) for c in r.json().get("coins", []): if c.get("symbol", "").upper() == sym: return c.get("id") if c.get("name", "").upper() == sym: return c.get("id") except Exception as e: print("price resolve failed " + sym + ": " + str(e)) return None def _fetch_coinbase(sym): pair = _COINBASE_MAP.get(sym) if not pair: return None try: r = requests.get("https://api.coinbase.com/v2/prices/" + pair + "/spot", timeout=6) amt = r.json().get("data", {}).get("amount") if amt is None: return None return {"price": float(amt), "change_24h": None} except Exception as e: print("coinbase fallback failed " + sym + ": " + str(e)) return None # ---------- DERIVATIVES (contango/backwardation) ---------- _DERIV_TTL = 300 _DERIV_CACHE = {"at": 0, "data": {}} def _median(vals): if not vals: return None vals = sorted(vals) n = len(vals) if n % 2 == 1: return vals[n // 2] return (vals[n // 2 - 1] + vals[n // 2]) / 2.0 def _fetch_derivatives_median(): """Fetch all perpetual derivatives, return {SYMBOL: {basis, funding}} medians.""" now = time.time() if now - _DERIV_CACHE.get("at", 0) < _DERIV_TTL and _DERIV_CACHE.get("data"): return _DERIV_CACHE["data"] try: url = "https://api.coingecko.com/api/v3/derivatives" params = {"include_tickers": "unexpired"} r = requests.get(url, params=params, timeout=15) if r.status_code != 200: print("derivatives failed: " + str(r.status_code)) return _DERIV_CACHE.get("data", {}) rows = r.json() except Exception as e: print("derivatives exception: " + str(e)) return _DERIV_CACHE.get("data", {}) by_sym = {} for row in rows: if row.get("contract_type") != "perpetual": continue sym = (row.get("index_id") or "").upper() if not sym: continue basis = row.get("basis") funding = row.get("funding_rate") if basis is None and funding is None: continue by_sym.setdefault(sym, {"basis": [], "funding": []}) if basis is not None: by_sym[sym]["basis"].append(float(basis)) if funding is not None: by_sym[sym]["funding"].append(float(funding)) out = {} for sym, d in by_sym.items(): med_basis = _median(d["basis"]) med_funding = _median(d["funding"]) signal = None if med_basis is not None: if med_basis > 0.0001: signal = "Contango" elif med_basis < -0.0001: signal = "Backwardation" else: signal = "Flat" out[sym] = { "basis_pct": round(med_basis * 100, 4) if med_basis is not None else None, "funding_pct": round(med_funding, 4) if med_funding is not None else None, "signal": signal, "samples": len(d["basis"]), } _DERIV_CACHE["at"] = now _DERIV_CACHE["data"] = out print("derivatives: " + str(len(out)) + " symbols cached") return out # ---------- ENRICHED PRICES (5-min cache, RSI/Z for BTC+ETH) ---------- _ENRICHED_TTL = 300 _ENRICHED_CACHE = {"at": 0, "data": {}} def _compute_rsi(closes, period=14): if not closes or len(closes) < period + 1: return None deltas = [closes[i] - closes[i-1] for i in range(1, len(closes))] recent = deltas[-period:] gains = sum(d for d in recent if d > 0) / period losses = sum(-d for d in recent if d < 0) / period if losses == 0: return 100.0 rs = gains / losses return round(100 - (100 / (1 + rs)), 2) def _compute_zscore(closes, window=20): if not closes or len(closes) < window: return None series = closes[-window:] mean = sum(series) / len(series) variance = sum((x - mean) ** 2 for x in series) / len(series) std = variance ** 0.5 if std == 0: return 0.0 return round((series[-1] - mean) / std, 2) def _fetch_ohlc_closes(coin_id, days=30): try: url = "https://api.coingecko.com/api/v3/coins/" + coin_id + "/ohlc" params = {"vs_currency": "usd", "days": str(days)} r = requests.get(url, params=params, timeout=10) if r.status_code != 200: return [] data = r.json() return [float(row[4]) for row in data] except Exception as e: print("OHLC fetch failed for " + coin_id + ": " + str(e)) return [] def _fetch_markets(coin_ids): if not coin_ids: return {} try: url = "https://api.coingecko.com/api/v3/coins/markets" params = { "vs_currency": "usd", "ids": ",".join(coin_ids), "price_change_percentage": "24h,7d,30d", } r = requests.get(url, params=params, timeout=12) if r.status_code != 200: print("markets failed: " + str(r.status_code)) return {} out = {} for c in r.json(): out[c["id"]] = { "price": c.get("current_price"), "change_24h": c.get("price_change_percentage_24h_in_currency"), "change_7d": c.get("price_change_percentage_7d_in_currency"), "change_30d": c.get("price_change_percentage_30d_in_currency"), } return out except Exception as e: print("markets exception: " + str(e)) return {} @app.route('/api/price/enriched') def price_enriched_api(): raw = (request.args.get("symbols") or "BTC,ETH,SOL,ADA,XRP").upper() symbols = [x.strip() for x in raw.split(",") if x.strip()][:15] now = time.time() if now - _ENRICHED_CACHE.get("at", 0) < _ENRICHED_TTL and _ENRICHED_CACHE.get("data"): cached = _ENRICHED_CACHE["data"] out = {s: cached.get(s, {}) for s in symbols} return jsonify({"status": "ok", "data": out, "timestamp": now, "cached": True}) id_map = {} for sym in symbols: cid = _resolve_symbol(sym) if cid: id_map[sym] = cid markets = _fetch_markets(list(id_map.values())) rsi_z = {} for sym, cid in id_map.items(): if sym in ("BTC", "ETH"): closes = _fetch_ohlc_closes(cid, days=30) rsi_z[sym] = { "rsi": _compute_rsi(closes, 14), "zscore": _compute_zscore(closes, 20), } out = {} for sym, cid in id_map.items(): m = markets.get(cid, {}) row = { "price": m.get("price"), "change_24h": m.get("change_24h"), "change_7d": m.get("change_7d"), "change_30d": m.get("change_30d"), "rsi": rsi_z.get(sym, {}).get("rsi"), "zscore": rsi_z.get(sym, {}).get("zscore"), } if row["price"] is None: cb = _fetch_coinbase(sym) if cb: row["price"] = cb.get("price") out[sym] = row deriv = _fetch_derivatives_median() for sym in out: d = deriv.get(sym, {}) out[sym]["basis_pct"] = d.get("basis_pct") out[sym]["funding_pct"] = d.get("funding_pct") out[sym]["signal"] = d.get("signal") _ENRICHED_CACHE["at"] = now _ENRICHED_CACHE["data"] = out return jsonify({"status": "ok", "data": out, "timestamp": now, "cached": False}) @app.route('/api/price/batch') def price_batch_api(): raw = (request.args.get("symbols") or "BTC,ETH,SOL,ADA,XRP").upper() symbols = [x.strip() for x in raw.split(",") if x.strip()][:15] if not symbols: return jsonify({"status": "error", "message": "no symbols"}), 400 now = time.time() out = {} need = [] for sym in symbols: c = _price_cache_get(sym, now) if c: out[sym] = {"price": c.get("price"), "change_24h": c.get("change_24h")} else: need.append(sym) if need: id_map = {} for sym in need: cid = _resolve_symbol(sym) if cid: id_map[sym] = cid if id_map: ids = ",".join(set(id_map.values())) url = "https://api.coingecko.com/api/v3/simple/price" params = {"ids": ids, "vs_currencies": "usd", "include_24hr_change": "true"} try: r = requests.get(url, params=params, timeout=10) if r.status_code == 200: prices = r.json() for sym, cid in id_map.items(): info = prices.get(cid) or {} rec = {"price": info.get("usd"), "change_24h": info.get("usd_24h_change"), "at": now} _PRICE_CACHE[sym] = rec out[sym] = {"price": rec["price"], "change_24h": rec["change_24h"]} else: print("coingecko status " + str(r.status_code)) except Exception as e: print("coingecko failed: " + str(e)) for sym in need: if sym in out and out[sym].get("price") is not None: continue cb = _fetch_coinbase(sym) if cb and cb.get("price") is not None: _PRICE_CACHE[sym] = {"price": cb["price"], "change_24h": None, "at": now} out[sym] = {"price": cb["price"], "change_24h": None} return jsonify({"status": "ok", "data": out, "timestamp": now}) @app.route('/api/market-data') def market_data_api(): return jsonify(get_market_data()) @app.route('/api/price-change') def price_change_api(): """24h price change (%) for a symbol — proxied from the trader service (europe-west1; Bybit geo-blocks the main app's us-central1 egress). Cached 60s server-side so page polling doesn't hit the trader hard.""" sym = (request.args.get('symbol') or 'BTCUSDT').upper().strip() if not re.match(r'^[A-Z0-9]{1,20}USDT$', sym): return jsonify({"status": "error", "message": "bad symbol"}), 400 try: url = ('https://blind-monkeys-trader-353804379600.europe-west1.run.app' '/price-change?symbol=' + sym) status, content, state = proxy_cached(url, 20, ttl=60) return _json_response(content, status=status, max_age=30, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/treasury') def treasury_api(): return jsonify(get_treasury_yields()) @app.route('/api/yield-curve') def yield_curve_api(): return jsonify(get_yield_curve_spread()) @app.route('/api/atr') def atr_api(): coins = request.args.get('coins', 'bitcoin,ethereum,solana,cardano,ripple').split(',') period = int(request.args.get('period', 14)) return jsonify(get_atr_for_coins(coins, period)) @app.route('/api/eth-chart/daily') def eth_chart_daily(): try: url = "https://api.binance.com/api/v3/klines" params = {"symbol": "ETHUSDT", "interval": "1d", "limit": 20} response = requests.get(url, params=params, timeout=10) if response.status_code != 200: return jsonify({"error": "Binance API failed"}), 500 klines = response.json() data = [] for k in klines: data.append({ "time": datetime.fromtimestamp(k[0] / 1000).strftime("%Y-%m-%d"), "open": float(k[1]), "high": float(k[2]), "low": float(k[3]), "close": float(k[4]), "volume": float(k[5]) }) return jsonify({"symbol": "ETHUSDT", "interval": "1d", "data": data}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/api/eth-chart/hourly') def eth_chart_hourly(): try: url = "https://api.binance.com/api/v3/klines" params = {"symbol": "ETHUSDT", "interval": "1h", "limit": 12} response = requests.get(url, params=params, timeout=10) if response.status_code != 200: return jsonify({"error": "Binance API failed"}), 500 klines = response.json() data = [] for k in klines: data.append({ "time": datetime.fromtimestamp(k[0] / 1000).strftime("%H:%M"), "open": float(k[1]), "high": float(k[2]), "low": float(k[3]), "close": float(k[4]), "volume": float(k[5]) }) return jsonify({"symbol": "ETHUSDT", "interval": "1h", "data": data}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/api/btc-chart/weekly') def btc_chart_weekly(): """BTC spot price (last 7 days, hourly) for the market-condition line charts.""" try: url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart" params = {"vs_currency": "usd", "days": "7"} response = requests.get(url, params=params, timeout=15) if response.status_code != 200: return jsonify({"error": "CoinGecko API failed"}), 500 prices = response.json().get("prices", []) data = [{"t": int(p[0]), "close": float(p[1])} for p in prices] return jsonify({"symbol": "BTCUSD", "interval": "auto", "data": data}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/api/market-regime') def market_regime(): """Check if ETH has dropped 2% from its 24-hour high""" try: url = f"{COINGECKO_BASE_URL}/coins/ethereum/market_chart" params = {"vs_currency": "usd", "days": 1} r = requests.get(url, params=params, timeout=15) if r.status_code != 200: return jsonify({"error": f"CoinGecko error: {r.status_code}"}), 500 data = r.json() prices = [p[1] for p in data.get("prices", [])] if len(prices) < 2: return jsonify({"error": "Not enough data"}), 500 high_24h = max(prices) current = prices[-1] drop_pct = ((current - high_24h) / high_24h) * 100 if drop_pct <= -2.0: status = "buy_zone" message = "Market pulled back ??? good time to scan for buys" icon = "????" elif drop_pct <= -1.0: status = "watch" message = "Market softening ??? prepare watchlist" icon = "????" else: status = "wait" message = "Market extended ??? wait for a 2% pullback" icon = "????" return jsonify({ "status": status, "message": message, "icon": icon, "eth_current": round(current, 2), "eth_high_24h": round(high_24h, 2), "drop_pct": round(drop_pct, 2) }) except Exception as e: return jsonify({"error": str(e)}), 500 # =================================================================== # BINGX ROUTES # =================================================================== @app.route('/api/bingx/balance') @require_admin def bingx_balance(): return jsonify(get_bingx_balance()) @app.route('/api/bingx/assets') @require_admin def bingx_assets(): return jsonify(get_bingx_assets()) @app.route('/api/bingx/positions') @require_admin def bingx_positions(): return jsonify(get_bingx_positions()) @app.route('/api/bingx/swap-balance') @require_admin def bingx_swap_balance(): return jsonify(get_bingx_swap_balance()) @app.route('/api/bingx/account') @require_admin def bingx_account(): return jsonify({ "spot_balance": get_bingx_balance(), "swap_balance": get_bingx_swap_balance(), "positions": get_bingx_positions() }) @app.route('/api/bingx/portfolio') @require_admin def bingx_portfolio(): return jsonify(get_portfolio()) @app.route('/api/bingx/hedge') @require_admin def bingx_hedge(): return jsonify(get_hedge()) @app.route('/api/bingx/order', methods=['POST']) @require_admin def bingx_order(): data = request.get_json() symbol = data.get('symbol') side = data.get('side') quantity = data.get('quantity') order_type = data.get('order_type', 'MARKET') price = data.get('price') if not symbol or not side or not quantity: return jsonify({"error": "Missing required fields"}), 400 return jsonify(place_bingx_order(symbol, side, quantity, order_type, price)) @app.route('/api/bingx/status') def bingx_status(): return jsonify({ "api_key_set": bool(BINGX_API_KEY), "secret_set": bool(BINGX_API_SECRET), "fred_key_set": bool(FRED_API_KEY), "api_key_preview": BINGX_API_KEY[:10] + "..." if BINGX_API_KEY else None, "secret_preview": BINGX_API_SECRET[:10] + "..." if BINGX_API_SECRET else None }) # =================================================================== # AUTOMATED TRADING ROUTES # =================================================================== @app.route('/api/bingx/order/batch', methods=['POST']) @require_admin def bingx_batch_order(): data = request.get_json() coins = data.get('coins', []) take_profit_pct = float(data.get('take_profit_pct', 0)) stop_loss_pct = float(data.get('stop_loss_pct', 0)) allocation_pct = int(data.get('allocation_pct', 100)) use_oco = bool(data.get('use_oco', True)) use_atr_sizing = bool(data.get('use_atr_sizing', False)) if not coins: return jsonify({"error": "No coins selected"}), 400 if len(coins) > 10: return jsonify({ "error": f"Maximum 10 coins allowed. You selected {len(coins)}.", "max_coins": 10, "selected": len(coins) }), 400 try: result = execute_batch_buy( coins, take_profit_pct, stop_loss_pct, allocation_pct, use_oco, save_as_batch=True, use_atr_sizing=use_atr_sizing ) return jsonify(result) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/api/bingx/spot-symbols') def bingx_spot_symbols(): coin_ids = get_coin_ids() symbols = {} for coin_id in coin_ids[:50]: symbol = get_spot_symbol(coin_id) if symbol: symbols[coin_id] = symbol return jsonify({"count": len(symbols), "symbols": symbols}) @app.route('/api/bingx/spot-price/') def bingx_spot_price(coin_id): symbol = get_spot_symbol(coin_id) if not symbol: return jsonify({"error": "Symbol not found"}), 404 price = get_spot_price(symbol) if price: return jsonify({"coin_id": coin_id, "symbol": symbol, "price": price}) return jsonify({"error": "Price not available"}), 500 # =================================================================== # PORTFOLIO MANAGEMENT ROUTES # =================================================================== @app.route('/api/portfolio/summary') def portfolio_summary(): batches = get_open_batches() if not batches: return jsonify({"total_batches": 0, "total_cost": 0, "total_value": 0, "total_pnl": 0, "total_pnl_pct": 0, "batches": []}) symbols = set() for b in batches: for c in b["coins"]: symbols.add(c["symbol"]) current_prices = {} for symbol in symbols: price = get_spot_price(symbol) if price: current_prices[symbol] = price summary = get_portfolio_summary(current_prices) return jsonify(summary) @app.route('/api/portfolio/batches') @require_admin def portfolio_batches(): return jsonify({"batches": get_all_batches()}) @app.route('/api/portfolio/check-triggers') def portfolio_check_triggers(): batches = get_open_batches() symbols = set() for b in batches: for c in b["coins"]: symbols.add(c["symbol"]) current_prices = {} for symbol in symbols: price = get_spot_price(symbol) if price: current_prices[symbol] = price triggered = check_triggers(current_prices) return jsonify({ "checked": len(batches), "triggered": len(triggered), "batches": triggered }) @app.route('/api/portfolio/close/', methods=['POST']) @require_admin def portfolio_close_batch(batch_id): try: result = close_batch_positions(batch_id) return jsonify(result) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/api/portfolio/delete/', methods=['DELETE']) @require_admin def portfolio_delete_batch(batch_id): delete_batch(batch_id) return jsonify({"status": "deleted"}) @app.route('/api/portfolio/auto-close', methods=['POST']) def portfolio_auto_close(): batches = get_open_batches() symbols = set() for b in batches: for c in b["coins"]: symbols.add(c["symbol"]) current_prices = {} for symbol in symbols: price = get_spot_price(symbol) if price: current_prices[symbol] = price triggered = check_triggers(current_prices) results = [] for batch in triggered: close_result = close_batch_positions(batch["id"]) results.append({ "batch_id": batch["id"], "batch_name": batch["name"], "trigger": batch["pending_trigger"], "result": close_result }) return jsonify({ "triggered": len(triggered), "closed": len(results), "results": results }) # =================================================================== # AUTH ROUTES # =================================================================== @app.route('/login', methods=['GET', 'POST']) def login_page(): if request.method == 'GET': return render_template('login.html', next=request.args.get('next', '/')) email = request.form.get('email', '') password = request.form.get('password', '') nxt = request.form.get('next', '/') user, err = verify_login(email, password) if not user: if err == 'pending': msg = 'Your registration is awaiting approval' elif err == 'rejected': msg = 'Your registration request was declined' else: msg = 'Invalid email or password' return render_template('login.html', error=msg, next=nxt), 401 login_user(user) return redirect(nxt) @app.route('/logout') def logout_page(): logout_user() return redirect('/login') @app.route('/reset', methods=['GET', 'POST']) def reset_request(): if request.method == 'GET': return render_template('reset.html') email = request.form.get('email', '') code = request.form.get('code', '') user = verify_recovery(email, code) if not user: return render_template('reset.html', error='Invalid email or recovery code'), 401 session['reset_email'] = user['email'] session['reset_verified_at'] = int(time.time()) return redirect('/reset/new') @app.route('/reset/new', methods=['GET', 'POST']) def reset_new(): email = session.get('reset_email') verified_at = session.get('reset_verified_at', 0) if not email or time.time() - verified_at > 900: return redirect('/reset') if request.method == 'GET': return render_template('reset_new.html', email=email) pw = request.form.get('password', '') confirm = request.form.get('confirm', '') if len(pw) < 8: return render_template('reset_new.html', email=email, error='Password must be at least 8 characters'), 400 if pw != confirm: return render_template('reset_new.html', email=email, error='Passwords do not match'), 400 ok = update_password(email, pw) session.pop('reset_email', None) session.pop('reset_verified_at', None) if not ok: return render_template('reset_new.html', email=email, error='Could not update password'), 500 return redirect('/login') # =================================================================== # SCAN ROUTES # =================================================================== @app.route('/api/debug/users') def debug_users_api(): import os as _os try: from modules import storage as _st from modules.auth import _load_users_raw, LOCAL_USERS_FILE users = _load_users_raw() return jsonify({ "gcs_bucket_env": _os.environ.get("GCS_BUCKET", "(unset)"), "storage_bucket": _st._BUCKET_NAME, "storage_is_gcs": _st._is_gcs(), "users_file_path": LOCAL_USERS_FILE, "normalized": _st._normalize(LOCAL_USERS_FILE), "users_count": len(users), "emails": [u.get("email") for u in users], }) except Exception as e: import traceback return jsonify({"error": str(e), "trace": traceback.format_exc()}) @app.route('/api/debug/apis') def debug_apis_api(): import requests as _rq out = {} tests = { "binance_klines": "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1d&limit=5", "coinbase_candles": "https://api.exchange.coinbase.com/products/BTC-USD/candles?granularity=86400", "bingx_symbols": "https://open-api.bingx.com/openApi/spot/v1/common/symbols", "coingecko_simple": "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd", } for k, u in tests.items(): try: r = _rq.get(u, timeout=8) out[k] = {"status": r.status_code, "bytes": len(r.content)} except Exception as e: out[k] = {"error": str(e)[:100]} return jsonify(out) @app.route('/api/sp500-30d') def sp500_30d_api(): """S&P 500 return over the last 30 days — FRED primary, Yahoo fallback.""" # --- Primary: FRED daily SP500 series --- try: url = ('https://api.stlouisfed.org/fred/series/observations' '?series_id=SP500&api_key={}&file_type=json&sort_order=desc&limit=25').format(FRED_API_KEY) r = requests.get(url, timeout=10) obs = [o for o in r.json().get('observations', []) if o.get('value', '.') != '.'] if obs: latest = obs[0] latest_dt = datetime.strptime(latest['date'], '%Y-%m-%d') cutoff = latest_dt - timedelta(days=30) base = None for o in obs[1:]: if datetime.strptime(o['date'], '%Y-%m-%d') <= cutoff: base = o break if base is None: base = obs[-1] ret = (float(latest['value']) / float(base['value']) - 1) * 100.0 return jsonify({"status": "ok", "source": "fred", "as_of": latest['date'], "base_date": base['date'], "return_pct": round(ret, 2)}) except Exception: pass # FRED down/maintenance — fall through to Yahoo # --- Fallback: Yahoo Finance chart API --- try: r = requests.get('https://query1.finance.yahoo.com/v8/finance/chart/%5EGSPC', params={'range': '2mo', 'interval': '1d'}, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10) res = r.json()['chart']['result'][0] pairs = [] for t, c in zip(res['timestamp'], res['indicators']['quote'][0]['close']): if c is not None: pairs.append((datetime.fromtimestamp(t, timezone.utc), c)) now_dt, now_px = pairs[-1] cutoff = now_dt - timedelta(days=30) older = [p for p in pairs if p[0] <= cutoff] s_dt, s_px = older[-1] if older else pairs[0] ret = (now_px / s_px - 1) * 100.0 return jsonify({"status": "ok", "source": "yahoo", "as_of": now_dt.strftime('%Y-%m-%d'), "base_date": s_dt.strftime('%Y-%m-%d'), "return_pct": round(ret, 2)}) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-returns') def grid_returns_api(): """Grid-bot realized return (last 30 days) via the scanner service (cached 5 min).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/returns', 25, ttl=300) d = json.loads(content) if d.get('status') != 'ok': return _json_response(content, status=502, cache_state=state) return _json_response(content, max_age=60, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-bots') def grid_bots_api(): """Live grid bots (running/paused) proxied from the scanner service (cached 60s).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/bots', 25, ttl=60) return _json_response(content, max_age=30, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-archived') def grid_archived_api(): """Archived/completed grid bots proxied from the scanner service (cached 5 min).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/archived', 25, ttl=300) return _json_response(content, max_age=120, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-candidates') def grid_candidates_api(): """Range-bound grid candidates proxied from the scanner service.""" try: r = requests.get('https://scan.blindmonkeys.org/grid/candidates.json', timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-config', methods=['GET']) def grid_config_get_api(): """Grid bot settings proxied from the scanner service (GET — read/view).""" url = 'https://scan.blindmonkeys.org/grid/config' try: r = requests.get(url, timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-config', methods=['POST']) @require_admin def grid_config_post_api(): """Grid bot settings proxied from the scanner service (POST — admin only).""" url = 'https://scan.blindmonkeys.org/grid/config' try: data = request.get_json(silent=True) or {} r = requests.post(url, json=data, timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/futures-config', methods=['GET']) def futures_config_get_api(): """Futures auto-trade settings proxied from the scanner service (GET — read/view).""" url = 'https://scan.blindmonkeys.org/config' try: r = requests.get(url, timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/futures-config', methods=['POST']) @require_admin def futures_config_post_api(): """Futures auto-trade settings proxied from the scanner service (POST — admin only).""" url = 'https://scan.blindmonkeys.org/config' try: data = request.get_json(silent=True) or {} r = requests.post(url, json=data, timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/grid-archive', methods=['POST']) @require_admin def grid_archive_api(): """Archive a completed grid bot via the trader (admin only). Moves the bot into the archive list so its slot frees up and its funds, already released by Bybit when the grid completed, are accounted for. """ data = request.get_json(silent=True) or {} bot_id = (data.get('bot_id') or '').strip() if not bot_id: return "bot_id required", 400 try: r = requests.get( 'https://blind-monkeys-trader-353804379600.europe-west1.run.app/grid/archive', params={'bot_id': bot_id}, timeout=30) return Response(r.text, status=r.status_code, mimetype='text/plain') except Exception as e: return f"archive failed: {str(e)[:120]}", 502 @app.route('/api/bybit-balance') def bybit_balance_api(): """Live Bybit account balances proxied from the scanner service (cached 60s).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/balance', 25, ttl=60) return _json_response(content, max_age=30, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/futures-closed') def futures_closed_api(): """Last 10 closed futures positions, proxied from the trader (cached 2 min).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/futures-closed', 90, ttl=120) return _json_response(content, max_age=60, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/futures-positions') def futures_positions_api(): """All open Bybit futures positions, proxied from the trader (cached 60s).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/futures-positions', 90, ttl=60) return _json_response(content, max_age=30, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/funding-summary') def funding_summary_api(): """Funding fees received/paid (7d/30d) from the trader's Bybit scan (cached 2 min).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/funding-summary', 60, ttl=120) return _json_response(content, max_age=60, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/balance-history') def balance_history_api(): """Daily Bybit balance snapshots proxied from the scanner service (cached 5 min).""" try: status, content, state = proxy_cached( 'https://scan.blindmonkeys.org/grid/balance-history', 25, ttl=300) return _json_response(content, max_age=120, cache_state=state) except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/riser-config', methods=['GET']) def riser_config_get_api(): """Rising-coins trading rules proxied from the scanner service (GET — view).""" url = 'https://scan.blindmonkeys.org/riser/config' try: r = requests.get(url, timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/riser-config', methods=['POST']) @require_admin def riser_config_post_api(): """Rising-coins trading rules proxied from the scanner service (POST — admin only).""" url = 'https://scan.blindmonkeys.org/riser/config' try: data = request.get_json(silent=True) or {} r = requests.post(url, json=data, timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/rising-coins') def rising_coins_api(): """Rising-coins (relative strength) data proxied from the scanner service.""" try: r = requests.get('https://scan.blindmonkeys.org/rising.json', timeout=60) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"status": "error", "message": str(e)[:120]}), 502 @app.route('/api/bot-pnl') def bot_pnl_api(): """Return Bybit bot P&L with 24h/7d/30d/YTD deltas computed from history.""" from modules.storage import load_json latest = load_json("bybit_pnl.json", default=None) if not latest: return jsonify({"status": "empty", "message": "No snapshot yet"}) history = load_json("bybit_pnl_history.json", default=None) or {"snapshots": []} snaps = sorted(history.get("snapshots", []), key=lambda x: x.get("updated_at", 0)) current_bot_id = str(latest.get("bot_id", "")) base_ts = latest.get("updated_at", 0) # Single pass over history: find, for the CURRENT bot only, the # snapshot closest to each window target (24h / 7d / 30d) and the # earliest snapshot on/after Jan 1 (YTD baseline). WINDOWS = ((86400, "w24h"), (7 * 86400, "w7d"), (30 * 86400, "w30d")) best = {"w24h": None, "w7d": None, "w30d": None} # (delta, snapshot) import datetime as _dt year_start_ts = int(_dt.datetime(_dt.datetime.now().year, 1, 1).timestamp()) ytd_snap = None for sn in snaps: if str(sn.get("bot_id", "")) != current_bot_id: continue # ignore snapshots from other bots ts = sn.get("updated_at", 0) if ytd_snap is None and ts >= year_start_ts: ytd_snap = sn for w, key in WINDOWS: d = abs(ts - (base_ts - w)) cur = best[key] if cur is None or d < cur[0]: best[key] = (d, sn) def _delta_from(entry, window): """P&L delta vs. the closest snapshot, same validity rules as the original per-window scan (preserves displayed values): - closest snapshot farther than half the window: use it (sparse history) - otherwise require it within 1h of the target time.""" if not entry: return None d, past = entry if d <= window * 0.5 and d >= 3600: return None try: now_v = float(latest.get("total_pnl", 0)) past_v = float(past.get("total_pnl", 0)) return round(now_v - past_v, 4) except Exception: return None ytd_delta = None if ytd_snap: try: ytd_delta = round(float(latest.get("total_pnl", 0)) - float(ytd_snap.get("total_pnl", 0)), 4) except Exception: pass resp = jsonify({ "status": "ok", "bot_id": latest.get("bot_id"), "bot_name": latest.get("bot_name"), "bot_status": latest.get("bot_status"), "leverage": latest.get("leverage"), "total_margin": latest.get("total_margin"), "equity": latest.get("equity"), "current_pnl": latest.get("total_pnl"), "current_pnl_per": latest.get("total_pnl_per"), "realized_pnl": latest.get("realized_pnl"), "unrealized_pnl": latest.get("unrealized_pnl"), "pnl_24h": _delta_from(best["w24h"], 86400), "pnl_7d": _delta_from(best["w7d"], 7 * 86400), "pnl_30d": _delta_from(best["w30d"], 30 * 86400), "pnl_ytd": ytd_delta, "updated_at": latest.get("updated_at"), "snapshot_count": len(snaps), }) resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0" resp.headers["Pragma"] = "no-cache" resp.headers["Expires"] = "0" return resp @app.route('/api/win-rate') def win_rate_api(): """Win rate across all bots that have run (closed + running).""" from modules.storage import load_json history = load_json("bybit_bots_history.json", default=None) if not history or not history.get("bots"): # Fallback: check current bot snapshot only latest = load_json("bybit_pnl.json", default=None) if latest: pnl = 0.0 try: pnl = float(latest.get("total_pnl", 0)) except Exception: pnl = 0.0 return jsonify({ "status": "ok", "win_rate": 100.0 if pnl > 0 else 0.0, "total_bots": 1, "wins": 1 if pnl > 0 else 0, "losses": 0 if pnl > 0 else 1, "active_ring": "ring-inner" if pnl > 0 else "ring-outer", "source": "current_only", }) return jsonify({ "status": "ok", "win_rate": None, "total_bots": 0, "wins": 0, "losses": 0, "active_ring": "ring-middle", "source": "empty", }) bots = history.get("bots", []) wins = sum(1 for b in bots if float(b.get("final_pnl", 0)) > 0) losses = len(bots) - wins total = len(bots) rate = round((wins / total) * 100, 1) if total else None if rate is None: active = "ring-middle" elif rate > 60: active = "ring-inner" # green elif rate >= 40: active = "ring-middle" # yellow else: active = "ring-outer" # red resp = jsonify({ "status": "ok", "win_rate": rate, "total_bots": total, "wins": wins, "losses": losses, "active_ring": active, "source": "history", }) resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0" return resp AM_TZ_OFFSET_HOURS = 4 def _load_manual_running_bots(): from modules.storage import load_json data = load_json("manual_running_bots.json", default=None) or {"bots": []} return data.get("bots", []) def _save_manual_running_bots(bots): from modules.storage import save_json save_json("manual_running_bots.json", {"bots": bots}) def bot_detail_page(bot_id): return render_template('bot_detail.html') @app.route('/license') def license_page(): return render_template('license.html') @app.route('/api/bot/') def bot_detail_api(bot_id): """Return bot summary + per-coin breakdown.""" from modules.storage import load_json latest = load_json("bybit_pnl.json", default=None) history = load_json("bybit_bots_history.json", default=None) or {"bots": []} if not latest or str(latest.get("bot_id", "")) != str(bot_id): # Look in history bot_meta = None for b in history.get("bots", []): if str(b.get("bot_id", "")) == str(bot_id): bot_meta = b break if not bot_meta: return jsonify({"status": "error", "message": "bot not found"}), 404 return jsonify({ "status": "ok", "bot_id": bot_id, "bot_name": bot_meta.get("bot_name", ""), "status_text": bot_meta.get("status", ""), "investment": bot_meta.get("investment", 0), "duration_seconds": bot_meta.get("duration_seconds", 0), "pnl": bot_meta.get("final_pnl", 0), "pnl_per": round(float(bot_meta.get("final_pnl_per", 0)) * 100, 2), "coins": bot_meta.get("coins", []), }) coins = latest.get("coins", []) resp = jsonify({ "status": "ok", "bot_id": latest.get("bot_id"), "bot_name": latest.get("bot_name"), "status_text": "running", "leverage": latest.get("leverage"), "investment": float(latest.get("total_margin", 0) or 0), "equity": float(latest.get("equity", 0) or 0), "pnl": float(latest.get("total_pnl", 0) or 0), "pnl_per": round(float(latest.get("total_pnl_per", 0) or 0) * 100, 2), "duration_seconds": int(latest.get("run_time_duration", 0) or 0), "coins": coins, }) resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0" return resp @app.route('/api/prices') def prices_api(): """Live prices from Bybit WebSocket bridge (via GCS).""" from modules.storage import load_json data = load_json("prices.json", default=None) if not data: return jsonify({"status": "empty", "symbols": {}}) resp = jsonify({ "status": "ok", "updated_at": data.get("updated_at"), "updated_iso": data.get("updated_iso"), "symbols": data.get("symbols", {}), }) resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0" return resp @app.route('/api/profile/alerts', methods=['GET', 'POST']) def api_profile_alerts(): """Get or update the current user's alert preferences.""" from modules.auth import get_user_alerts, update_user_alerts user = current_user() if not user: return jsonify({"error": "login required"}), 401 email = user.get("email") if request.method == 'GET': prefs = get_user_alerts(email) or {} return jsonify({"status": "ok", "alerts": prefs}) data = request.get_json(silent=True) or {} ok = update_user_alerts(email, data) if not ok: return jsonify({"error": "update failed"}), 500 return jsonify({"status": "ok", "alerts": get_user_alerts(email)}) # === Admin video management (added by patch_add_videos.py) === import re as _re import time as _time from modules.storage import load_json as _load_json, save_json as _save_json _YT_RE = _re.compile(r'(?:youtube\.com/(?:watch\?v=|embed/|shorts/)|youtu\.be/)([A-Za-z0-9_-]{11})') def _yt_id(url): if not url: return None m = _YT_RE.search(url.strip()) return m.group(1) if m else None def _videos_load(): data = _load_json('videos.json', default=None) if data is None: data = [{"id": "rXKxNvifHHY", "title": "I built a cryptocurrency scanner with an AI agent \u2014 Part 1", "added": "2026-09-17T00:00:00Z"}] try: _save_json('videos.json', data) except Exception as e: print("videos.json seed failed: " + str(e)) return data @app.route('/api/videos') def videos_list_api(): return jsonify({"videos": _videos_load()}) @app.route('/api/videos/add', methods=['POST']) def videos_add_api(): u = current_user() if not u or u.get('role') != 'admin': return jsonify({"error": "admin only"}), 403 body = request.get_json(silent=True) or {} vid = _yt_id(body.get('url') or '') if not vid: return jsonify({"error": "Not a valid YouTube URL"}), 400 data = _videos_load() if any(v.get('id') == vid for v in data): return jsonify({"error": "Video already in list", "videos": data}), 400 title = (body.get('title') or '').strip() or ("Video " + vid) entry = {"id": vid, "title": title[:200], "added": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime())} data.insert(0, entry) data = data[:12] try: _save_json('videos.json', data) except Exception as e: return jsonify({"error": "save failed: " + str(e)}), 500 return jsonify({"ok": True, "videos": data}) # === High-score alerts (added by patch_alerts.py) === @app.route('/api/alerts') def alerts_api(): u = current_user() if not u: return jsonify({"alerts": [], "threshold": 100}) from modules.high_score_alerts import get_active_alerts, filter_for_user from modules.alert_config import get_config cfg = get_config() all_a = get_active_alerts() mine = filter_for_user(all_a, u.get("email")) return jsonify({"alerts": mine, "banner_enabled": cfg.get("banner_enabled", True), "config": {"conservative": cfg.get("conservative"), "risk": cfg.get("risk")}}) @app.route('/api/alerts/dismiss', methods=['POST']) def alerts_dismiss_api(): u = current_user() if not u: return jsonify({"error": "login required"}), 401 body = request.get_json(silent=True) or {} sym = (body.get("symbol") or "").strip() if not sym: return jsonify({"error": "symbol required"}), 400 from modules.auth import add_dismissed_alert add_dismissed_alert(u.get("email"), sym) return jsonify({"ok": True}) @app.route('/api/alerts/flush-telegram', methods=['POST']) def alerts_flush_telegram(): expected = os.environ.get("CRON_SECRET", "") got = request.headers.get("X-Cron-Secret", "") if not expected or got != expected: return jsonify({"error": "forbidden"}), 403 from modules.high_score_alerts import flush_telegram_batch n = flush_telegram_batch() return jsonify({"sent": n}) # === Admin cron UI (added by patch_cron_ui.py) === def _cron_admin_gate(): u = current_user() if not u or u.get("role") != "admin": return jsonify({"error": "admin only"}), 403 return None @app.route('/admin/sops') @app.route('/admin/SOPs') @app.route('/admin/SOP\'s') def admin_sops_page(): u = current_user() if not u or u.get("role") != "admin": return redirect('/login?next=/admin/sops'), 302 return render_template('admin_sops.html') @app.route('/admin/cron') def admin_cron_page(): u = current_user() if not u or u.get("role") != "admin": return redirect('/login?next=/admin/cron'), 302 return render_template('admin_cron.html') @app.route('/api/admin/cron') def api_admin_cron_list(): g = _cron_admin_gate() if g: return g try: from modules.cron_manager import list_jobs return jsonify({"jobs": list_jobs()}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/api/admin/cron/create', methods=['POST']) def api_admin_cron_create(): g = _cron_admin_gate() if g: return g body = request.get_json(silent=True) or {} try: from modules.cron_manager import create_job job = create_job( name=(body.get("name") or "").strip(), description=(body.get("description") or "").strip(), schedule=(body.get("schedule") or "").strip(), time_zone=(body.get("time_zone") or "America/New_York").strip(), action=(body.get("action") or "").strip(), custom_url=(body.get("custom_url") or "").strip(), enabled=bool(body.get("enabled", True)), ) return jsonify({"ok": True, "job": job}) except Exception as e: return jsonify({"error": str(e)}), 400 @app.route('/api/admin/cron//', methods=['POST']) def api_admin_cron_action(action, name): g = _cron_admin_gate() if g: return g try: from modules import cron_manager as cm if action == "pause": cm.pause_job(name); return jsonify({"ok": True}) if action == "resume": cm.resume_job(name); return jsonify({"ok": True}) if action == "run": cm.run_job(name); return jsonify({"ok": True}) if action == "delete": cm.delete_job(name); return jsonify({"ok": True}) return jsonify({"error": "unknown action"}), 400 except Exception as e: return jsonify({"error": str(e)}), 400 # === Alert config (added by patch_alert_config.py) === @app.route('/api/admin/alert-config', methods=['GET', 'POST']) def api_admin_alert_config(): g = _cron_admin_gate() if g: return g from modules.alert_config import get_config, save_config if request.method == 'GET': return jsonify(get_config()) body = request.get_json(silent=True) or {} return jsonify(save_config(body)) @app.route('/api/admin/alerts/clear', methods=['POST']) def api_admin_alerts_clear(): g = _cron_admin_gate() if g: return g from modules.high_score_alerts import clear_alerts_log, reset_alert_state clear_alerts_log() reset_alert_state() return jsonify({"ok": True}) @app.route('/admin/alerts') def admin_alerts_page(): u = current_user() if not u or u.get("role") != "admin": return redirect('/login?next=/admin/alerts'), 302 return render_template('admin_alerts.html') @app.route('/about') @app.route('/about/') def about_page(): return render_template('about.html') @app.route('/glossary') @app.route('/glossary/') def glossary_page(): return render_template('glossary.html') @app.route('/glossary/risk_management') @app.route('/glossary/risk_management/') def glossary_risk_management_page(): return render_template('glossary_risk_management.html') @app.route('/glossary/market_regimes') @app.route('/glossary/market_regimes/') def glossary_market_regimes_page(): return render_template('glossary_market_regimes.html') @app.route('/glossary/learned_weights') @app.route('/glossary/learned_weights/') def glossary_learned_weights_page(): return render_template('glossary_learned_weights.html') @app.route('/glossary/futures_compounding') @app.route('/glossary/futures_compounding/') def glossary_futures_compounding_page(): return render_template('glossary_futures_compounding.html') @app.route('/glossary/api') @app.route('/glossary/api/') def glossary_api_page(): return render_template('glossary_api.html') @app.route('/api/telegram-stats') def telegram_stats_api(): """Proxy the trader's headline stats for the public /telegram page.""" import urllib.request as _ur import os as _os _turl = _os.environ.get( "TRADER_URL", "https://blind-monkeys-trader-353804379600.europe-west1.run.app") try: with _ur.urlopen(_turl.rstrip("/") + "/telegram-stats", timeout=40) as _r: return jsonify(json.loads(_r.read().decode("utf-8"))) except Exception as e: return jsonify({"error": str(e)[:150]}), 502 @app.route('/telegram') @app.route('/telegram/') def telegram_page(): return render_template('telegram.html') @app.route('/tech_stack') @app.route('/tech_stack/') def tech_stack_page(): return render_template('tech_stack.html') @app.route('/robots.txt') def robots_txt(): return send_from_directory('static', 'robots.txt', mimetype='text/plain') @app.route('/sitemap.xml') def sitemap_xml(): """Static sitemap plus live blog post URLs (kept in sync with /admin/blog).""" try: with open(os.path.join('static', 'sitemap.xml'), encoding='utf-8') as f: xml = f.read() except Exception: xml = ('' '') if '' not in xml: xml += '' extra = [' https://blindmonkeys.org/blog/0.7'] for p in _blog_posts(published_only=True): loc = 'https://blindmonkeys.org/blog/' + str(p.get('slug') or '') extra.append(' ' + loc + '0.6') xml = xml.replace('', '\n' + '\n'.join(extra) + '\n') return Response(xml, mimetype='application/xml') # =================================================================== # Blog — public posts (written via /admin/blog, stored in the data bucket) # =================================================================== BLOG_PREFIX = 'blog/' DEFAULT_BLOG_AUTHOR = 'Dean Powers' DEFAULT_AUTHOR_URL = 'https://www.linkedin.com/in/deanpowers/' def _blog_slug_ok(slug): """Slugs are lowercase letters/digits/hyphens, 1-80 chars.""" return bool(re.match(r'^[a-z0-9-]{1,80}$', slug or '')) def _blog_posts(published_only=False): """All blog posts, newest first. Each post is blog/.json in the data bucket: {slug, title, summary, date, published, body(markdown)}.""" posts = [] for name in list_prefix(BLOG_PREFIX): if not name.endswith('.json'): continue p = load_json(name, default=None) if not isinstance(p, dict): continue p.setdefault('slug', name[len(BLOG_PREFIX):-len('.json')]) posts.append(p) posts.sort(key=lambda p: str(p.get('date') or ''), reverse=True) if published_only: posts = [p for p in posts if p.get('published')] return posts @app.route('/blog') @app.route('/blog/') def blog_index_page(): posts = _blog_posts(published_only=True) return render_template('blog_index.html', posts=posts) @app.route('/blog/') def blog_post_page(slug): slug = (slug or '').lower().strip() if not _blog_slug_ok(slug): return render_template('blog_post.html', post=None, body_html=None), 404 p = load_json(BLOG_PREFIX + slug + '.json', default=None) if not p or not p.get('published'): return render_template('blog_post.html', post=None, body_html=None), 404 body_html = _markdown.markdown( str(p.get('body') or ''), extensions=['fenced_code', 'tables']) return render_template('blog_post.html', post=p, body_html=body_html) @app.route('/admin/grid-db') def admin_grid_db_page(): u = current_user() if not u or u.get('role') != 'admin': return redirect('/login?next=/admin/grid-db'), 302 return render_template('admin_grid_db.html') @app.route('/admin/blog') def admin_blog_page(): u = current_user() if not u or u.get('role') != 'admin': return redirect('/login?next=/admin/blog'), 302 return render_template('admin_blog.html') def _blog_admin_gate(): u = current_user() if not u or u.get('role') != 'admin': return jsonify({'error': 'login required'}), 401 return None @app.route('/api/admin/blog/list') def api_blog_list(): g = _blog_admin_gate() if g: return g posts = _blog_posts() for p in posts: p['body'] = str(p.get('body') or '') return jsonify({'posts': posts}) @app.route('/api/admin/blog/save', methods=['POST']) def api_blog_save(): g = _blog_admin_gate() if g: return g d = request.get_json(silent=True) or {} slug = str(d.get('slug') or '').lower().strip() title = str(d.get('title') or '').strip() body = str(d.get('body') or '') if not title or not body.strip(): return jsonify({'error': 'title and body are required'}), 400 if not _blog_slug_ok(slug): return jsonify({'error': 'slug must be lowercase letters, digits, and hyphens (1-80 chars)'}), 400 author = str(d.get('author') or DEFAULT_BLOG_AUTHOR).strip() or DEFAULT_BLOG_AUTHOR post = { 'slug': slug, 'title': title, 'summary': str(d.get('summary') or '').strip(), 'author': author, 'author_url': DEFAULT_AUTHOR_URL if author.lower() == 'dean powers' else '', 'date': str(d.get('date') or datetime.now(timezone.utc).date().isoformat()), 'published': bool(d.get('published')), 'body': body, } save_json(BLOG_PREFIX + slug + '.json', post) return jsonify({'status': 'ok', 'post': post}) @app.route('/api/admin/blog/delete', methods=['POST']) def api_blog_delete(): g = _blog_admin_gate() if g: return g d = request.get_json(silent=True) or {} slug = str(d.get('slug') or '').lower().strip() if not _blog_slug_ok(slug): return jsonify({'error': 'bad slug'}), 400 ok = delete_bytes(BLOG_PREFIX + slug + '.json') return jsonify({'status': 'ok' if ok else 'not-found'}) @app.route('/llms.txt') def llms_txt(): return send_from_directory('static', 'llms.txt', mimetype='text/plain') @app.route('/api/whoami') def whoami_api(): u = current_user() return jsonify({ "logged_in": bool(u), "role": (u.get("role") if u else None), "email": (u.get("email") if u else None), }) DBIP_KEY = os.environ.get("DBIP_KEY", "") def _geo_lookup(ip): """Look up city/state/country for an IP. Returns dict or None.""" if not ip or ip in ("unknown", "127.0.0.1"): return None if ip.startswith("10.") or ip.startswith("192.168.") or ip.startswith("172.") or ip.startswith("169.254."): return None if not DBIP_KEY: return None try: r = requests.get( "http://api.db-ip.com/v2/" + DBIP_KEY + "/" + ip, timeout=3 ) if r.status_code == 200: d = r.json() return { "city": d.get("city", "") or "", "state": d.get("stateProv", "") or "", "country": d.get("countryName", "") or "", } except Exception as e: print("geo lookup failed for " + ip + ": " + str(e)) return None def _geo_line(ip): """Return 'City, State, Country' string or empty.""" geo = _geo_lookup(ip) if not geo: return "" parts = [x for x in [geo.get("city"), geo.get("state"), geo.get("country")] if x] return ", ".join(parts) @app.route('/api/futures-weights') def futures_weights_api(): """Futures (upward) score weights, proxied same-origin from the scanner.""" try: r = requests.get('https://scan.blindmonkeys.org/futures/weights', timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"error": str(e)[:120]}), 502 @app.route('/api/futures-weights-history') def futures_weights_history_api(): """Futures (upward) weight daily snapshots, proxied same-origin.""" try: r = requests.get('https://scan.blindmonkeys.org/futures/weights-history', timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"error": str(e)[:120]}), 502 @app.route('/api/grid-score-weights-history') def grid_score_weights_history_api(): """Grid score-weight daily snapshots, proxied same-origin.""" try: r = requests.get('https://scan.blindmonkeys.org/grid/score-weights-history', timeout=25) r.raise_for_status() return Response(r.content, mimetype='application/json') except Exception as e: return jsonify({"error": str(e)[:120]}), 502 @app.route('/api/scan/latest') def latest_scan_api(): from modules.storage import load_json mode = (request.args.get('mode') or 'conservative').lower() if mode not in ('conservative', 'risk'): mode = 'conservative' data = load_json("latest_scan_" + mode + ".json", default=None) if data is None: return jsonify({"status": "empty", "message": "No scan yet.", "results": []}) return jsonify(data) @app.route('/api/scan', methods=['GET', 'POST']) def scan_api(): """Main scan endpoint (20-day lookback, 14-period RSI). Supports ?mode=conservative|risk""" ip = client_ip(request) _cron_secret = os.environ.get("CRON_SECRET", "") _is_cron = bool(_cron_secret) and request.headers.get("X-Cron-Secret") == _cron_secret _noalert = request.args.get("noalert") == "1" # machine calls: no alerts, no rate limit if not current_user() and not _is_cron and not _noalert: now_ts = time.time() last = _ANON_SCAN_LIMIT.get(ip, 0) elapsed = now_ts - last if elapsed < _ANON_SCAN_WINDOW: wait = int(_ANON_SCAN_WINDOW - elapsed) return jsonify({ "status": "rate_limited", "wait_seconds": wait, "message": "Please wait " + str(wait) + " seconds before scanning again." }), 429 _ANON_SCAN_LIMIT[ip] = now_ts mode = (request.args.get('mode') or 'conservative').lower() if mode == 'risk': coin_ids = get_risk_ids() scan_mode = 'risk' else: coin_ids = get_conservative_ids() scan_mode = 'conservative' try: result = _run_scan(coin_ids=coin_ids, limit=20, scan_mode=scan_mode) except Exception as e: return jsonify({"error": str(e)}), 500 try: log_admin_stat("scan", result.get("total_scanned", 0), extra={"mode": scan_mode}) except Exception as e: print(f"?????? admin_stats log failed: {e}") try: result["geo"] = _geo_lookup(ip) except Exception as _e: print("geo attach failed: " + str(_e)) if not _noalert: alert_on_buy_signals(result) payload = { "status": "success", "scan_type": "scan", "scan_mode": scan_mode, "criteria": result.get("criteria"), "timestamp": datetime.now().isoformat(), "total_scanned": result.get("total_scanned", 0), "coins_checked": result.get("coins_checked", 0), "lookback_days": result.get("lookback_days", 20), "rsi_period": result.get("rsi_period", 14), "results": result.get("results", []) } try: from modules.storage import save_json save_json("latest_scan_" + scan_mode + ".json", payload) except Exception as e: print("save latest_scan failed: " + str(e)) return jsonify(payload) @app.route('/api/short-scan', methods=['GET', 'POST']) def short_scan_api(): """Alias for /api/scan ??? no duplicate Telegram alert""" try: result = _run_scan(limit=10) except Exception as e: return jsonify({"error": str(e)}), 500 try: log_admin_stat("scan", result.get("total_scanned", 0)) except Exception as e: print(f"?????? admin_stats log failed: {e}") return jsonify({ "status": "success", "scan_type": "scan", "timestamp": datetime.now().isoformat(), "total_scanned": result.get("total_scanned", 0), "coins_checked": result.get("coins_checked", 0), "results": result.get("results", []) }) @app.route('/api/scan/') def scan_generic_api(scan_type): """Generic scan endpoint ??? all types return the same 20-day scan""" try: result = _run_scan(limit=10) except Exception as e: return jsonify({"error": str(e)}), 500 try: log_admin_stat("scan", result.get("total_scanned", 0), extra={"scan_type": scan_type}) except Exception as e: print(f"?????? admin_stats log failed: {e}") return jsonify({ "status": "success", "scan_type": scan_type, "timestamp": datetime.now().isoformat(), "total_scanned": result.get("total_scanned", 0), "coins_checked": result.get("coins_checked", 0), "results": result.get("results", []) }) @app.route('/api/cron/hourly-scan', methods=['GET', 'POST']) def cron_hourly_scan(): """Hourly cron trigger ??? secret-protected""" secret = request.headers.get("X-Cron-Secret") or request.args.get("secret") expected = os.environ.get("CRON_SECRET", "") if not expected or secret != expected: return jsonify({"error": "unauthorized"}), 401 try: result = _run_scan(limit=10) except Exception as e: return jsonify({"error": str(e)}), 500 try: log_admin_stat("scan", result.get("total_scanned", 0), extra={"trigger": "cron"}) except Exception as e: print(f"?????? admin_stats log failed: {e}") alert_on_buy_signals(result) return jsonify({ "ok": True, "buy_signals": sum(1 for r in result.get("results", []) if r.get("buy_signal")), "scanned": result.get("total_scanned", 0), }) # =================================================================== # JOURNAL ROUTES # =================================================================== @app.route('/api/journal') def journal_download(): journal_path = get_journal_path() return send_file(journal_path, as_attachment=True) @app.route('/api/journal/trades') def journal_trades(): return jsonify(get_all_trades()) @app.route('/api/journal/open') def journal_open(): return jsonify(get_open_trades()) @app.route('/api/journal/stats') def journal_stats(): return jsonify(get_journal_stats()) @app.route('/api/journal/add', methods=['POST']) def journal_add(): data = request.get_json() symbol = data.get('symbol') entry_price = data.get('entry_price') quantity = data.get('quantity') if not symbol or not entry_price or not quantity: return jsonify({"error": "Missing required fields"}), 400 success = add_trade(symbol, entry_price, quantity) return jsonify({"status": "added" if success else "failed"}) @app.route('/api/journal/close', methods=['POST']) def journal_close(): data = request.get_json() symbol = data.get('symbol') exit_price = data.get('exit_price') if not symbol or not exit_price: return jsonify({"error": "Missing required fields"}), 400 success = close_trade(symbol, exit_price) return jsonify({"status": "closed" if success else "failed"}) # =================================================================== # SETTINGS ROUTES # =================================================================== @app.route('/api/settings', methods=['GET']) def get_settings_api(): return jsonify(get_settings()) @app.route('/api/settings', methods=['POST']) @require_admin def update_settings_api(): data = request.get_json() if not data: return jsonify({"error": "No settings provided"}), 400 updated = update_settings(data) clear_cache() return jsonify({"status": "updated", "settings": updated, "cache_cleared": True}) @app.route('/api/settings/reset', methods=['POST']) @require_admin def reset_settings_api(): reset = reset_settings() clear_cache() return jsonify({"status": "reset", "settings": reset, "cache_cleared": True}) # =================================================================== # EXCLUSION LIST ROUTES # =================================================================== @app.route('/api/exclusions', methods=['GET']) def get_exclusions(): return jsonify({ "count": len(get_excluded_coins()), "excluded": get_excluded_coins() }) @app.route('/api/exclusions/add', methods=['POST']) def add_exclusion(): data = request.get_json() coin_id = data.get('coin_id') if not coin_id: return jsonify({"error": "Missing coin_id"}), 400 success = add_excluded_coin(coin_id) return jsonify({ "status": "added" if success else "already_exists", "coin_id": coin_id, "excluded": get_excluded_coins() }) @app.route('/api/exclusions/remove', methods=['POST']) def remove_exclusion(): data = request.get_json() coin_id = data.get('coin_id') if not coin_id: return jsonify({"error": "Missing coin_id"}), 400 success = remove_excluded_coin(coin_id) return jsonify({ "status": "removed" if success else "not_found", "coin_id": coin_id, "excluded": get_excluded_coins() }) @app.route('/api/exclusions/set', methods=['POST']) def set_exclusions(): data = request.get_json() coin_ids = data.get('coin_ids', []) if not isinstance(coin_ids, list): return jsonify({"error": "coin_ids must be a list"}), 400 result = set_excluded_coins(coin_ids) return jsonify({"status": "updated", "count": len(result), "excluded": result}) @app.route('/api/exclusions/clear', methods=['POST']) def clear_exclusions(): set_excluded_coins([]) return jsonify({"status": "cleared", "excluded": []}) @app.route('/api/bingx/availability') def bingx_availability(): from modules.bingx_client import get_bingx_available_symbols coin_ids = get_coin_ids() bingx_symbols = get_bingx_available_symbols() available = [] unavailable = [] for coin_id in coin_ids: symbol = get_spot_symbol(coin_id) if symbol and symbol in bingx_symbols: available.append({"coin_id": coin_id, "bingx_symbol": symbol}) else: unavailable.append({"coin_id": coin_id, "bingx_symbol": symbol or "N/A"}) return jsonify({ "available_count": len(available), "unavailable_count": len(unavailable), "available": available, "unavailable": unavailable }) # =================================================================== # COIN REGISTRY ROUTES # =================================================================== @app.route('/api/coins') def coins_api(): return jsonify({"count": get_coin_count(), "coins": get_all_coins()}) @app.route('/api/coins/refresh', methods=['POST']) @require_admin def coins_refresh_api(): coins = refresh_coins() return jsonify({"status": "refreshed", "count": len(coins), "coins": coins}) # =================================================================== # DIAGNOSTIC (public ??? cached top 20 for home page) # =================================================================== _DIAG_CACHE_DIR = os.environ.get("DATA_DIR", ".") def _diag_cache_path(mode): return os.path.join(_DIAG_CACHE_DIR, "diagnostic_cache_" + mode + ".json") from modules.storage import load_json, save_json def _diag_load_disk(mode): return load_json("diagnostic_cache_" + mode + ".json", default=None) def _diag_save_disk(mode, payload): results = (payload or {}).get("results") or [] if len(results) == 0: print("WARN diag save skipped (" + mode + "): 0 results - refusing to overwrite") return try: save_json("diagnostic_cache_" + mode + ".json", payload) except Exception as e: print("WARN diag save failed: " + str(e)) def _diag_run_scan(mode): if mode == 'risk': coin_ids = get_risk_ids() order = {cid: i for i, cid in enumerate(coin_ids)} else: coin_ids = get_conservative_ids() order = {cid: i for i, cid in enumerate(TOP20_COIN_IDS)} result = _run_scan(coin_ids=coin_ids, limit=20, scan_mode=mode) sorted_results = sorted( result.get("results", []), key=lambda x: order.get(x.get("coin_id"), 999) ) return { "status": "success", "scan_mode": mode, "criteria": result.get("criteria"), "timestamp": datetime.now().isoformat(), "total_scanned": result.get("total_scanned", 0), "results": sorted_results[:20], } def _diag_refresh_async(mode): def _worker(): try: payload = _diag_run_scan(mode) bucket = _diagnostic_cache[mode] bucket["data"] = payload bucket["at"] = time.time() _diag_save_disk(mode, payload) print("OK diag cache refreshed: " + mode) except Exception as e: print("WARN diag bg refresh failed (" + mode + "): " + str(e)) t = threading.Thread(target=_worker, daemon=True) t.start() _diagnostic_cache = {"conservative": {"data": None, "at": 0}, "risk": {"data": None, "at": 0}} @app.route('/api/diagnostic') def api_diagnostic(): mode = (request.args.get('mode') or 'conservative').lower() if mode not in ('conservative', 'risk'): mode = 'conservative' now = time.time() bucket = _diagnostic_cache[mode] # 1. Fresh in-memory (< 10 min) if bucket["data"] and now - bucket["at"] < 600: return jsonify(bucket["data"]) # 2. Disk cache exists ??? serve immediately, refresh in background disk = _diag_load_disk(mode) if disk: bucket["data"] = disk bucket["at"] = now _diag_refresh_async(mode) return jsonify(disk) # 3. No cache anywhere ??? synchronous scan (first-ever request only) try: payload = _diag_run_scan(mode) except Exception as e: return jsonify({"error": str(e)}), 500 bucket["data"] = payload bucket["at"] = now _diag_save_disk(mode, payload) return jsonify(payload) # =================================================================== # REGISTRATION (Phase 11) # =================================================================== def _tg_stamp(text): """Render a Telegram message at ~1.5× normal text size (Dean 2026-11-05): each line — including the green 🟢 timestamp heading — becomes an H2 markdown heading in a Rich Message. Classic messages have no font-size markup, so H2 headings are the only way to enlarge text. Timestamp in Yerevan time (UTC+4).""" from datetime import datetime, timezone, timedelta stamp = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d %H:%M:%S") lines = ["## 🟢 " + stamp] for ln in text.split("\n"): lines.append("## " + ln if ln.strip() else "") out = "\n".join(lines) if len(out) > 32000: out = out[:32000] + "…" return out def _tg_send(token, chat, text): """Send a Telegram message as a Rich Message (H2 timestamp heading, ~1.5× size); fall back to the classic bold-stamp sendMessage if the Rich Message API rejects it. Returns True on success.""" from datetime import datetime, timezone, timedelta api = "https://api.telegram.org/bot" + token try: r = requests.post(api + "/sendRichMessage", json={ "chat_id": chat, "rich_message": {"markdown": _tg_stamp(text)}, }, timeout=15) if r.status_code == 200: return True except Exception: pass stamp = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d %H:%M:%S") classic = f"🟢 {stamp}\n{text}" if len(classic) > 4090: classic = classic[:4090] + "…" r = requests.post(api + "/sendMessage", json={ "chat_id": chat, "text": classic, "parse_mode": "HTML", "disable_web_page_preview": True, }, timeout=15) return r.status_code == 200 def _notify_admin_new_registration(user, ip): """Send Telegram ping about a new pending registration.""" try: token = os.environ.get("TELEGRAM_BOT_TOKEN", "") chat = os.environ.get("TELEGRAM_CHAT_ID", "") if not token or not chat: return import html as _html name = (user.get("first_name", "") + " " + user.get("last_name", "")).strip() or "(no name)" ip_str = ip or "unknown" loc = _geo_line(ip_str) loc_part = ("\nLocation: " + loc) if loc else "" body = ( "\U0001F195 New registration request\n\n" "Name: " + _html.escape(name) + "\n" "Email: " + _html.escape(user.get("email", "")) + "\n" "IP: " + _html.escape(ip_str + loc_part) + "\n" "\nReview: /admin/users" ) _tg_send(token, chat, body) except Exception as e: print("WARN telegram notify failed: " + str(e)) @app.route('/register', methods=['GET', 'POST']) def register_page(): if request.method == 'GET': return render_template('register.html', loaded_at=time.time()) # POST form = request.form ip = client_ip(request) ok, wait = check_rate_limit(ip) if not ok: return render_template('register.html', loaded_at=time.time(), error="Too many signups from your network. Try again in " + str(wait) + "s."), 429 if not check_honeypot(form): # Silently pretend success for bots return redirect('/register/pending') if not check_timing(form): return render_template('register.html', loaded_at=time.time(), error="Form submitted too quickly. Please try again."), 400 all_users = list_all_users() pending_count = sum(1 for u in all_users if u.get('status') == 'pending') if not check_pending_cap(pending_count): return render_template('register.html', loaded_at=time.time(), error="Registration queue is full. Try again later."), 503 email = (form.get('email') or '').strip().lower() pw = form.get('password') or '' pw_confirm = form.get('password_confirm') or '' first = (form.get('first_name') or '').strip() last = (form.get('last_name') or '').strip() if not email or '@' not in email or '.' not in email.split('@')[-1]: return render_template('register.html', loaded_at=time.time(), error="Valid email required"), 400 if pw != pw_confirm: return render_template('register.html', loaded_at=time.time(), error="Passwords do not match"), 400 err = password_error(pw) if err: return render_template('register.html', loaded_at=time.time(), error=err), 400 if not first or not last: return render_template('register.html', loaded_at=time.time(), error="First and last name required"), 400 if not form.get('agree_terms'): return render_template('register.html', loaded_at=time.time(), error="You must agree to the Terms of Service and Privacy Policy"), 400 reg_message = (form.get('reg_message') or '').strip()[:80] new_user = create_user(email, pw, first_name=first, last_name=last, role='user', status='pending', reg_message=reg_message) if not new_user: return render_template('register.html', loaded_at=time.time(), error="That email is already registered"), 400 session['reg_email'] = email session['reg_recovery'] = new_user.get('recovery_code', '') _notify_admin_new_registration(new_user, ip) return redirect('/register/pending') @app.route('/register/pending') def register_pending_page(): email = session.get('reg_email', '') recovery = session.get('reg_recovery', '') return render_template('register_pending.html', email=email, recovery=recovery) @app.route('/terms/') @app.route('/terms') def terms_page(): return render_template('terms.html') @app.route('/privacy/') @app.route('/privacy') def privacy_page(): return render_template('privacy.html') @app.route('/home') @app.route('/home/') def home_redirect(): return redirect('/', code=302) @app.route('/regimes') def regimes_page(): return render_template('regimes.html') @app.route('/api/cf-visitors') def cf_visitors_api(): """7-day Cloudflare Analytics (daily requests + unique visitors) per zone.""" import json as _json import urllib.request as _ur from datetime import datetime, timedelta, timezone token = os.environ.get('CF_ANALYTICS_TOKEN', '') if not token: return jsonify({"error": "not configured"}), 503 zones = [ ("blindmonkeys.org", "ca9a68559bcee4ec3ac8e67b71c2b583"), ("zojax.com", "6ed26f1f956883a2ef952e05240c365a"), ("flaskfactory.ai", "1c383360e092ae6b380cdb9577316a7b"), ("gyumri.coffee", "11c5072abecd2b301828b149715659ab"), ] today = datetime.now(timezone.utc).date() since = (today - timedelta(days=6)).isoformat() until = (today + timedelta(days=1)).isoformat() out = [] for name, zid in zones: gql = ( 'query { viewer { zones(filter: {zoneTag: "%s"}) ' '{ httpRequests1dGroups(limit: 10, filter: {date_geq: "%s", date_lt: "%s"}) ' '{ dimensions { date } sum { requests } uniq { uniques } } } } }' ) % (zid, since, until) try: req = _ur.Request( "https://api.cloudflare.com/client/v4/graphql", data=_json.dumps({"query": gql}).encode("utf-8"), headers={"Content-Type": "application/json", "Authorization": "Bearer " + token}, ) with _ur.urlopen(req, timeout=15) as resp: data = _json.loads(resp.read().decode("utf-8")) groups = data["data"]["viewer"]["zones"][0]["httpRequests1dGroups"] # normalize into a full 7-day series (0 for missing days) by_date = {g["dimensions"]["date"]: { "requests": g["sum"]["requests"], "uniques": g["uniq"]["uniques"]} for g in groups} days = [] for i in range(7): d = (today - timedelta(days=6 - i)).isoformat() v = by_date.get(d, {"requests": 0, "uniques": 0}) days.append({"date": d, "requests": v["requests"], "uniques": v["uniques"]}) # True 7-day uniques: one window-wide count so a visitor who # comes on several days is counted once, not once per day. total_uniques = None total_requests = None try: gql2 = ( 'query { viewer { zones(filter: {zoneTag: "%s"}) ' '{ httpRequests1dGroups(limit: 1, filter: {date_geq: "%s", date_lt: "%s"}) ' '{ sum { requests } uniq { uniques } } } } }' ) % (zid, since, until) req2 = _ur.Request( "https://api.cloudflare.com/client/v4/graphql", data=_json.dumps({"query": gql2}).encode("utf-8"), headers={"Content-Type": "application/json", "Authorization": "Bearer " + token}, ) with _ur.urlopen(req2, timeout=15) as resp2: data2 = _json.loads(resp2.read().decode("utf-8")) g2 = (data2["data"]["viewer"]["zones"][0] ["httpRequests1dGroups"] or [{}])[0] total_uniques = g2.get("uniq", {}).get("uniques") total_requests = g2.get("sum", {}).get("requests") except Exception: pass out.append({"zone": name, "days": days, "total_uniques": total_uniques, "total_requests": total_requests}) except Exception as e: out.append({"zone": name, "days": [], "error": str(e)[:100]}) return jsonify(out) _CRAWLER_UA_MAP = [ ("googlebot", "Google"), ("googlebot-image", "Google"), ("googlebot-news", "Google"), ("adsbot-google", "Google"), ("google-site-verification", "Google"), ("google favicon", "Google"), ("bingbot", "Bing"), ("bingpreview", "Bing"), ("yandexbot", "Yandex"), ("yandeximages", "Yandex"), ("yandexmetrika", "Yandex"), ("duckduckbot", "DuckDuckGo"), ("duckduckgo-favicons-bot", "DuckDuckGo"), ("petalbot", "Huawei Petal"), ("applebot", "Apple"), ("facebookexternalhit", "Facebook"), ("meta-externalagent", "Facebook"), ("ahrefsbot", "Ahrefs"), ("semrushbot", "Semrush"), ("mj12bot", "Majestic"), ("gptbot", "OpenAI GPTBot"), ("oai-searchbot", "OpenAI"), ("claudebot", "Anthropic ClaudeBot"), ("claude-web", "Anthropic"), ("perplexitybot", "Perplexity"), ("bytespider", "ByteDance"), ("amazonbot", "Amazon"), ("ccbot", "Common Crawl"), ("archive.org_bot", "Internet Archive"), ("ia_archiver", "Internet Archive"), ] @app.route('/api/crawler-activity') def crawler_activity_api(): """7-day search-engine crawler activity per zone (Cloudflare, by user-agent).""" import json as _json import urllib.request as _ur from datetime import datetime, timedelta, timezone token = os.environ.get('CF_ANALYTICS_TOKEN', '') if not token: return jsonify({"error": "not configured"}), 503 zones = [ ("blindmonkeys.org", "ca9a68559bcee4ec3ac8e67b71c2b583"), ("zojax.com", "6ed26f1f956883a2ef952e05240c365a"), ("flaskfactory.ai", "1c383360e092ae6b380cdb9577316a7b"), ("gyumri.coffee", "11c5072abecd2b301828b149715659ab"), ] today = datetime.now(timezone.utc).date() def _classify(ua): low = ua.lower() for key, name in _CRAWLER_UA_MAP: if key in low: return name return None since = (today - timedelta(days=6)).isoformat() + "T00:00:00Z" until = (today + timedelta(days=1)).isoformat() + "T00:00:00Z" out = [] for zname, zid in zones: gql = ( 'query { viewer { zones(filter: {zoneTag: "%s"}) ' '{ httpRequestsAdaptiveGroups(limit: 1000, ' 'filter: {datetime_geq: "%s", datetime_lt: "%s"}, ' 'orderBy: [count_DESC]) ' '{ dimensions { date userAgent } count } } } }' ) % (zid, since, until) try: req = _ur.Request( "https://api.cloudflare.com/client/v4/graphql", data=_json.dumps({"query": gql}).encode("utf-8"), headers={"Content-Type": "application/json", "Authorization": "Bearer " + token}, ) with _ur.urlopen(req, timeout=20) as resp: data = _json.loads(resp.read().decode("utf-8")) groups = data["data"]["viewer"]["zones"][0]["httpRequestsAdaptiveGroups"] bots = {} for g in groups or []: dims = g.get("dimensions") or {} name = _classify(dims.get("userAgent") or "") if not name: continue dstr = dims.get("date") try: di = (datetime.strptime(dstr, "%Y-%m-%d").date() - today).days + 6 except Exception: di = 6 if not (0 <= di <= 6): continue if name not in bots: bots[name] = {"days": [0] * 7} bots[name]["days"][di] += g["count"] for name, b in bots.items(): b["total"] = sum(b["days"]) bot_list = sorted( ({"name": k, "days": v["days"], "total": v["total"]} for k, v in bots.items()), key=lambda x: -x["total"]) out.append({"zone": zname, "bots": bot_list}) except Exception as e: out.append({"zone": zname, "bots": [], "error": str(e)[:150]}) return jsonify(out) @app.route('/api/ai-visibility') def ai_visibility_api(): """Latest AI-LLM visibility status per engine (public, read-only).""" from modules.llm_visibility import latest_summary return jsonify(latest_summary()) @app.route('/api/cron/ai-visibility', methods=['GET', 'POST']) def cron_ai_visibility(): """Daily cron: ask each configured LLM what it knows about us.""" secret = request.headers.get("X-Cron-Secret") or request.args.get("secret") expected = os.environ.get("CRON_SECRET", "") if not expected or secret != expected: return jsonify({"error": "unauthorized"}), 401 from modules.llm_visibility import run_visibility_scan try: result = run_visibility_scan() except Exception as e: return jsonify({"error": str(e)}), 500 return jsonify({ "ok": True, "checked": len(result.get("engines", [])), "mentioned": sum(1 for e in result.get("engines", []) if e.get("mentioned")), "alert": result.get("alert"), }) @app.route('/api/rank-positions') def rank_positions_api(): """Latest keyword rankings for the family's domains (public, read-only).""" from modules.rank_tracker import latest_positions return jsonify(latest_positions()) @app.route('/api/cron/rank-check', methods=['GET', 'POST']) def cron_rank_check(): """Daily cron: keyword rank check (DuckDuckGo) across the family.""" secret = request.headers.get("X-Cron-Secret") or request.args.get("secret") expected = os.environ.get("CRON_SECRET", "") if not expected or secret != expected: return jsonify({"error": "unauthorized"}), 401 from modules.rank_tracker import run_rank_check try: result = run_rank_check() except Exception as e: return jsonify({"error": str(e)}), 500 return jsonify(result) @app.route('/algorithm') @app.route('/algorithm/') def algorithm_page(): return render_template('algorithm.html') @app.route('/analytics') def analytics_page(): # Read-only overview: public (Analytics for anonymous visitors). return render_template('analytics.html') @app.route('/admin') @require_admin def admin_home_page(): return render_template('admin_home.html') @app.route('/admin/users') @require_admin def admin_users_page(): return render_template('admin_users.html') @app.route('/api/admin/users') @require_admin def api_admin_users(): users = list_all_users() out = [] for u in users: out.append({ "email": u.get("email", ""), "first_name": u.get("first_name", ""), "last_name": u.get("last_name", ""), "role": u.get("role", "user"), "status": u.get("status", "active"), "created_at": u.get("created_at", 0), "approved_at": u.get("approved_at"), "reg_message": u.get("reg_message", ""), "approved_note": u.get("approved_note"), "rejected_note": u.get("rejected_note"), }) return jsonify({"users": out, "pending_count": sum(1 for u in out if u["status"] == "pending")}) @app.route('/api/admin/users//approve', methods=['POST']) @require_admin def api_admin_approve(email): me = current_user() or {} data = request.get_json(silent=True) or {} note = (data.get('note') or '').strip() if not note: return jsonify({"error": "An approval message is required"}), 400 if len(note) > 500: return jsonify({"error": "Message must be 500 characters or fewer"}), 400 ok = update_user_status(email, 'active', by_email=me.get('email'), note=note) if not ok: return jsonify({"error": "user not found"}), 404 return jsonify({"status": "approved", "email": email, "note": note}) @app.route('/api/admin/users//reject', methods=['POST']) @require_admin def api_admin_reject(email): me = current_user() or {} data = request.get_json(silent=True) or {} note = (data.get('note') or '').strip() if not note: return jsonify({"error": "A rejection message is required"}), 400 if len(note) > 500: return jsonify({"error": "Message must be 500 characters or fewer"}), 400 ok = update_user_status(email, 'rejected', by_email=me.get('email'), note=note) if not ok: return jsonify({"error": "user not found"}), 404 return jsonify({"status": "rejected", "email": email, "note": note}) @app.route('/api/admin/users/', methods=['DELETE']) @require_admin def api_admin_delete_user(email): me = current_user() or {} if email.lower() == (me.get('email') or '').lower(): return jsonify({"error": "cannot delete yourself"}), 400 ok = delete_user(email) if not ok: return jsonify({"error": "user not found"}), 404 return jsonify({"status": "deleted", "email": email}) # =================================================================== # PROFILE + SAVED ORDERS # =================================================================== @app.route('/profile/') def profile_page(): return render_template('profile.html') @app.route('/api/profile') def api_profile(): user = current_user() if not user: return jsonify({"error": "login required"}), 401 p = get_profile(user.get("email")) return jsonify(p or {}) # =================================================================== # MARKET REGIME PANEL (Phase 2) # =================================================================== @app.route('/api/regime-panel') def regime_panel(): """10Y Treasury + Fear & Greed + VIX for the scan page regime section.""" from modules.market_data import get_fear_greed, get_vix, get_treasury_history return jsonify({ "fear_greed": get_fear_greed(), "vix": get_vix(), "treasury": get_treasury_history(), }) # =================================================================== # PAGESPEED SCORES (cached, refreshed in background every 12h) # =================================================================== _PSI_URLS = [ "https://www.zojax.com/", "https://ai.zojax.com/", "https://wordpress.zojax.com/", "https://pardot.zojax.com/", "https://salesforce.zojax.com/", "https://gyumri.coffee/", "https://blindmonkeys.org/", ] _PSI_TTL = 12 * 3600 # 12 hours _PSI = {"scores": {}, "ts": 0, "refreshing": False} _PSI_LOCK = threading.Lock() def _psi_fetch(url): """One PageSpeed Insights mobile performance score (0-100).""" import urllib.request as _ur import urllib.parse as _up key = os.environ.get("PSI_API_KEY", "") if not key: return None q = _up.urlencode({"url": url, "strategy": "mobile", "category": "performance", "key": key}) req = _ur.Request("https://www.googleapis.com/pagespeedonline/v5/" "runPagespeed?" + q) with _ur.urlopen(req, timeout=120) as r: d = json.loads(r.read().decode()) score = (d.get("lighthouseResult", {}).get("categories", {}) .get("performance", {}).get("score")) audits = d.get("lighthouseResult", {}).get("audits", {}) out = {"url": url} if score is not None: out["score"] = int(round(score * 100)) for k, label in (("largest-contentful-paint", "lcp"), ("total-blocking-time", "tbt"), ("cumulative-layout-shift", "cls"), ("speed-index", "si")): v = audits.get(k, {}).get("displayValue") if v: out[label] = v return out def _psi_refresh(): """Refresh all PageSpeed scores in a background thread.""" with _PSI_LOCK: if _PSI["refreshing"]: return _PSI["refreshing"] = True try: scores = {} for u in _PSI_URLS: try: r = _psi_fetch(u) if r: scores[u] = r except Exception: continue with _PSI_LOCK: _PSI["scores"] = scores _PSI["ts"] = time.time() finally: with _PSI_LOCK: _PSI["refreshing"] = False @app.route('/api/psi-scores') def psi_scores_api(): """Mobile PageSpeed performance scores per site (12h cache).""" with _PSI_LOCK: stale = time.time() - _PSI["ts"] > _PSI_TTL has_any = bool(_PSI["scores"]) if stale and not has_any: # cold start: kick off refresh, caller polls for results threading.Thread(target=_psi_refresh, daemon=True).start() elif stale and not _PSI["refreshing"]: threading.Thread(target=_psi_refresh, daemon=True).start() with _PSI_LOCK: payload = { "scores": _PSI["scores"], "ts": _PSI["ts"], "status": "refreshing" if (stale and not has_any) else "ok", } return jsonify(payload) # =================================================================== # FRONTEND CATCH-ALL # =================================================================== @app.route('/', defaults={'path': ''}) @app.route('/') def serve_frontend(path): if path in ('', 'home', 'home/'): return send_from_directory(os.path.join('static', 'scan'), 'index.html') if path: clean_path = path.rstrip('/') dir_path = os.path.join('static', clean_path) if os.path.isdir(dir_path): index_file = os.path.join(dir_path, 'index.html') if os.path.exists(index_file): return send_from_directory(dir_path, 'index.html') if os.path.isfile(os.path.join('static', path)): return send_from_directory('static', path) return send_from_directory('static', 'index.html') # =================================================================== # CONTACT PAGE # =================================================================== _contact_last_by_ip = {} @app.route('/contact') def contact_page(): return render_template('contact.html') @app.route('/api/contact', methods=['POST']) def contact_submit(): import time as _t import json as _json import urllib.request as _ur import urllib.parse as _up data = request.get_json(silent=True) or {} # Honeypot: silently drop if (data.get('website') or '').strip(): return jsonify({"ok": True}) # Cloudflare Turnstile verification (server-side) ts_secret = os.environ.get('TURNSTILE_SECRET', '') ts_token = (data.get('turnstile') or '').strip() if ts_secret: if not ts_token: return jsonify({"ok": False, "error": "Please complete the human verification."}), 400 try: vpayload = _up.urlencode({ 'secret': ts_secret, 'response': ts_token, 'remoteip': (request.headers.get('X-Forwarded-For', request.remote_addr or '') or '').split(',')[0].strip(), }).encode('utf-8') vreq = _ur.Request("https://challenges.cloudflare.com/turnstile/v0/siteverify", data=vpayload) with _ur.urlopen(vreq, timeout=10) as vresp: vres = _json.loads(vresp.read().decode('utf-8')) if not vres.get('success'): return jsonify({"ok": False, "error": "Human verification failed. Please try again."}), 403 except Exception: return jsonify({"ok": False, "error": "Verification service unavailable. Please try again."}), 502 name = (data.get('name') or '').strip()[:120] email = (data.get('email') or '').strip()[:200] subject = (data.get('subject') or 'General').strip()[:80] message = (data.get('message') or '').strip() if not name or not email or not message: return jsonify({"ok": False, "error": "Missing required fields."}), 400 if '@' not in email or '.' not in email.split('@')[-1]: return jsonify({"ok": False, "error": "Please enter a valid email."}), 400 if len(message) > 5000: return jsonify({"ok": False, "error": "Message is too long (max 5000 characters)."}), 400 # Rate limit: 1 per IP per 5 min ip = (request.headers.get('X-Forwarded-For', request.remote_addr or '') or '').split(',')[0].strip() now = int(_t.time()) last = _contact_last_by_ip.get(ip, 0) if now - last < 300: wait = 300 - (now - last) return jsonify({"ok": False, "error": "Please wait %ds before sending another message." % wait}), 429 _contact_last_by_ip[ip] = now # Compose Telegram message (escaping user text; _tg_send adds the stamp) import html as _html body = ( "\U0001F4EC New contact form submission\n\n" "From: %s <%s>\n" "Subject: %s\n\n" "%s" % (_html.escape(name), _html.escape(email), _html.escape(subject), _html.escape(message)) ) token = os.environ.get('TELEGRAM_BOT_TOKEN', '') chat_id = os.environ.get('TELEGRAM_CONTACT_CHAT_ID') or os.environ.get('TELEGRAM_CHAT_ID', '') if not token or not chat_id: return jsonify({"ok": False, "error": "Contact form is not configured."}), 500 try: if not _tg_send(token, chat_id, body): return jsonify({"ok": False, "error": "Failed to deliver message."}), 502 except Exception as e: print("CONTACT send failed: %s" % e) return jsonify({"ok": False, "error": "Failed to deliver message."}), 502 return jsonify({"ok": True}) # =================================================================== # FAQ PAGE # =================================================================== @app.route('/faq') @app.route('/faq/') def faq_page(): return render_template('faq.html') if __name__ == '__main__': init_journal() port = int(os.environ.get('PORT', 8080)) app.run(host='0.0.0.0', port=port, debug=False)