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/Common/signer.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Signing with the user's own PFX (design-2025.md section 4).
|
|
2
|
+
|
|
3
|
+
The algorithm follows the static analysis in docs/design-capi-signature.md: RSA PKCS#1 v1.5 with
|
|
4
|
+
SHA-1 over the cp950 bytes of the plain text, base64 in 64 character lines, certNo = upper-case
|
|
5
|
+
hex of the certificate serial number. Nothing here talks to the network and nothing logs the
|
|
6
|
+
key, the password or a full certNo.
|
|
7
|
+
|
|
8
|
+
Whether the broker accepts these signatures is not verified yet (docs/design-2025.md R1, U6);
|
|
9
|
+
order sending is protected separately by ``conrich.Common.gate``.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
|
|
19
|
+
from cryptography import x509
|
|
20
|
+
from cryptography.hazmat.primitives import hashes
|
|
21
|
+
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
22
|
+
from cryptography.hazmat.primitives.serialization import pkcs12
|
|
23
|
+
from cryptography.x509.oid import NameOID
|
|
24
|
+
|
|
25
|
+
from .errors import CertificateError
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger('conrich.signer')
|
|
28
|
+
|
|
29
|
+
# U1: keep the leading 00 when the serial's top bit is set (DER content bytes). Change here only.
|
|
30
|
+
CERT_NO_KEEP_SIGN_BYTE: bool = True
|
|
31
|
+
SELFTEST_PLAIN = 'conrich-signer-selftest'
|
|
32
|
+
|
|
33
|
+
# design-2025.md 4.3 (texts of the DLL's GetCertErrorMsg)
|
|
34
|
+
REASON_TEXT = {
|
|
35
|
+
'expired': '[5011] 憑證已過期',
|
|
36
|
+
'not_yet_valid': '[5012] 憑證尚未有效',
|
|
37
|
+
'subject': '[5014] 憑證主旨比對錯誤',
|
|
38
|
+
'key_usage': '[5017] 錯誤的金鑰使用方式',
|
|
39
|
+
'sign_error': '簽章失敗',
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def mask_cert_no(cert_no: str) -> str:
|
|
44
|
+
"""Keep the last 4 characters, replace the others by '*' (same length)."""
|
|
45
|
+
return '*' * max(0, len(cert_no) - 4) + cert_no[-4:]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def wrap_base64(raw: bytes) -> str:
|
|
49
|
+
"""base64 in 64 character lines, every line (the last one too) followed by a newline."""
|
|
50
|
+
b64 = base64.b64encode(raw).decode('ascii')
|
|
51
|
+
return ''.join(b64[i:i + 64] + '\n' for i in range(0, len(b64), 64))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def cert_no_from_serial(serial: int, keep_sign_byte: bool = CERT_NO_KEEP_SIGN_BYTE) -> str:
|
|
55
|
+
b = serial.to_bytes(max(1, (serial.bit_length() + 7) // 8), 'big')
|
|
56
|
+
if keep_sign_byte and b[0] & 0x80:
|
|
57
|
+
b = b'\x00' + b
|
|
58
|
+
return b.hex().upper()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def login_plain(now: datetime) -> str:
|
|
62
|
+
return 'Login_' + now.strftime('%Y%m%d%H%M%S') + '_API_Win'
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True, repr=False)
|
|
66
|
+
class SignParts:
|
|
67
|
+
plain: str
|
|
68
|
+
signature: str
|
|
69
|
+
cert_no: str
|
|
70
|
+
|
|
71
|
+
def __repr__(self) -> str:
|
|
72
|
+
return f'SignParts(plain={self.plain!r}, signature=<masked>, cert_no={"****" + self.cert_no[-4:]})'
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _fail(reason: str, message: str | None = None) -> CertificateError:
|
|
76
|
+
return CertificateError(message or REASON_TEXT[reason], reason=reason)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _names(name: x509.Name, oid: x509.ObjectIdentifier) -> tuple[str, ...]:
|
|
80
|
+
return tuple(str(a.value) for a in name.get_attributes_for_oid(oid))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Signer:
|
|
84
|
+
"""One certificate and its RSA key, loaded from a PFX file."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, pfx_path: str | os.PathLike[str], pfx_password: str | bytes | None = None) -> None:
|
|
87
|
+
try:
|
|
88
|
+
with open(pfx_path, 'rb') as fh:
|
|
89
|
+
data = fh.read()
|
|
90
|
+
except OSError as exc:
|
|
91
|
+
raise CertificateError(f'cannot read the PFX file: {type(exc).__name__}', reason='missing') from None
|
|
92
|
+
self._init(data, pfx_password)
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def from_bytes(cls, data: bytes, password: str | bytes | None = None) -> 'Signer':
|
|
96
|
+
self = cls.__new__(cls)
|
|
97
|
+
self._init(data, password)
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
def _init(self, data: bytes, password: str | bytes | None) -> None:
|
|
101
|
+
pw = password.encode('utf-8') if isinstance(password, str) else password
|
|
102
|
+
try:
|
|
103
|
+
key, cert, extra = pkcs12.load_key_and_certificates(data, pw)
|
|
104
|
+
except Exception: # message of the library is not forwarded: it may mention the input
|
|
105
|
+
raise CertificateError('cannot load the PFX file (wrong password or not a PKCS#12 file)',
|
|
106
|
+
reason='load') from None
|
|
107
|
+
if key is None:
|
|
108
|
+
raise CertificateError('the PFX file contains no private key', reason='load')
|
|
109
|
+
if not isinstance(key, rsa.RSAPrivateKey):
|
|
110
|
+
raise CertificateError('私鑰不是 RSA', reason='not_rsa')
|
|
111
|
+
chosen = None
|
|
112
|
+
public = key.public_key().public_numbers()
|
|
113
|
+
for candidate in [cert, *(extra or [])]:
|
|
114
|
+
if candidate is None:
|
|
115
|
+
continue
|
|
116
|
+
pub = candidate.public_key()
|
|
117
|
+
if isinstance(pub, rsa.RSAPublicKey) and pub.public_numbers() == public:
|
|
118
|
+
chosen = candidate
|
|
119
|
+
break
|
|
120
|
+
if chosen is None:
|
|
121
|
+
raise CertificateError('the PFX file has no certificate that matches the private key', reason='load')
|
|
122
|
+
self._key = key
|
|
123
|
+
self._cert = chosen
|
|
124
|
+
self._selftest()
|
|
125
|
+
self.cert_no: str = cert_no_from_serial(chosen.serial_number)
|
|
126
|
+
self.subject: dict[str, tuple[str, ...]] = {
|
|
127
|
+
'CN': _names(chosen.subject, NameOID.COMMON_NAME),
|
|
128
|
+
'OU': _names(chosen.subject, NameOID.ORGANIZATIONAL_UNIT_NAME),
|
|
129
|
+
'O': _names(chosen.subject, NameOID.ORGANIZATION_NAME),
|
|
130
|
+
}
|
|
131
|
+
self.not_before: datetime = chosen.not_valid_before_utc
|
|
132
|
+
self.not_after: datetime = chosen.not_valid_after_utc
|
|
133
|
+
|
|
134
|
+
def _selftest(self) -> None:
|
|
135
|
+
try:
|
|
136
|
+
sig = self._key.sign(SELFTEST_PLAIN.encode('cp950'), padding.PKCS1v15(), hashes.SHA1()) # noqa: S303
|
|
137
|
+
self._key.public_key().verify(sig, SELFTEST_PLAIN.encode('cp950'), padding.PKCS1v15(), hashes.SHA1()) # noqa: S303
|
|
138
|
+
except Exception:
|
|
139
|
+
raise CertificateError('此環境不允許 SHA-1 簽章(例如 OpenSSL 的系統加密原則),無法產生康和要求的簽章',
|
|
140
|
+
reason='sha1') from None
|
|
141
|
+
|
|
142
|
+
def check(self, id_no: str, *, evaluation: bool, now: datetime | None = None) -> None:
|
|
143
|
+
"""Validity period, subject and key usage (design D15, D16). Raises CertificateError."""
|
|
144
|
+
now = now or datetime.now(timezone.utc)
|
|
145
|
+
if now.tzinfo is None:
|
|
146
|
+
now = now.replace(tzinfo=timezone.utc)
|
|
147
|
+
if now < self.not_before:
|
|
148
|
+
raise _fail('not_yet_valid')
|
|
149
|
+
if now > self.not_after:
|
|
150
|
+
raise _fail('expired')
|
|
151
|
+
if id_no and not any(id_no in cn for cn in self.subject['CN']):
|
|
152
|
+
raise _fail('subject')
|
|
153
|
+
if not any('CONCORDS' in ou for ou in self.subject['OU']):
|
|
154
|
+
raise _fail('subject')
|
|
155
|
+
if evaluation and not any('Evaluation' in o for o in self.subject['O']):
|
|
156
|
+
raise _fail('subject')
|
|
157
|
+
try:
|
|
158
|
+
usage = self._cert.extensions.get_extension_for_class(x509.KeyUsage).value
|
|
159
|
+
except x509.ExtensionNotFound:
|
|
160
|
+
return
|
|
161
|
+
if not usage.digital_signature:
|
|
162
|
+
raise _fail('key_usage')
|
|
163
|
+
|
|
164
|
+
def sign(self, plain: str) -> SignParts:
|
|
165
|
+
try:
|
|
166
|
+
raw = self._key.sign(plain.encode('cp950'), padding.PKCS1v15(), hashes.SHA1()) # noqa: S303
|
|
167
|
+
except Exception:
|
|
168
|
+
raise _fail('sign_error') from None
|
|
169
|
+
signature = wrap_base64(raw)
|
|
170
|
+
if len(signature.replace('\n', '')) % 64 == 0:
|
|
171
|
+
logger.warning('signature base64 length is a multiple of 64: whether the DLL ends it with one or two '
|
|
172
|
+
'newlines is unconfirmed (design-2025.md U10)')
|
|
173
|
+
return SignParts(plain=plain, signature=signature, cert_no=self.cert_no)
|
|
174
|
+
|
|
175
|
+
def __repr__(self) -> str:
|
|
176
|
+
return f'Signer(cert_no={mask_cert_no(self.cert_no)}, not_after={self.not_after:%Y-%m-%d})'
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""tag=value messages: ``|35=A|52=...`` (design.md 4.3)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Literal, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger('conrich.tagvalue')
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def compose(fields: Sequence[tuple[str, str]], sep: str = '|', kv: str = '=', trailing_sep: bool = False) -> str:
|
|
11
|
+
"""Join fields in the given order (never sorted)."""
|
|
12
|
+
text = sep.join(f'{k}{kv}{v}' for k, v in fields)
|
|
13
|
+
return text + sep if trailing_sep and text else text
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parse(text: str, sep: str = '|', kv: str = '=', duplicate: Literal['first', 'stop'] = 'first') -> dict[str, str]:
|
|
17
|
+
"""Split on ``sep`` / first ``kv``. Parts without ``kv`` or with a non-numeric tag are skipped.
|
|
18
|
+
|
|
19
|
+
duplicate='first' keeps the first value of a repeated tag (futures ParseFIX);
|
|
20
|
+
duplicate='stop' stops at the first repeated tag and keeps what was parsed (stock ParseMessageToDic).
|
|
21
|
+
"""
|
|
22
|
+
out: dict[str, str] = {}
|
|
23
|
+
for part in text.split(sep):
|
|
24
|
+
pair = part.split(kv, 1)
|
|
25
|
+
if len(pair) != 2 or not pair[0].isascii() or not pair[0].isdigit():
|
|
26
|
+
continue
|
|
27
|
+
if pair[0] in out:
|
|
28
|
+
if duplicate == 'stop':
|
|
29
|
+
logger.warning('duplicate tag %s: parsing stopped', pair[0])
|
|
30
|
+
break
|
|
31
|
+
continue
|
|
32
|
+
out[pair[0]] = pair[1]
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def label(tags: Mapping[str, str], names: Mapping[str, str]) -> dict[str, str]:
|
|
37
|
+
"""Replace tag numbers by their names; repeated names get '(tag)' appended."""
|
|
38
|
+
out: dict[str, str] = {}
|
|
39
|
+
for tag, value in tags.items():
|
|
40
|
+
name = names.get(tag)
|
|
41
|
+
if name is None:
|
|
42
|
+
out[tag] = value
|
|
43
|
+
elif name in out:
|
|
44
|
+
out[f'{name}({tag})'] = value
|
|
45
|
+
else:
|
|
46
|
+
out[name] = value
|
|
47
|
+
return out
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Time helpers. The broker works in Taipei time (UTC+8); the system zone is never read."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from datetime import date, datetime, timedelta, timezone
|
|
5
|
+
|
|
6
|
+
TAIPEI = timezone(timedelta(hours=8))
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def now_taipei() -> datetime:
|
|
10
|
+
return datetime.now(TAIPEI)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def to_yyyymmdd(value: date | datetime | str) -> str:
|
|
14
|
+
"""date / datetime -> 'YYYYMMDD'; str must already be 8 digits."""
|
|
15
|
+
if isinstance(value, str):
|
|
16
|
+
if len(value) != 8 or not value.isascii() or not value.isdigit():
|
|
17
|
+
raise ValueError(f'date must be 8 digits (YYYYMMDD): {value!r}')
|
|
18
|
+
return value
|
|
19
|
+
if isinstance(value, (date, datetime)):
|
|
20
|
+
return value.strftime('%Y%m%d')
|
|
21
|
+
raise ValueError(f'unsupported date value: {value!r}')
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fmt_timestamp(now: datetime) -> str:
|
|
25
|
+
"""Tag 52 format: yyyyMMdd-HH:mm:ss.fff"""
|
|
26
|
+
return now.strftime('%Y%m%d-%H:%M:%S.') + f'{now.microsecond // 1000:03d}'
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def fmt_date(now: datetime) -> str:
|
|
30
|
+
return now.strftime('%Y%m%d')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def fmt_reqtime(now: datetime) -> str:
|
|
34
|
+
""".NET 'hhmmss' = 12 hour clock (13:05:09 -> '010509'). Copied on purpose, tcode depends on it."""
|
|
35
|
+
return now.strftime('%I%M%S')
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""One TCP channel: receive thread, optional heartbeat thread, serialised sends."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import socket
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from typing import Callable
|
|
9
|
+
|
|
10
|
+
from .cipher import ConcordsCipher
|
|
11
|
+
from .errors import ProtocolError
|
|
12
|
+
from .framing import HEARTBEAT_PLAIN, IDLE_ACK_PLAIN, ConcordsFramer
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger('conrich.transport')
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Channel:
|
|
18
|
+
def __init__(self, name: str, host: str, port: int, framer: ConcordsFramer, cipher: ConcordsCipher,
|
|
19
|
+
on_text: Callable[[str, str], None],
|
|
20
|
+
on_closed: Callable[[str, str], None],
|
|
21
|
+
connect_timeout: float = 5.0, connect_delay: float = 0.0) -> None:
|
|
22
|
+
self.name = name
|
|
23
|
+
self.host = host
|
|
24
|
+
self.port = port
|
|
25
|
+
self.framer = framer
|
|
26
|
+
self.cipher = cipher
|
|
27
|
+
self._on_text = on_text # (channel, plain); runs on the receive thread
|
|
28
|
+
self._on_closed = on_closed # (channel, reason); called once
|
|
29
|
+
self._connect_timeout = connect_timeout
|
|
30
|
+
self._connect_delay = connect_delay
|
|
31
|
+
self._sock: socket.socket | None = None
|
|
32
|
+
self._connected = False
|
|
33
|
+
self._closed_notified = False
|
|
34
|
+
self._stop = threading.Event()
|
|
35
|
+
self._state_lock = threading.Lock()
|
|
36
|
+
self._send_lock = threading.Lock()
|
|
37
|
+
self._threads: list[threading.Thread] = []
|
|
38
|
+
self.last_received: float = time.monotonic() # time.monotonic() of the last frame (or of connect)
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def connected(self) -> bool:
|
|
42
|
+
return self._connected
|
|
43
|
+
|
|
44
|
+
def connect(self) -> None:
|
|
45
|
+
"""Open the socket and start the receive thread. Raises ConnectionError on failure."""
|
|
46
|
+
try:
|
|
47
|
+
sock = socket.create_connection((self.host, self.port), timeout=self._connect_timeout)
|
|
48
|
+
except OSError as exc:
|
|
49
|
+
raise ConnectionError(f'{self.name}: connect failed: {exc}') from exc
|
|
50
|
+
sock.settimeout(None)
|
|
51
|
+
try:
|
|
52
|
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
53
|
+
except OSError:
|
|
54
|
+
pass
|
|
55
|
+
with self._state_lock:
|
|
56
|
+
self._sock = sock
|
|
57
|
+
self._connected = True
|
|
58
|
+
self._closed_notified = False
|
|
59
|
+
self.last_received = time.monotonic()
|
|
60
|
+
self._stop.clear()
|
|
61
|
+
t = threading.Thread(target=self._recv_loop, args=(sock,), name=f'conrich-recv-{self.name}', daemon=True)
|
|
62
|
+
self._threads.append(t)
|
|
63
|
+
t.start()
|
|
64
|
+
if self._connect_delay > 0: # the DLL waits 3.5 s after connecting before it speaks
|
|
65
|
+
self._stop.wait(self._connect_delay)
|
|
66
|
+
if not self._connected:
|
|
67
|
+
raise ConnectionError(f'{self.name}: closed during connect')
|
|
68
|
+
|
|
69
|
+
def send_text(self, plain: str) -> None:
|
|
70
|
+
"""Encrypt, frame and send. Raises ConnectionError when not connected or the send fails."""
|
|
71
|
+
with self._send_lock:
|
|
72
|
+
sock = self._sock
|
|
73
|
+
if not self._connected or sock is None:
|
|
74
|
+
raise ConnectionError(f'{self.name}: not connected')
|
|
75
|
+
data = self.framer.encode(self.cipher.encrypt_text(plain))
|
|
76
|
+
try:
|
|
77
|
+
sock.sendall(data)
|
|
78
|
+
except OSError as exc:
|
|
79
|
+
self.close(f'send failed: {exc}')
|
|
80
|
+
raise ConnectionError(f'{self.name}: send failed: {exc}') from exc
|
|
81
|
+
|
|
82
|
+
def start_heartbeat(self, interval: float = 30.0) -> None:
|
|
83
|
+
t = threading.Thread(target=self._heartbeat_loop, args=(interval,), name=f'conrich-hb-{self.name}', daemon=True)
|
|
84
|
+
self._threads.append(t)
|
|
85
|
+
t.start()
|
|
86
|
+
|
|
87
|
+
def start_idle_monitor(self, *, check_every: float = 5.0, ack_after: float = 5.0, drop_after: float = 12.5,
|
|
88
|
+
ack_plain: str = IDLE_ACK_PLAIN) -> None:
|
|
89
|
+
"""Futures channels: every ``check_every`` s, send ``ack_plain`` when nothing was received
|
|
90
|
+
for more than ``ack_after`` s and close the channel ('idle timeout') after ``drop_after`` s
|
|
91
|
+
(design-2025.md D6; the DLL reconnects instead of closing, conrich only reports it)."""
|
|
92
|
+
t = threading.Thread(target=self._idle_loop, args=(check_every, ack_after, drop_after, ack_plain),
|
|
93
|
+
name=f'conrich-idle-{self.name}', daemon=True)
|
|
94
|
+
self._threads.append(t)
|
|
95
|
+
t.start()
|
|
96
|
+
|
|
97
|
+
def close(self, reason: str = '') -> None:
|
|
98
|
+
with self._state_lock:
|
|
99
|
+
sock, self._sock = self._sock, None
|
|
100
|
+
was_connected, self._connected = self._connected, False
|
|
101
|
+
notify = not self._closed_notified and (was_connected or sock is not None)
|
|
102
|
+
if notify:
|
|
103
|
+
self._closed_notified = True
|
|
104
|
+
self._stop.set()
|
|
105
|
+
if sock is not None:
|
|
106
|
+
try:
|
|
107
|
+
sock.shutdown(socket.SHUT_RDWR)
|
|
108
|
+
except OSError:
|
|
109
|
+
pass
|
|
110
|
+
try:
|
|
111
|
+
sock.close()
|
|
112
|
+
except OSError:
|
|
113
|
+
pass
|
|
114
|
+
me = threading.current_thread()
|
|
115
|
+
for t in list(self._threads):
|
|
116
|
+
if t is not me and t.is_alive(): # a thread that is not started yet cannot be joined
|
|
117
|
+
t.join(1.0)
|
|
118
|
+
self._threads = [t for t in self._threads if t.is_alive()]
|
|
119
|
+
if notify:
|
|
120
|
+
try:
|
|
121
|
+
self._on_closed(self.name, reason)
|
|
122
|
+
except Exception:
|
|
123
|
+
logger.exception('on_closed raised')
|
|
124
|
+
|
|
125
|
+
def _recv_loop(self, sock: socket.socket) -> None:
|
|
126
|
+
reason = 'closed'
|
|
127
|
+
try:
|
|
128
|
+
while self._connected:
|
|
129
|
+
data = sock.recv(65536)
|
|
130
|
+
if not data:
|
|
131
|
+
reason = 'closed by peer'
|
|
132
|
+
break
|
|
133
|
+
for body in self.framer.feed(data):
|
|
134
|
+
self.last_received = time.monotonic()
|
|
135
|
+
try:
|
|
136
|
+
plain = self.cipher.decrypt_text(body)
|
|
137
|
+
except ProtocolError:
|
|
138
|
+
logger.warning('%s: dropped a frame that could not be decrypted', self.name)
|
|
139
|
+
continue
|
|
140
|
+
try:
|
|
141
|
+
self._on_text(self.name, plain)
|
|
142
|
+
except Exception:
|
|
143
|
+
logger.exception('%s: on_text raised', self.name)
|
|
144
|
+
except ProtocolError as exc:
|
|
145
|
+
reason = f'protocol error: {exc}'
|
|
146
|
+
except OSError as exc:
|
|
147
|
+
reason = f'receive failed: {exc}' if self._connected else 'closed'
|
|
148
|
+
finally:
|
|
149
|
+
self.close(reason)
|
|
150
|
+
|
|
151
|
+
def _heartbeat_loop(self, interval: float) -> None:
|
|
152
|
+
while not self._stop.wait(interval):
|
|
153
|
+
try:
|
|
154
|
+
self.send_text(HEARTBEAT_PLAIN)
|
|
155
|
+
except ConnectionError:
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
def _idle_loop(self, check_every: float, ack_after: float, drop_after: float, ack_plain: str) -> None:
|
|
159
|
+
while not self._stop.wait(check_every):
|
|
160
|
+
if not self._connected:
|
|
161
|
+
return
|
|
162
|
+
silent = time.monotonic() - self.last_received
|
|
163
|
+
if silent > drop_after:
|
|
164
|
+
logger.warning('%s: nothing received for %.1f s, closing', self.name, silent)
|
|
165
|
+
self.close('idle timeout')
|
|
166
|
+
return
|
|
167
|
+
if silent > ack_after:
|
|
168
|
+
try:
|
|
169
|
+
self.send_text(ack_plain)
|
|
170
|
+
except ConnectionError:
|
|
171
|
+
return
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Version strings: '1.1.2025.0407' -> (1, 1, 2025, 407)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def parse_version(text: str) -> tuple[int, ...]:
|
|
6
|
+
parts = text.strip().split('.')
|
|
7
|
+
if not parts or any(not p.isascii() or not p.isdigit() for p in parts):
|
|
8
|
+
raise ValueError(f'bad version string: {text!r}')
|
|
9
|
+
return tuple(int(p) for p in parts)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def check_min_version(declared: str, minimum: str) -> bool:
|
|
13
|
+
"""True when declared >= minimum (missing trailing parts count as 0, like System.Version only if equal length)."""
|
|
14
|
+
a, b = parse_version(declared), parse_version(minimum)
|
|
15
|
+
width = max(len(a), len(b))
|
|
16
|
+
return a + (0,) * (width - len(a)) >= b + (0,) * (width - len(b))
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
| Method | 中文說明 | 國內API規格 | 參數 | 說明 |
|
|
2
|
+
|--------|------------------|------------------------|----------------|---------------------------------------------------------|
|
|
3
|
+
| 系統相關 | 登入 | login | in_no | 身分證字號 |
|
|
4
|
+
| | | | pwd | 密碼 |
|
|
5
|
+
| | | | branch_no | 分公司代號 例:F029000 |
|
|
6
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
7
|
+
| | 檢查連線狀況 | check_connect | | |
|
|
8
|
+
| 基本資料 | 查詢帳號資訊 | account_info | | |
|
|
9
|
+
| | 查詢是否多帳號登入 | check_multi_login | | |
|
|
10
|
+
| | 查詢期貨商品 | get_commodity | | |
|
|
11
|
+
| | 查詢期貨商品月份 | get_commodity_by_month | | |
|
|
12
|
+
| 交易相關 | 單筆下單 | order | action | OrderNew, OrderChangeQty, OrderChangePrice, OrderDelete |
|
|
13
|
+
| | | | branch_no | 分公司代號 例:F029000 |
|
|
14
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
15
|
+
| | | | market_type | 市場別 F=期貨、O=選擇權 |
|
|
16
|
+
| | | | compound_type | 單複式別 1=期貨單式、2=選擇權單式、3=選擇權複式、4=期貨複式 |
|
|
17
|
+
| | | | commodity | 商品代碼 |
|
|
18
|
+
| | | | time_in_force | 委託條件 F:=FOK、I=IOC、R=ROD |
|
|
19
|
+
| | | | writeoff | 沖銷別(開平倉碼) 0=開倉、1=平倉、2=期貨當沖、空白=自動 |
|
|
20
|
+
| | | | order_type | 委託方式 M=市價、L=限價、P=一定範圍市價 |
|
|
21
|
+
| | | | side | 買賣別 B=買、S=賣 |
|
|
22
|
+
| | | | quantity | 委託數量 新增時請輸入委託數量,例:1口=1、10口=10 |
|
|
23
|
+
| | | | price | 委託價格 市價委託時請輸入0,例:80.50、8000.00(含小數點+小數兩位) |
|
|
24
|
+
| | | | orig_net_no | 原網路單號 |
|
|
25
|
+
| | | | order_id | 委託書號 |
|
|
26
|
+
| | 回補 | order_recover | branch_no | 分公司代號 例:F029000 |
|
|
27
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
28
|
+
| | | | seq_start | 開始序號 |
|
|
29
|
+
| | | | seq_end | 結束序號 |
|
|
30
|
+
| | 回報查詢 | query_order | branch_no | 分公司代號 例:F029000 |
|
|
31
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
32
|
+
| | | | record_type | 記錄類別 Order, Deal |
|
|
33
|
+
| | | | period | 時間區間 History, Today |
|
|
34
|
+
| 帳務查詢 | 期貨保證金查詢 | margin | branch_no | 分公司代號 例:F029000 |
|
|
35
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
36
|
+
| | | | currency | 查詢幣別 TWD:國內台幣;US$:國內美元;** :約當台幣;ALL:全部 |
|
|
37
|
+
| | | | group | 群組 1.非子帳客戶傳空白 2.查詢子帳客戶所有組別資料傳’***’ |
|
|
38
|
+
| | | | trader | 交易員代號 1.非子帳客戶傳空白 2.查詢子帳客戶所有子帳資料傳"******" |
|
|
39
|
+
| | 未平倉查詢 (外期含多貨幣查詢) | position | branch_no | 分公司代號 例:F029000 |
|
|
40
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
41
|
+
| | | | group | 組別 1.非子帳客戶傳空白 2.查詢子帳客戶所有組別資料傳’***’ |
|
|
42
|
+
| | | | trader | 交易員 1.非子帳客戶傳空白 2.查詢子帳客戶所有子帳資料傳’******’ |
|
|
43
|
+
| | | | compound_type | 查詢類別 1:單式 2:複式 3:全部 |
|
|
44
|
+
| | 未平倉彙總查詢 | position_summary | branch_no | 分公司代號 例:F029000 |
|
|
45
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
46
|
+
| | | | compound_type | 查詢類別 1:單式 2:複式 3:全部 |
|
|
47
|
+
| | 即時部位查詢 | position_index | branch_no | 分公司代號 例:F029000 |
|
|
48
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
49
|
+
| | 沖銷明細查詢 | offset | branch_no | 分公司代號 例:F029000 |
|
|
50
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
51
|
+
| | 歷史沖銷明細查詢 | offset_history | branch_no | 分公司代號 例:F029000 |
|
|
52
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
53
|
+
| | | | strSDate | 起始日期 |
|
|
54
|
+
| | | | strEDate | 結束日期 |
|
|
55
|
+
| | 出入金查詢 | deposit | branch_no | 分公司代號 例:F029000 |
|
|
56
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
57
|
+
| | 歷史出入金查詢 | deposit_history | branch_no | 分公司代號 例:F029000 |
|
|
58
|
+
| | | | account_no | 帳號 例:1009991、0000455(含檢查碼) |
|
|
59
|
+
| | | | strSDate | 起始日期 |
|
|
60
|
+
| | | | strEDate | 結束日期 |
|
|
61
|
+
|
|
62
|
+
| Event | 中文說明 | 國內API規格 | 參數 | 說明 |
|
|
63
|
+
|--------|------------------|------------------------|----------------|---------------------------------------------------------|
|
|
64
|
+
| 系統相關 | 主動一般通知事件 | OnFGeneralReport | code | 代碼 |
|
|
65
|
+
| | | | msg | 訊息 |
|
|
66
|
+
| | 主動錯誤通知事件 | OnFErrorReport | code | 代碼 |
|
|
67
|
+
| | | | msg | 訊息 |
|
|
68
|
+
| | 主動公告通知事件 | OnFBulletinReport | code | 代碼 |
|
|
69
|
+
| | | | msg | 訊息 |
|
|
70
|
+
| 交易相關 | 主動委成回通知事件 | OnFOrderReport | code | 代碼 |
|
|
71
|
+
| | | | msg | 訊息 |
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Futures API (pure Python, 2025 protocol). The API classes are imported on first use."""
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
|
|
4
|
+
_LAZY = {'FuturesAPI': '.futures', 'ForeignFuturesAPI': '.foreign_futures'}
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def __getattr__(name):
|
|
8
|
+
if name in _LAZY:
|
|
9
|
+
value = getattr(import_module(_LAZY[name], __name__), name)
|
|
10
|
+
globals()[name] = value
|
|
11
|
+
return value
|
|
12
|
+
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
|