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
conrich/Stock/session.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Stock session: HTTPS login steps, two TCP channels, key switching, registration state machine.
|
|
3
|
+
|
|
4
|
+
Flow (design-2025.md 3.4): SYS_QVersion + SYS_QSocketConnIP -> certificate check -> sign ->
|
|
5
|
+
SYS_LoginByCA -> SYS_QAccountInfo [-> SYS_QMulitiAccount] -> connect push + order channel ->
|
|
6
|
+
35=A login (with certNo / signature / plain) on both -> 35=r registration on the push channel.
|
|
7
|
+
|
|
8
|
+
Orders can only leave through ``send_order()``, which asks the TradingGate first.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import ssl
|
|
14
|
+
import threading
|
|
15
|
+
from typing import Callable
|
|
16
|
+
|
|
17
|
+
from ..Common import cipher as cipher_mod
|
|
18
|
+
from ..Common.endpoints import is_evaluation, service_url_for
|
|
19
|
+
from ..Common.errors import CertificateError
|
|
20
|
+
from ..Common.events import Dispatcher
|
|
21
|
+
from ..Common.framing import ConcordsFramer
|
|
22
|
+
from ..Common.gate import TradingGate
|
|
23
|
+
from ..Common.records import mask_id
|
|
24
|
+
from ..Common.service import ServiceClient
|
|
25
|
+
from ..Common.signer import SignParts, Signer, login_plain as signed_login_plain
|
|
26
|
+
from ..Common.timeutil import now_taipei
|
|
27
|
+
from ..Common.transport import Channel
|
|
28
|
+
from ..Common.version import check_min_version, parse_version
|
|
29
|
+
from . import messages
|
|
30
|
+
from .fields import ConnectionWay
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger('conrich.stock')
|
|
33
|
+
|
|
34
|
+
PUSH, ORDER = 'Push', 'SOrderSend'
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class StockSession:
|
|
38
|
+
def __init__(self, gateway: str, api_version: str, dispatcher: Dispatcher, emit: Callable[..., None],
|
|
39
|
+
signer: Signer | None, gate: TradingGate, *, service_url: str | None = None,
|
|
40
|
+
ssl_context: ssl.SSLContext | None = None, ports_override: dict[str, int] | None = None,
|
|
41
|
+
connect_delay: float = 3.5, verify_mode: bool = False, service_timeout: float = 60.0,
|
|
42
|
+
heartbeat_interval: float = 30.0) -> None:
|
|
43
|
+
self.gateway = gateway
|
|
44
|
+
self.host = gateway # TCP host; replaced by SYS_QSocketConnIP during login
|
|
45
|
+
self.api_version = api_version
|
|
46
|
+
self.dispatcher = dispatcher
|
|
47
|
+
self._emit = emit # emit(event_name, *args); runs on the dispatcher thread
|
|
48
|
+
self.signer = signer
|
|
49
|
+
self.gate = gate
|
|
50
|
+
self.service_url = service_url or service_url_for(gateway)
|
|
51
|
+
self.ports_override = dict(ports_override or {})
|
|
52
|
+
self.connect_delay = connect_delay
|
|
53
|
+
self.verify_mode = verify_mode
|
|
54
|
+
self.heartbeat_interval = heartbeat_interval
|
|
55
|
+
self.service = ServiceClient(self.service_url, timeout=service_timeout, ssl_context=ssl_context,
|
|
56
|
+
product='stock')
|
|
57
|
+
self.accounts: dict[str, tuple[str, str]] = {} # CSEQ -> (name, BHNO)
|
|
58
|
+
self.sign_enhance = False
|
|
59
|
+
self.enhance: SignParts | None = None # reused signature when sign enhancement is on
|
|
60
|
+
self.order_lock = threading.Lock()
|
|
61
|
+
self.multi = False
|
|
62
|
+
self.last_message = ''
|
|
63
|
+
self.order_logged_in = False
|
|
64
|
+
self.push_logged_in = False
|
|
65
|
+
self.registered = False
|
|
66
|
+
self.login_completed = False # True once a login finished, until close(); drops do not reset it
|
|
67
|
+
self.id_no = ''
|
|
68
|
+
self._pwd_hash = ''
|
|
69
|
+
self._sign: SignParts | None = None
|
|
70
|
+
self._order_port = self._push_port = 0
|
|
71
|
+
self._channels: dict[str, Channel] = {}
|
|
72
|
+
self._failed = threading.Event()
|
|
73
|
+
self._done = threading.Event()
|
|
74
|
+
self._closing = False
|
|
75
|
+
self._lock = threading.Lock()
|
|
76
|
+
|
|
77
|
+
# ------------------------------------------------------------------ state
|
|
78
|
+
@property
|
|
79
|
+
def is_login(self) -> bool:
|
|
80
|
+
return self.order_logged_in and self.push_logged_in and self.registered
|
|
81
|
+
|
|
82
|
+
def _check_done(self) -> None:
|
|
83
|
+
if self.is_login:
|
|
84
|
+
self.login_completed = True
|
|
85
|
+
self._done.set()
|
|
86
|
+
|
|
87
|
+
def _fail(self) -> None:
|
|
88
|
+
self._failed.set()
|
|
89
|
+
self._done.set()
|
|
90
|
+
|
|
91
|
+
# ------------------------------------------------------------------ HTTP steps
|
|
92
|
+
def _q_version(self) -> bool:
|
|
93
|
+
"""SYS_QVersion and SYS_QSocketConnIP are both sent first, then the version is judged (3.3)."""
|
|
94
|
+
try:
|
|
95
|
+
major = str(parse_version(self.api_version)[0])
|
|
96
|
+
except ValueError:
|
|
97
|
+
self.last_message = '版本驗證:非預期錯誤'
|
|
98
|
+
return False
|
|
99
|
+
code, content = self.service.call('SYS_QVersion', ['S', major, self.id_no])
|
|
100
|
+
sock_code, sock_content = self.service.call('SYS_QSocketConnIP', ['S'])
|
|
101
|
+
if sock_code == '000' and sock_content.strip():
|
|
102
|
+
self.host = sock_content.strip()
|
|
103
|
+
else:
|
|
104
|
+
self.host = self.gateway
|
|
105
|
+
if code != '000':
|
|
106
|
+
self.last_message = content
|
|
107
|
+
return False
|
|
108
|
+
try:
|
|
109
|
+
ok = check_min_version(self.api_version, content)
|
|
110
|
+
except ValueError:
|
|
111
|
+
self.last_message = '版本驗證:非預期錯誤'
|
|
112
|
+
return False
|
|
113
|
+
if not ok:
|
|
114
|
+
self.last_message = '版本驗證:版本過舊'
|
|
115
|
+
logger.warning('server requires version %s, declared %s: login stopped before sending credentials',
|
|
116
|
+
content, self.api_version)
|
|
117
|
+
return False
|
|
118
|
+
return True
|
|
119
|
+
|
|
120
|
+
def _prepare_signature(self) -> bool:
|
|
121
|
+
"""Certificate check and the login signature (3.4 steps 2 and 3)."""
|
|
122
|
+
assert self.signer is not None
|
|
123
|
+
try:
|
|
124
|
+
self.signer.check(self.id_no, evaluation=is_evaluation(self.gateway), now=None)
|
|
125
|
+
self._sign = self.signer.sign(signed_login_plain(now_taipei()))
|
|
126
|
+
except CertificateError as exc:
|
|
127
|
+
logger.warning('login stopped: certificate problem (%s)', exc.reason or 'unknown')
|
|
128
|
+
self.last_message = '憑證驗證日期過期' if exc.reason in ('expired', 'not_yet_valid') else '簽章失敗'
|
|
129
|
+
return False
|
|
130
|
+
return True
|
|
131
|
+
|
|
132
|
+
def _q_login(self) -> bool:
|
|
133
|
+
assert self._sign is not None
|
|
134
|
+
sign = self._sign
|
|
135
|
+
code, content = self.service.call('SYS_LoginByCA', [
|
|
136
|
+
self.id_no, '', '', self._pwd_hash, 'S', '1', '', sign.cert_no, sign.signature, sign.plain, 'S', 'Z'])
|
|
137
|
+
if code != '000':
|
|
138
|
+
self.last_message = '帳號驗證:' + content
|
|
139
|
+
return False
|
|
140
|
+
try:
|
|
141
|
+
rows = [row.split(',') for row in content.split('\n')]
|
|
142
|
+
if any(len(cols) < 6 for cols in rows):
|
|
143
|
+
raise IndexError
|
|
144
|
+
for cols in rows:
|
|
145
|
+
self.accounts.setdefault(cols[5], (cols[2], cols[3]))
|
|
146
|
+
except IndexError:
|
|
147
|
+
self.last_message = '帳號驗證:非預期錯誤'
|
|
148
|
+
return False
|
|
149
|
+
return True
|
|
150
|
+
|
|
151
|
+
def _q_account(self) -> bool:
|
|
152
|
+
token = 'SYS_VerifyQAccount' if self.verify_mode else 'SYS_QAccountInfo'
|
|
153
|
+
code, content = self.service.call(token, ['S', self.id_no])
|
|
154
|
+
if code != '000':
|
|
155
|
+
self.last_message = 'API帳號資訊:' + content
|
|
156
|
+
return False
|
|
157
|
+
try:
|
|
158
|
+
cols = content.split(',')
|
|
159
|
+
self._order_port, self._push_port = int(cols[0]), int(cols[1])
|
|
160
|
+
self.multi = cols[6] == 'Y'
|
|
161
|
+
self.sign_enhance = cols[7] == 'Y'
|
|
162
|
+
except (IndexError, ValueError):
|
|
163
|
+
self.last_message = 'API帳號資訊:非預期錯誤'
|
|
164
|
+
return False
|
|
165
|
+
return True
|
|
166
|
+
|
|
167
|
+
def _q_multi(self) -> bool:
|
|
168
|
+
code, content = self.service.call('SYS_QMulitiAccount', ['S', self.id_no]) # token spelling as in the DLL
|
|
169
|
+
if code == '925':
|
|
170
|
+
return True
|
|
171
|
+
if code != '000':
|
|
172
|
+
self.last_message = '多帳號資訊:' + content
|
|
173
|
+
return False
|
|
174
|
+
try:
|
|
175
|
+
for row in content.split('\n'):
|
|
176
|
+
cols = row.split(',')
|
|
177
|
+
self.accounts.setdefault(cols[3], (cols[1], cols[2]))
|
|
178
|
+
except IndexError:
|
|
179
|
+
self.last_message = '多帳號資訊:非預期錯誤'
|
|
180
|
+
return False
|
|
181
|
+
return True
|
|
182
|
+
|
|
183
|
+
# ------------------------------------------------------------------ login
|
|
184
|
+
def login(self, id_no: str, pwd: str, timeout: float) -> bool:
|
|
185
|
+
self.id_no = id_no
|
|
186
|
+
self.last_message = ''
|
|
187
|
+
self._sign = None
|
|
188
|
+
logger.info('[Login] user %s', mask_id(id_no))
|
|
189
|
+
if self.signer is None:
|
|
190
|
+
self.last_message = '取得憑證狀態失敗'
|
|
191
|
+
return False
|
|
192
|
+
try:
|
|
193
|
+
self._pwd_hash = cipher_mod.hash_password(pwd, 'stock')
|
|
194
|
+
except ValueError:
|
|
195
|
+
self.last_message = '帳號驗證:密碼含無法編碼的字元'
|
|
196
|
+
return False
|
|
197
|
+
if not (self._q_version() and self._prepare_signature() and self._q_login() and self._q_account()):
|
|
198
|
+
return False
|
|
199
|
+
if self.multi and not self._q_multi():
|
|
200
|
+
return False
|
|
201
|
+
self._failed.clear()
|
|
202
|
+
self._done.clear()
|
|
203
|
+
self._closing = False
|
|
204
|
+
ports = {PUSH: self.ports_override.get(PUSH, self._push_port),
|
|
205
|
+
ORDER: self.ports_override.get(ORDER, self._order_port)}
|
|
206
|
+
for name in (PUSH, ORDER):
|
|
207
|
+
self._channels[name] = Channel(name, self.host, ports[name], ConcordsFramer(), cipher_mod.ConcordsCipher(),
|
|
208
|
+
self._on_text, self._on_closed, connect_delay=self.connect_delay)
|
|
209
|
+
errors: list[str] = []
|
|
210
|
+
threads = [threading.Thread(target=self._connect, args=(name, errors), daemon=True,
|
|
211
|
+
name=f'conrich-connect-{name}') for name in (PUSH, ORDER)]
|
|
212
|
+
for t in threads:
|
|
213
|
+
t.start()
|
|
214
|
+
for t in threads:
|
|
215
|
+
t.join(timeout + self.connect_delay + 6.0)
|
|
216
|
+
if errors:
|
|
217
|
+
self.last_message = '連線失敗'
|
|
218
|
+
self.close()
|
|
219
|
+
return False
|
|
220
|
+
self._done.wait(timeout)
|
|
221
|
+
if not self.is_login:
|
|
222
|
+
if not self.last_message:
|
|
223
|
+
self.last_message = '登入逾時'
|
|
224
|
+
return False
|
|
225
|
+
return True
|
|
226
|
+
|
|
227
|
+
def _connect(self, name: str, errors: list[str]) -> None:
|
|
228
|
+
ch = self._channels[name]
|
|
229
|
+
way = ConnectionWay.Receive if name == PUSH else ConnectionWay.Send
|
|
230
|
+
try:
|
|
231
|
+
ch.connect()
|
|
232
|
+
except ConnectionError as exc:
|
|
233
|
+
logger.error('[Socket]%s connect failed: %s', name, exc)
|
|
234
|
+
self.dispatcher.submit(lambda: self._emit('SocketStatusEvent', way, '連線失敗'))
|
|
235
|
+
errors.append(name)
|
|
236
|
+
return
|
|
237
|
+
self.dispatcher.submit(lambda: self._emit('SocketStatusEvent', way, '連線成功'))
|
|
238
|
+
try:
|
|
239
|
+
ch.send_text(messages.login_plain(self.id_no, self._pwd_hash, self.verify_mode, self.api_version,
|
|
240
|
+
now_taipei(), sign=self._sign))
|
|
241
|
+
ch.start_heartbeat(self.heartbeat_interval)
|
|
242
|
+
except ConnectionError as exc:
|
|
243
|
+
errors.append(name)
|
|
244
|
+
logger.error('[Socket]%s login send failed: %s', name, exc)
|
|
245
|
+
|
|
246
|
+
# ------------------------------------------------------------------ receiving
|
|
247
|
+
def _on_text(self, channel: str, plain: str) -> None:
|
|
248
|
+
"""Runs on the receive thread. The key switch must happen here, before the next frame is decrypted."""
|
|
249
|
+
tags = messages.parse_message(plain)
|
|
250
|
+
if tags.get('35') == 'A' and tags.get('20101') == '0':
|
|
251
|
+
key = tags.get('20103', '')
|
|
252
|
+
self._channels[channel].cipher.rekey(key.strip() if channel == PUSH else key)
|
|
253
|
+
self.dispatcher.submit(lambda: self._handle(channel, plain))
|
|
254
|
+
|
|
255
|
+
def _handle(self, channel: str, plain: str) -> None:
|
|
256
|
+
if channel == PUSH:
|
|
257
|
+
self._handle_push(plain)
|
|
258
|
+
else:
|
|
259
|
+
self._handle_order(plain)
|
|
260
|
+
|
|
261
|
+
def _handle_push(self, plain: str) -> None:
|
|
262
|
+
msg = messages.parse_push(plain)
|
|
263
|
+
tags = msg.tags
|
|
264
|
+
if msg.kind == 'login':
|
|
265
|
+
ok = tags.get('20101') == '0'
|
|
266
|
+
text = tags.get('20102', '')
|
|
267
|
+
if ok:
|
|
268
|
+
self.push_logged_in = True
|
|
269
|
+
code = ','.join(f'{bhno}{cseq}' for cseq, (_, bhno) in self.accounts.items())
|
|
270
|
+
try:
|
|
271
|
+
self._channels[PUSH].send_text(messages.register_plain(code, now_taipei()))
|
|
272
|
+
except ConnectionError:
|
|
273
|
+
logger.error('registration message could not be sent')
|
|
274
|
+
else:
|
|
275
|
+
logger.info('[push login] failed: %s', text)
|
|
276
|
+
self.push_logged_in = False
|
|
277
|
+
self._channels[PUSH].close('login refused')
|
|
278
|
+
self._fail()
|
|
279
|
+
self._emit('GeneralEvent', f'[回報登入驗證{"成功" if ok else "失敗"}]:{text}')
|
|
280
|
+
elif msg.kind == 'register':
|
|
281
|
+
ok = tags.get('20101') == '0'
|
|
282
|
+
self.registered = ok
|
|
283
|
+
self._emit('GeneralEvent', f'[註冊{"成功" if ok else "失敗"}]:{tags.get("20102", "")}')
|
|
284
|
+
if ok:
|
|
285
|
+
self._check_done()
|
|
286
|
+
else:
|
|
287
|
+
self._fail()
|
|
288
|
+
elif msg.kind == 'recover':
|
|
289
|
+
for text in msg.messages:
|
|
290
|
+
self._emit('GeneralEvent', text)
|
|
291
|
+
elif msg.kind == 'order_report':
|
|
292
|
+
self._emit('OrderReportEvent', msg.result, plain)
|
|
293
|
+
elif msg.kind == 'bulletin':
|
|
294
|
+
for text in msg.messages:
|
|
295
|
+
self._emit('BulletinEvent', text)
|
|
296
|
+
elif msg.kind == 'heartbeat':
|
|
297
|
+
pass
|
|
298
|
+
else:
|
|
299
|
+
logger.error('unknown push message (35=%s)', tags.get('35'))
|
|
300
|
+
|
|
301
|
+
def _handle_order(self, plain: str) -> None:
|
|
302
|
+
msg = messages.parse_order_channel(plain)
|
|
303
|
+
tags = msg.tags
|
|
304
|
+
if msg.kind == 'login':
|
|
305
|
+
ok = tags.get('20101') == '0'
|
|
306
|
+
text = tags.get('20102', '')
|
|
307
|
+
if ok:
|
|
308
|
+
self.order_logged_in = True
|
|
309
|
+
self._check_done()
|
|
310
|
+
else:
|
|
311
|
+
logger.info('[order login] failed: %s', text)
|
|
312
|
+
self.order_logged_in = False
|
|
313
|
+
self._channels[ORDER].close('login refused')
|
|
314
|
+
self._fail()
|
|
315
|
+
self._emit('GeneralEvent', f'[委託登入驗證{"成功" if ok else "失敗"}]:{text}')
|
|
316
|
+
elif msg.kind in ('order_accepted', 'order_rejected'):
|
|
317
|
+
self._emit('OrderReportEvent', msg.result, plain)
|
|
318
|
+
elif msg.kind == 'heartbeat':
|
|
319
|
+
pass
|
|
320
|
+
else:
|
|
321
|
+
logger.info('unknown order-channel message (35=%s)', tags.get('35'))
|
|
322
|
+
|
|
323
|
+
def _on_closed(self, channel: str, reason: str) -> None:
|
|
324
|
+
if self._closing:
|
|
325
|
+
return
|
|
326
|
+
logger.warning('[Socket]%s closed: %s', channel, reason)
|
|
327
|
+
if channel == PUSH:
|
|
328
|
+
self.push_logged_in = self.registered = False
|
|
329
|
+
else:
|
|
330
|
+
self.order_logged_in = False
|
|
331
|
+
way = ConnectionWay.Receive if channel == PUSH else ConnectionWay.Send
|
|
332
|
+
self.dispatcher.submit(lambda: self._emit('SocketStatusEvent', way, '連線中斷'))
|
|
333
|
+
self._fail()
|
|
334
|
+
|
|
335
|
+
# ------------------------------------------------------------------ sending / closing
|
|
336
|
+
def send_push(self, plain: str) -> None:
|
|
337
|
+
"""Send a (non-order) message on the push channel. ConnectionError when not connected."""
|
|
338
|
+
ch = self._channels.get(PUSH)
|
|
339
|
+
if ch is None:
|
|
340
|
+
raise ConnectionError('push channel not connected')
|
|
341
|
+
ch.send_text(plain)
|
|
342
|
+
|
|
343
|
+
def order_connected(self) -> bool:
|
|
344
|
+
ch = self._channels.get(ORDER)
|
|
345
|
+
return ch is not None and ch.connected and self.order_logged_in
|
|
346
|
+
|
|
347
|
+
def send_order(self, plain: str) -> None:
|
|
348
|
+
"""The only way an order leaves this process: gate first, never in dry-run mode."""
|
|
349
|
+
self.gate.check(next(iter(self.accounts), ''))
|
|
350
|
+
if self.gate.dry_run:
|
|
351
|
+
raise RuntimeError('send_order() must not be called in dry-run mode')
|
|
352
|
+
ch = self._channels.get(ORDER)
|
|
353
|
+
if ch is None or not self.order_connected():
|
|
354
|
+
raise ConnectionError('order channel not connected')
|
|
355
|
+
ch.send_text(plain)
|
|
356
|
+
|
|
357
|
+
def account_rows(self) -> list[str]:
|
|
358
|
+
return [f'{bhno},{cseq},{name}' for cseq, (name, bhno) in self.accounts.items()]
|
|
359
|
+
|
|
360
|
+
def query(self, token: str, params: list[str]) -> tuple[str, str]:
|
|
361
|
+
return self.service.call(token, params)
|
|
362
|
+
|
|
363
|
+
def close(self) -> None:
|
|
364
|
+
self._closing = True
|
|
365
|
+
for ch in list(self._channels.values()):
|
|
366
|
+
ch.close('logout')
|
|
367
|
+
self._channels.clear()
|
|
368
|
+
self.order_logged_in = self.push_logged_in = self.registered = self.login_completed = False
|
|
369
|
+
self.accounts = {}
|
|
370
|
+
self.sign_enhance = self.multi = False
|
|
371
|
+
self.id_no = self._pwd_hash = ''
|
|
372
|
+
self._sign = None
|
|
373
|
+
self.enhance = None
|
conrich/Stock/stock.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""StockAPI: pure Python client of the Concord stock trading API (2025 protocol).
|
|
3
|
+
|
|
4
|
+
Login follows design-2025.md 3.4 and needs the user's own PFX (``pfx_path``). Orders are behind the
|
|
5
|
+
trading gate (``enable_trading``, ``CONRICH_ALLOW_LIVE_ORDERS`` and the in-code ``ORDER_ENABLED``
|
|
6
|
+
switch); order() follows design-2025.md 3.7 and 8.1.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import re
|
|
12
|
+
import ssl
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from datetime import date, datetime
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
from ..Common.endpoints import LIVE_HOST, TEST_HOST, gateway_for, is_evaluation, is_loopback_url
|
|
20
|
+
from ..Common.errors import CertificateError
|
|
21
|
+
from ..Common.events import Dispatcher, Event, EventEmitter
|
|
22
|
+
from ..Common.gate import TradingGate
|
|
23
|
+
from ..Common.records import rows_to_dicts
|
|
24
|
+
from ..Common.signer import Signer, mask_cert_no
|
|
25
|
+
from ..Common.timeutil import now_taipei, to_yyyymmdd
|
|
26
|
+
from . import messages, orders
|
|
27
|
+
from .fields import API_VERSION, HEADERS, ConnectionWay
|
|
28
|
+
from .results import OrderResult
|
|
29
|
+
from .session import StockSession
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger('conrich.stock')
|
|
32
|
+
|
|
33
|
+
_ILLEGAL = (',', '<', '&')
|
|
34
|
+
_MASK_SIGNATURE = re.compile(r'\|21002=[^|]*')
|
|
35
|
+
_MASK_CERT = re.compile(r'\|21003=([^|]*)')
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def mask_preview(plain: str) -> str:
|
|
39
|
+
"""Preview text: signature replaced by <masked>, certNo reduced to its last 4 characters."""
|
|
40
|
+
plain = _MASK_SIGNATURE.sub('|21002=<masked>', plain)
|
|
41
|
+
return _MASK_CERT.sub(lambda m: '|21003=' + mask_cert_no(m.group(1)), plain)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _clean(value, name: str) -> str:
|
|
45
|
+
text = str(value)
|
|
46
|
+
if any(c in text for c in _ILLEGAL):
|
|
47
|
+
raise ValueError(f'{name} contains an illegal character')
|
|
48
|
+
return text
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class StockAPI(EventEmitter):
|
|
52
|
+
source = 'stock'
|
|
53
|
+
|
|
54
|
+
def __init__(self, debug: bool = False, *, pfx_path=None, pfx_password=None, enable_trading: bool = False,
|
|
55
|
+
dry_run: bool = False, ssl_context: ssl.SSLContext | None = None) -> None:
|
|
56
|
+
self.debug = debug
|
|
57
|
+
self.host = TEST_HOST if debug else LIVE_HOST
|
|
58
|
+
self.service_url: str | None = None # test hook: replaces the service URL (and the gateway)
|
|
59
|
+
self.ports_override: dict[str, int] = {}
|
|
60
|
+
self.connect_delay = 3.5
|
|
61
|
+
self.verify_mode = False
|
|
62
|
+
self.service_timeout = 60.0
|
|
63
|
+
self.heartbeat_interval = 30.0
|
|
64
|
+
self.ssl_context = ssl_context
|
|
65
|
+
self.last_order_preview = ''
|
|
66
|
+
self.BulletinEvent = Event()
|
|
67
|
+
self.GeneralEvent = Event()
|
|
68
|
+
self.OrderReportEvent = Event()
|
|
69
|
+
self.SocketStatusEvent = Event()
|
|
70
|
+
self._signer = Signer(pfx_path, pfx_password) if pfx_path is not None else None
|
|
71
|
+
self._gate = TradingGate(enable_trading=enable_trading, dry_run=dry_run, live_target=lambda: self._is_live_target(),
|
|
72
|
+
owner=type(self).__name__)
|
|
73
|
+
self._dispatcher = Dispatcher('stock')
|
|
74
|
+
self._session: StockSession | None = None
|
|
75
|
+
self._query_lock = threading.Lock()
|
|
76
|
+
self._last_query = 0.0
|
|
77
|
+
|
|
78
|
+
# ------------------------------------------------------------------ properties
|
|
79
|
+
@property
|
|
80
|
+
def enable_trading(self) -> bool:
|
|
81
|
+
return self._gate.enable_trading
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def dry_run(self) -> bool:
|
|
85
|
+
return self._gate.dry_run
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def is_login(self) -> bool:
|
|
89
|
+
return self._session is not None and self._session.is_login
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def last_login_message(self) -> str:
|
|
93
|
+
return self._session.last_message if self._session is not None else ''
|
|
94
|
+
|
|
95
|
+
def _is_live_target(self) -> bool:
|
|
96
|
+
if self.debug:
|
|
97
|
+
return False
|
|
98
|
+
if self.service_url is not None and is_loopback_url(self.service_url):
|
|
99
|
+
return False
|
|
100
|
+
return True
|
|
101
|
+
|
|
102
|
+
def _gateway(self) -> str:
|
|
103
|
+
if self.service_url is not None:
|
|
104
|
+
return urlsplit(self.service_url).hostname or self.host
|
|
105
|
+
return gateway_for(self.host)
|
|
106
|
+
|
|
107
|
+
# ------------------------------------------------------------------ events
|
|
108
|
+
def _fire(self, name: str, *args) -> None:
|
|
109
|
+
"""Runs on the dispatcher thread (or synchronously before login)."""
|
|
110
|
+
getattr(self, name).notify(*args)
|
|
111
|
+
if name == 'GeneralEvent':
|
|
112
|
+
self._emit('general', '', args[0])
|
|
113
|
+
elif name == 'BulletinEvent':
|
|
114
|
+
self._emit('bulletin', '', args[0])
|
|
115
|
+
elif name == 'SocketStatusEvent':
|
|
116
|
+
way, text = args
|
|
117
|
+
self._emit('socket_status', way.name if isinstance(way, ConnectionWay) else str(way), text)
|
|
118
|
+
elif name == 'OrderReportEvent':
|
|
119
|
+
result, text = args
|
|
120
|
+
self._emit('order_report', str(result.ResultType), text, result.to_dict())
|
|
121
|
+
|
|
122
|
+
# ------------------------------------------------------------------ login / logout
|
|
123
|
+
def login(self, id_no: str, pwd: str, timeout: float = 10.0) -> bool:
|
|
124
|
+
"""True when both channels are logged in and registered. ``last_login_message`` says why not."""
|
|
125
|
+
self.logout()
|
|
126
|
+
self._dispatcher.start()
|
|
127
|
+
session = StockSession(self._gateway(), API_VERSION, self._dispatcher, self._fire, self._signer, self._gate,
|
|
128
|
+
service_url=self.service_url, ssl_context=self.ssl_context,
|
|
129
|
+
ports_override=self.ports_override, connect_delay=self.connect_delay,
|
|
130
|
+
verify_mode=self.verify_mode, service_timeout=self.service_timeout,
|
|
131
|
+
heartbeat_interval=self.heartbeat_interval)
|
|
132
|
+
self._session = session
|
|
133
|
+
ok = session.login(id_no, pwd, timeout)
|
|
134
|
+
logger.info('[Login] %s %s', ok, session.last_message)
|
|
135
|
+
return ok
|
|
136
|
+
|
|
137
|
+
def logout(self) -> None:
|
|
138
|
+
session = self._session
|
|
139
|
+
if session is not None:
|
|
140
|
+
session.close()
|
|
141
|
+
self._session = None
|
|
142
|
+
self._dispatcher.stop()
|
|
143
|
+
|
|
144
|
+
def __enter__(self) -> 'StockAPI':
|
|
145
|
+
return self
|
|
146
|
+
|
|
147
|
+
def __exit__(self, *exc) -> None:
|
|
148
|
+
self.logout()
|
|
149
|
+
|
|
150
|
+
def __del__(self) -> None:
|
|
151
|
+
try:
|
|
152
|
+
self.logout()
|
|
153
|
+
except Exception: # interpreter shutdown
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
# ------------------------------------------------------------------ orders
|
|
157
|
+
def _post(self, fn) -> None:
|
|
158
|
+
"""Run on the dispatcher thread when it is running, else right now (nothing is logged in)."""
|
|
159
|
+
if self._dispatcher.running:
|
|
160
|
+
self._dispatcher.submit(fn)
|
|
161
|
+
else:
|
|
162
|
+
fn()
|
|
163
|
+
|
|
164
|
+
def _order_failed(self, desc: str, message: str) -> dict:
|
|
165
|
+
result = OrderResult(ResultType='0', StatusCode=-1, CodeDesc=desc)
|
|
166
|
+
self._post(lambda: self._fire('OrderReportEvent', result, message))
|
|
167
|
+
return result.to_dict()
|
|
168
|
+
|
|
169
|
+
def order(self, action, branch_no, account_no, lot_type, order_type, side, day_trade_flag,
|
|
170
|
+
symbol, quantity, price, price_flag, time_in_force, orig_net_no='', order_id='') -> dict:
|
|
171
|
+
"""Place, change or cancel an order (design-2025.md 8.1). The gate is checked first.
|
|
172
|
+
|
|
173
|
+
Raises TradingDisabledError (gate) or OrderError (arguments) before anything is signed or sent.
|
|
174
|
+
"""
|
|
175
|
+
self._gate.check(str(account_no).strip())
|
|
176
|
+
f = orders.build_fields(action, branch_no, account_no, lot_type, order_type, side, day_trade_flag, symbol,
|
|
177
|
+
quantity, price, price_flag, time_in_force, orig_net_no, order_id)
|
|
178
|
+
s = self._session
|
|
179
|
+
if s is None or not s.login_completed:
|
|
180
|
+
return self._order_failed('尚未成功登入', '尚未成功登入')
|
|
181
|
+
if not s.order_connected():
|
|
182
|
+
return self._order_failed('與中台斷線', '與中台斷線')
|
|
183
|
+
if f.account not in s.accounts:
|
|
184
|
+
return self._order_failed('非授權帳號', '非授權帳號' + f.account)
|
|
185
|
+
guid = str(uuid.uuid4())
|
|
186
|
+
dry = self._gate.dry_run
|
|
187
|
+
with s.order_lock:
|
|
188
|
+
try:
|
|
189
|
+
if self._signer is None:
|
|
190
|
+
raise CertificateError('no signer', reason='sign_error')
|
|
191
|
+
self._signer.check(s.id_no, evaluation=is_evaluation(self._gateway()))
|
|
192
|
+
if s.sign_enhance and s.enhance is not None:
|
|
193
|
+
sign = s.enhance
|
|
194
|
+
else:
|
|
195
|
+
sign = self._signer.sign(messages.order_sign_plain(f))
|
|
196
|
+
if s.sign_enhance and not dry:
|
|
197
|
+
s.enhance = sign
|
|
198
|
+
except CertificateError:
|
|
199
|
+
return self._order_failed('簽章失敗', '[委託作業]:簽章失敗')
|
|
200
|
+
plain = messages.order_body(f, guid=guid, now=now_taipei(), sign=sign, id_no=s.id_no)
|
|
201
|
+
if dry:
|
|
202
|
+
self.last_order_preview = mask_preview(plain)
|
|
203
|
+
return OrderResult(ResultType='0', StatusCode=0, CodeDesc='dry-run', OrderGuid=guid).to_dict()
|
|
204
|
+
try:
|
|
205
|
+
s.send_order(plain)
|
|
206
|
+
except ConnectionError:
|
|
207
|
+
logger.warning('order could not be sent; the host may have received it: use order_recover() or a query')
|
|
208
|
+
return self._order_failed('委託失敗', '[委託作業]: 傳送委託失敗')
|
|
209
|
+
return OrderResult(ResultType='0', StatusCode=0, OrderGuid=guid).to_dict()
|
|
210
|
+
|
|
211
|
+
def order_recover(self, branch_no: str, account_no: str) -> bool:
|
|
212
|
+
"""Ask the broker to resend today's reports. Progress is reported through GeneralEvent."""
|
|
213
|
+
session = self._session
|
|
214
|
+
if session is None or not session.is_login:
|
|
215
|
+
self._post(lambda: self._fire('GeneralEvent', '[回補請求]: 失敗-尚未登入成功'))
|
|
216
|
+
return False
|
|
217
|
+
authorised = session.accounts.get(str(account_no))
|
|
218
|
+
if authorised is None or authorised[1] != str(branch_no):
|
|
219
|
+
self._dispatcher.submit(lambda: self._fire('GeneralEvent', '[回補請求]: 失敗-非授權之帳號'))
|
|
220
|
+
return False
|
|
221
|
+
try:
|
|
222
|
+
session.send_push(messages.recover_plain(str(branch_no), str(account_no), now_taipei()))
|
|
223
|
+
except ConnectionError:
|
|
224
|
+
self._dispatcher.submit(lambda: self._fire('GeneralEvent', '[回補請求]: 失敗-尚未登入成功'))
|
|
225
|
+
return False
|
|
226
|
+
self._dispatcher.submit(lambda: self._fire('GeneralEvent', '[回補請求]: 發出回補成功'))
|
|
227
|
+
return True
|
|
228
|
+
|
|
229
|
+
# ------------------------------------------------------------------ queries
|
|
230
|
+
def accounts_info(self) -> list[dict[str, str]]:
|
|
231
|
+
session = self._session
|
|
232
|
+
if session is None or not session.is_login:
|
|
233
|
+
return []
|
|
234
|
+
return rows_to_dicts(session.account_rows(), HEADERS['accounts_info'])
|
|
235
|
+
|
|
236
|
+
def _query(self, token: str, header: str, branch_no, account_no, extra: list[str]) -> list[dict[str, str]]:
|
|
237
|
+
session = self._session
|
|
238
|
+
branch, account = _clean(branch_no, 'branch_no'), _clean(account_no, 'account_no')
|
|
239
|
+
extra = [_clean(x, 'date') if x else x for x in extra]
|
|
240
|
+
if session is None or not session.is_login:
|
|
241
|
+
logger.warning('[%s] not logged in', token)
|
|
242
|
+
return []
|
|
243
|
+
authorised = session.accounts.get(account)
|
|
244
|
+
if authorised is None or authorised[1] != branch:
|
|
245
|
+
logger.warning('[%s] account is not authorised for this login', token)
|
|
246
|
+
return []
|
|
247
|
+
with self._query_lock: # the DLL refuses a second query within one second
|
|
248
|
+
now = time.monotonic()
|
|
249
|
+
if now - self._last_query < 1.0:
|
|
250
|
+
logger.warning('[%s] a query was sent less than one second ago: not sent', token)
|
|
251
|
+
return []
|
|
252
|
+
self._last_query = now
|
|
253
|
+
code, content = session.query(token, [branch, account, *extra])
|
|
254
|
+
if code != '000':
|
|
255
|
+
logger.info('[%s] %s %s', token, code, content)
|
|
256
|
+
return []
|
|
257
|
+
return rows_to_dicts([r for r in content.split('\n') if r.strip()], HEADERS[header])
|
|
258
|
+
|
|
259
|
+
def current_delivery(self, branch_no, account_no) -> list[dict[str, str]]:
|
|
260
|
+
return self._query('S_QRealDelivery', 'current_delivery', branch_no, account_no, ['', '', ''])
|
|
261
|
+
|
|
262
|
+
def three_days_delivery(self, branch_no, account_no) -> list[dict[str, str]]:
|
|
263
|
+
return self._query('S_QThreeDayDelivery', 'three_days_delivery', branch_no, account_no, [])
|
|
264
|
+
|
|
265
|
+
def history_delivery(self, branch_no, account_no, start_date: date | datetime | str,
|
|
266
|
+
end_date: date | datetime | str) -> list[dict[str, str]]:
|
|
267
|
+
return self._query('S_QHisDelivery', 'history_delivery', branch_no, account_no,
|
|
268
|
+
[to_yyyymmdd(start_date), to_yyyymmdd(end_date), '', '', ''])
|
|
269
|
+
|
|
270
|
+
def realized_profit(self, branch_no, account_no, start_date: date | datetime | str,
|
|
271
|
+
end_date: date | datetime | str) -> list[dict[str, str]]:
|
|
272
|
+
return self._query('S_QHisPL', 'realized_profit', branch_no, account_no,
|
|
273
|
+
[to_yyyymmdd(start_date), to_yyyymmdd(end_date), '', ''])
|
|
274
|
+
|
|
275
|
+
def unrealized_profit(self, branch_no, account_no) -> list[dict[str, str]]:
|
|
276
|
+
return self._query('S_QRealPL', 'unrealized_profit', branch_no, account_no, ['', ''])
|
|
277
|
+
|
|
278
|
+
def maintenance_rate(self, branch_no, account_no) -> list[dict[str, str]]:
|
|
279
|
+
return self._query('S_QMaintain', 'maintenance_rate', branch_no, account_no, ['', ''])
|