alphaio-quote 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alphaio_quote-0.2.0.dist-info/METADATA +85 -0
- alphaio_quote-0.2.0.dist-info/RECORD +10 -0
- alphaio_quote-0.2.0.dist-info/WHEEL +4 -0
- alphaio_quote-0.2.0.dist-info/entry_points.txt +3 -0
- alphaio_quote-0.2.0.dist-info/licenses/LICENSE +21 -0
- hps_quote_client/__init__.py +61 -0
- hps_quote_client/__main__.py +188 -0
- hps_quote_client/client.py +465 -0
- hps_quote_client/curve_helpers.py +95 -0
- hps_quote_client/protocol.py +336 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: alphaio-quote
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Asyncio TCP client for AlphaIO quote-relay (aligned with @alphaio/quote-client).
|
|
5
|
+
Project-URL: Homepage, https://pypi.org/project/alphaio-quote/
|
|
6
|
+
Project-URL: Documentation, https://quote.alphaio.vip
|
|
7
|
+
Project-URL: Repository, https://github.com/hyperse-internal/hps-quote-relay
|
|
8
|
+
Author-email: AlphaIO <support@alphaio.vip>
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: alphaio,market-data,quote,tcp
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: twine>=5.0; extra == 'dev'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# `alphaio-quote` (Python)
|
|
31
|
+
|
|
32
|
+
AlphaIO quote-relay **完整用户端 SDK**(asyncio TCP + 协议类型 + 曲线收窄),对齐 Node `@alphaio/quote-client`。
|
|
33
|
+
|
|
34
|
+
**PyPI(public):** `pip install alphaio-quote`
|
|
35
|
+
导入名:`hps_quote_client`。
|
|
36
|
+
|
|
37
|
+
## 产品
|
|
38
|
+
|
|
39
|
+
| topic | 形态 | 事件 |
|
|
40
|
+
| ------------------------------------------ | ----- | -------------------------- |
|
|
41
|
+
| `l2.*` / `trans.*` / `order.*` | tick | `quote` / `quoteSnap` |
|
|
42
|
+
| `fenshi.*` / `fenshi_vol.*` / `mf_range.*` | curve | `curveSnap` / `curveDelta` |
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install alphaio-quote
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
仓库开发:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install -e "packages/client-sdk-python.[dev]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
import asyncio
|
|
60
|
+
from hps_quote_client import (
|
|
61
|
+
QuoteClient,
|
|
62
|
+
narrow_curve_snap,
|
|
63
|
+
last_mf_range_point,
|
|
64
|
+
QUOTE_STREAM_KINDS,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
async def main() -> None:
|
|
68
|
+
client = QuoteClient(
|
|
69
|
+
host="s1.diancha.vip",
|
|
70
|
+
port=17010,
|
|
71
|
+
auth={"activationKey": "…", "deviceId": "py-1"},
|
|
72
|
+
)
|
|
73
|
+
client.on(
|
|
74
|
+
"curveSnap",
|
|
75
|
+
lambda s: print(narrow_curve_snap(s), last_mf_range_point(s)),
|
|
76
|
+
)
|
|
77
|
+
await client.connect()
|
|
78
|
+
await client.subscribe(["mf_range.600519"])
|
|
79
|
+
await asyncio.sleep(30)
|
|
80
|
+
await client.close()
|
|
81
|
+
|
|
82
|
+
asyncio.run(main())
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
发布步骤见仓库 [`docs/PUBLISH_SDKS.md`](../../docs/PUBLISH_SDKS.md)。
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
hps_quote_client/__init__.py,sha256=D4iH_P3Mrs0IwjiaKSzzynEQHh47B3x6XAi4yS1rFtY,1338
|
|
2
|
+
hps_quote_client/__main__.py,sha256=TSxz6VKjArUS_iKo_5jmKYby51NDfI25b-QO5Fq7pHE,5595
|
|
3
|
+
hps_quote_client/client.py,sha256=OqeyllIpwU_8Dx6BzGFXBDLdjrYuMp-zV9rW57pRlyg,16144
|
|
4
|
+
hps_quote_client/curve_helpers.py,sha256=H4BuRFQUGVeUonL3C-znUvR7sqOqnej8ueNg_wfeF9Q,3030
|
|
5
|
+
hps_quote_client/protocol.py,sha256=dEpHK0LdbUyU6w2jH_Q0aawHOi7vfRXc345Y_KrzvE4,9693
|
|
6
|
+
alphaio_quote-0.2.0.dist-info/METADATA,sha256=_TXCWGf_fIS59AVAS0yhJSgzys3Q8KCHjuykkHDOTjY,2625
|
|
7
|
+
alphaio_quote-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
8
|
+
alphaio_quote-0.2.0.dist-info/entry_points.txt,sha256=tkVNyPB9iqjycr7lYpeeSAzdOO8US7tOGANB279viec,118
|
|
9
|
+
alphaio_quote-0.2.0.dist-info/licenses/LICENSE,sha256=zUIZ3FJ36lhckBT2DswWsbKdmaIFAIJu_PJ-biLegQ8,1059
|
|
10
|
+
alphaio_quote-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) AlphaIO
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""基于 asyncio 的 quote-relay 完整用户端 SDK(对齐 @alphaio/quote-client)。"""
|
|
2
|
+
|
|
3
|
+
from .client import QuoteClient
|
|
4
|
+
from .curve_helpers import (
|
|
5
|
+
CURVE_KINDS,
|
|
6
|
+
curve_kind_of,
|
|
7
|
+
diff_mf_range_points,
|
|
8
|
+
is_curve_stream_kind,
|
|
9
|
+
is_mf_range_point,
|
|
10
|
+
last_mf_range_point,
|
|
11
|
+
narrow_curve_delta,
|
|
12
|
+
narrow_curve_snap,
|
|
13
|
+
)
|
|
14
|
+
from .protocol import (
|
|
15
|
+
PROTOCOL_VERSION,
|
|
16
|
+
QUOTE_STREAM_KINDS,
|
|
17
|
+
AuthFailPayload,
|
|
18
|
+
AuthOkPayload,
|
|
19
|
+
AuthPayload,
|
|
20
|
+
CurveDeltaPayload,
|
|
21
|
+
CurveSnapPayload,
|
|
22
|
+
FrameType,
|
|
23
|
+
KickPayload,
|
|
24
|
+
QuotePayload,
|
|
25
|
+
QuoteSnapPayload,
|
|
26
|
+
QuoteStreamQuotas,
|
|
27
|
+
SubAckPayload,
|
|
28
|
+
SubRejected,
|
|
29
|
+
format_quote_topic,
|
|
30
|
+
is_quote_stream_kind,
|
|
31
|
+
parse_quote_topic,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"CURVE_KINDS",
|
|
36
|
+
"PROTOCOL_VERSION",
|
|
37
|
+
"QUOTE_STREAM_KINDS",
|
|
38
|
+
"AuthFailPayload",
|
|
39
|
+
"AuthOkPayload",
|
|
40
|
+
"AuthPayload",
|
|
41
|
+
"CurveDeltaPayload",
|
|
42
|
+
"CurveSnapPayload",
|
|
43
|
+
"FrameType",
|
|
44
|
+
"KickPayload",
|
|
45
|
+
"QuoteClient",
|
|
46
|
+
"QuotePayload",
|
|
47
|
+
"QuoteSnapPayload",
|
|
48
|
+
"QuoteStreamQuotas",
|
|
49
|
+
"SubAckPayload",
|
|
50
|
+
"SubRejected",
|
|
51
|
+
"curve_kind_of",
|
|
52
|
+
"diff_mf_range_points",
|
|
53
|
+
"format_quote_topic",
|
|
54
|
+
"is_curve_stream_kind",
|
|
55
|
+
"is_mf_range_point",
|
|
56
|
+
"is_quote_stream_kind",
|
|
57
|
+
"last_mf_range_point",
|
|
58
|
+
"narrow_curve_delta",
|
|
59
|
+
"narrow_curve_snap",
|
|
60
|
+
"parse_quote_topic",
|
|
61
|
+
]
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""演示用 CLI,行为对齐 packages/client-sdk/src/cli.ts。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import signal
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .client import QuoteClient
|
|
12
|
+
from .protocol import (
|
|
13
|
+
PROTOCOL_VERSION,
|
|
14
|
+
AuthOkPayload,
|
|
15
|
+
CurveDeltaPayload,
|
|
16
|
+
CurveSnapPayload,
|
|
17
|
+
QuotePayload,
|
|
18
|
+
QuoteSnapPayload,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _product(topic: str) -> str:
|
|
23
|
+
"""topic 前缀即产品:l2 / trans / order / fenshi / fenshi_vol / mf_range。"""
|
|
24
|
+
return topic.split(".", 1)[0] if topic else "?"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _mf_range_tail(items: list[dict[str, Any]]) -> str:
|
|
28
|
+
if not items:
|
|
29
|
+
return ""
|
|
30
|
+
last = items[-1]
|
|
31
|
+
net = last.get("mainNet")
|
|
32
|
+
if not isinstance(net, (int, float)):
|
|
33
|
+
return ""
|
|
34
|
+
return (
|
|
35
|
+
f" lastNet={net} buy={last.get('mainBuy', '—')} "
|
|
36
|
+
f"sell={last.get('mainSell', '—')} ts={last.get('ts', '—')}"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def _run() -> None:
|
|
41
|
+
host = os.environ.get("RELAY_HOST", "127.0.0.1")
|
|
42
|
+
port = int(os.environ.get("RELAY_LISTEN_PORT") or 17010)
|
|
43
|
+
topics = [
|
|
44
|
+
s.strip()
|
|
45
|
+
for s in os.environ.get(
|
|
46
|
+
"QUOTE_TOPICS",
|
|
47
|
+
"l2.600519,trans.600519,order.600519,fenshi.600519,fenshi_vol.600519,mf_range.600519",
|
|
48
|
+
).split(",")
|
|
49
|
+
if s.strip()
|
|
50
|
+
]
|
|
51
|
+
quiet = os.environ.get("QUOTE_DEMO_QUIET") == "1"
|
|
52
|
+
summary_every_ms = max(1_000, int(os.environ.get("QUOTE_DEMO_SUMMARY_MS") or 5_000))
|
|
53
|
+
|
|
54
|
+
client = QuoteClient(
|
|
55
|
+
host=host,
|
|
56
|
+
port=port,
|
|
57
|
+
auth={
|
|
58
|
+
"activationKey": os.environ.get("QUOTE_ACTIVATION_KEY", "dev-all-streams"),
|
|
59
|
+
"deviceId": os.environ.get("QUOTE_DEVICE_ID", "demo-device-py-1"),
|
|
60
|
+
},
|
|
61
|
+
auto_reconnect=True,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
counts = {
|
|
65
|
+
"quote": 0,
|
|
66
|
+
"quoteSnap": 0,
|
|
67
|
+
"curveSnap": 0,
|
|
68
|
+
"curveDelta": 0,
|
|
69
|
+
"byTopic": defaultdict(int),
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
def bump(topic: str) -> None:
|
|
73
|
+
counts["byTopic"][topic] += 1
|
|
74
|
+
|
|
75
|
+
client.on("state", lambda s: print(f"[sdk] state → {s}"))
|
|
76
|
+
client.on(
|
|
77
|
+
"kick",
|
|
78
|
+
lambda k: print(f"[sdk] KICK {k.reason} {k.message or ''}"),
|
|
79
|
+
)
|
|
80
|
+
client.on("error", lambda e: print(f"[sdk] error {e}"))
|
|
81
|
+
|
|
82
|
+
# —— 产品 → 事件 ——
|
|
83
|
+
# l2.* / trans.* / order.* → tick:quote + quoteSnap
|
|
84
|
+
# fenshi.* / fenshi_vol.* / mf_range.* → curveSnap + curveDelta
|
|
85
|
+
|
|
86
|
+
def on_quote(q: QuotePayload) -> None:
|
|
87
|
+
counts["quote"] += 1
|
|
88
|
+
bump(q.topic)
|
|
89
|
+
if not quiet:
|
|
90
|
+
print(
|
|
91
|
+
f"[sdk] QUOTE [{_product(q.topic)}] {q.topic} last={q.last} ts={q.ts}"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def on_quote_snap(snap: QuoteSnapPayload) -> None:
|
|
95
|
+
counts["quoteSnap"] += 1
|
|
96
|
+
bump(snap.topic)
|
|
97
|
+
if not quiet:
|
|
98
|
+
print(
|
|
99
|
+
f"[sdk] QUOTE_SNAP [{_product(snap.topic)}] {snap.topic} "
|
|
100
|
+
f"items={len(snap.items)}"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def on_curve_snap(snap: CurveSnapPayload) -> None:
|
|
104
|
+
counts["curveSnap"] += 1
|
|
105
|
+
bump(snap.topic)
|
|
106
|
+
product = _product(snap.topic)
|
|
107
|
+
extra = _mf_range_tail(snap.items) if product == "mf_range" else ""
|
|
108
|
+
total = snap.total if snap.total is not None else "—"
|
|
109
|
+
print(
|
|
110
|
+
f"[sdk] CURVE_SNAP [{product}] {snap.topic} "
|
|
111
|
+
f"items={len(snap.items)} total={total}{extra}"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def on_curve_delta(delta: CurveDeltaPayload) -> None:
|
|
115
|
+
counts["curveDelta"] += 1
|
|
116
|
+
bump(delta.topic)
|
|
117
|
+
if not quiet:
|
|
118
|
+
product = _product(delta.topic)
|
|
119
|
+
extra = _mf_range_tail(delta.items) if product == "mf_range" else ""
|
|
120
|
+
print(
|
|
121
|
+
f"[sdk] CURVE_DELTA [{product}] {delta.topic} "
|
|
122
|
+
f"items={len(delta.items)}{extra}"
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
client.on("quote", on_quote)
|
|
126
|
+
client.on("quoteSnap", on_quote_snap)
|
|
127
|
+
client.on("curveSnap", on_curve_snap)
|
|
128
|
+
client.on("curveDelta", on_curve_delta)
|
|
129
|
+
|
|
130
|
+
print(
|
|
131
|
+
f"[sdk] PROTOCOL {PROTOCOL_VERSION} → {host}:{port} topics={','.join(topics)}"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
lease: AuthOkPayload = await client.connect()
|
|
135
|
+
print(
|
|
136
|
+
f"[sdk] AUTH_OK lease={lease.lease_id} quotas={lease.stream_quotas} "
|
|
137
|
+
f"until={lease.valid_until}"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
ack = await client.subscribe(topics)
|
|
141
|
+
print(
|
|
142
|
+
f"[sdk] SUB_ACK accepted={','.join(ack.accepted) or '—'} "
|
|
143
|
+
f"rejected={len(ack.rejected)}"
|
|
144
|
+
)
|
|
145
|
+
for r in ack.rejected:
|
|
146
|
+
print(f"[sdk] REJECTED {r.topic} {r.code}: {r.message}")
|
|
147
|
+
|
|
148
|
+
stop = asyncio.Event()
|
|
149
|
+
|
|
150
|
+
def _stop(*_args: object) -> None:
|
|
151
|
+
stop.set()
|
|
152
|
+
|
|
153
|
+
loop = asyncio.get_running_loop()
|
|
154
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
155
|
+
try:
|
|
156
|
+
loop.add_signal_handler(sig, _stop)
|
|
157
|
+
except NotImplementedError:
|
|
158
|
+
signal.signal(sig, lambda *_: _stop())
|
|
159
|
+
|
|
160
|
+
async def _summary() -> None:
|
|
161
|
+
while not stop.is_set():
|
|
162
|
+
await asyncio.sleep(summary_every_ms / 1000)
|
|
163
|
+
topic_line = " ".join(
|
|
164
|
+
f"{t}={n}" for t, n in sorted(counts["byTopic"].items())
|
|
165
|
+
)
|
|
166
|
+
print(
|
|
167
|
+
f"[sdk] summary quote={counts['quote']} quoteSnap={counts['quoteSnap']} "
|
|
168
|
+
f"curveSnap={counts['curveSnap']} curveDelta={counts['curveDelta']}"
|
|
169
|
+
+ (f" | {topic_line}" if topic_line else "")
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
summary_task = asyncio.create_task(_summary())
|
|
173
|
+
try:
|
|
174
|
+
await stop.wait()
|
|
175
|
+
finally:
|
|
176
|
+
summary_task.cancel()
|
|
177
|
+
await client.close()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def main() -> None:
|
|
181
|
+
try:
|
|
182
|
+
asyncio.run(_run())
|
|
183
|
+
except KeyboardInterrupt:
|
|
184
|
+
pass
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
if __name__ == "__main__":
|
|
188
|
+
main()
|
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
"""基于 asyncio 的 TCP QuoteClient,行为对齐 @alphaio/quote-client。
|
|
2
|
+
|
|
3
|
+
支持 tick(l2 / trans / order)与 curve(fenshi / fenshi_vol / mf_range)。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
import socket as socket_mod
|
|
11
|
+
import time
|
|
12
|
+
from collections import defaultdict
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
from .protocol import (
|
|
17
|
+
DEFAULT_HEARTBEAT_INTERVAL_SEC,
|
|
18
|
+
DEFAULT_IDLE_MISS_LIMIT,
|
|
19
|
+
PROTOCOL_VERSION,
|
|
20
|
+
AuthFailPayload,
|
|
21
|
+
AuthOkPayload,
|
|
22
|
+
AuthPayload,
|
|
23
|
+
CurveDeltaPayload,
|
|
24
|
+
CurveSnapPayload,
|
|
25
|
+
DecodedFrame,
|
|
26
|
+
FrameReader,
|
|
27
|
+
FrameType,
|
|
28
|
+
KickPayload,
|
|
29
|
+
QuotePayload,
|
|
30
|
+
QuoteSnapPayload,
|
|
31
|
+
SubAckPayload,
|
|
32
|
+
encode_frame,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
SessionState = Literal[
|
|
36
|
+
"connecting", "authenticating", "ready", "subscribed", "closed"
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
Listener = Callable[..., Any]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class QuoteClient:
|
|
43
|
+
"""
|
|
44
|
+
quote-relay 轻量 TCP 客户端。
|
|
45
|
+
|
|
46
|
+
事件(``on`` / ``off`` / ``once``):
|
|
47
|
+
state、authOk、authFail、subAck、quote、quoteSnap、curveSnap、curveDelta、
|
|
48
|
+
kick、error、close,以及按 topic 分发的 ``quote:<topic>`` / ``curve:<topic>``。
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
*,
|
|
54
|
+
auth: AuthPayload | dict[str, Any],
|
|
55
|
+
host: str | None = None,
|
|
56
|
+
port: int | None = None,
|
|
57
|
+
auto_reconnect: bool = True,
|
|
58
|
+
client_version: str | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
self._auth = self._normalize_auth(auth)
|
|
61
|
+
self._host = host
|
|
62
|
+
self._port = port
|
|
63
|
+
self._auto_reconnect = auto_reconnect
|
|
64
|
+
self._client_version = client_version or PROTOCOL_VERSION
|
|
65
|
+
|
|
66
|
+
self.state: SessionState = "closed"
|
|
67
|
+
self.lease: AuthOkPayload | None = None
|
|
68
|
+
self.topics: set[str] = set()
|
|
69
|
+
|
|
70
|
+
self._reader = FrameReader()
|
|
71
|
+
self._writer: asyncio.StreamWriter | None = None
|
|
72
|
+
self._read_task: asyncio.Task[None] | None = None
|
|
73
|
+
self._ping_task: asyncio.Task[None] | None = None
|
|
74
|
+
self._reconnect_task: asyncio.Task[None] | None = None
|
|
75
|
+
self._idle_misses = 0
|
|
76
|
+
self._reconnect_attempt = 0
|
|
77
|
+
self._stopping = False
|
|
78
|
+
self._closing_socket = False
|
|
79
|
+
self._listeners: dict[str, list[Listener]] = defaultdict(list)
|
|
80
|
+
self._auth_fut: asyncio.Future[AuthOkPayload] | None = None
|
|
81
|
+
self._sub_futs: list[asyncio.Future[SubAckPayload]] = []
|
|
82
|
+
|
|
83
|
+
# ── 事件 ──────────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
def on(self, event: str, listener: Listener) -> Callable[[], None]:
|
|
86
|
+
self._listeners[event].append(listener)
|
|
87
|
+
return lambda: self.off(event, listener)
|
|
88
|
+
|
|
89
|
+
def once(self, event: str, listener: Listener) -> Callable[[], None]:
|
|
90
|
+
def wrapper(*args: Any) -> None:
|
|
91
|
+
self.off(event, wrapper)
|
|
92
|
+
listener(*args)
|
|
93
|
+
|
|
94
|
+
return self.on(event, wrapper)
|
|
95
|
+
|
|
96
|
+
def off(self, event: str, listener: Listener) -> None:
|
|
97
|
+
lst = self._listeners.get(event)
|
|
98
|
+
if not lst:
|
|
99
|
+
return
|
|
100
|
+
try:
|
|
101
|
+
lst.remove(listener)
|
|
102
|
+
except ValueError:
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
def emit(self, event: str, *args: Any) -> None:
|
|
106
|
+
for listener in list(self._listeners.get(event, ())):
|
|
107
|
+
try:
|
|
108
|
+
result = listener(*args)
|
|
109
|
+
if asyncio.iscoroutine(result):
|
|
110
|
+
asyncio.create_task(result)
|
|
111
|
+
except Exception as exc: # noqa: BLE001 — 用户回调异常不向外传播
|
|
112
|
+
if event != "error":
|
|
113
|
+
self.emit("error", exc)
|
|
114
|
+
|
|
115
|
+
def on_topic(
|
|
116
|
+
self, topic: str, handler: Callable[[QuotePayload], Any]
|
|
117
|
+
) -> Callable[[], None]:
|
|
118
|
+
"""注册单个 topic 的 QUOTE 本地回调(不会发送 UNSUB)。"""
|
|
119
|
+
return self.on(f"quote:{topic}", handler)
|
|
120
|
+
|
|
121
|
+
def on_curve_topic(
|
|
122
|
+
self,
|
|
123
|
+
topic: str,
|
|
124
|
+
handler: Callable[[CurveSnapPayload | CurveDeltaPayload], Any],
|
|
125
|
+
) -> Callable[[], None]:
|
|
126
|
+
"""注册单个 topic 的 CURVE_SNAP / CURVE_DELTA 本地回调(不会发送 UNSUB)。"""
|
|
127
|
+
return self.on(f"curve:{topic}", handler)
|
|
128
|
+
|
|
129
|
+
# ── 对外 API ───────────────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
async def connect(self) -> AuthOkPayload:
|
|
132
|
+
self._stopping = False
|
|
133
|
+
return await self._connect_once()
|
|
134
|
+
|
|
135
|
+
async def subscribe(
|
|
136
|
+
self,
|
|
137
|
+
topics: list[str],
|
|
138
|
+
*,
|
|
139
|
+
with_snap: bool | None = None,
|
|
140
|
+
) -> SubAckPayload:
|
|
141
|
+
self._ensure_ready()
|
|
142
|
+
payload: dict[str, Any] = {"topics": topics}
|
|
143
|
+
if with_snap is not None:
|
|
144
|
+
payload["withSnap"] = with_snap
|
|
145
|
+
|
|
146
|
+
loop = asyncio.get_running_loop()
|
|
147
|
+
fut: asyncio.Future[SubAckPayload] = loop.create_future()
|
|
148
|
+
self._sub_futs.append(fut)
|
|
149
|
+
self._write(FrameType.SUB, payload)
|
|
150
|
+
try:
|
|
151
|
+
return await asyncio.wait_for(fut, timeout=10.0)
|
|
152
|
+
except asyncio.TimeoutError as exc:
|
|
153
|
+
if fut in self._sub_futs:
|
|
154
|
+
self._sub_futs.remove(fut)
|
|
155
|
+
raise asyncio.TimeoutError("SUB_ACK timeout") from exc
|
|
156
|
+
|
|
157
|
+
def unsubscribe(self, topics: list[str]) -> None:
|
|
158
|
+
self._ensure_ready()
|
|
159
|
+
self._write(FrameType.UNSUB, {"topics": topics})
|
|
160
|
+
|
|
161
|
+
async def close(self) -> None:
|
|
162
|
+
self._stopping = True
|
|
163
|
+
await self._cancel_task(self._reconnect_task)
|
|
164
|
+
self._reconnect_task = None
|
|
165
|
+
await self._cancel_task(self._ping_task)
|
|
166
|
+
self._ping_task = None
|
|
167
|
+
|
|
168
|
+
writer = self._writer
|
|
169
|
+
read_task = self._read_task
|
|
170
|
+
if writer is not None and not writer.is_closing():
|
|
171
|
+
writer.close()
|
|
172
|
+
try:
|
|
173
|
+
await writer.wait_closed()
|
|
174
|
+
except Exception: # noqa: BLE001
|
|
175
|
+
pass
|
|
176
|
+
|
|
177
|
+
if read_task is not None and not read_task.done():
|
|
178
|
+
try:
|
|
179
|
+
await read_task
|
|
180
|
+
except asyncio.CancelledError:
|
|
181
|
+
pass
|
|
182
|
+
elif self.state != "closed":
|
|
183
|
+
self._writer = None
|
|
184
|
+
self._read_task = None
|
|
185
|
+
self._set_state("closed")
|
|
186
|
+
self.emit("close")
|
|
187
|
+
|
|
188
|
+
# ── 内部实现 ────────────────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
async def _connect_once(self) -> AuthOkPayload:
|
|
191
|
+
host = self._host or os.environ.get("RELAY_HOST") or "127.0.0.1"
|
|
192
|
+
port = self._port
|
|
193
|
+
if port is None:
|
|
194
|
+
port = int(os.environ.get("RELAY_LISTEN_PORT") or 17010)
|
|
195
|
+
|
|
196
|
+
self._set_state("connecting")
|
|
197
|
+
self._reader.reset()
|
|
198
|
+
self._closing_socket = False
|
|
199
|
+
|
|
200
|
+
reader, writer = await asyncio.open_connection(host, port)
|
|
201
|
+
self._writer = writer
|
|
202
|
+
sock = writer.get_extra_info("socket")
|
|
203
|
+
if sock is not None:
|
|
204
|
+
try:
|
|
205
|
+
sock.setsockopt(socket_mod.IPPROTO_TCP, socket_mod.TCP_NODELAY, 1)
|
|
206
|
+
except OSError:
|
|
207
|
+
pass
|
|
208
|
+
|
|
209
|
+
self._set_state("authenticating")
|
|
210
|
+
loop = asyncio.get_running_loop()
|
|
211
|
+
self._auth_fut = loop.create_future()
|
|
212
|
+
self._read_task = asyncio.create_task(
|
|
213
|
+
self._read_loop(reader), name="quote-client-read"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
auth_wire = self._auth.to_wire()
|
|
217
|
+
auth_wire["clientVersion"] = self._client_version
|
|
218
|
+
self._write(FrameType.AUTH, auth_wire)
|
|
219
|
+
|
|
220
|
+
assert self._auth_fut is not None
|
|
221
|
+
return await self._auth_fut
|
|
222
|
+
|
|
223
|
+
async def _read_loop(self, reader: asyncio.StreamReader) -> None:
|
|
224
|
+
try:
|
|
225
|
+
while True:
|
|
226
|
+
chunk = await reader.read(65536)
|
|
227
|
+
if not chunk:
|
|
228
|
+
break
|
|
229
|
+
try:
|
|
230
|
+
frames = self._reader.push(chunk)
|
|
231
|
+
except ValueError as err:
|
|
232
|
+
self.emit("error", err)
|
|
233
|
+
self._stopping = True
|
|
234
|
+
if self._writer and not self._writer.is_closing():
|
|
235
|
+
self._writer.close()
|
|
236
|
+
break
|
|
237
|
+
for frame in frames:
|
|
238
|
+
self._handle(frame)
|
|
239
|
+
except asyncio.CancelledError:
|
|
240
|
+
raise
|
|
241
|
+
except Exception as err: # noqa: BLE001
|
|
242
|
+
self.emit(
|
|
243
|
+
"error", err if isinstance(err, Exception) else Exception(str(err))
|
|
244
|
+
)
|
|
245
|
+
finally:
|
|
246
|
+
await self._on_socket_close()
|
|
247
|
+
|
|
248
|
+
def _handle(self, frame: DecodedFrame) -> None:
|
|
249
|
+
self._idle_misses = 0
|
|
250
|
+
raw = frame.payload if isinstance(frame.payload, dict) else {}
|
|
251
|
+
|
|
252
|
+
if frame.type is FrameType.AUTH_OK:
|
|
253
|
+
lease = AuthOkPayload.from_wire(raw)
|
|
254
|
+
self.lease = lease
|
|
255
|
+
self._set_state("ready")
|
|
256
|
+
self._reconnect_attempt = 0
|
|
257
|
+
self._start_ping(lease.heartbeat_interval_sec)
|
|
258
|
+
fut = self._auth_fut
|
|
259
|
+
self._auth_fut = None
|
|
260
|
+
if fut and not fut.done():
|
|
261
|
+
fut.set_result(lease)
|
|
262
|
+
self.emit("authOk", lease)
|
|
263
|
+
return
|
|
264
|
+
|
|
265
|
+
if frame.type is FrameType.AUTH_FAIL:
|
|
266
|
+
fail = AuthFailPayload.from_wire(raw)
|
|
267
|
+
err = Exception(f"{fail.code}: {fail.message}")
|
|
268
|
+
fut = self._auth_fut
|
|
269
|
+
self._auth_fut = None
|
|
270
|
+
if fut and not fut.done():
|
|
271
|
+
fut.set_exception(err)
|
|
272
|
+
self.emit("authFail", fail)
|
|
273
|
+
self._request_close()
|
|
274
|
+
return
|
|
275
|
+
|
|
276
|
+
if frame.type is FrameType.SUB_ACK:
|
|
277
|
+
ack = SubAckPayload.from_wire(raw)
|
|
278
|
+
for t in ack.accepted:
|
|
279
|
+
self.topics.add(t)
|
|
280
|
+
self._set_state("subscribed" if self.topics else "ready")
|
|
281
|
+
pending = self._sub_futs[:]
|
|
282
|
+
self._sub_futs.clear()
|
|
283
|
+
for fut in pending:
|
|
284
|
+
if not fut.done():
|
|
285
|
+
fut.set_result(ack)
|
|
286
|
+
self.emit("subAck", ack)
|
|
287
|
+
return
|
|
288
|
+
|
|
289
|
+
if frame.type is FrameType.UNSUB_ACK:
|
|
290
|
+
for t in raw.get("topics") or []:
|
|
291
|
+
self.topics.discard(str(t))
|
|
292
|
+
self._set_state("subscribed" if self.topics else "ready")
|
|
293
|
+
return
|
|
294
|
+
|
|
295
|
+
if frame.type is FrameType.QUOTE:
|
|
296
|
+
self._emit_quote(QuotePayload.from_wire(raw))
|
|
297
|
+
return
|
|
298
|
+
|
|
299
|
+
if frame.type is FrameType.QUOTE_SNAP:
|
|
300
|
+
snap = QuoteSnapPayload.from_wire(raw)
|
|
301
|
+
self.emit("quoteSnap", snap)
|
|
302
|
+
for q in snap.items:
|
|
303
|
+
self._emit_quote(q)
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
if frame.type is FrameType.QUOTE_BATCH:
|
|
307
|
+
for item in raw.get("items") or []:
|
|
308
|
+
self._emit_quote(QuotePayload.from_wire(item))
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
if frame.type is FrameType.CURVE_SNAP:
|
|
312
|
+
self._emit_curve("curveSnap", CurveSnapPayload.from_wire(raw))
|
|
313
|
+
return
|
|
314
|
+
|
|
315
|
+
if frame.type is FrameType.CURVE_DELTA:
|
|
316
|
+
self._emit_curve("curveDelta", CurveDeltaPayload.from_wire(raw))
|
|
317
|
+
return
|
|
318
|
+
|
|
319
|
+
if frame.type is FrameType.PING:
|
|
320
|
+
ts = raw.get("ts", int(time.time() * 1000))
|
|
321
|
+
self._write(FrameType.PONG, {"ts": ts})
|
|
322
|
+
return
|
|
323
|
+
|
|
324
|
+
if frame.type is FrameType.PONG:
|
|
325
|
+
return
|
|
326
|
+
|
|
327
|
+
if frame.type is FrameType.KICK:
|
|
328
|
+
kick = KickPayload.from_wire(raw)
|
|
329
|
+
self.emit("kick", kick)
|
|
330
|
+
self._request_close()
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
if frame.type is FrameType.ERROR:
|
|
334
|
+
self.emit(
|
|
335
|
+
"error",
|
|
336
|
+
Exception(f"{raw.get('code', 'ERROR')}: {raw.get('message', '')}"),
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def _emit_quote(self, quote: QuotePayload) -> None:
|
|
340
|
+
self.emit("quote", quote)
|
|
341
|
+
self.emit(f"quote:{quote.topic}", quote)
|
|
342
|
+
|
|
343
|
+
def _emit_curve(
|
|
344
|
+
self,
|
|
345
|
+
kind: Literal["curveSnap", "curveDelta"],
|
|
346
|
+
payload: CurveSnapPayload | CurveDeltaPayload,
|
|
347
|
+
) -> None:
|
|
348
|
+
self.emit(kind, payload)
|
|
349
|
+
self.emit(f"curve:{payload.topic}", payload)
|
|
350
|
+
|
|
351
|
+
def _request_close(self) -> None:
|
|
352
|
+
"""关闭连接且不触发自动重连(用于 AUTH_FAIL / KICK)。"""
|
|
353
|
+
self._stopping = True
|
|
354
|
+
writer = self._writer
|
|
355
|
+
if writer is not None and not writer.is_closing():
|
|
356
|
+
writer.close()
|
|
357
|
+
|
|
358
|
+
async def _on_socket_close(self) -> None:
|
|
359
|
+
if self._closing_socket:
|
|
360
|
+
return
|
|
361
|
+
self._closing_socket = True
|
|
362
|
+
|
|
363
|
+
await self._cancel_task(self._ping_task)
|
|
364
|
+
self._ping_task = None
|
|
365
|
+
self._read_task = None
|
|
366
|
+
|
|
367
|
+
writer = self._writer
|
|
368
|
+
self._writer = None
|
|
369
|
+
if writer is not None:
|
|
370
|
+
try:
|
|
371
|
+
if not writer.is_closing():
|
|
372
|
+
writer.close()
|
|
373
|
+
await writer.wait_closed()
|
|
374
|
+
except Exception: # noqa: BLE001
|
|
375
|
+
pass
|
|
376
|
+
|
|
377
|
+
fut = self._auth_fut
|
|
378
|
+
self._auth_fut = None
|
|
379
|
+
if fut and not fut.done():
|
|
380
|
+
fut.set_exception(Exception("connection closed during AUTH"))
|
|
381
|
+
|
|
382
|
+
pending = self._sub_futs[:]
|
|
383
|
+
self._sub_futs.clear()
|
|
384
|
+
for sub_fut in pending:
|
|
385
|
+
if not sub_fut.done():
|
|
386
|
+
sub_fut.set_exception(Exception("connection closed during SUB"))
|
|
387
|
+
|
|
388
|
+
was_stopping = self._stopping
|
|
389
|
+
self._set_state("closed")
|
|
390
|
+
self.emit("close")
|
|
391
|
+
|
|
392
|
+
if not was_stopping and self._auto_reconnect:
|
|
393
|
+
delay = min(10.0, 0.5 * (2**self._reconnect_attempt))
|
|
394
|
+
self._reconnect_attempt += 1
|
|
395
|
+
self._reconnect_task = asyncio.create_task(
|
|
396
|
+
self._reconnect_after(delay), name="quote-client-reconnect"
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
async def _reconnect_after(self, delay: float) -> None:
|
|
400
|
+
await asyncio.sleep(delay)
|
|
401
|
+
if self._stopping:
|
|
402
|
+
return
|
|
403
|
+
try:
|
|
404
|
+
await self._connect_once()
|
|
405
|
+
if self.topics:
|
|
406
|
+
await self.subscribe(list(self.topics))
|
|
407
|
+
except Exception as err: # noqa: BLE001
|
|
408
|
+
self.emit(
|
|
409
|
+
"error", err if isinstance(err, Exception) else Exception(str(err))
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
def _start_ping(
|
|
413
|
+
self, interval_sec: int = DEFAULT_HEARTBEAT_INTERVAL_SEC
|
|
414
|
+
) -> None:
|
|
415
|
+
if self._ping_task and not self._ping_task.done():
|
|
416
|
+
self._ping_task.cancel()
|
|
417
|
+
|
|
418
|
+
async def ping_loop() -> None:
|
|
419
|
+
period = max(5, interval_sec)
|
|
420
|
+
while True:
|
|
421
|
+
await asyncio.sleep(period)
|
|
422
|
+
self._idle_misses += 1
|
|
423
|
+
if self._idle_misses >= DEFAULT_IDLE_MISS_LIMIT:
|
|
424
|
+
self.emit("error", Exception("IDLE_TIMEOUT"))
|
|
425
|
+
if self._writer and not self._writer.is_closing():
|
|
426
|
+
self._writer.close()
|
|
427
|
+
return
|
|
428
|
+
self._write(FrameType.PING, {"ts": int(time.time() * 1000)})
|
|
429
|
+
|
|
430
|
+
self._ping_task = asyncio.create_task(ping_loop(), name="quote-client-ping")
|
|
431
|
+
|
|
432
|
+
def _write(self, frame_type: FrameType, payload: dict[str, Any]) -> None:
|
|
433
|
+
writer = self._writer
|
|
434
|
+
if writer is None or writer.is_closing():
|
|
435
|
+
return
|
|
436
|
+
writer.write(encode_frame(frame_type, payload))
|
|
437
|
+
|
|
438
|
+
def _set_state(self, state: SessionState) -> None:
|
|
439
|
+
self.state = state
|
|
440
|
+
self.emit("state", state)
|
|
441
|
+
|
|
442
|
+
def _ensure_ready(self) -> None:
|
|
443
|
+
if self.state not in ("ready", "subscribed"):
|
|
444
|
+
raise RuntimeError(f"not ready (state={self.state})")
|
|
445
|
+
|
|
446
|
+
@staticmethod
|
|
447
|
+
async def _cancel_task(task: asyncio.Task[Any] | None) -> None:
|
|
448
|
+
if task is None or task.done():
|
|
449
|
+
return
|
|
450
|
+
task.cancel()
|
|
451
|
+
try:
|
|
452
|
+
await task
|
|
453
|
+
except asyncio.CancelledError:
|
|
454
|
+
pass
|
|
455
|
+
|
|
456
|
+
@staticmethod
|
|
457
|
+
def _normalize_auth(auth: AuthPayload | dict[str, Any]) -> AuthPayload:
|
|
458
|
+
if isinstance(auth, AuthPayload):
|
|
459
|
+
return auth
|
|
460
|
+
return AuthPayload(
|
|
461
|
+
token=auth.get("token"),
|
|
462
|
+
activation_key=auth.get("activationKey") or auth.get("activation_key"),
|
|
463
|
+
device_id=auth.get("deviceId") or auth.get("device_id"),
|
|
464
|
+
client_version=auth.get("clientVersion") or auth.get("client_version"),
|
|
465
|
+
)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""曲线产品收窄 / 区间主力差分(对齐 Node `@alphaio/quote-client`)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping, MutableMapping, Sequence
|
|
6
|
+
|
|
7
|
+
from .protocol import CurveDeltaPayload, CurveSnapPayload, is_quote_stream_kind, parse_quote_topic
|
|
8
|
+
|
|
9
|
+
CURVE_KINDS = frozenset({"fenshi", "fenshi_vol", "mf_range"})
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def curve_kind_of(topic: str) -> str | None:
|
|
13
|
+
parsed = parse_quote_topic(topic)
|
|
14
|
+
if not parsed:
|
|
15
|
+
return None
|
|
16
|
+
kind, _symbol = parsed
|
|
17
|
+
return kind if kind in CURVE_KINDS else None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_mf_range_point(point: Mapping[str, Any]) -> bool:
|
|
21
|
+
return (
|
|
22
|
+
isinstance(point.get("mainNet"), (int, float))
|
|
23
|
+
and isinstance(point.get("mainBuy"), (int, float))
|
|
24
|
+
and isinstance(point.get("mainSell"), (int, float))
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def narrow_curve_snap(snap: CurveSnapPayload) -> dict[str, Any]:
|
|
29
|
+
kind = curve_kind_of(snap.topic) or "unknown"
|
|
30
|
+
out: dict[str, Any] = {
|
|
31
|
+
"kind": kind,
|
|
32
|
+
"topic": snap.topic,
|
|
33
|
+
"items": list(snap.items),
|
|
34
|
+
}
|
|
35
|
+
if snap.total is not None:
|
|
36
|
+
out["total"] = snap.total
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def narrow_curve_delta(delta: CurveDeltaPayload) -> dict[str, Any]:
|
|
41
|
+
kind = curve_kind_of(delta.topic) or "unknown"
|
|
42
|
+
return {"kind": kind, "topic": delta.topic, "items": list(delta.items)}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def last_mf_range_point(
|
|
46
|
+
snap_or_items: CurveSnapPayload | CurveDeltaPayload | Sequence[Mapping[str, Any]],
|
|
47
|
+
topic_hint: str | None = None,
|
|
48
|
+
) -> dict[str, Any] | None:
|
|
49
|
+
if isinstance(snap_or_items, (CurveSnapPayload, CurveDeltaPayload)):
|
|
50
|
+
topic = topic_hint or snap_or_items.topic
|
|
51
|
+
items: Sequence[Mapping[str, Any]] = snap_or_items.items
|
|
52
|
+
else:
|
|
53
|
+
topic = topic_hint
|
|
54
|
+
items = snap_or_items
|
|
55
|
+
if topic is not None:
|
|
56
|
+
kind = curve_kind_of(topic)
|
|
57
|
+
if kind is not None and kind != "mf_range":
|
|
58
|
+
return None
|
|
59
|
+
if not items:
|
|
60
|
+
return None
|
|
61
|
+
last = items[-1]
|
|
62
|
+
return dict(last) if isinstance(last, Mapping) else None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def diff_mf_range_points(
|
|
66
|
+
left: Mapping[str, Any], right: Mapping[str, Any]
|
|
67
|
+
) -> dict[str, Any]:
|
|
68
|
+
def sub(a: Any, b: Any) -> float | None:
|
|
69
|
+
if a is None and b is None:
|
|
70
|
+
return None
|
|
71
|
+
return float(a or 0) - float(b or 0)
|
|
72
|
+
|
|
73
|
+
out: MutableMapping[str, Any] = {
|
|
74
|
+
"ts": right.get("ts"),
|
|
75
|
+
"mainBuy": float(right.get("mainBuy", 0)) - float(left.get("mainBuy", 0)),
|
|
76
|
+
"mainSell": float(right.get("mainSell", 0)) - float(left.get("mainSell", 0)),
|
|
77
|
+
"mainNet": float(right.get("mainNet", 0)) - float(left.get("mainNet", 0)),
|
|
78
|
+
}
|
|
79
|
+
for key in (
|
|
80
|
+
"turnover",
|
|
81
|
+
"turnoverRatio",
|
|
82
|
+
"changCount",
|
|
83
|
+
"chipLarge",
|
|
84
|
+
"chipMiddle",
|
|
85
|
+
"chipSmall",
|
|
86
|
+
"chipSmallest",
|
|
87
|
+
):
|
|
88
|
+
v = sub(right.get(key), left.get(key))
|
|
89
|
+
if v is not None:
|
|
90
|
+
out[key] = int(v) if key == "changCount" else v
|
|
91
|
+
return dict(out)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def is_curve_stream_kind(value: str) -> bool:
|
|
95
|
+
return value in CURVE_KINDS and is_quote_stream_kind(value)
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""线缆协议类型与长度前缀帧编解码(见 PROTOCOL.md §3)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import struct
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from enum import IntEnum
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
PROTOCOL_VERSION = "0.5.0"
|
|
13
|
+
DEFAULT_HEARTBEAT_INTERVAL_SEC = 30
|
|
14
|
+
DEFAULT_IDLE_MISS_LIMIT = 3
|
|
15
|
+
HEADER_SIZE = 5 # 4 字节长度 + 1 字节类型
|
|
16
|
+
MAX_FRAME_BYTES = 1024 * 1024 # 1 MiB
|
|
17
|
+
TOPIC_RE = re.compile(r"^[a-z0-9_-]+\.[A-Za-z0-9._-]+$")
|
|
18
|
+
QUOTE_STREAM_KINDS = ("l2", "trans", "order", "fenshi", "fenshi_vol", "mf_range")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FrameType(IntEnum):
|
|
22
|
+
AUTH = 0x01
|
|
23
|
+
AUTH_OK = 0x02
|
|
24
|
+
AUTH_FAIL = 0x03
|
|
25
|
+
SUB = 0x10
|
|
26
|
+
SUB_ACK = 0x11
|
|
27
|
+
UNSUB = 0x12
|
|
28
|
+
UNSUB_ACK = 0x13
|
|
29
|
+
PING = 0x20
|
|
30
|
+
PONG = 0x21
|
|
31
|
+
KICK = 0x30
|
|
32
|
+
ERROR = 0x31
|
|
33
|
+
QUOTE = 0x40
|
|
34
|
+
QUOTE_BATCH = 0x41
|
|
35
|
+
QUOTE_SNAP = 0x42
|
|
36
|
+
CURVE_SNAP = 0x50
|
|
37
|
+
CURVE_DELTA = 0x51
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_KNOWN_TYPES = frozenset(int(t) for t in FrameType)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class AuthPayload:
|
|
45
|
+
token: str | None = None
|
|
46
|
+
activation_key: str | None = None
|
|
47
|
+
device_id: str | None = None
|
|
48
|
+
client_version: str | None = None
|
|
49
|
+
|
|
50
|
+
def to_wire(self) -> dict[str, Any]:
|
|
51
|
+
out: dict[str, Any] = {}
|
|
52
|
+
if self.token is not None:
|
|
53
|
+
out["token"] = self.token
|
|
54
|
+
if self.activation_key is not None:
|
|
55
|
+
out["activationKey"] = self.activation_key
|
|
56
|
+
if self.device_id is not None:
|
|
57
|
+
out["deviceId"] = self.device_id
|
|
58
|
+
if self.client_version is not None:
|
|
59
|
+
out["clientVersion"] = self.client_version
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class QuoteStreamQuotas:
|
|
65
|
+
l2: int = 0
|
|
66
|
+
trans: int = 0
|
|
67
|
+
order: int = 0
|
|
68
|
+
fenshi: int = 0
|
|
69
|
+
fenshi_vol: int = 0
|
|
70
|
+
mf_range: int = 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class AuthOkPayload:
|
|
75
|
+
lease_id: str
|
|
76
|
+
stream_quotas: QuoteStreamQuotas
|
|
77
|
+
valid_until: str
|
|
78
|
+
heartbeat_interval_sec: int
|
|
79
|
+
customer_id: str | None = None
|
|
80
|
+
device_id: str | None = None
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def from_wire(cls, raw: dict[str, Any]) -> AuthOkPayload:
|
|
84
|
+
sq = raw.get("streamQuotas") or {}
|
|
85
|
+
return cls(
|
|
86
|
+
lease_id=str(raw["leaseId"]),
|
|
87
|
+
stream_quotas=QuoteStreamQuotas(
|
|
88
|
+
l2=int(sq.get("l2", 0)),
|
|
89
|
+
trans=int(sq.get("trans", 0)),
|
|
90
|
+
order=int(sq.get("order", 0)),
|
|
91
|
+
fenshi=int(sq.get("fenshi", 0)),
|
|
92
|
+
fenshi_vol=int(sq.get("fenshiVol", 0)),
|
|
93
|
+
mf_range=int(sq.get("mfRange", 0)),
|
|
94
|
+
),
|
|
95
|
+
valid_until=str(raw.get("validUntil", "")),
|
|
96
|
+
heartbeat_interval_sec=int(
|
|
97
|
+
raw.get("heartbeatIntervalSec", DEFAULT_HEARTBEAT_INTERVAL_SEC)
|
|
98
|
+
),
|
|
99
|
+
customer_id=raw.get("customerId"),
|
|
100
|
+
device_id=raw.get("deviceId"),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class AuthFailPayload:
|
|
106
|
+
code: str
|
|
107
|
+
message: str
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def from_wire(cls, raw: dict[str, Any]) -> AuthFailPayload:
|
|
111
|
+
return cls(code=str(raw.get("code", "AUTH_INVALID")), message=str(raw.get("message", "")))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class SubRejected:
|
|
116
|
+
topic: str
|
|
117
|
+
code: str
|
|
118
|
+
message: str
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class SubAckPayload:
|
|
123
|
+
accepted: list[str] = field(default_factory=list)
|
|
124
|
+
rejected: list[SubRejected] = field(default_factory=list)
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def from_wire(cls, raw: dict[str, Any]) -> SubAckPayload:
|
|
128
|
+
rejected: list[SubRejected] = []
|
|
129
|
+
for item in raw.get("rejected") or []:
|
|
130
|
+
rejected.append(
|
|
131
|
+
SubRejected(
|
|
132
|
+
topic=str(item.get("topic", "")),
|
|
133
|
+
code=str(item.get("code", "SUB_BAD_TOPIC")),
|
|
134
|
+
message=str(item.get("message", "")),
|
|
135
|
+
)
|
|
136
|
+
)
|
|
137
|
+
return cls(
|
|
138
|
+
accepted=[str(t) for t in (raw.get("accepted") or [])],
|
|
139
|
+
rejected=rejected,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass
|
|
144
|
+
class QuotePayload:
|
|
145
|
+
topic: str
|
|
146
|
+
ts: int
|
|
147
|
+
last: float
|
|
148
|
+
bid: float | None = None
|
|
149
|
+
ask: float | None = None
|
|
150
|
+
date: int | None = None
|
|
151
|
+
time: int | None = None
|
|
152
|
+
index: int | None = None
|
|
153
|
+
price: float | None = None
|
|
154
|
+
volume: int | None = None
|
|
155
|
+
turnover: int | None = None
|
|
156
|
+
bs_flag: str | None = None
|
|
157
|
+
order_no: int | None = None
|
|
158
|
+
buy_id: int | None = None
|
|
159
|
+
sell_id: int | None = None
|
|
160
|
+
order_kind: str | None = None
|
|
161
|
+
function_code: str | None = None
|
|
162
|
+
channel: int | None = None
|
|
163
|
+
market: int | None = None
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def from_wire(cls, raw: dict[str, Any]) -> QuotePayload:
|
|
167
|
+
return cls(
|
|
168
|
+
topic=str(raw.get("topic", "")),
|
|
169
|
+
ts=int(raw.get("ts", 0)),
|
|
170
|
+
last=float(raw.get("last", 0)),
|
|
171
|
+
bid=_opt_float(raw.get("bid")),
|
|
172
|
+
ask=_opt_float(raw.get("ask")),
|
|
173
|
+
date=_opt_int(raw.get("date")),
|
|
174
|
+
time=_opt_int(raw.get("time")),
|
|
175
|
+
index=_opt_int(raw.get("index")),
|
|
176
|
+
price=_opt_float(raw.get("price")),
|
|
177
|
+
volume=_opt_int(raw.get("volume")),
|
|
178
|
+
turnover=_opt_int(raw.get("turnover")),
|
|
179
|
+
bs_flag=_opt_str(raw.get("bs_flag")),
|
|
180
|
+
order_no=_opt_int(raw.get("order_no")),
|
|
181
|
+
buy_id=_opt_int(raw.get("buy_id")),
|
|
182
|
+
sell_id=_opt_int(raw.get("sell_id")),
|
|
183
|
+
order_kind=_opt_str(raw.get("order_kind")),
|
|
184
|
+
function_code=_opt_str(raw.get("function_code")),
|
|
185
|
+
channel=_opt_int(raw.get("channel")),
|
|
186
|
+
market=_opt_int(raw.get("market")),
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass
|
|
191
|
+
class QuoteSnapPayload:
|
|
192
|
+
topic: str
|
|
193
|
+
items: list[QuotePayload] = field(default_factory=list)
|
|
194
|
+
|
|
195
|
+
@classmethod
|
|
196
|
+
def from_wire(cls, raw: dict[str, Any]) -> QuoteSnapPayload:
|
|
197
|
+
return cls(
|
|
198
|
+
topic=str(raw.get("topic", "")),
|
|
199
|
+
items=[QuotePayload.from_wire(i) for i in (raw.get("items") or [])],
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass
|
|
204
|
+
class CurveSnapPayload:
|
|
205
|
+
"""CURVE_SNAP — 当日曲线快照(按 topic 区分 fenshi / fenshi_vol / mf_range)。"""
|
|
206
|
+
|
|
207
|
+
topic: str
|
|
208
|
+
items: list[dict[str, Any]] = field(default_factory=list)
|
|
209
|
+
total: int | None = None
|
|
210
|
+
|
|
211
|
+
@classmethod
|
|
212
|
+
def from_wire(cls, raw: dict[str, Any]) -> CurveSnapPayload:
|
|
213
|
+
total = raw.get("total")
|
|
214
|
+
return cls(
|
|
215
|
+
topic=str(raw.get("topic", "")),
|
|
216
|
+
items=[item for item in (raw.get("items") or []) if isinstance(item, dict)],
|
|
217
|
+
total=int(total) if total is not None else None,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass
|
|
222
|
+
class CurveDeltaPayload:
|
|
223
|
+
"""CURVE_DELTA — 曲线增量点列。"""
|
|
224
|
+
|
|
225
|
+
topic: str
|
|
226
|
+
items: list[dict[str, Any]] = field(default_factory=list)
|
|
227
|
+
|
|
228
|
+
@classmethod
|
|
229
|
+
def from_wire(cls, raw: dict[str, Any]) -> CurveDeltaPayload:
|
|
230
|
+
return cls(
|
|
231
|
+
topic=str(raw.get("topic", "")),
|
|
232
|
+
items=[item for item in (raw.get("items") or []) if isinstance(item, dict)],
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@dataclass
|
|
237
|
+
class KickPayload:
|
|
238
|
+
reason: str
|
|
239
|
+
message: str | None = None
|
|
240
|
+
|
|
241
|
+
@classmethod
|
|
242
|
+
def from_wire(cls, raw: dict[str, Any]) -> KickPayload:
|
|
243
|
+
return cls(reason=str(raw.get("reason", "")), message=raw.get("message"))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@dataclass
|
|
247
|
+
class DecodedFrame:
|
|
248
|
+
type: FrameType
|
|
249
|
+
payload: Any
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _opt_float(value: Any) -> float | None:
|
|
253
|
+
if value is None:
|
|
254
|
+
return None
|
|
255
|
+
return float(value)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _opt_int(value: Any) -> int | None:
|
|
259
|
+
if value is None:
|
|
260
|
+
return None
|
|
261
|
+
return int(value)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _opt_str(value: Any) -> str | None:
|
|
265
|
+
if value is None:
|
|
266
|
+
return None
|
|
267
|
+
return str(value)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def encode_frame(frame_type: FrameType | int, payload: dict[str, Any] | None = None) -> bytes:
|
|
271
|
+
body = json.dumps(payload or {}, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
272
|
+
length = 1 + len(body)
|
|
273
|
+
if length > MAX_FRAME_BYTES:
|
|
274
|
+
raise ValueError(f"frame too large: {length}")
|
|
275
|
+
return struct.pack(">IB", length, int(frame_type)) + body
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def try_decode_frame(buffer: memoryview | bytes) -> tuple[DecodedFrame, int] | None:
|
|
279
|
+
if len(buffer) < 4:
|
|
280
|
+
return None
|
|
281
|
+
(length,) = struct.unpack_from(">I", buffer, 0)
|
|
282
|
+
if length < 1 or length > MAX_FRAME_BYTES:
|
|
283
|
+
raise ValueError(f"invalid frame length: {length}")
|
|
284
|
+
if len(buffer) < 4 + length:
|
|
285
|
+
return None
|
|
286
|
+
type_byte = buffer[4]
|
|
287
|
+
raw_json = bytes(buffer[5 : 4 + length]).decode("utf-8")
|
|
288
|
+
try:
|
|
289
|
+
payload: Any = json.loads(raw_json) if raw_json else {}
|
|
290
|
+
except json.JSONDecodeError as exc:
|
|
291
|
+
raise ValueError("invalid JSON payload") from exc
|
|
292
|
+
if type_byte not in _KNOWN_TYPES:
|
|
293
|
+
raise ValueError(f"unknown frame type: 0x{type_byte:02x}")
|
|
294
|
+
return DecodedFrame(type=FrameType(type_byte), payload=payload), 4 + length
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class FrameReader:
|
|
298
|
+
"""从 TCP 字节流增量解析长度前缀帧。"""
|
|
299
|
+
|
|
300
|
+
def __init__(self) -> None:
|
|
301
|
+
self._buf = bytearray()
|
|
302
|
+
|
|
303
|
+
def push(self, chunk: bytes) -> list[DecodedFrame]:
|
|
304
|
+
self._buf.extend(chunk)
|
|
305
|
+
frames: list[DecodedFrame] = []
|
|
306
|
+
while True:
|
|
307
|
+
decoded = try_decode_frame(self._buf)
|
|
308
|
+
if decoded is None:
|
|
309
|
+
break
|
|
310
|
+
frame, consumed = decoded
|
|
311
|
+
frames.append(frame)
|
|
312
|
+
del self._buf[:consumed]
|
|
313
|
+
return frames
|
|
314
|
+
|
|
315
|
+
def reset(self) -> None:
|
|
316
|
+
self._buf.clear()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def is_quote_stream_kind(value: str) -> bool:
|
|
320
|
+
return value in QUOTE_STREAM_KINDS
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def parse_quote_topic(topic: str) -> tuple[str, str] | None:
|
|
324
|
+
"""解析 ``l2|trans|order|fenshi|fenshi_vol|mf_range.{symbol}``;未知前缀返回 None。"""
|
|
325
|
+
parts = topic.strip().split(".")
|
|
326
|
+
if len(parts) < 2:
|
|
327
|
+
return None
|
|
328
|
+
head, *rest = parts
|
|
329
|
+
symbol = ".".join(rest).strip()
|
|
330
|
+
if not symbol or not is_quote_stream_kind(head):
|
|
331
|
+
return None
|
|
332
|
+
return head, symbol
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def format_quote_topic(kind: str, symbol: str) -> str:
|
|
336
|
+
return f"{kind}.{symbol.strip()}"
|