Spaces:
Paused
Paused
zt p commited on
Commit ·
d44feb9
1
Parent(s): 46b44fb
STRC 升级为完整币种(与BTC/TON同样的多维监控+历史自动校准),数据走OKX适配器,带休市属性; 新增OKXMarketAdapter; OKX标的合约不受ENABLE_FUTURES限制; 老配置自动迁移注入STRC
Browse files- README.md +7 -6
- coinpush.py +222 -26
README.md
CHANGED
|
@@ -33,10 +33,11 @@ pinned: false
|
|
| 33 |
- `BITGET_BASE` / `OKX_BASE`(可选,受限区域可指向可用代理)
|
| 34 |
|
| 35 |
## 多交易所扩展
|
| 36 |
-
-
|
| 37 |
-
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
- Bitget
|
| 41 |
-
-
|
|
|
|
| 42 |
若 Space 处于受限区域,需通过 `BITGET_BASE` / `OKX_BASE` 指向可用代理。
|
|
|
|
| 33 |
- `BITGET_BASE` / `OKX_BASE`(可选,受限区域可指向可用代理)
|
| 34 |
|
| 35 |
## 多交易所扩展
|
| 36 |
+
- 监控币种:BTC、TON(Binance)、STRC(OKX `STRC-USDT-SWAP`)。三者均走相同的多维监控 + 历史自动校准。
|
| 37 |
+
- STRC 作为完整币种处理(与 BTC/TON 一样:快速涨跌、突破、成交量、振幅、盘口、均线、RSI、资金费率、持仓量),
|
| 38 |
+
数据来源走 OKX(交易量更大),并多一个「休市」属性:价格长时间不变即判定休市,期间不推送任何提醒。
|
| 39 |
+
- OKX 标的的合约信息(资金费率/持仓量)不受 `ENABLE_FUTURES`(仅针对币安 US 限制)约束。
|
| 40 |
+
- 跨所差价提醒:BTC、TON/GRAM、STRC 在 Binance / Bitget / OKX 之间的价差(Binance 仍叫 TON,Bitget/OKX 已改名 GRAM;STRC 用 Bitget 现货 vs OKX 永续对比)。
|
| 41 |
+
- OKX GRAM 永续合约(`GRAM-USDT-SWAP`)关键信息:合约价异动、资金费率、持仓量变化。
|
| 42 |
+
- 以上均可在页面「多交易所设置」与各币种页开关、调参。Bitget/OKX 对部分地区有访问限制,
|
| 43 |
若 Space 处于受限区域,需通过 `BITGET_BASE` / `OKX_BASE` 指向可用代理。
|
coinpush.py
CHANGED
|
@@ -78,6 +78,12 @@ def _btc_defaults():
|
|
| 78 |
return {
|
| 79 |
"symbol": "BTCUSDT",
|
| 80 |
"futures_symbol": "BTCUSDT",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
# 默认关闭合约监控:币安合约接口(/fapi)与强平 websocket 对部分地区(如US)
|
| 82 |
# 返回 451,而 HuggingFace Space 运行在 US 区域。现货数据走 data-api.binance.vision
|
| 83 |
# 不受限制。如自带可访问合约接口的代理,可在页面重新开启。
|
|
@@ -156,10 +162,47 @@ def _ton_defaults():
|
|
| 156 |
return d
|
| 157 |
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
DEFAULT_CONFIG = {
|
| 160 |
"coins": {
|
| 161 |
"BTC": _btc_defaults(),
|
| 162 |
"TON": _ton_defaults(),
|
|
|
|
| 163 |
},
|
| 164 |
"global": {
|
| 165 |
"poll_interval_sec": 30,
|
|
@@ -187,7 +230,7 @@ DEFAULT_CONFIG = {
|
|
| 187 |
{"name": "STRC", "binance": "", "bitget": "RSTRCUSDT", "okx": "STRC-USDT-SWAP"},
|
| 188 |
],
|
| 189 |
},
|
| 190 |
-
# OKX 永续合约关键信息(
|
| 191 |
"okx_contracts": [
|
| 192 |
{
|
| 193 |
"name": "GRAM", "inst_id": "GRAM-USDT-SWAP", "enable": True,
|
|
@@ -199,16 +242,6 @@ DEFAULT_CONFIG = {
|
|
| 199 |
"market_close_aware": False, # 普通合约 7x24 交易
|
| 200 |
"static_secs": 600,
|
| 201 |
},
|
| 202 |
-
{
|
| 203 |
-
"name": "STRC", "inst_id": "STRC-USDT-SWAP", "enable": True,
|
| 204 |
-
"price_change_pct": 1.0,
|
| 205 |
-
"funding_high": 0.05,
|
| 206 |
-
"funding_neg": -0.05,
|
| 207 |
-
"oi_change_pct": 5.0,
|
| 208 |
-
"amp_24h_pct": 3.0,
|
| 209 |
-
"market_close_aware": True, # 股票类合约,休市价格不变时不提醒
|
| 210 |
-
"static_secs": 600, # 多久不变判定为休市
|
| 211 |
-
},
|
| 212 |
],
|
| 213 |
},
|
| 214 |
}
|
|
@@ -285,6 +318,10 @@ def _normalize_exchanges(ex):
|
|
| 285 |
ex["okx_contracts"] = contracts
|
| 286 |
ex.pop("okx_gram_swap", None)
|
| 287 |
ex.pop("strc", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
return ex
|
| 289 |
|
| 290 |
|
|
@@ -305,6 +342,9 @@ def load_config():
|
|
| 305 |
merged_coins[name] = _deep_merge(template, coin_cfg)
|
| 306 |
if merged_coins:
|
| 307 |
cfg["coins"] = merged_coins
|
|
|
|
|
|
|
|
|
|
| 308 |
# exchanges:跨所/STRC/OKX 合约配置,缺失字段以默认补全
|
| 309 |
cfg["exchanges"] = _deep_merge(cfg["exchanges"], saved.get("exchanges", {}))
|
| 310 |
cfg["exchanges"] = _normalize_exchanges(cfg["exchanges"])
|
|
@@ -471,6 +511,10 @@ class BinanceAPI:
|
|
| 471 |
def open_interest(self, symbol):
|
| 472 |
return self._get(FAPI_BASE, "/fapi/v1/openInterest", {"symbol": symbol})
|
| 473 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
|
| 475 |
# --- 6b. Bitget 行情接口(现货 + STRC 股票代币)---
|
| 476 |
class BitgetAPI:
|
|
@@ -627,6 +671,109 @@ class OKXAPI:
|
|
| 627 |
return None
|
| 628 |
|
| 629 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 630 |
# --- 7. 实时强平监控(websocket,可选)---
|
| 631 |
class LiquidationTracker:
|
| 632 |
"""
|
|
@@ -869,10 +1016,10 @@ def calibrate_thresholds(api, coin_cfg, logger=print, sensitivity=1.0):
|
|
| 869 |
out["liq_5m_usdt"] = round(max(avg5 * 0.5, 10000))
|
| 870 |
out["liq_severe_usdt"] = round(out["liq_5m_usdt"] * 4)
|
| 871 |
|
| 872 |
-
# 7) 资金费率:历史费率分位(
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
if fr:
|
| 877 |
try:
|
| 878 |
rates = [float(x["fundingRate"]) * 100 for x in fr]
|
|
@@ -897,17 +1044,19 @@ class CoinEvaluator:
|
|
| 897 |
WINDOW_BACK = {"1m": 2, "5m": 6, "15m": 16, "1h": 61}
|
| 898 |
WINDOW_CN = {"1m": "1分钟", "5m": "5分钟", "15m": "15分钟", "1h": "1小时"}
|
| 899 |
|
| 900 |
-
def __init__(self, name, api, liq_tracker, logger):
|
| 901 |
self.name = name
|
| 902 |
self.api = api
|
| 903 |
self.liq = liq_tracker
|
| 904 |
self.logger = logger
|
|
|
|
| 905 |
# 状态
|
| 906 |
self.break_24h_since = {} # 'high'/'low' -> ts
|
| 907 |
self.break_7d_alerted = {}
|
| 908 |
self.prev_walls = {} # 'bid'/'ask' -> notional
|
| 909 |
self.oi_history = deque(maxlen=2000) # (ts, oi)
|
| 910 |
self.last_price = None
|
|
|
|
| 911 |
self.last_funding_pct = None
|
| 912 |
self.last_rsi = None
|
| 913 |
|
|
@@ -929,6 +1078,21 @@ class CoinEvaluator:
|
|
| 929 |
high24 = float(ticker.get("highPrice") or 0)
|
| 930 |
low24 = float(ticker.get("lowPrice") or 0)
|
| 931 |
qvol24 = float(ticker.get("quoteVolume") or 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 932 |
self.last_price = price
|
| 933 |
|
| 934 |
def add(category, key, direction, headline, body):
|
|
@@ -1018,8 +1182,8 @@ class CoinEvaluator:
|
|
| 1018 |
# 11) RSI
|
| 1019 |
self._check_rsi(cfg, sym, head, add)
|
| 1020 |
|
| 1021 |
-
# 12) 合约类
|
| 1022 |
-
if
|
| 1023 |
self._check_futures(cfg, head, add)
|
| 1024 |
|
| 1025 |
snapshot = {
|
|
@@ -1484,6 +1648,7 @@ class CryptoMonitor:
|
|
| 1484 |
self.api = BinanceAPI(self.log)
|
| 1485 |
self.bitget = BitgetAPI(self.log)
|
| 1486 |
self.okx = OKXAPI(self.log)
|
|
|
|
| 1487 |
self.pusher = WeWorkBotPusher(WEWORK_BOT_WEBHOOK)
|
| 1488 |
self.alert_mgr = AlertManager(self.pusher, self.log, self.stats)
|
| 1489 |
self.liq = LiquidationTracker(self._futures_symbols(), self.log)
|
|
@@ -1505,20 +1670,31 @@ class CryptoMonitor:
|
|
| 1505 |
print(entry)
|
| 1506 |
self.logs.appendleft(entry)
|
| 1507 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1508 |
def _futures_symbols(self):
|
|
|
|
| 1509 |
if not FUTURES_ENABLED:
|
| 1510 |
return []
|
| 1511 |
return [c["futures_symbol"] for c in self.config["coins"].values()
|
| 1512 |
-
if c.get("enable_futures")]
|
| 1513 |
|
| 1514 |
def _rebuild_evaluators(self):
|
| 1515 |
with self.lock:
|
| 1516 |
for name in list(self.evaluators.keys()):
|
| 1517 |
if name not in self.config["coins"]:
|
| 1518 |
self.evaluators.pop(name, None)
|
| 1519 |
-
for name in self.config["coins"]:
|
| 1520 |
-
|
| 1521 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1522 |
|
| 1523 |
def update_config(self, new_cfg):
|
| 1524 |
"""由前端调用:保存并热更新配置"""
|
|
@@ -1536,7 +1712,7 @@ class CryptoMonitor:
|
|
| 1536 |
scale = float(cfg["global"].get("alert_sensitivity", 1.0))
|
| 1537 |
for name, coin in cfg["coins"].items():
|
| 1538 |
try:
|
| 1539 |
-
overrides = calibrate_thresholds(self.
|
| 1540 |
cfg["coins"][name] = _deep_merge(coin, overrides)
|
| 1541 |
except Exception as e:
|
| 1542 |
self.log(f"⚠️ {name} 校准失败: {e}")
|
|
@@ -1857,10 +2033,17 @@ def render_config_editor(monitor):
|
|
| 1857 |
for i, name in enumerate(coin_names):
|
| 1858 |
with tabs[i]:
|
| 1859 |
coin = cfg["coins"][name]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1860 |
cc1, cc2, cc3 = st.columns(3)
|
| 1861 |
with cc1:
|
|
|
|
| 1862 |
coin["symbol"] = st.text_input(
|
| 1863 |
-
|
| 1864 |
with cc2:
|
| 1865 |
coin["futures_symbol"] = st.text_input(
|
| 1866 |
"合约交易对", value=coin["futures_symbol"], key=f"{name}_fsym")
|
|
@@ -1868,12 +2051,25 @@ def render_config_editor(monitor):
|
|
| 1868 |
coin["enable_futures"] = st.checkbox(
|
| 1869 |
"启用合约监控", value=coin.get("enable_futures", False), key=f"{name}_futenable")
|
| 1870 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1871 |
cal_col, _ = st.columns([1, 3])
|
| 1872 |
if cal_col.button("📈 历史自动校准", key=f"cal_{name}",
|
| 1873 |
help="拉取该币种历史行情,自动推算更贴合的阈值"):
|
| 1874 |
with st.spinner(f"正在根据历史行情校准 {name} ..."):
|
| 1875 |
scale = float(cfg["global"].get("alert_sensitivity", 1.0))
|
| 1876 |
-
overrides = calibrate_thresholds(monitor.
|
| 1877 |
cfg["coins"][name] = _deep_merge(coin, overrides)
|
| 1878 |
monitor.update_config(cfg)
|
| 1879 |
st.success(f"{name} 已根据历史校准并保存")
|
|
@@ -1933,7 +2129,7 @@ def render_config_editor(monitor):
|
|
| 1933 |
template["enable_futures"] = False
|
| 1934 |
with st.spinner(f"正在根据历史行情自动校准 {new_name} 的默认值..."):
|
| 1935 |
scale = float(cfg["global"].get("alert_sensitivity", 1.0))
|
| 1936 |
-
overrides = calibrate_thresholds(monitor.
|
| 1937 |
template = _deep_merge(template, overrides)
|
| 1938 |
cfg["coins"][new_name] = template
|
| 1939 |
monitor.update_config(cfg)
|
|
|
|
| 78 |
return {
|
| 79 |
"symbol": "BTCUSDT",
|
| 80 |
"futures_symbol": "BTCUSDT",
|
| 81 |
+
# 数据来源:binance(默认)或 okx。okx 标的走 OKXMarketAdapter,
|
| 82 |
+
# 合约信息(资金费率/持仓量)不受 FUTURES_ENABLED(仅针对币安US限制)约束。
|
| 83 |
+
"data_source": "binance",
|
| 84 |
+
# 休市属性:股票类标的(如 STRC)休市时价格长时间不变,期间不推送任何提醒
|
| 85 |
+
"market_close": False,
|
| 86 |
+
"market_close_static_secs": 600,
|
| 87 |
# 默认关闭合约监控:币安合约接口(/fapi)与强平 websocket 对部分地区(如US)
|
| 88 |
# 返回 451,而 HuggingFace Space 运行在 US 区域。现货数据走 data-api.binance.vision
|
| 89 |
# 不受限制。如自带可访问合约接口的代理,可在页面重新开启。
|
|
|
|
| 162 |
return d
|
| 163 |
|
| 164 |
|
| 165 |
+
def _strc_defaults():
|
| 166 |
+
"""STRC:与 BTC/TON 同样的多维监控 + 历史自动校准,数据走 OKX 永续,
|
| 167 |
+
并带「休市」属性(股票类,休市价格不变时不提醒)。阈值会被历史校准刷新。"""
|
| 168 |
+
d = _btc_defaults()
|
| 169 |
+
d.update({
|
| 170 |
+
"symbol": "STRC-USDT-SWAP",
|
| 171 |
+
"futures_symbol": "STRC-USDT-SWAP",
|
| 172 |
+
"data_source": "okx",
|
| 173 |
+
"enable_futures": True, # OKX 合约不受 FUTURES_ENABLED 限制
|
| 174 |
+
"market_close": True,
|
| 175 |
+
"market_close_static_secs": 600,
|
| 176 |
+
"price_change": {
|
| 177 |
+
"1m": 0.50,
|
| 178 |
+
"5m": 1.00,
|
| 179 |
+
"15m": 1.80,
|
| 180 |
+
"1h": 3.00,
|
| 181 |
+
},
|
| 182 |
+
"break_24h_pct": 0.3, "break_24h_hold_sec": 120,
|
| 183 |
+
"break_7d_pct": 0.8,
|
| 184 |
+
"vol_anomaly_mult": 3.0, "vol_severe_mult": 6.0,
|
| 185 |
+
"amp_5m": 1.5, "amp_15m": 2.5, "amp_1h": 4.0,
|
| 186 |
+
"big_trade_usdt": 50_000, "cum_trade_5m_usdt": 300_000,
|
| 187 |
+
"spread_pct": 0.05, "spread_severe_pct": 0.15,
|
| 188 |
+
"imbalance_depth_pct": 1.0, "imbalance_ratio": 3.0,
|
| 189 |
+
"wall_depth_pct": 1.5, "wall_mult": 3.5, "wall_vanish_pct": 65.0,
|
| 190 |
+
"wall_min_usdt": 100_000, "wall_dominance": 1.8,
|
| 191 |
+
"ma_deviation_pct": 3.5,
|
| 192 |
+
"consecutive_klines": 5,
|
| 193 |
+
"rsi_high": 78.0, "rsi_low": 22.0,
|
| 194 |
+
"funding_high": 0.05, "funding_hot": 0.12, "funding_neg": -0.05,
|
| 195 |
+
"oi_15m": 3.0, "oi_1h": 6.0, "oi_4h": 12.0,
|
| 196 |
+
"liq_5m_usdt": 200_000, "liq_severe_usdt": 800_000,
|
| 197 |
+
})
|
| 198 |
+
return d
|
| 199 |
+
|
| 200 |
+
|
| 201 |
DEFAULT_CONFIG = {
|
| 202 |
"coins": {
|
| 203 |
"BTC": _btc_defaults(),
|
| 204 |
"TON": _ton_defaults(),
|
| 205 |
+
"STRC": _strc_defaults(),
|
| 206 |
},
|
| 207 |
"global": {
|
| 208 |
"poll_interval_sec": 30,
|
|
|
|
| 230 |
{"name": "STRC", "binance": "", "bitget": "RSTRCUSDT", "okx": "STRC-USDT-SWAP"},
|
| 231 |
],
|
| 232 |
},
|
| 233 |
+
# OKX 永续合约关键信息(GRAM 等普通合约;STRC 已作为币种走完整监控)
|
| 234 |
"okx_contracts": [
|
| 235 |
{
|
| 236 |
"name": "GRAM", "inst_id": "GRAM-USDT-SWAP", "enable": True,
|
|
|
|
| 242 |
"market_close_aware": False, # 普通合约 7x24 交易
|
| 243 |
"static_secs": 600,
|
| 244 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
],
|
| 246 |
},
|
| 247 |
}
|
|
|
|
| 318 |
ex["okx_contracts"] = contracts
|
| 319 |
ex.pop("okx_gram_swap", None)
|
| 320 |
ex.pop("strc", None)
|
| 321 |
+
# STRC 现已作为币种(coins)走完整监控,从 okx_contracts 移除以免重复
|
| 322 |
+
ex["okx_contracts"] = [c for c in ex["okx_contracts"]
|
| 323 |
+
if c.get("name") != "STRC"
|
| 324 |
+
and c.get("inst_id") != "STRC-USDT-SWAP"]
|
| 325 |
return ex
|
| 326 |
|
| 327 |
|
|
|
|
| 342 |
merged_coins[name] = _deep_merge(template, coin_cfg)
|
| 343 |
if merged_coins:
|
| 344 |
cfg["coins"] = merged_coins
|
| 345 |
+
# STRC 现作为币种处理:老配置缺失时自动注入(OKX 数据 + 休市属性)
|
| 346 |
+
if "STRC" not in cfg["coins"]:
|
| 347 |
+
cfg["coins"]["STRC"] = _strc_defaults()
|
| 348 |
# exchanges:跨所/STRC/OKX 合约配置,缺失字段以默认补全
|
| 349 |
cfg["exchanges"] = _deep_merge(cfg["exchanges"], saved.get("exchanges", {}))
|
| 350 |
cfg["exchanges"] = _normalize_exchanges(cfg["exchanges"])
|
|
|
|
| 511 |
def open_interest(self, symbol):
|
| 512 |
return self._get(FAPI_BASE, "/fapi/v1/openInterest", {"symbol": symbol})
|
| 513 |
|
| 514 |
+
def funding_rate_history(self, symbol, limit=500):
|
| 515 |
+
return self._get(FAPI_BASE, "/fapi/v1/fundingRate",
|
| 516 |
+
{"symbol": symbol, "limit": limit})
|
| 517 |
+
|
| 518 |
|
| 519 |
# --- 6b. Bitget 行情接口(现货 + STRC 股票代币)---
|
| 520 |
class BitgetAPI:
|
|
|
|
| 671 |
return None
|
| 672 |
|
| 673 |
|
| 674 |
+
# --- 6d. OKX → Binance 接口适配器 ---
|
| 675 |
+
class OKXMarketAdapter:
|
| 676 |
+
"""把 OKX v5 行情包装成与 BinanceAPI 兼容的接口,使 CoinEvaluator / calibrate_thresholds
|
| 677 |
+
可无改动地像监控 BTC/TON 一样监控 OKX 标的(如 STRC-USDT-SWAP 股票类合约)。"""
|
| 678 |
+
BAR = {"1m": "1m", "5m": "5m", "15m": "15m", "1h": "1H", "1d": "1D"}
|
| 679 |
+
|
| 680 |
+
def __init__(self, okx_api, logger):
|
| 681 |
+
self.okx = okx_api
|
| 682 |
+
self.logger = logger
|
| 683 |
+
|
| 684 |
+
@staticmethod
|
| 685 |
+
def _is_swap(inst):
|
| 686 |
+
return inst.endswith("-SWAP")
|
| 687 |
+
|
| 688 |
+
@staticmethod
|
| 689 |
+
def _to_kline(r):
|
| 690 |
+
# OKX: [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]
|
| 691 |
+
# Binance: [openTime, open, high, low, close, vol, closeTime, quoteAssetVolume, ...]
|
| 692 |
+
ts = int(r[0])
|
| 693 |
+
return [ts, r[1], r[2], r[3], r[4], r[5], ts, r[7], 0, 0, 0, 0]
|
| 694 |
+
|
| 695 |
+
def ticker_24h(self, inst):
|
| 696 |
+
t = self.okx.ticker(inst)
|
| 697 |
+
if not t:
|
| 698 |
+
return None
|
| 699 |
+
qvol = t["qvol"] * t["price"] if self._is_swap(inst) else t["qvol"]
|
| 700 |
+
return {"lastPrice": t["price"], "highPrice": t["high24"],
|
| 701 |
+
"lowPrice": t["low24"], "quoteVolume": qvol}
|
| 702 |
+
|
| 703 |
+
def klines(self, inst, interval, limit):
|
| 704 |
+
bar = self.BAR.get(interval, interval)
|
| 705 |
+
data = self.okx._get("/api/v5/market/candles",
|
| 706 |
+
{"instId": inst, "bar": bar, "limit": str(min(int(limit), 300))})
|
| 707 |
+
if not data:
|
| 708 |
+
return None
|
| 709 |
+
rows = sorted(data, key=lambda r: int(r[0]))
|
| 710 |
+
return [self._to_kline(r) for r in rows]
|
| 711 |
+
|
| 712 |
+
def klines_history(self, inst, interval, days, max_calls=40):
|
| 713 |
+
bar = self.BAR.get(interval, interval)
|
| 714 |
+
start_ms = int((time.time() - days * 86400) * 1000)
|
| 715 |
+
collected, after, calls = {}, None, 0
|
| 716 |
+
while calls < max_calls:
|
| 717 |
+
params = {"instId": inst, "bar": bar, "limit": "300"}
|
| 718 |
+
endpoint = "/api/v5/market/candles"
|
| 719 |
+
if after is not None:
|
| 720 |
+
params["after"] = str(after)
|
| 721 |
+
endpoint = "/api/v5/market/history-candles"
|
| 722 |
+
data = self.okx._get(endpoint, params)
|
| 723 |
+
calls += 1
|
| 724 |
+
if not data:
|
| 725 |
+
break
|
| 726 |
+
for r in data:
|
| 727 |
+
collected[int(r[0])] = r
|
| 728 |
+
oldest = min(int(r[0]) for r in data)
|
| 729 |
+
if oldest <= start_ms or len(data) < 300:
|
| 730 |
+
break
|
| 731 |
+
after = oldest
|
| 732 |
+
rows = [collected[ts] for ts in sorted(collected) if ts >= start_ms]
|
| 733 |
+
return [self._to_kline(r) for r in rows]
|
| 734 |
+
|
| 735 |
+
def depth(self, inst, limit=500):
|
| 736 |
+
data = self.okx._get("/api/v5/market/books",
|
| 737 |
+
{"instId": inst, "sz": str(min(int(limit), 400))})
|
| 738 |
+
if not data:
|
| 739 |
+
return None
|
| 740 |
+
d = data[0]
|
| 741 |
+
return {"bids": [[p, q] for p, q, *_ in d.get("bids", [])],
|
| 742 |
+
"asks": [[p, q] for p, q, *_ in d.get("asks", [])]}
|
| 743 |
+
|
| 744 |
+
def agg_trades(self, inst, limit=1000):
|
| 745 |
+
data = self.okx._get("/api/v5/market/trades",
|
| 746 |
+
{"instId": inst, "limit": str(min(int(limit), 500))})
|
| 747 |
+
if not data:
|
| 748 |
+
return None
|
| 749 |
+
out = []
|
| 750 |
+
for t in data:
|
| 751 |
+
try:
|
| 752 |
+
out.append({"p": t["px"], "q": t["sz"], "T": int(t["ts"])})
|
| 753 |
+
except (KeyError, ValueError, TypeError):
|
| 754 |
+
continue
|
| 755 |
+
return out
|
| 756 |
+
|
| 757 |
+
def premium_index(self, inst):
|
| 758 |
+
fr = self.okx.funding_rate(inst)
|
| 759 |
+
if not fr:
|
| 760 |
+
return None
|
| 761 |
+
return {"lastFundingRate": fr["rate_pct"] / 100.0}
|
| 762 |
+
|
| 763 |
+
def open_interest(self, inst):
|
| 764 |
+
oi = self.okx.open_interest(inst)
|
| 765 |
+
if not oi:
|
| 766 |
+
return None
|
| 767 |
+
return {"openInterest": oi["oi"]}
|
| 768 |
+
|
| 769 |
+
def funding_rate_history(self, inst, limit=100):
|
| 770 |
+
data = self.okx._get("/api/v5/public/funding-rate-history",
|
| 771 |
+
{"instId": inst, "limit": str(min(int(limit), 100))})
|
| 772 |
+
if not data:
|
| 773 |
+
return None
|
| 774 |
+
return [{"fundingRate": x["fundingRate"]} for x in data if "fundingRate" in x]
|
| 775 |
+
|
| 776 |
+
|
| 777 |
# --- 7. 实时强平监控(websocket,可选)---
|
| 778 |
class LiquidationTracker:
|
| 779 |
"""
|
|
|
|
| 1016 |
out["liq_5m_usdt"] = round(max(avg5 * 0.5, 10000))
|
| 1017 |
out["liq_severe_usdt"] = round(out["liq_5m_usdt"] * 4)
|
| 1018 |
|
| 1019 |
+
# 7) 资金费率:历史费率分位(合约启用时;OKX 标的不受 FUTURES_ENABLED 限制)
|
| 1020 |
+
_ds = coin_cfg.get("data_source", "binance")
|
| 1021 |
+
if coin_cfg.get("enable_futures") and (_ds == "okx" or FUTURES_ENABLED):
|
| 1022 |
+
fr = api.funding_rate_history(coin_cfg["futures_symbol"], 500)
|
| 1023 |
if fr:
|
| 1024 |
try:
|
| 1025 |
rates = [float(x["fundingRate"]) * 100 for x in fr]
|
|
|
|
| 1044 |
WINDOW_BACK = {"1m": 2, "5m": 6, "15m": 16, "1h": 61}
|
| 1045 |
WINDOW_CN = {"1m": "1分钟", "5m": "5分钟", "15m": "15分钟", "1h": "1小时"}
|
| 1046 |
|
| 1047 |
+
def __init__(self, name, api, liq_tracker, logger, data_source="binance"):
|
| 1048 |
self.name = name
|
| 1049 |
self.api = api
|
| 1050 |
self.liq = liq_tracker
|
| 1051 |
self.logger = logger
|
| 1052 |
+
self.data_source = data_source
|
| 1053 |
# 状态
|
| 1054 |
self.break_24h_since = {} # 'high'/'low' -> ts
|
| 1055 |
self.break_7d_alerted = {}
|
| 1056 |
self.prev_walls = {} # 'bid'/'ask' -> notional
|
| 1057 |
self.oi_history = deque(maxlen=2000) # (ts, oi)
|
| 1058 |
self.last_price = None
|
| 1059 |
+
self.last_price_change_ts = 0.0 # 价格最后变动时间(休市判定用)
|
| 1060 |
self.last_funding_pct = None
|
| 1061 |
self.last_rsi = None
|
| 1062 |
|
|
|
|
| 1078 |
high24 = float(ticker.get("highPrice") or 0)
|
| 1079 |
low24 = float(ticker.get("lowPrice") or 0)
|
| 1080 |
qvol24 = float(ticker.get("quoteVolume") or 0)
|
| 1081 |
+
|
| 1082 |
+
# 休市判定(股票类标的):价格长时间不变则视为休市,期间不推送任何提醒
|
| 1083 |
+
now_ts = time.time()
|
| 1084 |
+
if self.last_price is not None and price != self.last_price:
|
| 1085 |
+
self.last_price_change_ts = now_ts
|
| 1086 |
+
elif self.last_price_change_ts == 0.0:
|
| 1087 |
+
self.last_price_change_ts = now_ts
|
| 1088 |
+
snapshot = {"price": price, "high24": high24, "low24": low24,
|
| 1089 |
+
"rsi": self.last_rsi, "funding": self.last_funding_pct}
|
| 1090 |
+
if cfg.get("market_close"):
|
| 1091 |
+
static_secs = float(cfg.get("market_close_static_secs", 600))
|
| 1092 |
+
if (self.last_price is not None and price == self.last_price
|
| 1093 |
+
and now_ts - self.last_price_change_ts >= static_secs):
|
| 1094 |
+
self.last_price = price
|
| 1095 |
+
return alerts, snapshot # 休市中,跳过所有告警
|
| 1096 |
self.last_price = price
|
| 1097 |
|
| 1098 |
def add(category, key, direction, headline, body):
|
|
|
|
| 1182 |
# 11) RSI
|
| 1183 |
self._check_rsi(cfg, sym, head, add)
|
| 1184 |
|
| 1185 |
+
# 12) 合约类(OKX 标的不受 FUTURES_ENABLED 限制)
|
| 1186 |
+
if cfg.get("enable_futures") and (self.data_source == "okx" or FUTURES_ENABLED):
|
| 1187 |
self._check_futures(cfg, head, add)
|
| 1188 |
|
| 1189 |
snapshot = {
|
|
|
|
| 1648 |
self.api = BinanceAPI(self.log)
|
| 1649 |
self.bitget = BitgetAPI(self.log)
|
| 1650 |
self.okx = OKXAPI(self.log)
|
| 1651 |
+
self.okx_adapter = OKXMarketAdapter(self.okx, self.log)
|
| 1652 |
self.pusher = WeWorkBotPusher(WEWORK_BOT_WEBHOOK)
|
| 1653 |
self.alert_mgr = AlertManager(self.pusher, self.log, self.stats)
|
| 1654 |
self.liq = LiquidationTracker(self._futures_symbols(), self.log)
|
|
|
|
| 1670 |
print(entry)
|
| 1671 |
self.logs.appendleft(entry)
|
| 1672 |
|
| 1673 |
+
def _api_for(self, coin_cfg):
|
| 1674 |
+
"""按币种数据来源选择行情接口(binance / okx)"""
|
| 1675 |
+
if coin_cfg.get("data_source") == "okx":
|
| 1676 |
+
return self.okx_adapter
|
| 1677 |
+
return self.api
|
| 1678 |
+
|
| 1679 |
def _futures_symbols(self):
|
| 1680 |
+
# 仅币安来源且全局开启时才订阅币安强平流;OKX 标的不走该 websocket
|
| 1681 |
if not FUTURES_ENABLED:
|
| 1682 |
return []
|
| 1683 |
return [c["futures_symbol"] for c in self.config["coins"].values()
|
| 1684 |
+
if c.get("enable_futures") and c.get("data_source", "binance") == "binance"]
|
| 1685 |
|
| 1686 |
def _rebuild_evaluators(self):
|
| 1687 |
with self.lock:
|
| 1688 |
for name in list(self.evaluators.keys()):
|
| 1689 |
if name not in self.config["coins"]:
|
| 1690 |
self.evaluators.pop(name, None)
|
| 1691 |
+
for name, coin in self.config["coins"].items():
|
| 1692 |
+
ds = coin.get("data_source", "binance")
|
| 1693 |
+
ev = self.evaluators.get(name)
|
| 1694 |
+
# 数据来源变化时重建评估器
|
| 1695 |
+
if ev is None or getattr(ev, "data_source", "binance") != ds:
|
| 1696 |
+
self.evaluators[name] = CoinEvaluator(
|
| 1697 |
+
name, self._api_for(coin), self.liq, self.log, data_source=ds)
|
| 1698 |
|
| 1699 |
def update_config(self, new_cfg):
|
| 1700 |
"""由前端调用:保存并热更新配置"""
|
|
|
|
| 1712 |
scale = float(cfg["global"].get("alert_sensitivity", 1.0))
|
| 1713 |
for name, coin in cfg["coins"].items():
|
| 1714 |
try:
|
| 1715 |
+
overrides = calibrate_thresholds(self._api_for(coin), coin, self.log, scale)
|
| 1716 |
cfg["coins"][name] = _deep_merge(coin, overrides)
|
| 1717 |
except Exception as e:
|
| 1718 |
self.log(f"⚠️ {name} 校准失败: {e}")
|
|
|
|
| 2033 |
for i, name in enumerate(coin_names):
|
| 2034 |
with tabs[i]:
|
| 2035 |
coin = cfg["coins"][name]
|
| 2036 |
+
ds_label = st.radio(
|
| 2037 |
+
"数据来源", ["Binance", "OKX"],
|
| 2038 |
+
index=1 if coin.get("data_source") == "okx" else 0,
|
| 2039 |
+
horizontal=True, key=f"{name}_ds",
|
| 2040 |
+
help="OKX 标的(如 STRC-USDT-SWAP)合约信息不受 ENABLE_FUTURES 限制")
|
| 2041 |
+
coin["data_source"] = "okx" if ds_label == "OKX" else "binance"
|
| 2042 |
cc1, cc2, cc3 = st.columns(3)
|
| 2043 |
with cc1:
|
| 2044 |
+
sym_label = "OKX instId" if coin["data_source"] == "okx" else "现货交易对"
|
| 2045 |
coin["symbol"] = st.text_input(
|
| 2046 |
+
sym_label, value=coin["symbol"], key=f"{name}_symbol")
|
| 2047 |
with cc2:
|
| 2048 |
coin["futures_symbol"] = st.text_input(
|
| 2049 |
"合约交易对", value=coin["futures_symbol"], key=f"{name}_fsym")
|
|
|
|
| 2051 |
coin["enable_futures"] = st.checkbox(
|
| 2052 |
"启用合约监控", value=coin.get("enable_futures", False), key=f"{name}_futenable")
|
| 2053 |
|
| 2054 |
+
mc1, mc2 = st.columns([1, 2])
|
| 2055 |
+
with mc1:
|
| 2056 |
+
coin["market_close"] = st.checkbox(
|
| 2057 |
+
"股票类(含休市)", value=coin.get("market_close", False),
|
| 2058 |
+
key=f"{name}_mclose",
|
| 2059 |
+
help="价格长时间不变即判定休市,期间不推送任何提醒")
|
| 2060 |
+
with mc2:
|
| 2061 |
+
if coin["market_close"]:
|
| 2062 |
+
coin["market_close_static_secs"] = st.number_input(
|
| 2063 |
+
"判定休市的静止秒数", min_value=60, max_value=7200,
|
| 2064 |
+
value=int(coin.get("market_close_static_secs", 600)),
|
| 2065 |
+
step=60, key=f"{name}_mcsec")
|
| 2066 |
+
|
| 2067 |
cal_col, _ = st.columns([1, 3])
|
| 2068 |
if cal_col.button("📈 历史自动校准", key=f"cal_{name}",
|
| 2069 |
help="拉取该币种历史行情,自动推算更贴合的阈值"):
|
| 2070 |
with st.spinner(f"正在根据历史行情校准 {name} ..."):
|
| 2071 |
scale = float(cfg["global"].get("alert_sensitivity", 1.0))
|
| 2072 |
+
overrides = calibrate_thresholds(monitor._api_for(coin), coin, monitor.log, scale)
|
| 2073 |
cfg["coins"][name] = _deep_merge(coin, overrides)
|
| 2074 |
monitor.update_config(cfg)
|
| 2075 |
st.success(f"{name} 已根据历史校准并保存")
|
|
|
|
| 2129 |
template["enable_futures"] = False
|
| 2130 |
with st.spinner(f"正在根据历史行情自动校准 {new_name} 的默认值..."):
|
| 2131 |
scale = float(cfg["global"].get("alert_sensitivity", 1.0))
|
| 2132 |
+
overrides = calibrate_thresholds(monitor._api_for(template), template, monitor.log, scale)
|
| 2133 |
template = _deep_merge(template, overrides)
|
| 2134 |
cfg["coins"][new_name] = template
|
| 2135 |
monitor.update_config(cfg)
|