Spaces:
Paused
Paused
zt p commited on
Commit ·
ce673a5
1
Parent(s): 537797a
Add market move monitor
Browse filesFiles changed (4)
- README.md+11
- app/core/platform.py+16
- app/main.py+16
- app/monitors/market_move.pyAdded+1459
22 unmodified lines2324252627285 unmodified lines34353637383958 unmodified lines98991001011021036 unmodified lines11011111211311411522 unmodified lines- 每日健康报告会汇总正常、异常、暂停、禁用的监控项,并列出异常原因。- 保留原有币价监控规则:快速涨跌、关键价位、突破 24h/7 日高低、成交量异常、振幅、大额成交、盘口、均线、连续 K 线、RSI、资金费率、持仓量、强平、跨交易所差价等。- Strategy 财务监控:每分钟解析最新 SEC 8-K 获取 BTC 持仓和现金储备,数值变化时推送通知;获取失败时显示在面板和每日健康报告中。## 架构5 unmodified linesapp/core/dashboard.py 简单 Dashboardapp/monitors/base.py 监控插件接口app/monitors/crypto_price.py 当前币价监控插件app/monitors/strategy_treasury.py Strategy BTC 持仓与现金储备插件coinpush.py 原币价业务逻辑,作为可复用业务库保留```58 unmodified lines- `PUT /api/config`:保存完整配置 JSON- `POST /api/calibrate`:校准全部币种阈值- `POST /api/calibrate/{coin}`:校准单个币种阈值## 环境变量6 unmodified lines- `STRATEGY_TREASURY_INTERVAL_SEC`:Strategy BTC 持仓/现金储备轮询间隔,默认 `60`。- `STRATEGY_SEC_8K_SCAN_LIMIT`:启动或最新 8-K 变化时最多扫描多少份 8-K,默认 `20`。- `SEC_USER_AGENT`:SEC API User-Agent,建议配置成包含联系方式的字符串。- `BINANCE_API_KEY` / `BINANCE_API_SECRET`:币安私有接口凭证,可选。- `BINANCE_SPOT_BASE` / `BINANCE_FAPI_BASE` / `BINANCE_FSTREAM_BASE`:币安接口基址,可选。- `BINANCE_ALPHA_BASE`:Binance Alpha 公共行情基址,默认 `https://www.binance.com`。22 unmodified lines232425262728295 unmodified lines3536373839404158 unmodified lines1001011021031041051061076 unmodified lines11411511611711811912012112212312412512622 unmodified lines- 每日健康报告会汇总正常、异常、暂停、禁用的监控项,并列出异常原因。- 保留原有币价监控规则:快速涨跌、关键价位、突破 24h/7 日高低、成交量异常、振幅、大额成交、盘口、均线、连续 K 线、RSI、资金费率、持仓量、强平、跨交易所差价等。- Strategy 财务监控:每分钟解析最新 SEC 8-K 获取 BTC 持仓和现金储备,数值变化时推送通知;获取失败时显示在面板和每日健康报告中。- 全市场日/月涨跌监控:默认覆盖指定 50 个币种,每 5 分钟从 Binance、OKX、Bitget、Hyperliquid、Asterdex、Bybit、Gate、KuCoin、MEXC、Kraken、Upbit 的公开接口发现 USDT/USD 市场,按 24h 成交额最大的交易所报价,对比 24h 与 30d 参考价,涨跌超过 30% 时推送通知。## 架构5 unmodified linesapp/core/dashboard.py 简单 Dashboardapp/monitors/base.py 监控插件接口app/monitors/crypto_price.py 当前币价监控插件app/monitors/market_move.py 全市场日/月涨跌监控插件app/monitors/strategy_treasury.py Strategy BTC 持仓与现金储备插件coinpush.py 原币价业务逻辑,作为可复用业务库保留```58 unmodified lines- `PUT /api/config`:保存完整配置 JSON- `POST /api/calibrate`:校准全部币种阈值- `POST /api/calibrate/{coin}`:校准单个币种阈值- `GET /api/market-move/config`:读取全市场日/月涨跌监控配置- `PUT /api/market-move/config`:保存全市场日/月涨跌监控配置,便于追加币种## 环境变量6 unmodified lines- `STRATEGY_TREASURY_INTERVAL_SEC`:Strategy BTC 持仓/现金储备轮询间隔,默认 `60`。- `STRATEGY_SEC_8K_SCAN_LIMIT`:启动或最新 8-K 变化时最多扫描多少份 8-K,默认 `20`。- `SEC_USER_AGENT`:SEC API User-Agent,建议配置成包含联系方式的字符串。- `ENABLE_MARKET_MOVE`:是否启用全市场日/月涨跌监控,默认 `true`。- `MARKET_MOVE_INTERVAL_SEC`:全市场涨跌监控轮询间隔,默认 `300`。- `MARKET_MOVE_THRESHOLD_PCT`:24h/30d 涨跌提醒阈值百分比,默认 `30`。- `MARKET_MOVE_LOOKBACK_DAYS`:月线对比天数,默认 `30`。- `MARKET_MOVE_EXCHANGES`:启用的交易所列表,逗号分隔;默认启用 Binance、OKX、Bitget、Hyperliquid、Asterdex、Bybit、Gate、KuCoin、MEXC、Kraken、Upbit。- `MARKET_MOVE_COINS`:覆盖默认币种列表,格式如 `BTC,ETH,HYPE:Hyperliquid`。- `MARKET_MOVE_EXTRA_COINS`:在默认币种列表后追加币种,格式同上。- `BINANCE_API_KEY` / `BINANCE_API_SECRET`:币安私有接口凭证,可选。- `BINANCE_SPOT_BASE` / `BINANCE_FAPI_BASE` / `BINANCE_FSTREAM_BASE`:币安接口基址,可选。- `BINANCE_ALPHA_BASE`:Binance Alpha 公共行情基址,默认 `https://www.binance.com`。
2 unmodified lines3456789 unmodified lines18192021222324252631 unmodified lines58596061626312 unmodified lines7677782 unmodified linesfrom app.core.database import MonitorStorefrom app.monitors.crypto_price import CryptoPriceMonitorfrom app.monitors.strategy_treasury import StrategyTreasuryMonitor9 unmodified linesself._lock = threading.RLock()self.crypto = CryptoPriceMonitor(self.store)self.strategy_treasury = StrategyTreasuryMonitor(self.store)self.plugins = {"crypto_price": self.crypto,"strategy_treasury": self.strategy_treasury,}self.started = False31 unmodified lines"interval": self.strategy_treasury.interval,"stats": self.strategy_treasury.stats,},}def set_monitor_paused(self, monitor_id, paused):12 unmodified linesdef calibrate_coin(self, name):return self.crypto.calibrate_coin(name)2 unmodified lines34567899 unmodified lines192021222324252627282931 unmodified lines6162636465666768697071727312 unmodified lines8687888990919293942 unmodified linesfrom app.core.database import MonitorStorefrom app.monitors.crypto_price import CryptoPriceMonitorfrom app.monitors.market_move import MarketMoveMonitorfrom app.monitors.strategy_treasury import StrategyTreasuryMonitor9 unmodified linesself._lock = threading.RLock()self.crypto = CryptoPriceMonitor(self.store)self.strategy_treasury = StrategyTreasuryMonitor(self.store)self.market_move = MarketMoveMonitor(self.store)self.plugins = {"crypto_price": self.crypto,"strategy_treasury": self.strategy_treasury,"market_move": self.market_move,}self.started = False31 unmodified lines"interval": self.strategy_treasury.interval,"stats": self.strategy_treasury.stats,},"market_move": {"enabled": self.market_move.enabled,"interval": self.market_move.interval,"threshold_pct": self.market_move.threshold_pct,"stats": self.market_move.stats,"snapshots": self.market_move.snapshots,},}def set_monitor_paused(self, monitor_id, paused):12 unmodified linesdef calibrate_coin(self, name):return self.crypto.calibrate_coin(name)def get_market_move_config(self):return self.market_move.get_config()def update_market_move_config(self, cfg):return self.market_move.update_config(cfg)
188 unmodified lines189190191188 unmodified linesraise HTTPException(status_code=404, detail=str(exc)) from excexcept Exception as exc:raise HTTPException(status_code=500, detail=str(exc)) from exc188 unmodified lines189190191192193194195196197198199200201202203204205206207188 unmodified linesraise HTTPException(status_code=404, detail=str(exc)) from excexcept Exception as exc:raise HTTPException(status_code=500, detail=str(exc)) from exc@app.get("/api/market-move/config")def api_get_market_move_config():return platform.get_market_move_config()@app.put("/api/market-move/config")async def api_update_market_move_config(request: Request):try:cfg = await request.json()if not isinstance(cfg, dict) or "coins" not in cfg:raise ValueError("配置必须包含 coins")return platform.update_market_move_config(cfg)except Exception as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459import copyimport osimport threadingimport timefrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezone
import requests
os.environ.setdefault("COINPUSH_DISABLE_STREAMLIT_BOOTSTRAP", "1")import coinpush as legacy # noqa: E402
from app.monitors.base import BaseMonitor
SERVICE_ID = "market_move:service"CONFIG_KEY = "market_move:config"ALERT_STATE_KEY = "market_move:alert_state"HEALTH_ALERT_COOLDOWN_SEC = 3600
SUPPORTED_EXCHANGES = [ "binance", "okx", "bitget", "hyperliquid", "asterdex", "bybit", "gate", "kucoin", "mexc", "kraken", "upbit",]
EXCHANGE_LABELS = { "binance": "Binance", "okx": "OKX", "bitget": "Bitget", "hyperliquid": "Hyperliquid", "asterdex": "Asterdex", "bybit": "Bybit", "gate": "Gate", "kucoin": "KuCoin", "mexc": "MEXC", "kraken": "Kraken", "upbit": "Upbit",}
EXCHANGE_ALIASES = { "aster": "asterdex", "gateio": "gate", "gate.io": "gate",}
DEFAULT_COINS = [ {"symbol": "BTC", "name": "比特币"}, {"symbol": "ETH", "name": "以太币"}, {"symbol": "BNB", "name": "币安币"}, {"symbol": "XRP", "name": "瑞波币"}, {"symbol": "SOL", "name": "Solana"}, {"symbol": "TRX", "name": "波场币"}, {"symbol": "HYPE", "name": "Hyperliquid"}, {"symbol": "LEO", "name": "UNUS SED LEO"}, {"symbol": "ZEC", "name": "Zcash"}, {"symbol": "XLM", "name": "Stellar"}, {"symbol": "XMR", "name": "Monero"}, {"symbol": "CC", "name": "Canton"}, {"symbol": "GRAM", "name": "Gram (prev. Toncoin)"}, {"symbol": "LTC", "name": "莱特币"}, {"symbol": "SUI", "name": "Sui"}, {"symbol": "OKB", "name": "OKB"}, {"symbol": "M", "name": "MemeCore"}, {"symbol": "ONDO", "name": "Ondo"}, {"symbol": "MNT", "name": "Mantle"}, {"symbol": "BGB", "name": "Bitget Token"}, {"symbol": "ETC", "name": "Ethereum Classic"}, {"symbol": "PEPE", "name": "Pepe"}, {"symbol": "KCS", "name": "KuCoin Token"}, {"symbol": "STABLE", "name": "Stable"}, {"symbol": "KAS", "name": "Kaspa"}, {"symbol": "RENDER", "name": "Render"}, {"symbol": "ENA", "name": "Ethena"}, {"symbol": "GT", "name": "GateToken"}, {"symbol": "BEAT", "name": "Audiera"}, {"symbol": "VVV", "name": "Venice Token"}, {"symbol": "INJ", "name": "Injective"}, {"symbol": "STX", "name": "Stacks"}, {"symbol": "GNO", "name": "Gnosis"}, {"symbol": "FLOKI", "name": "FLOKI"}, {"symbol": "KITE", "name": "Kite"}, {"symbol": "DCR", "name": "Decred"}, {"symbol": "VELVET", "name": "Velvet"}, {"symbol": "PIEVERSE", "name": "Pieverse"}, {"symbol": "MX", "name": "MX Token"}, {"symbol": "GWEI", "name": "ETHGas"}, {"symbol": "FARTCOIN", "name": "Fartcoin"}, {"symbol": "BAT", "name": "Basic Attention Token"}, {"symbol": "GOMINING", "name": "GoMining"}, {"symbol": "TAG", "name": "Tagger"}, {"symbol": "BANANAS31", "name": "Banana For Scale"}, {"symbol": "RAIN", "name": "Rain"}, {"symbol": "CTM", "name": "c8ntinuum"}, {"symbol": "BDX", "name": "Beldex"}, {"symbol": "UB", "name": "Unibase"}, {"symbol": "BTW", "name": "Bitway"},]
DEFAULT_CONFIG = { "enabled": True, "interval_sec": 300, "threshold_pct": 30.0, "reset_ratio": 0.8, "lookback_days": 30, "exchanges": SUPPORTED_EXCHANGES, "coins": DEFAULT_COINS,}
STABLE_QUOTES = ("USDT", "USDC", "USD")ALL_QUOTES = ("USDT", "USDC", "USD", "KRW")
@dataclassclass MarketTicker: asset: str exchange_key: str exchange: str market_type: str market_id: str quote: str price: float quote_volume_usd: float open_24h: float = None raw_price: float = None raw_quote_volume: float = None
@dataclassclass DailyCandle: ts_ms: int open: float high: float low: float close: float
def utc_now_iso(): return datetime.now(timezone.utc).isoformat(timespec="seconds")
def utc_after_iso(seconds): return (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat(timespec="seconds")
def coin_monitor_id(symbol): return f"market_move:coin:{str(symbol).upper()}"
def normalize_asset(asset): asset = str(asset or "").upper().strip() return "BTC" if asset == "XBT" else asset
def normalize_exchange(value): key = str(value or "").strip().lower() return EXCHANGE_ALIASES.get(key, key)
def num(value, default=None): if value is None: return default try: return float(str(value).replace(",", "")) except (TypeError, ValueError): return default
def pct_change(current, reference): current = num(current) reference = num(reference) if current is None or reference is None or reference <= 0: return None return (current - reference) / reference * 100.0
def fmt_price(value): value = num(value) if value is None: return "--" if value >= 1000: return f"${value:,.2f}" if value >= 1: return f"${value:,.4f}" if value >= 0.01: return f"${value:,.6f}" return f"${value:,.10f}".rstrip("0").rstrip(".")
def fmt_usd(value): value = num(value) if value is None: return "--" sign = "-" if value < 0 else "" value = abs(value) if value >= 1_000_000_000_000: return f"{sign}${value / 1_000_000_000_000:,.2f}T" if value >= 1_000_000_000: return f"{sign}${value / 1_000_000_000:,.2f}B" if value >= 1_000_000: return f"{sign}${value / 1_000_000:,.2f}M" if value >= 1_000: return f"{sign}${value / 1_000:,.2f}K" return f"{sign}${value:,.2f}"
def format_pct(value): value = num(value) if value is None: return "--" return f"{value:+.2f}%"
def market_type_label(value): return "现货" if value == "spot" else "合约"
def split_joined_symbol(symbol, quotes=ALL_QUOTES): symbol = str(symbol or "").upper().strip() for quote in sorted(quotes, key=len, reverse=True): if symbol.endswith(quote) and len(symbol) > len(quote): return normalize_asset(symbol[:-len(quote)]), quote return None, None
def open_from_change(last_price, change_value, percent=False): last_price = num(last_price) change_value = num(change_value) if last_price is None or change_value is None: return None ratio = change_value / 100.0 if percent else change_value if ratio <= -0.999999: return None return last_price / (1.0 + ratio)
def deep_merge(base, override): result = copy.deepcopy(base) for key, value in (override or {}).items(): if isinstance(value, dict) and isinstance(result.get(key), dict): result[key] = deep_merge(result[key], value) else: result[key] = copy.deepcopy(value) return result
def parse_coin_list(value): coins = [] for raw in str(value or "").replace("\n", ",").split(","): raw = raw.strip() if not raw: continue if ":" in raw: symbol, name = raw.split(":", 1) else: symbol, name = raw, raw symbol = normalize_asset(symbol) if symbol: coins.append({"symbol": symbol, "name": name.strip() or symbol}) return coins
def normalize_config(config): cfg = deep_merge(DEFAULT_CONFIG, config or {}) cfg["enabled"] = str(cfg.get("enabled", True)).lower() not in ("0", "false", "no", "off") cfg["interval_sec"] = max(60, int(num(cfg.get("interval_sec"), 300))) cfg["threshold_pct"] = max(0.1, float(num(cfg.get("threshold_pct"), 30.0))) cfg["reset_ratio"] = min(0.99, max(0.1, float(num(cfg.get("reset_ratio"), 0.8)))) cfg["lookback_days"] = max(2, int(num(cfg.get("lookback_days"), 30)))
exchanges = [] for exchange in cfg.get("exchanges") or SUPPORTED_EXCHANGES: key = normalize_exchange(exchange) if key in SUPPORTED_EXCHANGES and key not in exchanges: exchanges.append(key) cfg["exchanges"] = exchanges or copy.deepcopy(SUPPORTED_EXCHANGES)
seen = set() coins = [] for coin in cfg.get("coins") or DEFAULT_COINS: if isinstance(coin, str): symbol, name = coin, coin else: symbol, name = coin.get("symbol"), coin.get("name") or coin.get("symbol") symbol = normalize_asset(symbol) if not symbol or symbol in seen: continue seen.add(symbol) coins.append({"symbol": symbol, "name": str(name or symbol)}) cfg["coins"] = coins return cfg
def apply_env_overrides(config): cfg = copy.deepcopy(config) if "ENABLE_MARKET_MOVE" in os.environ: cfg["enabled"] = os.getenv("ENABLE_MARKET_MOVE", "").lower() not in ("0", "false", "no", "off") if os.getenv("MARKET_MOVE_INTERVAL_SEC"): cfg["interval_sec"] = int(num(os.getenv("MARKET_MOVE_INTERVAL_SEC"), cfg["interval_sec"])) if os.getenv("MARKET_MOVE_THRESHOLD_PCT"): cfg["threshold_pct"] = float(num(os.getenv("MARKET_MOVE_THRESHOLD_PCT"), cfg["threshold_pct"])) if os.getenv("MARKET_MOVE_LOOKBACK_DAYS"): cfg["lookback_days"] = int(num(os.getenv("MARKET_MOVE_LOOKBACK_DAYS"), cfg["lookback_days"])) if os.getenv("MARKET_MOVE_EXCHANGES"): cfg["exchanges"] = [ normalize_exchange(item) for item in os.getenv("MARKET_MOVE_EXCHANGES", "").split(",") if item.strip() ] if os.getenv("MARKET_MOVE_COINS"): cfg["coins"] = parse_coin_list(os.getenv("MARKET_MOVE_COINS")) if os.getenv("MARKET_MOVE_EXTRA_COINS"): cfg["coins"] = list(cfg.get("coins") or []) + parse_coin_list(os.getenv("MARKET_MOVE_EXTRA_COINS")) return normalize_config(cfg)
class PublicMarketDataClient: """Public exchange market data normalized to USD quote volume."""
def __init__(self, logger, config): self.logger = logger self.config = normalize_config(config) self.session = requests.Session() self.session.headers.update(legacy.REQ_HEADERS) self.last_error_log = {} self._upbit_krw_usdt = None
def update_config(self, config): self.config = normalize_config(config)
def _log_error_once(self, key, message, cooldown=600): now = time.time() if now - self.last_error_log.get(key, 0) >= cooldown: self.last_error_log[key] = now self.logger(message, level="error")
def _get_json(self, base, path, params=None, timeout=12): url = base.rstrip("/") + path last_exc = None for attempt in range(2): try: resp = self.session.get(url, params=params, timeout=timeout) if resp.status_code != 200: self._log_error_once((base, path, resp.status_code), f"{base}{path} 状态码 {resp.status_code}") return None return resp.json() except Exception as exc: last_exc = exc if attempt == 0: time.sleep(0.2) self._log_error_once((base, path, "exception"), f"{base}{path} 请求异常: {last_exc}") return None
def _post_json(self, base, path, body=None, timeout=12): url = base.rstrip("/") + path last_exc = None for attempt in range(2): try: resp = self.session.post(url, json=body or {}, timeout=timeout) if resp.status_code != 200: self._log_error_once((base, path, resp.status_code), f"{base}{path} 状态码 {resp.status_code}") return None return resp.json() except Exception as exc: last_exc = exc if attempt == 0: time.sleep(0.2) self._log_error_once((base, path, "exception"), f"{base}{path} 请求异常: {last_exc}") return None
def candidates(self, coins): wanted = {normalize_asset(symbol) for symbol in coins} all_candidates = [] for exchange in self.config.get("exchanges", SUPPORTED_EXCHANGES): method = getattr(self, f"_candidates_{exchange}", None) if not method: continue try: all_candidates.extend(method(wanted)) except Exception as exc: self._log_error_once(exchange, f"{EXCHANGE_LABELS.get(exchange, exchange)} 行情解析异常: {exc}") return all_candidates
def candles(self, ticker, days): method = getattr(self, f"_candles_{ticker.exchange_key}", None) if not method: return [] try: return method(ticker, days) except Exception as exc: self._log_error_once( (ticker.exchange_key, ticker.market_id, "candles"), f"{ticker.exchange} {ticker.market_id} K线解析异常: {exc}", ) return []
def _candidate( self, wanted, exchange_key, market_type, market_id, asset, quote, price, quote_volume, open_24h=None, quote_is_usd=True, ): asset = normalize_asset(asset) quote = str(quote or "").upper() price = num(price) quote_volume = num(quote_volume) if asset not in wanted or price is None or price <= 0 or quote_volume is None or quote_volume <= 0: return None raw_price = price raw_quote_volume = quote_volume if quote == "KRW": krw_per_usdt = self._upbit_krw_per_usdt() if not krw_per_usdt: return None price = price / krw_per_usdt quote_volume = quote_volume / krw_per_usdt if open_24h is not None: open_24h = num(open_24h) open_24h = open_24h / krw_per_usdt if open_24h else None elif not quote_is_usd: quote_volume = quote_volume * price return MarketTicker( asset=asset, exchange_key=exchange_key, exchange=EXCHANGE_LABELS.get(exchange_key, exchange_key), market_type=market_type, market_id=market_id, quote=quote, price=price, quote_volume_usd=quote_volume, open_24h=num(open_24h), raw_price=raw_price, raw_quote_volume=raw_quote_volume, )
def _append(self, out, candidate): if candidate: out.append(candidate)
def _upbit_krw_per_usdt(self): now = time.time() cached = self._upbit_krw_usdt if cached and now - cached["ts"] < 3600: return cached["value"] data = self._get_json(legacy.UPBIT_BASE, "/v1/ticker", {"markets": "KRW-USDT"}, timeout=8) if isinstance(data, list) and data: value = num(data[0].get("trade_price")) if value and value > 0: self._upbit_krw_usdt = {"ts": now, "value": value} return value return None
def _binance_spot_bases(self): bases = [] for base in [legacy.SPOT_BASE] + list(getattr(legacy, "SPOT_FALLBACK_BASES", [])): base = str(base or "").rstrip("/") if base and base not in bases: bases.append(base) return bases
def _candidates_binance(self, wanted): out = [] spot_data = None for base in self._binance_spot_bases(): spot_data = self._get_json(base, "/api/v3/ticker/24hr", timeout=15) if isinstance(spot_data, list): break for row in spot_data or []: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "binance", "spot", row.get("symbol"), asset, quote, row.get("lastPrice"), row.get("quoteVolume"), row.get("openPrice"), ), )
futures_data = self._get_json(legacy.FAPI_BASE, "/fapi/v1/ticker/24hr", timeout=15) if isinstance(futures_data, list): for row in futures_data: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "binance", "perp", row.get("symbol"), asset, quote, row.get("lastPrice"), row.get("quoteVolume"), row.get("openPrice"), ), ) return out
def _binance_spot_klines(self, symbol, limit): for base in self._binance_spot_bases(): rows = self._get_json(base, "/api/v3/klines", {"symbol": symbol, "interval": "1d", "limit": limit}) if isinstance(rows, list): return rows return []
def _binance_futures_klines(self, symbol, limit): rows = self._get_json(legacy.FAPI_BASE, "/fapi/v1/klines", {"symbol": symbol, "interval": "1d", "limit": limit}) return rows if isinstance(rows, list) else []
def _candidates_okx(self, wanted): out = [] for inst_type, market_type in (("SPOT", "spot"), ("SWAP", "perp")): data = self._get_json(legacy.OKX_BASE, "/api/v5/market/tickers", {"instType": inst_type}, timeout=15) if not isinstance(data, dict) or str(data.get("code")) != "0": continue for row in data.get("data") or []: parts = str(row.get("instId") or "").split("-") if len(parts) < 2: continue asset, quote = normalize_asset(parts[0]), parts[1].upper() if quote not in STABLE_QUOTES: continue price = num(row.get("last")) self._append( out, self._candidate( wanted, "okx", market_type, row.get("instId"), asset, quote, price, row.get("volCcy24h"), row.get("open24h"), quote_is_usd=market_type == "spot", ), ) return out
def _candidates_bitget(self, wanted): out = [] spot = self._get_json(legacy.BITGET_BASE, "/api/v2/spot/market/tickers", timeout=15) if isinstance(spot, dict) and str(spot.get("code")) == "00000": for row in spot.get("data") or []: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "bitget", "spot", row.get("symbol"), asset, quote, row.get("lastPr"), row.get("usdtVolume") or row.get("quoteVolume"), row.get("open"), ), ) futures = self._get_json( legacy.BITGET_BASE, "/api/v2/mix/market/tickers", {"productType": "USDT-FUTURES"}, timeout=15, ) if isinstance(futures, dict) and str(futures.get("code")) == "00000": for row in futures.get("data") or []: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "bitget", "perp", row.get("symbol"), asset, quote, row.get("lastPr"), row.get("usdtVolume") or row.get("quoteVolume"), row.get("open24h"), ), ) return out
def _candidates_hyperliquid(self, wanted): out = [] data = self._post_json(legacy.HYPERLIQUID_BASE, "/info", {"type": "metaAndAssetCtxs"}, timeout=15) if not isinstance(data, list) or len(data) < 2: return out for meta, ctx in zip((data[0] or {}).get("universe") or [], data[1] or []): asset = normalize_asset(meta.get("name")) price = num(ctx.get("markPx") or ctx.get("midPx") or ctx.get("oraclePx")) self._append( out, self._candidate( wanted, "hyperliquid", "perp", asset, asset, "USD", price, ctx.get("dayNtlVlm"), ctx.get("prevDayPx"), ), ) return out
def _candidates_asterdex(self, wanted): out = [] data = self._get_json(legacy.ASTER_FAPI_BASE, "/fapi/v1/ticker/24hr", timeout=15) if not isinstance(data, list): return out for row in data: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "asterdex", "perp", row.get("symbol"), asset, quote, row.get("lastPrice"), row.get("quoteVolume"), row.get("openPrice"), ), ) return out
def _candidates_bybit(self, wanted): out = [] for category, market_type in (("spot", "spot"), ("linear", "perp")): data = self._get_json(legacy.BYBIT_BASE, "/v5/market/tickers", {"category": category}, timeout=15) if not isinstance(data, dict) or str(data.get("retCode")) != "0": continue for row in (data.get("result") or {}).get("list") or []: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "bybit", market_type, row.get("symbol"), asset, quote, row.get("lastPrice"), row.get("turnover24h"), row.get("prevPrice24h"), ), ) return out
def _candidates_gate(self, wanted): out = [] spot = self._get_json(legacy.GATE_BASE, "/spot/tickers", timeout=15) if isinstance(spot, list): for row in spot: parts = str(row.get("currency_pair") or "").split("_") if len(parts) != 2 or parts[1].upper() not in STABLE_QUOTES: continue price = num(row.get("last")) self._append( out, self._candidate( wanted, "gate", "spot", row.get("currency_pair"), parts[0], parts[1], price, row.get("quote_volume"), open_from_change(price, row.get("change_percentage"), percent=True), ), ) futures = self._get_json(legacy.GATE_BASE, "/futures/usdt/tickers", timeout=15) if isinstance(futures, list): for row in futures: parts = str(row.get("contract") or "").split("_") if len(parts) != 2: continue price = num(row.get("last")) self._append( out, self._candidate( wanted, "gate", "perp", row.get("contract"), parts[0], "USDT", price, row.get("volume_24h_quote") or row.get("volume_24h"), open_from_change(price, row.get("change_percentage"), percent=True), ), ) return out
def _candidates_kucoin(self, wanted): out = [] spot = self._get_json(legacy.KUCOIN_BASE, "/api/v1/market/allTickers", timeout=15) if isinstance(spot, dict) and str(spot.get("code")) == "200000": for row in (spot.get("data") or {}).get("ticker") or []: parts = str(row.get("symbol") or "").split("-") if len(parts) != 2 or parts[1].upper() not in STABLE_QUOTES: continue price = num(row.get("last")) self._append( out, self._candidate( wanted, "kucoin", "spot", row.get("symbol"), parts[0], parts[1], price, row.get("volValue"), open_from_change(price, row.get("changeRate"), percent=False), ), ) futures = self._get_json("https://api-futures.kucoin.com", "/api/v1/contracts/active", timeout=15) if isinstance(futures, dict) and str(futures.get("code")) == "200000": for row in futures.get("data") or []: quote = str(row.get("quoteCurrency") or row.get("settleCurrency") or "").upper() if quote not in STABLE_QUOTES: continue price = num(row.get("lastTradePrice") or row.get("markPrice")) self._append( out, self._candidate( wanted, "kucoin", "perp", row.get("symbol"), row.get("displayBaseCurrency") or row.get("baseCurrency"), quote, price, row.get("turnoverOf24h"), open_from_change(price, row.get("priceChgPct"), percent=False), ), ) return out
def _candidates_mexc(self, wanted): out = [] spot = self._get_json(legacy.MEXC_BASE, "/api/v3/ticker/24hr", timeout=15) if isinstance(spot, list): for row in spot: asset, quote = split_joined_symbol(row.get("symbol"), STABLE_QUOTES) self._append( out, self._candidate( wanted, "mexc", "spot", row.get("symbol"), asset, quote, row.get("lastPrice"), row.get("quoteVolume"), row.get("openPrice"), ), ) futures = self._get_json("https://contract.mexc.com", "/api/v1/contract/ticker", timeout=15) if isinstance(futures, dict) and futures.get("success"): rows = futures.get("data") rows = [rows] if isinstance(rows, dict) else rows for row in rows or []: parts = str(row.get("symbol") or "").split("_") if len(parts) != 2 or parts[1].upper() not in STABLE_QUOTES: continue price = num(row.get("lastPrice")) self._append( out, self._candidate( wanted, "mexc", "perp", row.get("symbol"), parts[0], parts[1], price, row.get("amount24") or row.get("volume24"), open_from_change(price, row.get("riseFallRate"), percent=False), ), ) return out
def _candidates_kraken(self, wanted): out = [] pairs = self._get_json(legacy.KRAKEN_BASE, "/0/public/AssetPairs", timeout=15) if not isinstance(pairs, dict) or pairs.get("error"): return out pair_meta = {} request_pairs = [] for pair_id, info in (pairs.get("result") or {}).items(): wsname = info.get("wsname") or "" if "/" not in wsname: continue base, quote = wsname.split("/", 1) asset = normalize_asset(base) quote = quote.upper() if asset not in wanted or quote not in STABLE_QUOTES: continue altname = info.get("altname") or pair_id pair_meta[pair_id] = (asset, quote, altname) pair_meta[altname] = (asset, quote, altname) request_pairs.append(altname) for idx in range(0, len(request_pairs), 25): chunk = request_pairs[idx:idx + 25] data = self._get_json(legacy.KRAKEN_BASE, "/0/public/Ticker", {"pair": ",".join(chunk)}, timeout=15) if not isinstance(data, dict) or data.get("error"): continue for pair_id, row in (data.get("result") or {}).items(): asset, quote, market_id = pair_meta.get(pair_id, (None, None, pair_id)) price = num((row.get("c") or [None])[0]) base_volume = num((row.get("v") or [None, None])[1]) quote_volume = price * base_volume if price and base_volume else None self._append( out, self._candidate( wanted, "kraken", "spot", market_id, asset, quote, price, quote_volume, ), ) return out
def _candidates_upbit(self, wanted): out = [] markets = self._get_json(legacy.UPBIT_BASE, "/v1/market/all", timeout=15) if not isinstance(markets, list): return out selected = [] for item in markets: market = str(item.get("market") or "") if "-" not in market: continue quote, asset = market.split("-", 1) if quote.upper() in ("USDT", "KRW") and normalize_asset(asset) in wanted: selected.append(market) for idx in range(0, len(selected), 100): chunk = selected[idx:idx + 100] data = self._get_json(legacy.UPBIT_BASE, "/v1/ticker", {"markets": ",".join(chunk)}, timeout=15) if not isinstance(data, list): continue for row in data: quote, asset = str(row.get("market") or "").split("-", 1) self._append( out, self._candidate( wanted, "upbit", "spot", row.get("market"), asset, quote, row.get("trade_price"), row.get("acc_trade_price_24h"), row.get("opening_price"), ), ) return out
def _parse_binance_klines(self, rows): out = [] for row in rows or []: try: out.append(DailyCandle(int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_binance(self, ticker, days): limit = min(days + 8, 1000) if ticker.market_type == "perp": rows = self._binance_futures_klines(ticker.market_id, limit) else: rows = self._binance_spot_klines(ticker.market_id, limit) return self._parse_binance_klines(rows)
def _candles_okx(self, ticker, days): data = self._get_json( legacy.OKX_BASE, "/api/v5/market/candles", {"instId": ticker.market_id, "bar": "1D", "limit": str(min(days + 8, 300))}, timeout=15, ) if not isinstance(data, dict) or str(data.get("code")) != "0": return [] out = [] for row in data.get("data") or []: try: out.append(DailyCandle(int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_bitget(self, ticker, days): if ticker.market_type == "perp": path = "/api/v2/mix/market/candles" params = { "symbol": ticker.market_id, "productType": "USDT-FUTURES", "granularity": "1D", "limit": str(min(days + 8, 200)), } else: path = "/api/v2/spot/market/candles" params = {"symbol": ticker.market_id, "granularity": "1day", "limit": str(min(days + 8, 200))} data = self._get_json(legacy.BITGET_BASE, path, params, timeout=15) if not isinstance(data, dict) or str(data.get("code")) != "00000": return [] out = [] for row in data.get("data") or []: try: out.append(DailyCandle(int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_hyperliquid(self, ticker, days): end = int(time.time() * 1000) start = end - int((days + 8) * 86_400_000) data = self._post_json( legacy.HYPERLIQUID_BASE, "/info", {"type": "candleSnapshot", "req": {"coin": ticker.market_id, "interval": "1d", "startTime": start, "endTime": end}}, timeout=15, ) out = [] for row in data or []: try: out.append(DailyCandle(int(row["t"]), float(row["o"]), float(row["h"]), float(row["l"]), float(row["c"]))) except (TypeError, ValueError, KeyError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_asterdex(self, ticker, days): rows = self._get_json( legacy.ASTER_FAPI_BASE, "/fapi/v1/klines", {"symbol": ticker.market_id, "interval": "1d", "limit": min(days + 8, 1000)}, timeout=15, ) return self._parse_binance_klines(rows if isinstance(rows, list) else [])
def _candles_bybit(self, ticker, days): category = "linear" if ticker.market_type == "perp" else "spot" data = self._get_json( legacy.BYBIT_BASE, "/v5/market/kline", {"category": category, "symbol": ticker.market_id, "interval": "D", "limit": min(days + 8, 1000)}, timeout=15, ) if not isinstance(data, dict) or str(data.get("retCode")) != "0": return [] out = [] for row in (data.get("result") or {}).get("list") or []: try: out.append(DailyCandle(int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_gate(self, ticker, days): out = [] if ticker.market_type == "perp": rows = self._get_json( legacy.GATE_BASE, "/futures/usdt/candlesticks", {"contract": ticker.market_id, "interval": "1d", "limit": min(days + 8, 1000)}, timeout=15, ) for row in rows or []: try: out.append(DailyCandle(int(row["t"]) * 1000, float(row["o"]), float(row["h"]), float(row["l"]), float(row["c"]))) except (TypeError, ValueError, KeyError): continue else: rows = self._get_json( legacy.GATE_BASE, "/spot/candlesticks", {"currency_pair": ticker.market_id, "interval": "1d", "limit": min(days + 8, 1000)}, timeout=15, ) for row in rows or []: try: out.append(DailyCandle(int(row[0]) * 1000, float(row[5]), float(row[3]), float(row[4]), float(row[2]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_kucoin(self, ticker, days): end = int(time.time()) start = end - int((days + 8) * 86400) out = [] if ticker.market_type == "perp": data = self._get_json( "https://api-futures.kucoin.com", "/api/v1/kline/query", {"symbol": ticker.market_id, "granularity": 1440, "from": start * 1000, "to": end * 1000}, timeout=15, ) rows = data.get("data") if isinstance(data, dict) and str(data.get("code")) == "200000" else [] for row in rows or []: try: out.append(DailyCandle(int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]))) except (TypeError, ValueError, IndexError): continue else: data = self._get_json( legacy.KUCOIN_BASE, "/api/v1/market/candles", {"symbol": ticker.market_id, "type": "1day", "startAt": start, "endAt": end}, timeout=15, ) rows = data.get("data") if isinstance(data, dict) and str(data.get("code")) == "200000" else [] for row in rows or []: try: out.append(DailyCandle(int(row[0]) * 1000, float(row[1]), float(row[3]), float(row[4]), float(row[2]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_mexc(self, ticker, days): if ticker.market_type == "perp": end = int(time.time()) start = end - int((days + 8) * 86400) data = self._get_json( "https://contract.mexc.com", f"/api/v1/contract/kline/{ticker.market_id}", {"interval": "Day1", "start": start, "end": end}, timeout=15, ) payload = data.get("data") if isinstance(data, dict) and data.get("success") else {} out = [] for idx, ts in enumerate(payload.get("time") or []): try: out.append(DailyCandle( int(ts) * 1000, float(payload["open"][idx]), float(payload["high"][idx]), float(payload["low"][idx]), float(payload["close"][idx]), )) except (TypeError, ValueError, IndexError, KeyError): continue return sorted(out, key=lambda item: item.ts_ms) rows = self._get_json( legacy.MEXC_BASE, "/api/v3/klines", {"symbol": ticker.market_id, "interval": "1d", "limit": min(days + 8, 1000)}, timeout=15, ) return self._parse_binance_klines(rows if isinstance(rows, list) else [])
def _candles_kraken(self, ticker, days): data = self._get_json(legacy.KRAKEN_BASE, "/0/public/OHLC", {"pair": ticker.market_id, "interval": 1440}, timeout=15) if not isinstance(data, dict) or data.get("error"): return [] rows = [] for key, value in (data.get("result") or {}).items(): if key != "last": rows = value break out = [] cutoff = int((time.time() - (days + 8) * 86400) * 1000) for row in rows or []: try: ts = int(row[0]) * 1000 if ts >= cutoff: out.append(DailyCandle(ts, float(row[1]), float(row[2]), float(row[3]), float(row[4]))) except (TypeError, ValueError, IndexError): continue return sorted(out, key=lambda item: item.ts_ms)
def _candles_upbit(self, ticker, days): rows = self._get_json( legacy.UPBIT_BASE, "/v1/candles/days", {"market": ticker.market_id, "count": min(days + 8, 200)}, timeout=15, ) if not isinstance(rows, list): return [] divisor = self._upbit_krw_per_usdt() if ticker.quote == "KRW" else 1.0 out = [] for row in rows: try: ts = int(datetime.fromisoformat(row["candle_date_time_utc"]).replace(tzinfo=timezone.utc).timestamp() * 1000) out.append(DailyCandle( ts, float(row["opening_price"]) / divisor, float(row["high_price"]) / divisor, float(row["low_price"]) / divisor, float(row["trade_price"]) / divisor, )) except (TypeError, ValueError, KeyError): continue return sorted(out, key=lambda item: item.ts_ms)
class MarketMoveMonitor(BaseMonitor): """Broad coin price move monitor using the highest-volume public exchange market."""
monitor_type = "market_move"
def __init__(self, store): super().__init__(store) self.config = self._load_config() self.enabled = bool(self.config.get("enabled", True)) self.interval = int(self.config.get("interval_sec", 300)) self.threshold_pct = float(self.config.get("threshold_pct", 30.0)) self._stop_event = threading.Event() self._thread = None self._lock = threading.RLock() self.snapshots = {} self.stats = {"loops": 0, "alerts": 0, "notify_fails": 0, "api_fails": 0, "markets": 0, "missing": 0} self._failure_counts = {} self._health_alert_at = {} self.client = PublicMarketDataClient(self.log, self.config) self.pusher = legacy.WeWorkBotPusher(legacy.WEWORK_BOT_WEBHOOK) self._register_monitors()
def start(self): if not self.enabled: self.log("全市场涨跌监控已禁用") return if self._thread and self._thread.is_alive(): return self._stop_event.clear() self._thread = threading.Thread(target=self._run_loop, name="market-move-worker", daemon=True) self._thread.start()
def stop(self): self._stop_event.set() if self._thread and self._thread.is_alive(): self._thread.join(timeout=5)
def get_config(self): with self._lock: return copy.deepcopy(self.config)
def update_config(self, config): cfg = apply_env_overrides(normalize_config(config)) with self._lock: self.config = cfg self.enabled = bool(cfg.get("enabled", True)) self.interval = int(cfg.get("interval_sec", 300)) self.threshold_pct = float(cfg.get("threshold_pct", 30.0)) self.client.update_config(cfg) self.store.set_kv(CONFIG_KEY, cfg) self._register_monitors() self.log("全市场涨跌监控配置已更新") return self.get_config()
def _load_config(self): stored = self.store.get_kv(CONFIG_KEY, {}) return apply_env_overrides(normalize_config(stored))
def _register_monitors(self): with self._lock: cfg = copy.deepcopy(self.config) self.store.upsert_monitor( SERVICE_ID, self.monitor_type, "全市场币种日/月涨跌监控", enabled=cfg.get("enabled", True), schedule_seconds=int(cfg.get("interval_sec", 300)), metadata={ "threshold_pct": cfg.get("threshold_pct", 30.0), "lookback_days": cfg.get("lookback_days", 30), "exchanges": cfg.get("exchanges", []), }, ) for coin in cfg.get("coins", []): symbol = normalize_asset(coin.get("symbol")) if not symbol: continue self.store.upsert_monitor( coin_monitor_id(symbol), "market_move_coin", f"{coin.get('name') or symbol} ({symbol}) 日/月涨跌", enabled=cfg.get("enabled", True), schedule_seconds=int(cfg.get("interval_sec", 300)), metadata={"symbol": symbol, "name": coin.get("name") or symbol}, )
def _run_loop(self): self.log("全市场日/月涨跌监控 worker 已启动") while not self._stop_event.is_set(): interval = self.interval try: interval = self.run_once() except Exception as exc: self._record_failure(SERVICE_ID, f"主循环异常: {exc}") self._stop_event.wait(interval)
def run_once(self): with self._lock: cfg = copy.deepcopy(self.config) interval = int(cfg.get("interval_sec", 300)) next_run_at = utc_after_iso(interval) self._register_monitors()
if self.store.is_monitor_paused(SERVICE_ID): self.store.mark_paused(SERVICE_ID) return interval self.store.mark_started(SERVICE_ID)
coins = cfg.get("coins", []) active_symbols = [ normalize_asset(coin.get("symbol")) for coin in coins if not self.store.is_monitor_paused(coin_monitor_id(coin.get("symbol"))) ] if not active_symbols: self._record_success(SERVICE_ID, {"status": "所有币种均已暂停", "stats": copy.deepcopy(self.stats)}, next_run_at) return interval
candidates = self.client.candidates(active_symbols) by_asset = {} for candidate in candidates: current = by_asset.get(candidate.asset) if current is None or candidate.quote_volume_usd > current.quote_volume_usd: by_asset[candidate.asset] = candidate self.stats["markets"] = len(candidates)
found = 0 missing = 0 alerts = 0 for coin in coins: symbol = normalize_asset(coin.get("symbol")) if not symbol: continue monitor_id = coin_monitor_id(symbol) if self.store.is_monitor_paused(monitor_id): self.store.mark_paused(monitor_id) continue self.store.mark_started(monitor_id) ticker = by_asset.get(symbol) if not ticker: missing += 1 snapshot = { "symbol": symbol, "name": coin.get("name") or symbol, "status": "unavailable", "message": f"{symbol} 未在启用交易所找到可用 USDT/USD 行情", "updated_at": utc_now_iso(), } self.snapshots[symbol] = snapshot self._record_success(monitor_id, value=snapshot, next_run_at=next_run_at) continue found += 1 candles = self.client.candles(ticker, int(cfg.get("lookback_days", 30)) + 8) snapshot = self._snapshot(coin, ticker, candles, cfg) self.snapshots[symbol] = snapshot alerts += self._handle_snapshot_alerts(snapshot, cfg) self._record_success( monitor_id, value=snapshot, next_run_at=next_run_at, metadata={ "symbol": symbol, "exchange": ticker.exchange, "market_type": ticker.market_type, "market_id": ticker.market_id, "quote_volume_usd": ticker.quote_volume_usd, }, )
self.stats["loops"] += 1 self.stats["missing"] = missing if found == 0: self._record_failure(SERVICE_ID, "所有币种均未找到可用公开行情") else: self._record_success( SERVICE_ID, value={ "status": "监控中", "found": found, "missing": missing, "coins": len(coins), "alerts_this_loop": alerts, "stats": copy.deepcopy(self.stats), "updated_at": utc_now_iso(), }, next_run_at=next_run_at, ) return interval
def _snapshot(self, coin, ticker, candles, cfg): lookback_days = int(cfg.get("lookback_days", 30)) day_ref = ticker.open_24h or self._reference_close(candles, 1) month_ref = self._reference_close(candles, lookback_days) changes = { "24h": { "label": "24小时", "reference_price": day_ref, "change_pct": pct_change(ticker.price, day_ref), }, f"{lookback_days}d": { "label": f"{lookback_days}天", "reference_price": month_ref, "change_pct": pct_change(ticker.price, month_ref), }, } return { "symbol": normalize_asset(coin.get("symbol")), "name": coin.get("name") or normalize_asset(coin.get("symbol")), "price": ticker.price, "exchange": ticker.exchange, "exchange_key": ticker.exchange_key, "market_type": ticker.market_type, "market_id": ticker.market_id, "quote": ticker.quote, "quote_volume_usd": ticker.quote_volume_usd, "changes": changes, "candle_count": len(candles or []), "updated_at": utc_now_iso(), }
def _reference_close(self, candles, days): if not candles: return None target = int((time.time() - days * 86400) * 1000) older = [candle for candle in candles if candle.ts_ms <= target] if older: return older[-1].close return candles[0].close
def _handle_snapshot_alerts(self, snapshot, cfg): threshold = float(cfg.get("threshold_pct", 30.0)) reset_threshold = threshold * float(cfg.get("reset_ratio", 0.8)) state = self.store.get_kv(ALERT_STATE_KEY, {}) sent = 0 changed = False now = time.time()
for window, change_info in snapshot.get("changes", {}).items(): change_pct = change_info.get("change_pct") key = f"{snapshot['symbol']}:{window}" if change_pct is None: continue if abs(change_pct) >= threshold: direction = "涨" if change_pct > 0 else "跌" previous = state.get(key) or {} if previous.get("direction") != direction or not previous.get("active"): delivered = self._send_move_alert(snapshot, window, change_info, direction, threshold) sent += 1 self.stats["alerts"] += 1 if not delivered: self.stats["notify_fails"] += 1 state[key] = { "active": True, "direction": direction, "change_pct": change_pct, "last_seen_at": now, "last_alert_at": previous.get("last_alert_at") or now, } changed = True elif abs(change_pct) <= reset_threshold and key in state: state.pop(key, None) changed = True if changed: self.store.set_kv(ALERT_STATE_KEY, state) return sent
def _send_move_alert(self, snapshot, window, change_info, direction, threshold): title = f"{snapshot['symbol']} {change_info.get('label') or window}涨跌超过 {threshold:g}%" text = ( "币种价格异动\n\n" f"币种:{snapshot.get('name')} ({snapshot.get('symbol')})\n" f"方向:{direction}\n" f"周期:{change_info.get('label') or window}\n" f"涨跌幅:{format_pct(change_info.get('change_pct'))}\n" f"当前价格:{fmt_price(snapshot.get('price'))}\n" f"参考价格:{fmt_price(change_info.get('reference_price'))}\n" f"数据源:{snapshot.get('exchange')} {market_type_label(snapshot.get('market_type'))} {snapshot.get('market_id')}\n" f"24h 成交额:{fmt_usd(snapshot.get('quote_volume_usd'))}\n" f"检查时间:{legacy.get_beijing_now().strftime('%Y-%m-%d %H:%M:%S')}" ) delivered = self.pusher.send_text(text) self.store.add_alert( monitor_id=coin_monitor_id(snapshot.get("symbol")), text=text, category="market_move", title=title, direction=direction, delivered=delivered, error=None if delivered else "notifier returned false", ) self.log(title, monitor_id=coin_monitor_id(snapshot.get("symbol"))) return delivered
def _record_success(self, monitor_id, value=None, next_run_at=None, metadata=None): self._failure_counts[monitor_id] = 0 self.store.mark_success(monitor_id, value=value, next_run_at=next_run_at, metadata=metadata)
def _record_failure(self, monitor_id, error): self._failure_counts[monitor_id] = self._failure_counts.get(monitor_id, 0) + 1 self.store.mark_failure(monitor_id, error) self.store.add_event(monitor_id, "error", str(error)) failures = self._failure_counts[monitor_id] last_alert = self._health_alert_at.get(monitor_id, 0) if failures >= 3 and time.time() - last_alert >= HEALTH_ALERT_COOLDOWN_SEC: text = ( "全市场涨跌监控异常\n\n" f"监控项:{monitor_id}\n" f"连续失败:{failures} 次\n" f"错误:{error}" ) delivered = self.pusher.send_text(text) self.store.add_alert( monitor_id=monitor_id, text=text, category="health", title="全市场涨跌监控异常", direction="关注", delivered=delivered, error=None if delivered else "notifier returned false", ) self._health_alert_at[monitor_id] = time.time()
def log(self, message, monitor_id=SERVICE_ID, level="info"): print(f"[{legacy.get_beijing_now().strftime('%H:%M:%S')}] {message}") self.store.add_event(monitor_id, level, str(message))README.md+11
app/core/platform.py+16
app/main.py+16
app/monitors/market_move.pyAdded+1459