Domain migration to blindmonkeys.org (proxies, sitemap, zone IDs, PSI, links) + sideways Score Required
30ed22f Download app.py from deanpowers/blind-monkeys: direct link, hf CLI and curl.
- Browser
- Download file 23 kB
-
https://huggingface.co/deanpowers/blind-monkeys/resolve/main/app.py
- Command line
-
hf download hf://deanpowers/blind-monkeys/app.py
-
curl -L -o app.py https://huggingface.co/deanpowers/blind-monkeys/resolve/main/app.py
23 kB
| from dotenv import load_dotenv | |
| load_dotenv() | |
| import os | |
| import json | |
| import hashlib | |
| import hmac | |
| import time | |
| import requests | |
| import pandas as pd | |
| import numpy as np | |
| from flask import Flask, jsonify, send_file, request, send_from_directory | |
| from flask_cors import CORS | |
| from datetime import datetime, timedelta | |
| from modules.telegram_alert import alert_on_buy_signals | |
| from modules.stats import log_admin_stat | |
| app = Flask(__name__) | |
| CORS(app, resources={r"/*": {"origins": "*"}}) | |
| # 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. | |
| 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 | |
| # ---------- Configuration ---------- | |
| JOURNAL_FILE = 'trade_journal.csv' | |
| BINGX_API_KEY = os.environ.get('BINGX_API_KEY') | |
| BINGX_API_SECRET = os.environ.get('BINGX_API_SECRET') | |
| # ---------- Coin List ---------- | |
| COINS = [ | |
| "bitcoin", "ethereum", "solana", "cardano", "ripple", | |
| "polkadot", "chainlink", "litecoin", "bitcoin-cash", "stellar", | |
| "dogecoin", "matic-network", "uniswap", "aave", "cosmos", | |
| "algorand", "avalanche-2", "vechain", "filecoin", "theta-token", | |
| "ethereum-classic", "near", "monero", "tezos", "eos", | |
| "quant-network", "hedera-hashgraph", "elrond-egld", "internet-computer", | |
| "the-graph", "decentraland", "sandbox", "axie-infinity", "enjin-coin", | |
| "basic-attention-token", "zilliqa", "theta-fuel", "harmony", | |
| "icon", "ontology", "nano", "digibyte", "siacoin", | |
| "qtum", "waves", "ardor", "verge", "bytecoin", | |
| "shiba-inu", "floki", "bonk" | |
| ] | |
| # ---------- Journal Functions ---------- | |
| def init_journal(): | |
| if not os.path.isfile(JOURNAL_FILE): | |
| with open(JOURNAL_FILE, 'w') as f: | |
| f.write('symbol,entry_price,exit_price,quantity,entry_date,exit_date,pnl,status\n') | |
| # ---------- Market Data Functions ---------- | |
| def get_market_data(): | |
| """Fetch real crypto prices from CoinGecko API""" | |
| try: | |
| url = "https://api.coingecko.com/api/v3/simple/price" | |
| params = { | |
| "ids": "bitcoin,ethereum,solana,cardano,ripple", | |
| "vs_currencies": "usd" | |
| } | |
| response = requests.get(url, params=params, timeout=10) | |
| response.raise_for_status() | |
| data = response.json() | |
| return { | |
| "BTC": data.get("bitcoin", {}).get("usd", 0), | |
| "ETH": data.get("ethereum", {}).get("usd", 0), | |
| "SOL": data.get("solana", {}).get("usd", 0), | |
| "ADA": data.get("cardano", {}).get("usd", 0), | |
| "XRP": data.get("ripple", {}).get("usd", 0), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| except Exception as e: | |
| return { | |
| "BTC": 65000.00, | |
| "ETH": 3500.00, | |
| "error": str(e), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| # ---------- Direct BingX API (No external library) ---------- | |
| def bingx_request(endpoint, method="GET", params=None, signed=True): | |
| """Make a direct request to BingX API""" | |
| base_url = "https://open-api.bingx.com" | |
| url = f"{base_url}{endpoint}" | |
| headers = { | |
| "X-BX-APIKEY": BINGX_API_KEY, | |
| "Content-Type": "application/json" | |
| } | |
| if signed and BINGX_API_KEY and BINGX_API_SECRET: | |
| timestamp = str(int(time.time() * 1000)) | |
| signature_string = f"{timestamp}{method}{endpoint}" | |
| signature = hmac.new( | |
| BINGX_API_SECRET.encode('utf-8'), | |
| signature_string.encode('utf-8'), | |
| hashlib.sha256 | |
| ).hexdigest() | |
| headers["X-BX-TIMESTAMP"] = timestamp | |
| headers["X-BX-SIGNATURE"] = signature | |
| try: | |
| response = requests.request(method, url, headers=headers, json=params, timeout=10) | |
| return response.json() | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def get_bingx_balance(): | |
| """Get BingX spot account balance using direct API""" | |
| try: | |
| # Construct the correct endpoint | |
| endpoint = "/openApi/spot/v1/account/balance" | |
| url = f"https://open-api.bingx.com{endpoint}" | |
| # Generate required parameters | |
| timestamp = str(int(time.time() * 1000)) | |
| params = { | |
| "timestamp": timestamp | |
| } | |
| # Create the signature string | |
| signature_string = timestamp + endpoint | |
| signature = hmac.new( | |
| BINGX_API_SECRET.encode('utf-8'), | |
| signature_string.encode('utf-8'), | |
| hashlib.sha256 | |
| ).hexdigest() | |
| params["signature"] = signature | |
| # Prepare headers | |
| headers = { | |
| "X-BX-APIKEY": BINGX_API_KEY, | |
| } | |
| # Make the request | |
| response = requests.get(url, headers=headers, params=params, timeout=10) | |
| # Parse the response | |
| result = response.json() | |
| # Check if the response is successful | |
| if result.get('code') == 0: | |
| return result.get('data', {}) | |
| else: | |
| # Return the full response for debugging | |
| return { | |
| "error": "BingX API error", | |
| "code": result.get('code'), | |
| "msg": result.get('msg'), | |
| "full_response": result | |
| } | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def get_bingx_assets(): | |
| """Get BingX spot assets using direct API""" | |
| try: | |
| endpoint = "/openApi/spot/v1/account/assets" | |
| url = f"https://open-api.bingx.com{endpoint}" | |
| timestamp = str(int(time.time() * 1000)) | |
| params = {"timestamp": timestamp} | |
| signature_string = timestamp + endpoint | |
| signature = hmac.new( | |
| BINGX_API_SECRET.encode('utf-8'), | |
| signature_string.encode('utf-8'), | |
| hashlib.sha256 | |
| ).hexdigest() | |
| params["signature"] = signature | |
| headers = {"X-BX-APIKEY": BINGX_API_KEY} | |
| response = requests.get(url, headers=headers, params=params, timeout=10) | |
| result = response.json() | |
| if result.get('code') == 0: | |
| return result.get('data', {}) | |
| else: | |
| return {"error": result.get('msg', 'Unknown error')} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def get_bingx_positions(): | |
| """Get BingX swap positions using direct API""" | |
| try: | |
| endpoint = "/openApi/swap/v2/position/list" | |
| url = f"https://open-api.bingx.com{endpoint}" | |
| timestamp = str(int(time.time() * 1000)) | |
| params = {"timestamp": timestamp} | |
| signature_string = timestamp + endpoint | |
| signature = hmac.new( | |
| BINGX_API_SECRET.encode('utf-8'), | |
| signature_string.encode('utf-8'), | |
| hashlib.sha256 | |
| ).hexdigest() | |
| params["signature"] = signature | |
| headers = {"X-BX-APIKEY": BINGX_API_KEY} | |
| response = requests.get(url, headers=headers, params=params, timeout=10) | |
| result = response.json() | |
| if result.get('code') == 0: | |
| return result.get('data', {}) | |
| else: | |
| return {"error": result.get('msg', 'Unknown error')} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def get_bingx_swap_balance(): | |
| """Get BingX swap account balance using direct API""" | |
| try: | |
| endpoint = "/openApi/swap/v2/account/balance" | |
| url = f"https://open-api.bingx.com{endpoint}" | |
| timestamp = str(int(time.time() * 1000)) | |
| params = {"timestamp": timestamp} | |
| signature_string = timestamp + endpoint | |
| signature = hmac.new( | |
| BINGX_API_SECRET.encode('utf-8'), | |
| signature_string.encode('utf-8'), | |
| hashlib.sha256 | |
| ).hexdigest() | |
| params["signature"] = signature | |
| headers = {"X-BX-APIKEY": BINGX_API_KEY} | |
| response = requests.get(url, headers=headers, params=params, timeout=10) | |
| result = response.json() | |
| if result.get('code') == 0: | |
| return result.get('data', {}) | |
| else: | |
| return {"error": result.get('msg', 'Unknown error')} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def place_bingx_order(symbol, side, quantity, order_type="MARKET", price=None): | |
| """Place an order on BingX swap""" | |
| try: | |
| params = { | |
| "symbol": symbol, | |
| "side": side, | |
| "type": order_type, | |
| "quantity": quantity | |
| } | |
| if price and order_type == "LIMIT": | |
| params["price"] = price | |
| response = bingx_request("/openApi/swap/v2/trade/order", method="POST", params=params, signed=True) | |
| return response | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def calculate_portfolio_allocation(balance_data, prices): | |
| """Calculate portfolio allocation percentages""" | |
| total_value = 0 | |
| allocations = {} | |
| if balance_data and not balance_data.get('error'): | |
| # Check if balance_data is a dict with coin keys | |
| for coin, value in balance_data.items(): | |
| if isinstance(value, dict): | |
| available = float(value.get('available', 0)) | |
| if available > 0: | |
| # Try to get price from the prices dict | |
| price = prices.get(coin, 1) | |
| usdt_value = available * price | |
| allocations[coin] = { | |
| "available": available, | |
| "price": price, | |
| "usdt_value": usdt_value | |
| } | |
| total_value += usdt_value | |
| if total_value > 0: | |
| for coin in allocations: | |
| allocations[coin]["percentage"] = round((allocations[coin]["usdt_value"] / total_value) * 100, 2) | |
| return { | |
| "total_value": total_value, | |
| "allocations": allocations | |
| } | |
| def calculate_hedging_percentage(spot_balance, swap_positions): | |
| """Calculate hedging percentage based on spot and swap positions""" | |
| total_spot_value = 0 | |
| total_swap_value = 0 | |
| if spot_balance and not spot_balance.get('error'): | |
| for coin, value in spot_balance.items(): | |
| if isinstance(value, dict): | |
| total_spot_value += float(value.get('available', 0)) | |
| if swap_positions and not swap_positions.get('error'): | |
| if 'data' in swap_positions: | |
| for position in swap_positions.get('data', []): | |
| total_swap_value += float(position.get('positionValue', 0)) | |
| if total_spot_value == 0: | |
| return {"hedge_percentage": 0, "message": "No spot balance to hedge"} | |
| hedge_percentage = (total_swap_value / total_spot_value) * 100 | |
| return { | |
| "total_spot_value": total_spot_value, | |
| "total_swap_value": total_swap_value, | |
| "hedge_percentage": round(hedge_percentage, 2) | |
| } | |
| # ---------- Scan Functions ---------- | |
| def fetch_coin_data(coin_id, days=30): | |
| """Fetch historical price data for a coin""" | |
| try: | |
| url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart" | |
| params = { | |
| "vs_currency": "usd", | |
| "days": days, | |
| "interval": "daily" | |
| } | |
| response = requests.get(url, params=params, timeout=15) | |
| response.raise_for_status() | |
| data = response.json() | |
| if 'prices' in data and len(data['prices']) > 0: | |
| prices = [p[1] for p in data['prices']] | |
| return prices | |
| return None | |
| except Exception as e: | |
| print(f"Error fetching {coin_id}: {e}") | |
| return None | |
| def calculate_zscore(prices): | |
| """Calculate Z-score for a price series""" | |
| if not prices or len(prices) < 10: | |
| return 0 | |
| recent_prices = prices[-30:] if len(prices) >= 30 else prices | |
| mean = np.mean(recent_prices) | |
| std = np.std(recent_prices) | |
| if std == 0: | |
| return 0 | |
| current_price = prices[-1] | |
| return (current_price - mean) / std | |
| def calculate_volatility(prices): | |
| """Calculate volatility (standard deviation of daily returns)""" | |
| if not prices or len(prices) < 10: | |
| return 0 | |
| returns = [prices[i] / prices[i-1] - 1 for i in range(1, len(prices))] | |
| return np.std(returns) * 100 | |
| def calculate_momentum(prices): | |
| """Calculate 7-day momentum""" | |
| if not prices or len(prices) < 7: | |
| return 0 | |
| current = prices[-1] | |
| past = prices[-7] | |
| if past == 0: | |
| return 0 | |
| return ((current / past) - 1) * 100 | |
| def run_scan(coin_ids, lookback_days=30, limit=10): | |
| """Run scan on a list of coins""" | |
| results = [] | |
| total = len(coin_ids) | |
| progress = 0 | |
| for coin_id in coin_ids: | |
| progress += 1 | |
| print(f"Scanning {coin_id} ({progress}/{total})...") | |
| prices = fetch_coin_data(coin_id, lookback_days) | |
| if not prices or len(prices) < 7: | |
| continue | |
| current_price = prices[-1] | |
| zscore = calculate_zscore(prices) | |
| volatility = calculate_volatility(prices) | |
| momentum = calculate_momentum(prices) | |
| rsi = calculate_rsi(prices, period=14) | |
| # RSI penalty (same logic as modules/scanner.py) | |
| rsi_penalty = 0 | |
| if rsi > 70: | |
| rsi_penalty = (rsi - 70) * 0.5 | |
| elif rsi < 30: | |
| rsi_penalty = -2.0 | |
| composite_score = -zscore * 1.5 + momentum * 1.0 - volatility * 0.5 - rsi_penalty | |
| buy_signal = ( | |
| zscore < -1 and | |
| momentum > 5 and | |
| volatility < 8 and | |
| rsi < 70 | |
| ) | |
| results.append({ | |
| "symbol": coin_id.upper(), | |
| "coin_id": coin_id, | |
| "price": round(current_price, 4), | |
| "zscore": round(zscore, 2), | |
| "volatility": round(volatility, 2), | |
| "momentum": round(momentum, 2), | |
| "rsi": rsi, | |
| "composite_score": round(composite_score, 2), | |
| "buy_signal": buy_signal | |
| }) | |
| results.sort(key=lambda x: x["composite_score"], reverse=True) | |
| return results[:limit] | |
| # ---------- Serve Frontend ---------- | |
| def serve_frontend(path): | |
| """Serve the React frontend from the static folder""" | |
| if path and os.path.exists(os.path.join('static', path)): | |
| return send_from_directory('static', path) | |
| return send_from_directory('static', 'index.html') | |
| # ---------- API Routes ---------- | |
| def market_data_api(): | |
| return jsonify(get_market_data()) | |
| def get_journal(): | |
| if not os.path.isfile(JOURNAL_FILE): | |
| init_journal() | |
| return send_file(JOURNAL_FILE, as_attachment=True) | |
| # ---------- BingX Routes ---------- | |
| def bingx_balance(): | |
| """Get BingX spot account balance""" | |
| try: | |
| balance = get_bingx_balance() | |
| return jsonify(balance) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_assets(): | |
| """Get BingX spot assets""" | |
| try: | |
| assets = get_bingx_assets() | |
| return jsonify(assets) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_positions(): | |
| """Get BingX swap positions""" | |
| try: | |
| positions = get_bingx_positions() | |
| return jsonify(positions) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_swap_balance(): | |
| """Get BingX swap account balance""" | |
| try: | |
| balance = get_bingx_swap_balance() | |
| return jsonify(balance) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_account(): | |
| """Get full BingX account overview""" | |
| try: | |
| spot_balance = get_bingx_balance() | |
| swap_balance = get_bingx_swap_balance() | |
| positions = get_bingx_positions() | |
| return jsonify({ | |
| "spot_balance": spot_balance, | |
| "swap_balance": swap_balance, | |
| "positions": positions | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_portfolio(): | |
| """Get portfolio allocation percentages""" | |
| try: | |
| spot_balance = get_bingx_balance() | |
| prices = get_market_data() | |
| portfolio = calculate_portfolio_allocation(spot_balance, prices) | |
| return jsonify(portfolio) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_hedge(): | |
| """Get hedging percentage""" | |
| try: | |
| spot_balance = get_bingx_balance() | |
| positions = get_bingx_positions() | |
| hedge = calculate_hedging_percentage(spot_balance, positions) | |
| return jsonify(hedge) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def bingx_order(): | |
| """Place an order on BingX""" | |
| try: | |
| 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: symbol, side, quantity"}), 400 | |
| result = place_bingx_order(symbol, side, quantity, order_type, price) | |
| return jsonify(result) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # ---------- Scan Routes ---------- | |
| def scan_api(): | |
| """Main scan endpoint (20-day lookback, 14-period RSI).""" | |
| try: | |
| results = run_scan(COINS, lookback_days=20, limit=10) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| scan_data = { | |
| "results": results, | |
| "total_scanned": len(results), | |
| "lookback_days": 20, | |
| "rsi_period": 14, | |
| } | |
| try: | |
| log_admin_stat("scan", len(results)) | |
| except Exception as e: | |
| print(f"⚠️ admin_stats log failed: {e}") | |
| alert_on_buy_signals(scan_data) | |
| return jsonify({ | |
| "status": "success", | |
| "scan_type": "scan", | |
| "timestamp": datetime.now().isoformat(), | |
| "total_scanned": len(results), | |
| "results": results, | |
| }) | |
| def short_scan_api(): | |
| """Alias for /api/scan — no duplicate Telegram alert.""" | |
| try: | |
| results = run_scan(COINS, lookback_days=20, limit=10) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| try: | |
| log_admin_stat("scan", len(results)) | |
| except Exception as e: | |
| print(f"⚠️ admin_stats log failed: {e}") | |
| return jsonify({ | |
| "status": "success", | |
| "scan_type": "scan", | |
| "timestamp": datetime.now().isoformat(), | |
| "total_scanned": len(results), | |
| "results": results, | |
| }) | |
| def long_scan_api(): | |
| """Long scan (90-day lookback).""" | |
| try: | |
| results = run_scan(COINS, lookback_days=90, limit=10) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| try: | |
| log_admin_stat("scan", len(results), extra={"scan_type": "long"}) | |
| except Exception as e: | |
| print(f"⚠️ admin_stats log failed: {e}") | |
| return jsonify({ | |
| "status": "success", | |
| "scan_type": "long", | |
| "timestamp": datetime.now().isoformat(), | |
| "total_scanned": len(results), | |
| "results": results, | |
| }) | |
| def scan_generic_api(scan_type): | |
| """Generic scan endpoint — short=20d, long=90d.""" | |
| lookback_days = 90 if scan_type == "long" else 20 | |
| try: | |
| results = run_scan(COINS, lookback_days=lookback_days, limit=10) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| try: | |
| log_admin_stat("scan", len(results), 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": len(results), | |
| "results": results, | |
| }) | |
| 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: | |
| results = run_scan(COINS, lookback_days=20, limit=10) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| scan_data = { | |
| "results": results, | |
| "total_scanned": len(results), | |
| "lookback_days": 20, | |
| "rsi_period": 14, | |
| } | |
| try: | |
| log_admin_stat("scan", len(results), extra={"trigger": "cron"}) | |
| except Exception as e: | |
| print(f"⚠️ admin_stats log failed: {e}") | |
| alert_on_buy_signals(scan_data) | |
| return jsonify({ | |
| "ok": True, | |
| "buy_signals": sum(1 for r in results if r.get("buy_signal")), | |
| "scanned": len(results), | |
| }) | |
| def bingx_debug(): | |
| """Debug BingX API response""" | |
| try: | |
| endpoint = "/openApi/spot/v1/account/balance" | |
| url = f"https://open-api.bingx.com{endpoint}" | |
| timestamp = str(int(time.time() * 1000)) | |
| params = {"timestamp": timestamp} | |
| signature_string = timestamp + endpoint | |
| signature = hmac.new( | |
| BINGX_API_SECRET.encode('utf-8'), | |
| signature_string.encode('utf-8'), | |
| hashlib.sha256 | |
| ).hexdigest() | |
| params["signature"] = signature | |
| headers = {"X-BX-APIKEY": BINGX_API_KEY} | |
| response = requests.get(url, headers=headers, params=params, timeout=10) | |
| # Return the RAW response for debugging | |
| return jsonify({ | |
| "status_code": response.status_code, | |
| "headers": dict(response.headers), | |
| "raw_response": response.text, | |
| "parsed_response": response.json() if response.text else None | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # ---------- Run Server ---------- | |
| if __name__ == '__main__': | |
| init_journal() | |
| port = int(os.environ.get('PORT', 8080)) | |
| app.run(host='0.0.0.0', port=port) | |