File size: 9,565 Bytes
5f20dc6 951488d 5f20dc6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | 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)
|