blind-monkeys / modules /scanner.py
deanpowers's picture
feat(admin): cron + coin alerts UIs, per-mode thresholds, custom domain
951488d
Raw History Blame Contribute Delete
9.57 kB
import numpy as np
from modules.coin_registry import get_coin_ids
from modules.market_data import fetch_coin_data
from modules.settings_manager import get_excluded_coins, get_auto_filter_bingx
from modules.bingx_client import is_on_bingx, get_bingx_available_symbols, get_spot_symbol
from modules.coin_registry import get_coin_symbols
def _bingx_variants(symbol):
"""Return possible BingX formats for a Binance-style symbol."""
if not symbol:
return []
variants = [symbol]
if symbol.endswith("USDT"):
base = symbol[:-4]
variants.append(base + "-USDT")
variants.append(base + "_USDT")
return variants
# ---------------------------------------------------------------------------
# Scan criteria per mode
# ---------------------------------------------------------------------------
SCAN_CRITERIA = {
"conservative": {"zscore": -1.0, "momentum": 5.0, "volatility": 8.0, "rsi": 70.0},
"risk": {"zscore": -1.5, "momentum": 10.0, "volatility": 25.0, "rsi": 60.0},
}
# ---------------------------------------------------------------------------
# PUBLIC_COINS β€” dynamic, computed fresh on every call
# ---------------------------------------------------------------------------
def get_public_coins():
"""Return the top 20 coins from the registry (fresh each call)."""
return get_coin_ids()[:100]
# ---------------------------------------------------------------------------
# Indicator helpers
# ---------------------------------------------------------------------------
def calculate_zscore(prices):
"""Calculate Z-score for a price series"""
if not prices or len(prices) < 10:
return 0
recent = prices[-30:] if len(prices) >= 30 else prices
mean = np.mean(recent)
std = np.std(recent)
if std == 0:
return 0
return float((prices[-1] - 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 float(np.std(returns) * 100)
def calculate_momentum(prices):
"""Calculate 7-day momentum"""
if not prices or len(prices) < 7:
return 0
past = prices[-7]
if past == 0:
return 0
return float(((prices[-1] / past) - 1) * 100)
def calculate_rsi(prices, period=14):
"""Calculate RSI for a price series"""
if not prices or len(prices) < period + 1:
return 50
deltas = [prices[i] - prices[i-1] for i in range(1, len(prices))]
recent_deltas = deltas[-period:]
gains = [d for d in recent_deltas if d > 0]
losses = [-d for d in recent_deltas if d < 0]
avg_gain = sum(gains) / period if gains else 0
avg_loss = sum(losses) / period if losses else 0
if avg_loss == 0:
return 100.0
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return round(float(rsi), 2)
def calculate_atr_from_prices(prices, period=14):
"""Calculate 14-day ATR approximation from closing prices (close-to-close)."""
if not prices or len(prices) < period + 1:
return None
try:
trs = [abs(prices[i] - prices[i-1]) for i in range(1, len(prices))]
atr = sum(trs[-period:]) / period
return round(float(atr), 6)
except Exception:
return None
# ---------------------------------------------------------------------------
# Data fetch wrapper β€” thin wrapper with 20-day default
# ---------------------------------------------------------------------------
def _fetch_coin_data(coin_id, days=20):
"""Thin wrapper around market_data.fetch_coin_data with 20-day default."""
return fetch_coin_data(coin_id, days)
# ---------------------------------------------------------------------------
# Data fetch wrapper β€” thin wrapper with 20-day default
# ---------------------------------------------------------------------------
def _fetch_coin_data(coin_id, days=20):
"""Thin wrapper around market_data.fetch_coin_data with 20-day default."""
return fetch_coin_data(coin_id, days)
# ---------------------------------------------------------------------------
# Main scan
# ---------------------------------------------------------------------------
def _run_scan(coin_ids=None, lookback_days=20, limit=10, rsi_period=14, scan_mode="conservative"):
"""
Run scan on coins with auto-filtering.
- Defaults: 20-day lookback, 14-period RSI
- Auto-filters by BingX availability (if enabled in settings)
- Applies manual exclusion list
- Uses Binance for fast historical data
- Computes RSI penalty and Buy Signal
"""
if coin_ids is None:
coin_ids = get_public_coins()
print(f"πŸ“Š Scanning {len(coin_ids)} public coins...")
excluded = set(get_excluded_coins())
auto_filter = get_auto_filter_bingx()
print(f"πŸ” Auto-filter by BingX: {'ENABLED' if auto_filter else 'DISABLED'}")
if excluded:
print(f"🚫 {len(excluded)} manually excluded coins")
_ticker_map = get_coin_symbols()
bingx_available = set()
bingx_loaded = False
if auto_filter:
print(f"πŸ” Fetching BingX symbol list...")
bingx_symbols = get_bingx_available_symbols()
if bingx_symbols:
bingx_loaded = True
print(f"πŸ” Checking {len(coin_ids)} coins against {len(bingx_symbols)} BingX symbols...")
for coin_id in coin_ids:
if coin_id in excluded:
continue
symbol = get_spot_symbol(coin_id)
if symbol:
for v in _bingx_variants(symbol):
if v in bingx_symbols:
bingx_available.add(coin_id)
break
else:
print("⚠️ BingX symbol list unavailable - marking all coins as unverified")
results = []
skipped = 0
excluded_count = 0
not_on_bingx = 0
for coin_id in coin_ids:
if coin_id in excluded:
excluded_count += 1
continue
prices = _fetch_coin_data(coin_id, lookback_days)
if not prices or len(prices) < 7:
skipped += 1
continue
zscore = calculate_zscore(prices)
volatility = calculate_volatility(prices)
momentum = calculate_momentum(prices)
rsi = calculate_rsi(prices, period=rsi_period)
rsi_penalty = 0
if rsi > 70:
rsi_penalty = (rsi - 70) * 0.5
elif rsi < 30:
rsi_penalty = -2.0
composite = -zscore * 1.5 + momentum * 1.0 - volatility * 0.5 - rsi_penalty
crit = SCAN_CRITERIA.get(scan_mode, SCAN_CRITERIA["conservative"])
buy_signal = (
zscore < crit["zscore"] and
momentum > crit["momentum"] and
volatility < crit["volatility"] and
rsi < crit["rsi"]
)
# ATR-based TP/SL
atr = calculate_atr_from_prices(prices, period=14)
atr_pct = 0
tp_2x = sl_2x = tp_3x = sl_3x = None
if atr:
entry_price = prices[-1]
tp_2x = round(entry_price + 2 * atr, 6)
sl_2x = round(entry_price - 2 * atr, 6)
tp_3x = round(entry_price + 3 * atr, 6)
sl_3x = round(entry_price - 3 * atr, 6)
atr_pct = round((atr / entry_price) * 100, 2) if entry_price else 0
if not bingx_loaded:
on_bingx = None
elif coin_id in bingx_available:
on_bingx = True
else:
on_bingx = False
results.append({
"symbol": _ticker_map.get(coin_id, coin_id).upper(),
"coin_id": coin_id,
"on_bingx": on_bingx,
"price": round(prices[-1], 6),
"zscore": round(zscore, 2),
"volatility": round(volatility, 2),
"momentum": round(momentum, 2),
"rsi": rsi,
"composite_score": round(composite, 2),
"buy_signal": buy_signal,
"atr": atr,
"atr_pct": atr_pct,
"tp_2x": tp_2x,
"sl_2x": sl_2x,
"tp_3x": tp_3x,
"sl_3x": sl_3x
})
print(f"πŸ“Š Scanned: {len(results)} coins")
if skipped:
print(f"⚠️ Skipped {skipped} (no data)")
if excluded_count:
print(f"🚫 Skipped {excluded_count} (manual exclusions)")
if not_on_bingx:
print(f"🚫 Skipped {not_on_bingx} (not on BingX)")
results.sort(key=lambda x: x["composite_score"], reverse=True)
try:
from modules.high_score_alerts import check_scan_results as _hs_check
_hs_check(results, scan_mode=scan_mode)
except Exception as _e:
print("high_score_alerts hook failed: " + str(_e))
return {
"results": results[:limit],
"total_scanned": len(results),
"coins_checked": len(coin_ids),
"lookback_days": lookback_days,
"rsi_period": rsi_period,
"scan_mode": scan_mode,
"criteria": SCAN_CRITERIA.get(scan_mode, SCAN_CRITERIA["conservative"])
}
# Backwards-compat aliases
run_scan = _run_scan
scan = _run_scan # ← ADD THIS LINE β€” fixes local_app.py line 27 import
def short_scan(limit=10):
"""Short scan alias (now uses new defaults)."""
return _run_scan(limit=limit)
def long_scan(limit=10):
"""Long scan β€” 90-day lookback, 14-period RSI."""
return _run_scan(lookback_days=90, limit=limit, rsi_period=14)