spot_ws_client.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:developer' as developer;
  4. import 'dart:math';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:web_socket_channel/web_socket_channel.dart';
  7. /// 现货 WS:`event=sub/unsub/req`;行情 `market_{symbol}_*`;用户 `spot_asset` / `spot_order`(需 uid)。
  8. class SpotWsClient {
  9. SpotWsClient({
  10. required String wsSpotUrl,
  11. String? uid,
  12. this.onPersistentFailure,
  13. }) : _wsUrl = wsSpotUrl,
  14. _uid = uid {
  15. _connect();
  16. }
  17. String _wsUrl;
  18. final String? _uid;
  19. final void Function()? onPersistentFailure;
  20. static const int _maxReconnectCount = 50;
  21. static const int _lowFreqReconnectSec = 120;
  22. static const int _failoverNotifyCount = 2;
  23. final _connStateCtrl = StreamController<SpotWsState>.broadcast();
  24. final _tickerCtrl = StreamController<Map<String, dynamic>>.broadcast();
  25. final _depthCtrl = StreamController<Map<String, dynamic>>.broadcast();
  26. final _tradeCtrl = StreamController<Map<String, dynamic>>.broadcast();
  27. final _klineCtrl = StreamController<Map<String, dynamic>>.broadcast();
  28. final _assetCtrl = StreamController<Map<String, dynamic>>.broadcast();
  29. final _orderCtrl = StreamController<Map<String, dynamic>>.broadcast();
  30. final _klineReqCompleters = <String, Completer<List<Map<String, dynamic>>>>{};
  31. SpotWsState _state = SpotWsState.disconnected;
  32. final _subscribedChannels = <String>{};
  33. int _spotAssetChannelHolds = 0; // spot_asset 页面 retain 计数
  34. int _spotOrderChannelHolds = 0; // spot_order
  35. int _reconnectCount = 0;
  36. int _spotWsRawLogCount = 0;
  37. int _spotWsDispatchTickerLogCount = 0;
  38. int _spotWsRawDepthLogCount = 0;
  39. int _spotWsParsedDepthLogCount = 0;
  40. WebSocketChannel? _channel;
  41. StreamSubscription? _channelSub;
  42. Timer? _reconnectTimer;
  43. Stream<SpotWsState> get connectionStream => _connStateCtrl.stream;
  44. Stream<Map<String, dynamic>> get tickerStream => _tickerCtrl.stream;
  45. Stream<Map<String, dynamic>> get depthStream => _depthCtrl.stream;
  46. Stream<Map<String, dynamic>> get tradeStream => _tradeCtrl.stream;
  47. Stream<Map<String, dynamic>> get klineStream => _klineCtrl.stream;
  48. Stream<Map<String, dynamic>> get assetStream => _assetCtrl.stream;
  49. Stream<Map<String, dynamic>> get orderStream => _orderCtrl.stream;
  50. SpotWsState get currentState => _state;
  51. void _connect() {
  52. _setState(SpotWsState.connecting);
  53. _connectReal();
  54. }
  55. void reconnectWithUrl(String url, {String? uid}) {
  56. _wsUrl = url;
  57. _channelSub?.cancel();
  58. _channel?.sink.close();
  59. _reconnectTimer?.cancel();
  60. _reconnectCount = 0;
  61. _connectReal();
  62. }
  63. void _connectReal() async {
  64. _setState(SpotWsState.connecting);
  65. try {
  66. final uid = _uid;
  67. final query = [
  68. 'clientType=flutter',
  69. if (uid != null && uid.isNotEmpty) 'uid=$uid',
  70. ].join('&');
  71. final uri = Uri.parse('$_wsUrl?$query');
  72. _channel = WebSocketChannel.connect(uri);
  73. await _channel!.ready;
  74. if (_connStateCtrl.isClosed) return;
  75. _setState(SpotWsState.connected);
  76. _reconnectCount = 0;
  77. if (!kReleaseMode) {
  78. debugPrint('[SpotWs] connected uri=$uri');
  79. developer.log('connected SpotWs uri=$uri', name: 'SpotWs');
  80. }
  81. _channelSub = _channel!.stream.listen(
  82. _onMessage,
  83. onError: (_) => _onDisconnect(),
  84. onDone: () => _onDisconnect(),
  85. );
  86. if (_subscribedChannels.isNotEmpty) {
  87. _sendSub(_subscribedChannels.toList());
  88. }
  89. } catch (_) {
  90. _onDisconnect();
  91. }
  92. }
  93. void _onDisconnect() {
  94. _channelSub?.cancel();
  95. _channel = null;
  96. if (_connStateCtrl.isClosed) return;
  97. if (!kReleaseMode) {
  98. developer.log('disconnect reconnectCount=$_reconnectCount',
  99. name: 'SpotWs');
  100. }
  101. _setState(SpotWsState.reconnecting);
  102. _reconnectCount++;
  103. if (_reconnectCount == _failoverNotifyCount) {
  104. try {
  105. onPersistentFailure?.call();
  106. } catch (_) {}
  107. }
  108. final delay = _reconnectCount > _maxReconnectCount
  109. ? _lowFreqReconnectSec
  110. : min(pow(2, _reconnectCount).toInt(), 30);
  111. _reconnectTimer?.cancel();
  112. _reconnectTimer = Timer(Duration(seconds: delay), _connectReal);
  113. }
  114. void _onMessage(dynamic raw) {
  115. if (raw is! String) return;
  116. final Map<String, dynamic> msg;
  117. try {
  118. msg = jsonDecode(raw) as Map<String, dynamic>;
  119. } catch (_) {
  120. return;
  121. }
  122. if (msg.containsKey('ping')) {
  123. try {
  124. _channel?.sink.add(jsonEncode({'pong': msg['ping']}));
  125. } catch (_) {}
  126. return;
  127. }
  128. // 用户资产/订单:body 无 channel,仅有 type=asset|order
  129. final pushType = msg['type']?.toString();
  130. if (pushType == 'asset') {
  131. if (!_assetCtrl.isClosed) {
  132. _assetCtrl.add(Map<String, dynamic>.from(msg));
  133. }
  134. return;
  135. }
  136. if (pushType == 'order') {
  137. if (!_orderCtrl.isClosed) {
  138. _orderCtrl.add(Map<String, dynamic>.from(msg));
  139. }
  140. return;
  141. }
  142. final channel = msg['channel'] as String?;
  143. if (channel == null) return;
  144. final tick = msg['tick'];
  145. if (!kReleaseMode &&
  146. channel.endsWith('_ticker') &&
  147. _spotWsRawLogCount < 6) {
  148. _spotWsRawLogCount++;
  149. final s = raw.length > 420 ? '${raw.substring(0, 420)}…' : raw;
  150. developer.log('raw ticker msg: $s', name: 'SpotWs');
  151. }
  152. // 必须先判断 trade_ticker:channel 为 market_{sym}_trade_ticker,同样以 `_ticker` 结尾,
  153. // 若先匹配 `_ticker` 会误走行情 ticker,导致最新成交永远进不了 _dispatchTrade。
  154. if (channel.endsWith('_trade_ticker')) {
  155. _dispatchTrade(channel, tick);
  156. } else if (channel.endsWith('_ticker')) {
  157. _dispatchTicker(channel, tick);
  158. } else if (channel.endsWith('_depth')) {
  159. if (!kReleaseMode && _spotWsRawDepthLogCount < 3) {
  160. _spotWsRawDepthLogCount++;
  161. final s = raw.length > 800 ? '${raw.substring(0, 800)}…' : raw;
  162. developer.log('[SPOT_DEPTH_DEBUG] raw[$_spotWsRawDepthLogCount]: $s',
  163. name: 'SpotWs');
  164. }
  165. _dispatchDepth(channel, tick);
  166. } else if (channel.contains('_kline_')) {
  167. _dispatchKline(channel, tick);
  168. }
  169. // kline req 响应
  170. if (msg.containsKey('event_rep') && msg['event_rep'] == 'req') {
  171. _handleKlineReqResponse(msg);
  172. }
  173. }
  174. static String? _symbolFromChannel(String channel) {
  175. if (channel.startsWith('market_')) {
  176. final parts = channel.split('_');
  177. if (parts.length >= 3) return parts[1].toUpperCase();
  178. }
  179. return null;
  180. }
  181. /// 涨跌幅:解析 rose / 或用 open、close 推算(不盲目 ×100)。
  182. static double? _parseSpotRose(dynamic rose, double open, double close) {
  183. if (rose != null && '$rose'.trim().isNotEmpty) {
  184. final raw =
  185. rose.toString().trim().replaceAll('%', '').replaceAll(',', '');
  186. final n = double.tryParse(raw);
  187. if (n != null && !n.isNaN) return n;
  188. }
  189. if (open > 0 && close > 0) return (close - open) / open * 100;
  190. return null;
  191. }
  192. /// ticker channel:标准字段 + 兼容 o/h/l/c、v/q、b/a、P。
  193. void _dispatchTicker(String channel, dynamic tick) {
  194. if (tick is! Map) {
  195. if (!kReleaseMode) {
  196. developer.log(
  197. '_dispatchTicker: tick not map channel=$channel tickType=${tick.runtimeType}',
  198. name: 'SpotWs',
  199. );
  200. }
  201. return;
  202. }
  203. final t = Map<String, dynamic>.from(tick);
  204. final symbol = _symbolFromChannel(channel);
  205. if (symbol == null) return;
  206. final rawClose =
  207. t['close'] ?? t['last'] ?? t['price'] ?? t['c'] ?? t['latest'] ?? t['es_price'];
  208. final close = _toDouble(rawClose);
  209. final open = _toDouble(t['open'] ?? t['o']);
  210. if (!kReleaseMode && close <= 0 && _spotWsDispatchTickerLogCount < 4) {
  211. _spotWsDispatchTickerLogCount++;
  212. developer.log(
  213. 'ticker close<=0 ch=$channel tickKeys=${t.keys.toList()}',
  214. name: 'SpotWs',
  215. );
  216. }
  217. final change24h = _parseSpotRose(
  218. t['rose'] ?? t['P'] ?? t['priceChangePercent'],
  219. open,
  220. close,
  221. );
  222. if (!_tickerCtrl.isClosed) {
  223. _tickerCtrl.add({
  224. 'symbol': symbol,
  225. 'price': close,
  226. 'priceStr': rawClose?.toString() ?? '', // WS 原始价格字符串,保留精度
  227. 'open': open,
  228. 'high': _toDouble(t['high'] ?? t['h']),
  229. 'low': _toDouble(t['low'] ?? t['l']),
  230. 'volume': _toDouble(
  231. t['vol'] ?? t['volume'] ?? t['v'] ?? t['baseVolume'],
  232. ),
  233. 'turnover': _toDouble(
  234. t['amount'] ?? t['quoteVolume'] ?? t['q'] ?? t['turnover'],
  235. ),
  236. 'change24h': change24h,
  237. 'buyOne': _toDouble(t['buyOne'] ?? t['b']),
  238. 'sellOne': _toDouble(t['sellOne'] ?? t['a']),
  239. });
  240. }
  241. }
  242. void _dispatchDepth(String channel, dynamic tick) {
  243. if (tick is! Map) return;
  244. var t = Map<String, dynamic>.from(tick);
  245. final symbol = _symbolFromChannel(channel);
  246. if (symbol == null) return;
  247. if (t['bids'] == null &&
  248. t['buys'] == null &&
  249. t['asks'] == null &&
  250. t['sells'] == null &&
  251. t['data'] is Map) {
  252. t = Map<String, dynamic>.from(t['data'] as Map);
  253. }
  254. List<Map<String, double>> parseLevels(dynamic raw) {
  255. if (raw is! List) return [];
  256. final out = <Map<String, double>>[];
  257. for (final e in raw) {
  258. if (e is List && e.isNotEmpty) {
  259. final price = _toDouble(e[0]);
  260. final qty = _toDouble(e.length > 1 ? e[1] : 0);
  261. if (price > 0 && qty > 0) {
  262. out.add({'price': price, 'quantity': qty});
  263. }
  264. } else if (e is Map) {
  265. final m = Map<dynamic, dynamic>.from(e);
  266. final price = _toDouble(
  267. m['price'] ??
  268. m['limitPrice'] ??
  269. m['entrustPrice'] ??
  270. m['tradePrice'] ??
  271. m['p'] ??
  272. m['P'],
  273. );
  274. final qty = _toDouble(
  275. m['quantity'] ?? m['amount'] ?? m['qty'] ?? m['q'] ?? m['a'],
  276. );
  277. if (price > 0 && qty > 0) {
  278. out.add({'price': price, 'quantity': qty});
  279. }
  280. }
  281. }
  282. return out;
  283. }
  284. final payload = <String, dynamic>{'symbol': symbol};
  285. payload['asks'] = parseLevels(t['asks'] ?? t['sells']);
  286. payload['bids'] = parseLevels(t['bids'] ?? t['buys']);
  287. if ((payload['asks'] as List).isEmpty && (payload['bids'] as List).isEmpty) return;
  288. if (!kReleaseMode && _spotWsParsedDepthLogCount < 3) {
  289. _spotWsParsedDepthLogCount++;
  290. final asks = payload['asks'] as List;
  291. final bids = payload['bids'] as List;
  292. final ask0 = asks.isNotEmpty ? asks.first : null;
  293. final bid0 = bids.isNotEmpty ? bids.first : null;
  294. developer.log(
  295. '[SPOT_DEPTH_DEBUG] parsed[$_spotWsParsedDepthLogCount] symbol=$symbol '
  296. 'asks=${asks.length} bids=${bids.length} '
  297. 'ask0=$ask0 bid0=$bid0',
  298. name: 'SpotWs',
  299. );
  300. }
  301. if (!_depthCtrl.isClosed) {
  302. _depthCtrl.add(payload);
  303. }
  304. }
  305. void _dispatchTrade(String channel, dynamic tick) {
  306. if (tick is! Map) return;
  307. final m = Map<String, dynamic>.from(tick);
  308. final symbol = _symbolFromChannel(channel);
  309. if (symbol == null) return;
  310. void emitOne(Map<String, dynamic> one) {
  311. final ts = one['time'] ?? one['ts'];
  312. int timeMs = 0;
  313. if (ts is int) {
  314. timeMs = ts;
  315. } else if (ts is num) {
  316. timeMs = ts.toInt();
  317. }
  318. if (timeMs > 0 && timeMs < 10000000000) timeMs *= 1000;
  319. if (!_tradeCtrl.isClosed) {
  320. _tradeCtrl.add({
  321. 'symbol': symbol,
  322. 'id': one['id'],
  323. 'price': _toDouble(one['price']),
  324. 'quantity': _toDouble(one['vol'] ?? one['quantity']),
  325. 'amount': _toDouble(one['amount']),
  326. 'side': '${one['side'] ?? ''}',
  327. 'time': timeMs,
  328. });
  329. }
  330. }
  331. final data = m['data'];
  332. if (data is List) {
  333. for (final e in data) {
  334. if (e is Map) emitOne(Map<String, dynamic>.from(e));
  335. }
  336. return;
  337. }
  338. emitOne(m);
  339. }
  340. void _dispatchKline(String channel, dynamic tick) {
  341. if (tick is! Map) return;
  342. final t = Map<String, dynamic>.from(tick);
  343. final symbol = _symbolFromChannel(channel);
  344. if (symbol == null) return;
  345. if (!channel.contains('_kline_')) return;
  346. final parts = channel.split('_');
  347. if (parts.length < 4) return;
  348. final interval = parts.sublist(3).join('_');
  349. final rawTime = t['time'];
  350. int timeMs = 0;
  351. if (rawTime is int) {
  352. timeMs = rawTime;
  353. } else if (rawTime is num) {
  354. timeMs = rawTime.toInt();
  355. }
  356. if (timeMs > 0 && timeMs < 10000000000) timeMs *= 1000;
  357. final rawId = t['id'];
  358. int id = 0;
  359. if (rawId is int) {
  360. id = rawId;
  361. } else if (rawId is num) {
  362. id = rawId.toInt();
  363. }
  364. if (!_klineCtrl.isClosed) {
  365. _klineCtrl.add({
  366. 'symbol': symbol,
  367. 'interval': interval,
  368. 'time': timeMs,
  369. 'open': _toDouble(t['open']),
  370. 'close': _toDouble(t['close']),
  371. 'high': _toDouble(t['high']),
  372. 'low': _toDouble(t['low']),
  373. 'volume': _toDouble(t['vol']),
  374. 'amount': _toDouble(t['amount']),
  375. 'ratio': _toDouble(t['ratio']),
  376. 'id': id,
  377. });
  378. }
  379. }
  380. void _handleKlineReqResponse(Map<String, dynamic> msg) {
  381. final channel = msg['channel'] as String?;
  382. if (channel == null) return;
  383. final completer = _klineReqCompleters.remove(channel);
  384. if (completer == null || completer.isCompleted) return;
  385. final data = msg['data'];
  386. if (data is List) {
  387. completer.complete(data.whereType<Map<String, dynamic>>().toList());
  388. } else {
  389. completer.complete([]);
  390. }
  391. }
  392. void subscribeTicker(String symbol) {
  393. _sub('market_${symbol.toLowerCase()}_ticker');
  394. }
  395. void unsubscribeTicker(String symbol) {
  396. _unsub('market_${symbol.toLowerCase()}_ticker');
  397. }
  398. void subscribeTickerBatch(List<String> symbols) {
  399. for (final s in symbols.map((e) => e.toLowerCase())) {
  400. _sub('market_${s}_ticker');
  401. }
  402. }
  403. void resubscribeTickerBatch(List<String> newSymbols) {
  404. final newChannels = <String>{};
  405. for (final s in newSymbols.map((e) => e.toLowerCase())) {
  406. newChannels.add('market_${s}_ticker');
  407. }
  408. final oldChannels =
  409. _subscribedChannels.where((c) => c.endsWith('_ticker')).toSet();
  410. final toUnsub = oldChannels.difference(newChannels);
  411. if (toUnsub.isNotEmpty) {
  412. for (final c in toUnsub) {
  413. _subscribedChannels.remove(c);
  414. }
  415. if (_state == SpotWsState.connected) _sendUnsub(toUnsub.toList());
  416. }
  417. final toSub = newChannels.difference(oldChannels);
  418. for (final c in toSub) {
  419. _sub(c);
  420. }
  421. }
  422. void subscribeDepth(String symbol) {
  423. _sub('market_${symbol.toLowerCase()}_depth');
  424. }
  425. void unsubscribeDepth(String symbol) {
  426. _unsub('market_${symbol.toLowerCase()}_depth');
  427. }
  428. void subscribeTrade(String symbol) {
  429. _sub('market_${symbol.toLowerCase()}_trade_ticker');
  430. }
  431. void unsubscribeTrade(String symbol) {
  432. _unsub('market_${symbol.toLowerCase()}_trade_ticker');
  433. }
  434. void subscribeKline(String symbol, String interval) {
  435. _sub('market_${symbol.toLowerCase()}_kline_$interval');
  436. }
  437. void unsubscribeKline(String symbol, String interval) {
  438. _unsub('market_${symbol.toLowerCase()}_kline_$interval');
  439. }
  440. void retainSpotAssetChannel() {
  441. _spotAssetChannelHolds++;
  442. if (_spotAssetChannelHolds == 1) {
  443. _sub('spot_asset');
  444. }
  445. }
  446. void releaseSpotAssetChannel() {
  447. if (_spotAssetChannelHolds <= 0) return;
  448. _spotAssetChannelHolds--;
  449. if (_spotAssetChannelHolds == 0) {
  450. _unsub('spot_asset');
  451. }
  452. }
  453. void retainSpotOrderChannel() {
  454. _spotOrderChannelHolds++;
  455. if (_spotOrderChannelHolds == 1) {
  456. _sub('spot_order');
  457. }
  458. }
  459. void releaseSpotOrderChannel() {
  460. if (_spotOrderChannelHolds <= 0) return;
  461. _spotOrderChannelHolds--;
  462. if (_spotOrderChannelHolds == 0) {
  463. _unsub('spot_order');
  464. }
  465. }
  466. /// K 线历史 `event=req`;[endIdx] 秒,0=最新。
  467. Future<List<Map<String, dynamic>>> requestKlineHistory({
  468. required String symbol,
  469. required String interval,
  470. int pageSize = 150,
  471. int endIdx = 0,
  472. }) {
  473. if (_state != SpotWsState.connected) return Future.value([]);
  474. final channel = 'market_${symbol.toLowerCase()}_kline_$interval';
  475. final completer = Completer<List<Map<String, dynamic>>>();
  476. _klineReqCompleters[channel] = completer;
  477. final msg = jsonEncode({
  478. 'event': 'req',
  479. 'params': {
  480. 'channel': channel,
  481. 'cb_id': symbol.toLowerCase(),
  482. 'pageSize': pageSize,
  483. 'endIdx': endIdx,
  484. },
  485. });
  486. try {
  487. _channel?.sink.add(msg);
  488. } catch (_) {
  489. _klineReqCompleters.remove(channel);
  490. return Future.value([]);
  491. }
  492. return completer.future.timeout(
  493. const Duration(seconds: 10),
  494. onTimeout: () {
  495. _klineReqCompleters.remove(channel);
  496. return [];
  497. },
  498. );
  499. }
  500. void _sub(String channel) {
  501. _subscribedChannels.add(channel);
  502. if (_state == SpotWsState.connected) _sendSub([channel]);
  503. }
  504. void _unsub(String channel) {
  505. _subscribedChannels.remove(channel);
  506. if (_state == SpotWsState.connected) _sendUnsub([channel]);
  507. }
  508. void _sendSub(List<String> channels) {
  509. if (!kReleaseMode && channels.isNotEmpty) {
  510. debugPrint('[SpotWs] sub count=${channels.length} $channels');
  511. developer.log(
  512. 'send sub count=${channels.length} first=${channels.take(4)}',
  513. name: 'SpotWs',
  514. );
  515. }
  516. for (final ch in channels) {
  517. try {
  518. _channel?.sink.add(jsonEncode({
  519. 'event': 'sub',
  520. 'params': {'channel': ch},
  521. }));
  522. } catch (_) {}
  523. }
  524. }
  525. void _sendUnsub(List<String> channels) {
  526. for (final ch in channels) {
  527. try {
  528. _channel?.sink.add(jsonEncode({
  529. 'event': 'unsub',
  530. 'params': {'channel': ch},
  531. }));
  532. } catch (_) {}
  533. }
  534. }
  535. void _setState(SpotWsState s) {
  536. _state = s;
  537. if (!_connStateCtrl.isClosed) _connStateCtrl.add(s);
  538. }
  539. static double _toDouble(dynamic v) {
  540. if (v == null) return 0.0;
  541. if (v is num) return v.toDouble();
  542. return double.tryParse(v.toString()) ?? 0.0;
  543. }
  544. void dispose() {
  545. _spotAssetChannelHolds = 0;
  546. _spotOrderChannelHolds = 0;
  547. _channelSub?.cancel();
  548. _reconnectTimer?.cancel();
  549. _channel?.sink.close();
  550. _connStateCtrl.close();
  551. _tickerCtrl.close();
  552. _depthCtrl.close();
  553. _tradeCtrl.close();
  554. _klineCtrl.close();
  555. _assetCtrl.close();
  556. _orderCtrl.close();
  557. for (final c in _klineReqCompleters.values) {
  558. if (!c.isCompleted) c.complete([]);
  559. }
  560. _klineReqCompleters.clear();
  561. }
  562. }
  563. enum SpotWsState { connecting, connected, disconnected, reconnecting }