conrich2 1.0.0.dev0__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.
- conrich/Common/__init__.py +0 -0
- conrich/Common/cipher.py +74 -0
- conrich/Common/endpoints.py +49 -0
- conrich/Common/errors.py +29 -0
- conrich/Common/events.py +117 -0
- conrich/Common/framing.py +70 -0
- conrich/Common/gate.py +65 -0
- conrich/Common/normalize.py +46 -0
- conrich/Common/records.py +44 -0
- conrich/Common/service.py +110 -0
- conrich/Common/signer.py +176 -0
- conrich/Common/tagvalue.py +47 -0
- conrich/Common/timeutil.py +35 -0
- conrich/Common/transport.py +171 -0
- conrich/Common/version.py +16 -0
- conrich/Futures/Futures_README.md +71 -0
- conrich/Futures/__init__.py +12 -0
- conrich/Futures/base.py +236 -0
- conrich/Futures/constant.py +63 -0
- conrich/Futures/fields.py +716 -0
- conrich/Futures/foreign_futures.py +53 -0
- conrich/Futures/futures.py +74 -0
- conrich/Futures/messages.py +97 -0
- conrich/Futures/session.py +464 -0
- conrich/Quote/__init__.py +15 -0
- conrich/Quote/event.py +4 -0
- conrich/Quote/quote.py +116 -0
- conrich/Quote/server.py +10 -0
- conrich/Quote/symbols.py +18 -0
- conrich/Stock/__init__.py +10 -0
- conrich/Stock/constant.py +48 -0
- conrich/Stock/fields.py +147 -0
- conrich/Stock/messages.py +179 -0
- conrich/Stock/orders.py +104 -0
- conrich/Stock/results.py +53 -0
- conrich/Stock/session.py +373 -0
- conrich/Stock/stock.py +279 -0
- conrich/__init__.py +38 -0
- conrich2-1.0.0.dev0.dist-info/METADATA +242 -0
- conrich2-1.0.0.dev0.dist-info/RECORD +43 -0
- conrich2-1.0.0.dev0.dist-info/WHEEL +5 -0
- conrich2-1.0.0.dev0.dist-info/licenses/LICENSE +21 -0
- conrich2-1.0.0.dev0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Futures session: HTTPS login steps, order channel, report channel, state flags.
|
|
3
|
+
|
|
4
|
+
Flow (design-2025.md 3.5): SYS_QVersion + SYS_QSocketConnIP -> certificate check -> sign ->
|
|
5
|
+
SYS_LoginByCA -> SYS_QFMarketType -> SYS_QSignEnhance -> SYS_QAccountInfo -> order channel (35=A) ->
|
|
6
|
+
report channel (35=A, 35=r) -> code 102. Orders leave only through ``send_order()`` (gate first).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import ssl
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from typing import Callable
|
|
15
|
+
|
|
16
|
+
from ..Common import cipher as cipher_mod
|
|
17
|
+
from ..Common.endpoints import is_evaluation, service_url_for
|
|
18
|
+
from ..Common.errors import CertificateError
|
|
19
|
+
from ..Common.events import Dispatcher
|
|
20
|
+
from ..Common.framing import HEARTBEAT_PLAIN, ConcordsFramer
|
|
21
|
+
from ..Common.gate import TradingGate
|
|
22
|
+
from ..Common.records import mask_id
|
|
23
|
+
from ..Common.service import ServiceClient
|
|
24
|
+
from ..Common.signer import REASON_TEXT, SignParts, Signer, login_plain as signed_login_plain
|
|
25
|
+
from ..Common.timeutil import now_taipei
|
|
26
|
+
from ..Common.transport import Channel
|
|
27
|
+
from ..Common.version import check_min_version, parse_version
|
|
28
|
+
from . import messages
|
|
29
|
+
from .messages import DOMESTIC, FOREIGN, MarketSpec
|
|
30
|
+
|
|
31
|
+
__all__ = ['FuturesSession', 'MarketSpec', 'DOMESTIC', 'FOREIGN']
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger('conrich.futures')
|
|
34
|
+
|
|
35
|
+
SIGN_FAILED = '登入驗證失敗:憑證或簽章無法使用'
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FuturesSession:
|
|
39
|
+
def __init__(self, spec: MarketSpec, gateway: str, api_version: str, dispatcher: Dispatcher,
|
|
40
|
+
on_report: Callable[[str, str, str], None], signer: Signer | None, gate: TradingGate, *,
|
|
41
|
+
service_url: str | None = None, ssl_context: ssl.SSLContext | None = None,
|
|
42
|
+
ports_override: dict[str, int] | None = None, heartbeat_interval: float = 30.0,
|
|
43
|
+
idle: tuple[float, float, float] = (5.0, 5.0, 12.5), service_timeout: float = 60.0,
|
|
44
|
+
retry_interval: float = 0.5) -> None:
|
|
45
|
+
self.spec = spec
|
|
46
|
+
self.gateway = gateway
|
|
47
|
+
self.host = gateway # TCP host; replaced by SYS_QSocketConnIP during login
|
|
48
|
+
self.api_version = api_version
|
|
49
|
+
self.dispatcher = dispatcher
|
|
50
|
+
self._report = on_report # (kind, code, msg); called on the dispatcher thread
|
|
51
|
+
self.signer = signer
|
|
52
|
+
self.gate = gate
|
|
53
|
+
self.service = ServiceClient(service_url or service_url_for(gateway), timeout=service_timeout,
|
|
54
|
+
ssl_context=ssl_context, product='futures')
|
|
55
|
+
self.ports_override = dict(ports_override or {})
|
|
56
|
+
self.heartbeat_interval = heartbeat_interval
|
|
57
|
+
self.idle = idle
|
|
58
|
+
self.retry_interval = retry_interval
|
|
59
|
+
self.accounts: list[str] = [] # account rows of this market (column 0 == spec.name)
|
|
60
|
+
self.multi = False
|
|
61
|
+
self.sign_enhance = False
|
|
62
|
+
self.enhance: SignParts | None = None
|
|
63
|
+
self.order_lock = threading.Lock()
|
|
64
|
+
self.seen_bulletins: set[str] = set()
|
|
65
|
+
self.last_code = ''
|
|
66
|
+
self.last_message = ''
|
|
67
|
+
self.id_no = ''
|
|
68
|
+
self._pwd_hash = ''
|
|
69
|
+
self._sign: SignParts | None = None
|
|
70
|
+
self._account_login = False
|
|
71
|
+
self._bhno = ''
|
|
72
|
+
self._account = ''
|
|
73
|
+
self._order_port = self._receive_port = 0
|
|
74
|
+
self._order: Channel | None = None
|
|
75
|
+
self._receive: Channel | None = None
|
|
76
|
+
self.order_login = False
|
|
77
|
+
self.receive_login = False
|
|
78
|
+
self.logged_in = False
|
|
79
|
+
self._done = threading.Event()
|
|
80
|
+
self._closing = False
|
|
81
|
+
self._deadline = 0.0
|
|
82
|
+
|
|
83
|
+
# ------------------------------------------------------------------ helpers
|
|
84
|
+
def _submit(self, kind: str, code: str, msg: str) -> None:
|
|
85
|
+
self.dispatcher.submit(lambda: self._report(kind, code, msg))
|
|
86
|
+
|
|
87
|
+
def _fail(self, code: str, msg: str) -> None:
|
|
88
|
+
self.last_code, self.last_message = code, msg
|
|
89
|
+
self._done.set()
|
|
90
|
+
|
|
91
|
+
def is_connected(self) -> bool:
|
|
92
|
+
return bool(self._order and self._order.connected and self._receive and self._receive.connected
|
|
93
|
+
and self.order_login and self.receive_login)
|
|
94
|
+
|
|
95
|
+
def check_connect(self) -> tuple[str, str]:
|
|
96
|
+
"""FCheckConnect: 102, else 210 / 214 / 211 / 215."""
|
|
97
|
+
order_ok = bool(self._order and self._order.connected)
|
|
98
|
+
recv_ok = bool(self._receive and self._receive.connected)
|
|
99
|
+
if order_ok and recv_ok and self.order_login and self.receive_login:
|
|
100
|
+
return '102', '登入成功'
|
|
101
|
+
if not order_ok:
|
|
102
|
+
return '210', '下單連線中斷'
|
|
103
|
+
if not recv_ok:
|
|
104
|
+
return '214', '回報連線中斷'
|
|
105
|
+
if not self.order_login:
|
|
106
|
+
return '211', '下單登入驗證失敗'
|
|
107
|
+
return '215', '回報登入驗證失敗'
|
|
108
|
+
|
|
109
|
+
def check_account(self, bhno: str, cseq: str) -> bool:
|
|
110
|
+
for row in self.accounts:
|
|
111
|
+
cols = row.split(',')
|
|
112
|
+
if len(cols) > 4 and cols[3] == bhno.strip() and cols[4] == cseq.strip():
|
|
113
|
+
return True
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
def cert_ok(self) -> tuple[bool, str]:
|
|
117
|
+
"""Re-check the certificate when an order is placed (validity period, subject, key usage)."""
|
|
118
|
+
if self.signer is None:
|
|
119
|
+
return False, REASON_TEXT['sign_error']
|
|
120
|
+
try:
|
|
121
|
+
self.signer.check(self.id_no, evaluation=is_evaluation(self.gateway))
|
|
122
|
+
except CertificateError as exc:
|
|
123
|
+
return False, str(exc)
|
|
124
|
+
return True, ''
|
|
125
|
+
|
|
126
|
+
def clear_enhance(self) -> None:
|
|
127
|
+
self.enhance = None
|
|
128
|
+
|
|
129
|
+
# ------------------------------------------------------------------ HTTP steps
|
|
130
|
+
def _q_version(self) -> bool:
|
|
131
|
+
"""SYS_QVersion and SYS_QSocketConnIP are both sent before the version is judged (3.3)."""
|
|
132
|
+
try:
|
|
133
|
+
major = str(parse_version(self.api_version)[0])
|
|
134
|
+
except ValueError:
|
|
135
|
+
self._fail('999', '查無對應版號')
|
|
136
|
+
return False
|
|
137
|
+
code, content = self.service.call('SYS_QVersion', ['F', major])
|
|
138
|
+
sock_code, sock_content = self.service.call('SYS_QSocketConnIP', ['F'])
|
|
139
|
+
self.host = sock_content.strip() if sock_code == '000' and sock_content.strip() else self.gateway
|
|
140
|
+
if code != '000':
|
|
141
|
+
self._fail('999', '查無對應版號')
|
|
142
|
+
return False
|
|
143
|
+
try:
|
|
144
|
+
ok = check_min_version(self.api_version, content)
|
|
145
|
+
except ValueError:
|
|
146
|
+
self._fail('999', '查無對應版號')
|
|
147
|
+
return False
|
|
148
|
+
if not ok:
|
|
149
|
+
logger.warning('server requires version %s, declared %s: login stopped before sending credentials',
|
|
150
|
+
content, self.api_version)
|
|
151
|
+
self._fail('204', '版本過舊,請更新至最新版')
|
|
152
|
+
return False
|
|
153
|
+
return True
|
|
154
|
+
|
|
155
|
+
def _prepare_signature(self) -> bool:
|
|
156
|
+
assert self.signer is not None
|
|
157
|
+
try:
|
|
158
|
+
self.signer.check(self.id_no, evaluation=is_evaluation(self.gateway))
|
|
159
|
+
self._sign = self.signer.sign(signed_login_plain(now_taipei()))
|
|
160
|
+
except CertificateError as exc:
|
|
161
|
+
logger.warning('login stopped: certificate problem (%s)', exc.reason or 'unknown')
|
|
162
|
+
self._fail('998', str(exc))
|
|
163
|
+
return False
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
def _http_login(self) -> bool:
|
|
167
|
+
assert self._sign is not None
|
|
168
|
+
sign = self._sign
|
|
169
|
+
code, content = self.service.call('SYS_LoginByCA', [
|
|
170
|
+
self.id_no, self._bhno, self._account, self._pwd_hash, 'F', '4' if self._account_login else '1', '',
|
|
171
|
+
sign.cert_no, sign.signature, sign.plain, 'F', 'Z'])
|
|
172
|
+
if code != '000':
|
|
173
|
+
self._fail('998', '[0507] 驗章失敗' if code == '507' else content)
|
|
174
|
+
return False
|
|
175
|
+
if self._account_login:
|
|
176
|
+
for row in content.split('\n'):
|
|
177
|
+
cols = row.split(',')
|
|
178
|
+
if len(cols) > 2:
|
|
179
|
+
self.id_no = cols[1]
|
|
180
|
+
break
|
|
181
|
+
return True
|
|
182
|
+
|
|
183
|
+
def _market_open(self) -> bool:
|
|
184
|
+
code, content = self.service.call('SYS_QFMarketType', [self.id_no])
|
|
185
|
+
if code != '000':
|
|
186
|
+
self._fail('104', f'取得權限錯誤:{content}')
|
|
187
|
+
return False
|
|
188
|
+
domestic = foreign = False
|
|
189
|
+
for row in content.split('\n'):
|
|
190
|
+
cols = row.split(',')
|
|
191
|
+
if len(cols) > 2:
|
|
192
|
+
if cols[2] == 'A':
|
|
193
|
+
domestic = foreign = True
|
|
194
|
+
elif cols[2] == 'I':
|
|
195
|
+
domestic = True
|
|
196
|
+
elif cols[2] == 'O':
|
|
197
|
+
foreign = True
|
|
198
|
+
if not (domestic if self.spec is DOMESTIC else foreign):
|
|
199
|
+
self._fail('104', '未開期貨戶')
|
|
200
|
+
return False
|
|
201
|
+
return True
|
|
202
|
+
|
|
203
|
+
def _sign_enhance(self) -> None:
|
|
204
|
+
code, content = self.service.call('SYS_QSignEnhance', [self.id_no])
|
|
205
|
+
if code != '000':
|
|
206
|
+
return
|
|
207
|
+
for row in content.split('\n'):
|
|
208
|
+
cols = row.split(',')
|
|
209
|
+
if len(cols) > 1 and cols[0] == self.spec.name and cols[1] == 'Y':
|
|
210
|
+
self.sign_enhance = True
|
|
211
|
+
|
|
212
|
+
def _account_info(self) -> bool:
|
|
213
|
+
code, content = self.service.call('SYS_QAccountInfo', [self.spec.name, self.id_no, 'A'])
|
|
214
|
+
if code != '000':
|
|
215
|
+
self._fail('105', '未授權API')
|
|
216
|
+
return False
|
|
217
|
+
try:
|
|
218
|
+
cols = content.split('\n')[-1].split(',') # the DLL loop keeps the last row
|
|
219
|
+
self._order_port = self.ports_override.get(self.spec.order_channel, int(cols[2]))
|
|
220
|
+
self._receive_port = self.ports_override.get(self.spec.receive_channel, int(cols[3]))
|
|
221
|
+
self.multi = len(cols) > 6 and cols[6] == 'Y'
|
|
222
|
+
except (IndexError, ValueError):
|
|
223
|
+
self._fail('999', '非預期錯誤')
|
|
224
|
+
return False
|
|
225
|
+
return True
|
|
226
|
+
|
|
227
|
+
# ------------------------------------------------------------------ login
|
|
228
|
+
def login(self, id_no: str, pwd: str, branch_no: str, account_no: str, timeout: float) -> bool:
|
|
229
|
+
self._account_login = not id_no
|
|
230
|
+
self.id_no = id_no if self._account_login else id_no.strip().upper()
|
|
231
|
+
self._bhno, self._account = (branch_no, account_no) if self._account_login else ('', '')
|
|
232
|
+
self.last_code, self.last_message = '', ''
|
|
233
|
+
self._sign = None
|
|
234
|
+
self._done.clear()
|
|
235
|
+
self._closing = False
|
|
236
|
+
self._deadline = time.monotonic() + timeout
|
|
237
|
+
logger.info('[Login] user %s', mask_id(self.id_no) if self.id_no else '(by account)')
|
|
238
|
+
try:
|
|
239
|
+
self._pwd_hash = cipher_mod.hash_password(pwd, 'futures')
|
|
240
|
+
except ValueError:
|
|
241
|
+
self._fail('998', '登入驗證失敗:密碼含無法編碼的字元')
|
|
242
|
+
self._submit('error', self.last_code, self.last_message)
|
|
243
|
+
return False
|
|
244
|
+
if self.signer is None:
|
|
245
|
+
self._submit('general', '101', '登入開始')
|
|
246
|
+
self._fail('998', '登入驗證失敗:未提供憑證')
|
|
247
|
+
self._submit('error', self.last_code, self.last_message)
|
|
248
|
+
return False
|
|
249
|
+
if not self._q_version():
|
|
250
|
+
self._submit('error', self.last_code, self.last_message)
|
|
251
|
+
return False
|
|
252
|
+
self._submit('general', '101', '登入開始')
|
|
253
|
+
if not (self._prepare_signature() and self._http_login()):
|
|
254
|
+
self._submit('error', self.last_code, self.last_message)
|
|
255
|
+
return False
|
|
256
|
+
if not self._market_open():
|
|
257
|
+
self._submit('general' if self.last_message == '未開期貨戶' else 'error', self.last_code, self.last_message)
|
|
258
|
+
return False
|
|
259
|
+
self._sign_enhance()
|
|
260
|
+
if not self._account_info():
|
|
261
|
+
self._submit('general' if self.last_code == '105' else 'error', self.last_code, self.last_message)
|
|
262
|
+
return False
|
|
263
|
+
self._connect_order()
|
|
264
|
+
self._done.wait(max(0.0, self._deadline - time.monotonic()))
|
|
265
|
+
if not self.logged_in and not self.last_code:
|
|
266
|
+
self.last_code, self.last_message = '999', '登入逾時'
|
|
267
|
+
return self.logged_in
|
|
268
|
+
|
|
269
|
+
def _new_channel(self, name: str, port: int) -> Channel:
|
|
270
|
+
return Channel(name, self.host, port, ConcordsFramer(), cipher_mod.ConcordsCipher(), self._on_text, self._on_closed)
|
|
271
|
+
|
|
272
|
+
def _login_message(self) -> str:
|
|
273
|
+
assert self._sign is not None
|
|
274
|
+
return messages.login_plain(self.spec, self.id_no, self._pwd_hash, self.api_version, now_taipei(),
|
|
275
|
+
sign=self._sign, account_login=self._account_login,
|
|
276
|
+
bhno=self._bhno, account=self._account)
|
|
277
|
+
|
|
278
|
+
def _connect_order(self) -> None:
|
|
279
|
+
ch = self._order = self._new_channel(self.spec.order_channel, self._order_port)
|
|
280
|
+
reported = False
|
|
281
|
+
while True:
|
|
282
|
+
try:
|
|
283
|
+
ch.connect()
|
|
284
|
+
break
|
|
285
|
+
except ConnectionError:
|
|
286
|
+
if not reported:
|
|
287
|
+
self._submit('error', '210', '下單連線中斷')
|
|
288
|
+
reported = True
|
|
289
|
+
if self._closing or time.monotonic() + self.retry_interval >= self._deadline:
|
|
290
|
+
self._fail('210', '下單連線中斷')
|
|
291
|
+
return
|
|
292
|
+
time.sleep(self.retry_interval)
|
|
293
|
+
self._submit('general', '110', '下單連線成功')
|
|
294
|
+
self._send_login(ch)
|
|
295
|
+
|
|
296
|
+
def _connect_receive(self) -> None:
|
|
297
|
+
ch = self._receive = self._new_channel(self.spec.receive_channel, self._receive_port)
|
|
298
|
+
while True:
|
|
299
|
+
try:
|
|
300
|
+
ch.connect()
|
|
301
|
+
break
|
|
302
|
+
except ConnectionError:
|
|
303
|
+
if self._closing or time.monotonic() + self.retry_interval >= self._deadline:
|
|
304
|
+
self._submit('error', '214', '回報連線中斷')
|
|
305
|
+
self._fail('214', '回報連線中斷')
|
|
306
|
+
return
|
|
307
|
+
time.sleep(self.retry_interval)
|
|
308
|
+
self._submit('general', '114', '回報連線成功')
|
|
309
|
+
self._send_login(ch)
|
|
310
|
+
|
|
311
|
+
def _send_login(self, ch: Channel) -> None:
|
|
312
|
+
try:
|
|
313
|
+
ch.send_text(self._login_message())
|
|
314
|
+
ch.start_heartbeat(self.heartbeat_interval)
|
|
315
|
+
check_every, ack_after, drop_after = self.idle
|
|
316
|
+
ch.start_idle_monitor(check_every=check_every, ack_after=ack_after, drop_after=drop_after)
|
|
317
|
+
except ConnectionError:
|
|
318
|
+
logger.error('%s: login message could not be sent', ch.name)
|
|
319
|
+
|
|
320
|
+
# ------------------------------------------------------------------ receiving
|
|
321
|
+
def _on_text(self, channel: str, plain: str) -> None:
|
|
322
|
+
"""Receive thread: switch the key at once, hand the rest to the dispatcher."""
|
|
323
|
+
if '|35=A' in plain:
|
|
324
|
+
tags = messages.parse_message(plain)
|
|
325
|
+
if tags.get('20101') == '0':
|
|
326
|
+
ch = self._order if channel == self.spec.order_channel else self._receive
|
|
327
|
+
if ch is not None:
|
|
328
|
+
ch.cipher.rekey(tags.get('20103', ''))
|
|
329
|
+
self.dispatcher.submit(lambda: self._handle(channel, plain))
|
|
330
|
+
|
|
331
|
+
def _handle(self, channel: str, plain: str) -> None:
|
|
332
|
+
if channel == self.spec.order_channel:
|
|
333
|
+
self._handle_order(plain)
|
|
334
|
+
else:
|
|
335
|
+
self._handle_receive(plain)
|
|
336
|
+
|
|
337
|
+
def _login_failed(self, ch: Channel | None, text: str, fail_event: str) -> None:
|
|
338
|
+
if ch is not None:
|
|
339
|
+
ch.close('login refused')
|
|
340
|
+
code = '999' if text == '非預期錯誤' else '998'
|
|
341
|
+
self._report('error', code, text)
|
|
342
|
+
self._report('error', fail_event, '下單登入驗證失敗' if fail_event == '211' else '回報登入驗證失敗')
|
|
343
|
+
self._fail(code, text)
|
|
344
|
+
|
|
345
|
+
def _handle_order(self, plain: str) -> None:
|
|
346
|
+
if '|35=A' in plain:
|
|
347
|
+
tags = messages.parse_message(plain)
|
|
348
|
+
if tags.get('20101') == '0':
|
|
349
|
+
rows = [r for r in tags.get('20102', '').split('\n') if r]
|
|
350
|
+
self.accounts = [r for r in rows if r.split(',')[0] == self.spec.name]
|
|
351
|
+
self.order_login = True
|
|
352
|
+
self._report('general', '111', '下單登入驗證成功')
|
|
353
|
+
self._report('general', '102', '登入成功')
|
|
354
|
+
threading.Thread(target=self._connect_receive, name=f'conrich-connect-{self.spec.receive_channel}',
|
|
355
|
+
daemon=True).start()
|
|
356
|
+
else:
|
|
357
|
+
self.order_login = False
|
|
358
|
+
self._login_failed(self._order, tags.get('20102', ''), '211')
|
|
359
|
+
return
|
|
360
|
+
if plain != HEARTBEAT_PLAIN and messages.parse_message(plain).get('35') not in ('0', 'h'):
|
|
361
|
+
self._report('order_report', '000', plain)
|
|
362
|
+
|
|
363
|
+
def _clears_enhance(self, plain: str, tags: dict[str, str]) -> bool:
|
|
364
|
+
if self.spec is DOMESTIC:
|
|
365
|
+
return tags.get('150') in ('8', 'P8')
|
|
366
|
+
return '150=8' in plain or '150=P8' in plain # substring test, copied from the DLL
|
|
367
|
+
|
|
368
|
+
def _handle_receive(self, plain: str) -> None:
|
|
369
|
+
tags = messages.parse_message(plain)
|
|
370
|
+
t = tags.get('35')
|
|
371
|
+
if t == 'A':
|
|
372
|
+
if tags.get('20101') == '0':
|
|
373
|
+
self.receive_login = True
|
|
374
|
+
self._report('general', '115', '回報登入驗證成功')
|
|
375
|
+
try:
|
|
376
|
+
self._receive.send_text(messages.register_plain(self.accounts, now_taipei()))
|
|
377
|
+
except (ConnectionError, IndexError, AttributeError):
|
|
378
|
+
logger.error('registration message could not be sent')
|
|
379
|
+
else:
|
|
380
|
+
self.receive_login = False
|
|
381
|
+
self._login_failed(self._receive, tags.get('20102', ''), '215')
|
|
382
|
+
elif t == 'r':
|
|
383
|
+
self._report('general', '116', '回報註冊完成')
|
|
384
|
+
self.logged_in = True
|
|
385
|
+
self._report('general', '102', '登入成功')
|
|
386
|
+
self._done.set()
|
|
387
|
+
else:
|
|
388
|
+
if t in ('8', '9') and self._clears_enhance(plain, tags):
|
|
389
|
+
self.clear_enhance()
|
|
390
|
+
kind, code, msg = messages.parse_receive(plain)
|
|
391
|
+
if kind == 'bulletin':
|
|
392
|
+
if messages.is_bulletin_for_futures(plain) and plain not in self.seen_bulletins:
|
|
393
|
+
self.seen_bulletins.add(plain)
|
|
394
|
+
self._report('bulletin', code, msg)
|
|
395
|
+
elif kind == 'order_report':
|
|
396
|
+
self._report(kind, code, msg)
|
|
397
|
+
|
|
398
|
+
def _on_closed(self, channel: str, reason: str) -> None:
|
|
399
|
+
if self._closing:
|
|
400
|
+
return
|
|
401
|
+
logger.warning('%s closed: %s', channel, reason)
|
|
402
|
+
was = self.logged_in
|
|
403
|
+
if channel == self.spec.order_channel:
|
|
404
|
+
self.order_login = False
|
|
405
|
+
self._submit('error', '210', '下單連線中斷')
|
|
406
|
+
else:
|
|
407
|
+
self.receive_login = False
|
|
408
|
+
self._submit('error', '214', '回報連線中斷')
|
|
409
|
+
self.logged_in = False
|
|
410
|
+
if not was:
|
|
411
|
+
self._fail('210' if channel == self.spec.order_channel else '214', '連線中斷')
|
|
412
|
+
|
|
413
|
+
# ------------------------------------------------------------------ requests / closing
|
|
414
|
+
def query(self, token: str, params: list[str]) -> tuple[str, str]:
|
|
415
|
+
return self.service.call(token, params)
|
|
416
|
+
|
|
417
|
+
def send_order(self, plain: str) -> None:
|
|
418
|
+
"""The only way an order leaves this process: gate first, never in dry-run mode."""
|
|
419
|
+
self.gate.check(self.accounts[0].split(',')[4] if self.accounts else '')
|
|
420
|
+
if self.gate.dry_run:
|
|
421
|
+
raise RuntimeError('send_order() must not be called in dry-run mode')
|
|
422
|
+
ch = self._order
|
|
423
|
+
if ch is None or not ch.connected:
|
|
424
|
+
raise ConnectionError('order channel not connected')
|
|
425
|
+
ch.send_text(plain)
|
|
426
|
+
|
|
427
|
+
def recover(self, bhno: str, cseq: str, seq_start: int | str, seq_end: int | str) -> tuple[str, str]:
|
|
428
|
+
code, msg = self.check_connect()
|
|
429
|
+
if code != '102':
|
|
430
|
+
return code, msg
|
|
431
|
+
if not self.check_account(bhno, cseq):
|
|
432
|
+
return '224', '回補送出失敗,帳號未授權'
|
|
433
|
+
try:
|
|
434
|
+
self._receive.send_text(messages.recover_plain(self.spec, bhno, cseq, seq_start, seq_end))
|
|
435
|
+
except ConnectionError:
|
|
436
|
+
return '224', '回補送出失敗'
|
|
437
|
+
return '124', '回補送出成功'
|
|
438
|
+
|
|
439
|
+
def logout(self) -> tuple[str, str]:
|
|
440
|
+
was_order = bool(self._order and self._order.connected)
|
|
441
|
+
was_recv = bool(self._receive and self._receive.connected)
|
|
442
|
+
self._closing = True
|
|
443
|
+
for ch in (self._order, self._receive):
|
|
444
|
+
if ch is not None and ch.connected:
|
|
445
|
+
try:
|
|
446
|
+
ch.send_text(messages.logout_plain(self.spec))
|
|
447
|
+
except ConnectionError:
|
|
448
|
+
pass
|
|
449
|
+
for ch in (self._order, self._receive):
|
|
450
|
+
if ch is not None:
|
|
451
|
+
ch.close('logout')
|
|
452
|
+
if was_order:
|
|
453
|
+
self._submit('general', '113', '下單連線結束')
|
|
454
|
+
if was_recv:
|
|
455
|
+
self._submit('general', '118', '回報連線結束')
|
|
456
|
+
self._order = self._receive = None
|
|
457
|
+
self.order_login = self.receive_login = self.logged_in = False
|
|
458
|
+
self.accounts = []
|
|
459
|
+
self.multi = self.sign_enhance = False
|
|
460
|
+
self.enhance = None
|
|
461
|
+
self.seen_bulletins = set()
|
|
462
|
+
self._pwd_hash = ''
|
|
463
|
+
self._sign = None
|
|
464
|
+
return '103', '登出成功'
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Quote API (pure Python). ``QuoteAPI`` / ``QuoteServer`` are imported on first use."""
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
|
|
4
|
+
from ..Common.events import Event # noqa: F401
|
|
5
|
+
from .symbols import code_convert # noqa: F401
|
|
6
|
+
|
|
7
|
+
_LAZY = {'QuoteAPI': '.quote', 'QuoteServer': '.server'}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def __getattr__(name):
|
|
11
|
+
if name in _LAZY:
|
|
12
|
+
value = getattr(import_module(_LAZY[name], __name__), name)
|
|
13
|
+
globals()[name] = value
|
|
14
|
+
return value
|
|
15
|
+
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
|
conrich/Quote/event.py
ADDED
conrich/Quote/quote.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""QuoteAPI: polls FuturesAPI.quote() and fires OnQuoteUpdate when a field changes.
|
|
3
|
+
|
|
4
|
+
UNVERIFIED: FuturesAPI.quote() depends on the FQueryQuote answer layout, which is unknown without a
|
|
5
|
+
recording. With the default headers the columns are 'col1', 'col2', ...
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from ..Common.events import Event, EventEmitter
|
|
14
|
+
from ..Futures import fields
|
|
15
|
+
from ..Futures.futures import FuturesAPI
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger('conrich.quote')
|
|
18
|
+
|
|
19
|
+
MIN_INTERVAL = 0.5
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class QuoteAPI(EventEmitter):
|
|
23
|
+
source = 'quote'
|
|
24
|
+
|
|
25
|
+
def __init__(self, futures_api: FuturesAPI, interval: float = 1.0) -> None:
|
|
26
|
+
if not isinstance(futures_api, FuturesAPI):
|
|
27
|
+
raise TypeError('futures_api must be a FuturesAPI')
|
|
28
|
+
if interval < MIN_INTERVAL:
|
|
29
|
+
raise ValueError(f'interval must be >= {MIN_INTERVAL}')
|
|
30
|
+
self.OnQuoteUpdate = Event() # handler(commodity, topic, value)
|
|
31
|
+
self.futures_api = futures_api
|
|
32
|
+
self._interval = interval
|
|
33
|
+
self._topics: dict[tuple[str, str], str] = {} # (commodity, topic as given) -> column name
|
|
34
|
+
self._last: dict[tuple[str, str], str] = {}
|
|
35
|
+
self._lock = threading.Lock()
|
|
36
|
+
self._stop = threading.Event()
|
|
37
|
+
self._thread: threading.Thread | None = None
|
|
38
|
+
self._failing: set[str] = set()
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def interval(self) -> float:
|
|
42
|
+
return self._interval
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def running(self) -> bool:
|
|
46
|
+
return self._thread is not None and self._thread.is_alive()
|
|
47
|
+
|
|
48
|
+
def register_topic(self, commodity: str, topic: str) -> None:
|
|
49
|
+
column = fields.TOPIC_ALIASES.get(topic, topic)
|
|
50
|
+
header = fields.HEADERS['Futures'].get('quote') or []
|
|
51
|
+
if header and column not in header:
|
|
52
|
+
raise ValueError(f'unknown topic: {topic!r}')
|
|
53
|
+
with self._lock:
|
|
54
|
+
self._topics[(commodity, topic)] = column
|
|
55
|
+
|
|
56
|
+
def unregister_topic(self, commodity: str, topic: str) -> None:
|
|
57
|
+
with self._lock:
|
|
58
|
+
self._topics.pop((commodity, topic), None)
|
|
59
|
+
self._last.pop((commodity, topic), None)
|
|
60
|
+
|
|
61
|
+
def topics(self) -> dict[str, set[str]]:
|
|
62
|
+
with self._lock:
|
|
63
|
+
out: dict[str, set[str]] = {}
|
|
64
|
+
for (commodity, _), column in self._topics.items():
|
|
65
|
+
out.setdefault(commodity, set()).add(column)
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
def get_quote(self, commodity: str) -> dict[str, str]:
|
|
69
|
+
return self.futures_api.quote(commodity)
|
|
70
|
+
|
|
71
|
+
def start(self) -> None:
|
|
72
|
+
if self.running:
|
|
73
|
+
return
|
|
74
|
+
self._stop.clear()
|
|
75
|
+
self._thread = threading.Thread(target=self._run, name='conrich-quote', daemon=True)
|
|
76
|
+
self._thread.start()
|
|
77
|
+
|
|
78
|
+
def stop(self) -> None:
|
|
79
|
+
self._stop.set()
|
|
80
|
+
t = self._thread
|
|
81
|
+
if t is not None and t is not threading.current_thread():
|
|
82
|
+
t.join(self._interval + 1.0)
|
|
83
|
+
|
|
84
|
+
def __enter__(self) -> 'QuoteAPI':
|
|
85
|
+
self.start()
|
|
86
|
+
return self
|
|
87
|
+
|
|
88
|
+
def __exit__(self, *exc) -> None:
|
|
89
|
+
self.stop()
|
|
90
|
+
|
|
91
|
+
def _run(self) -> None:
|
|
92
|
+
while not self._stop.is_set():
|
|
93
|
+
started = time.monotonic()
|
|
94
|
+
if self.futures_api.is_login:
|
|
95
|
+
with self._lock:
|
|
96
|
+
snapshot = dict(self._topics)
|
|
97
|
+
for commodity in sorted({c for c, _ in snapshot}):
|
|
98
|
+
row = self.futures_api.quote(commodity)
|
|
99
|
+
if not row:
|
|
100
|
+
if commodity not in self._failing:
|
|
101
|
+
self._failing.add(commodity)
|
|
102
|
+
logger.warning('no quote for %s (code %s)', commodity, self.futures_api.last_code)
|
|
103
|
+
continue
|
|
104
|
+
self._failing.discard(commodity)
|
|
105
|
+
for (c, topic), column in snapshot.items():
|
|
106
|
+
if c != commodity:
|
|
107
|
+
continue
|
|
108
|
+
value = row.get(column, '')
|
|
109
|
+
key = (c, topic)
|
|
110
|
+
if self._last.get(key) != value:
|
|
111
|
+
self._last[key] = value
|
|
112
|
+
self.OnQuoteUpdate.notify(c, topic, value)
|
|
113
|
+
self._emit('quote', '', '', {'commodity': c, 'topic': topic, 'value': value})
|
|
114
|
+
if self._stop.is_set():
|
|
115
|
+
break
|
|
116
|
+
self._stop.wait(max(0.0, self._interval - (time.monotonic() - started)))
|
conrich/Quote/server.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""0.7.x QuoteServer drove a Windows COM RTD server. It cannot exist in a pure Python build."""
|
|
2
|
+
from .symbols import code_convert
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class QuoteServer:
|
|
6
|
+
def __init__(self, *args, **kwargs):
|
|
7
|
+
raise NotImplementedError('QuoteServer needed the Windows COM quote server and is gone. '
|
|
8
|
+
'Use conrich.Quote.QuoteAPI(FuturesAPI(...)) instead.')
|
|
9
|
+
|
|
10
|
+
code_convert = staticmethod(code_convert)
|
conrich/Quote/symbols.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""code_convert(): XQ topic codes of the old COM quote server (not usable with FuturesAPI.quote())."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def code_convert(commodity: str, commodity_type: str = 'F', strike_price: int = 0,
|
|
9
|
+
expire_date: datetime | None = None, after_hour: bool = False) -> str:
|
|
10
|
+
if expire_date is None:
|
|
11
|
+
expire_date = datetime.now() # 0.7.x froze this default at import time (a bug)
|
|
12
|
+
if commodity_type == 'S':
|
|
13
|
+
return f'{commodity}.TW'
|
|
14
|
+
if commodity_type == 'F':
|
|
15
|
+
return f'FI{commodity}{"N" if after_hour else ""}{expire_date.month:02}.TF'
|
|
16
|
+
if commodity_type in ('C', 'P'):
|
|
17
|
+
return f'{commodity}{"N" if after_hour else ""}{expire_date.month:02}{commodity_type:1}{strike_price:05}.TF'
|
|
18
|
+
raise ValueError(f'unknown commodity_type: {commodity_type!r}')
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Stock API (pure Python, 2025 protocol). ``StockAPI`` is imported on first use."""
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def __getattr__(name):
|
|
6
|
+
if name == 'StockAPI':
|
|
7
|
+
value = import_module('.stock', __name__).StockAPI
|
|
8
|
+
globals()[name] = value
|
|
9
|
+
return value
|
|
10
|
+
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
|