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.
Files changed (43) hide show
  1. conrich/Common/__init__.py +0 -0
  2. conrich/Common/cipher.py +74 -0
  3. conrich/Common/endpoints.py +49 -0
  4. conrich/Common/errors.py +29 -0
  5. conrich/Common/events.py +117 -0
  6. conrich/Common/framing.py +70 -0
  7. conrich/Common/gate.py +65 -0
  8. conrich/Common/normalize.py +46 -0
  9. conrich/Common/records.py +44 -0
  10. conrich/Common/service.py +110 -0
  11. conrich/Common/signer.py +176 -0
  12. conrich/Common/tagvalue.py +47 -0
  13. conrich/Common/timeutil.py +35 -0
  14. conrich/Common/transport.py +171 -0
  15. conrich/Common/version.py +16 -0
  16. conrich/Futures/Futures_README.md +71 -0
  17. conrich/Futures/__init__.py +12 -0
  18. conrich/Futures/base.py +236 -0
  19. conrich/Futures/constant.py +63 -0
  20. conrich/Futures/fields.py +716 -0
  21. conrich/Futures/foreign_futures.py +53 -0
  22. conrich/Futures/futures.py +74 -0
  23. conrich/Futures/messages.py +97 -0
  24. conrich/Futures/session.py +464 -0
  25. conrich/Quote/__init__.py +15 -0
  26. conrich/Quote/event.py +4 -0
  27. conrich/Quote/quote.py +116 -0
  28. conrich/Quote/server.py +10 -0
  29. conrich/Quote/symbols.py +18 -0
  30. conrich/Stock/__init__.py +10 -0
  31. conrich/Stock/constant.py +48 -0
  32. conrich/Stock/fields.py +147 -0
  33. conrich/Stock/messages.py +179 -0
  34. conrich/Stock/orders.py +104 -0
  35. conrich/Stock/results.py +53 -0
  36. conrich/Stock/session.py +373 -0
  37. conrich/Stock/stock.py +279 -0
  38. conrich/__init__.py +38 -0
  39. conrich2-1.0.0.dev0.dist-info/METADATA +242 -0
  40. conrich2-1.0.0.dev0.dist-info/RECORD +43 -0
  41. conrich2-1.0.0.dev0.dist-info/WHEEL +5 -0
  42. conrich2-1.0.0.dev0.dist-info/licenses/LICENSE +21 -0
  43. conrich2-1.0.0.dev0.dist-info/top_level.txt +1 -0
File without changes
@@ -0,0 +1,74 @@
1
+ """Channel cipher and password hash (design-2025.md 1.1 N5, N8)."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import hashlib
6
+ import threading
7
+ from typing import Literal
8
+
9
+ from cryptography.hazmat.primitives import padding
10
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
11
+
12
+ from .errors import ProtocolError
13
+
14
+ DEFAULT_KEY = '00000000-AAAA-BBBB-CCCC-0000FFFF0000'
15
+
16
+
17
+ def derive_key(key_text: str) -> bytes:
18
+ """AES-128 key AND iv: MD5 of the UTF-16LE text."""
19
+ return hashlib.md5(key_text.encode('utf-16-le')).digest()
20
+
21
+
22
+ class ConcordsCipher:
23
+ """AES-128-CBC / PKCS7, iv == key, UTF-16LE plaintext, base64 output.
24
+
25
+ The iv is fixed, so every message starts from the same iv (like the .NET
26
+ TransformFinalBlock); a fresh cipher context is built per message.
27
+ One instance per channel.
28
+ """
29
+
30
+ def __init__(self, key_text: str = DEFAULT_KEY) -> None:
31
+ self._lock = threading.Lock()
32
+ self._state = (key_text, derive_key(key_text))
33
+
34
+ @property
35
+ def key_text(self) -> str:
36
+ return self._state[0]
37
+
38
+ def rekey(self, key_text: str) -> None:
39
+ state = (key_text, derive_key(key_text))
40
+ with self._lock:
41
+ self._state = state
42
+
43
+ def encrypt_text(self, plain: str) -> str:
44
+ key = self._state[1]
45
+ padder = padding.PKCS7(128).padder()
46
+ data = padder.update(plain.encode('utf-16-le')) + padder.finalize()
47
+ enc = Cipher(algorithms.AES(key), modes.CBC(key)).encryptor()
48
+ return base64.b64encode(enc.update(data) + enc.finalize()).decode('ascii')
49
+
50
+ def decrypt_text(self, b64: str) -> str:
51
+ key = self._state[1]
52
+ try:
53
+ raw = base64.b64decode(b64, validate=True)
54
+ dec = Cipher(algorithms.AES(key), modes.CBC(key)).decryptor()
55
+ data = dec.update(raw) + dec.finalize()
56
+ unpadder = padding.PKCS7(128).unpadder()
57
+ return (unpadder.update(data) + unpadder.finalize()).decode('utf-16-le')
58
+ except Exception as exc: # bad base64, bad length, bad padding, bad utf-16
59
+ raise ProtocolError('cannot decrypt message') from exc
60
+
61
+
62
+ def hash_password(password: str, product: Literal['stock', 'futures']) -> str:
63
+ """md5 of the cp950 bytes as lower-case hex, for both products (design-2025.md N5).
64
+
65
+ Raises ValueError when the password cannot be encoded as cp950 (the DLL uses
66
+ Encoding.Default, which is cp950 on a Traditional Chinese Windows).
67
+ """
68
+ if product not in ('stock', 'futures'):
69
+ raise ValueError(f'unknown product: {product!r}')
70
+ try:
71
+ data = password.encode('cp950')
72
+ except UnicodeEncodeError as exc:
73
+ raise ValueError('password contains a character that cannot be encoded as cp950') from exc
74
+ return hashlib.md5(data).hexdigest()
@@ -0,0 +1,49 @@
1
+ """Gateway and URL rules of the 2025 protocol (design-2025.md 3.1)."""
2
+ from __future__ import annotations
3
+
4
+ import ssl
5
+ from urllib.parse import urlsplit
6
+
7
+ LIVE_HOST = 'tradeapi.concords.com.tw'
8
+ TEST_HOST = 'tradeapitest.concords.com.tw'
9
+ LIVE_GATEWAY = 'TradeAPIP.concords.com.tw'
10
+ TEST_GATEWAY = 'TradeAPITestP.concords.com.tw'
11
+
12
+ _LOOPBACK_HOSTS = ('127.0.0.1', '::1', 'localhost')
13
+
14
+
15
+ def gateway_for(host: str) -> str:
16
+ """Map the user-visible host to the gateway the DLL connects to (TradeAPI.cs:322-331)."""
17
+ if host == '' or host.upper() == LIVE_HOST.upper():
18
+ return LIVE_GATEWAY
19
+ if 'test' in host: # case sensitive, as in the DLL
20
+ return TEST_GATEWAY
21
+ return host
22
+
23
+
24
+ def service_url_for(gateway: str) -> str:
25
+ return f'https://{gateway}/QueryService.aspx'
26
+
27
+
28
+ def is_evaluation(gateway: str) -> bool:
29
+ """True when the certificate subject must also carry O=Evaluation (design D15)."""
30
+ return 'test' in gateway or gateway.startswith(('192.168.199.', '192.168.198.'))
31
+
32
+
33
+ def is_loopback_url(url: str | None) -> bool:
34
+ if url is None:
35
+ return False
36
+ try:
37
+ return urlsplit(url).hostname in _LOOPBACK_HOSTS
38
+ except ValueError:
39
+ return False
40
+
41
+
42
+ def make_ssl_context(custom: ssl.SSLContext | None) -> ssl.SSLContext:
43
+ """A user supplied context is used as is; otherwise verify the server (unlike the DLL)."""
44
+ if custom is not None:
45
+ return custom
46
+ ctx = ssl.create_default_context()
47
+ ctx.minimum_version = ssl.TLSVersion.TLSv1_2
48
+ ctx.check_hostname = True
49
+ return ctx
@@ -0,0 +1,29 @@
1
+ """Exception types shared by every conrich API."""
2
+
3
+
4
+ class ConrichError(Exception):
5
+ """Base class of all conrich errors."""
6
+
7
+
8
+ class OrderError(ConrichError, ValueError):
9
+ """An order argument could not be converted or is out of range."""
10
+
11
+
12
+ class TradingDisabledError(OrderError):
13
+ """order() was called while trading is not enabled (see conrich.Common.gate)."""
14
+
15
+
16
+ class CertificateError(ConrichError):
17
+ """No usable signing certificate, or the certificate cannot sign.
18
+
19
+ ``reason`` is one of: 'missing', 'load', 'not_rsa', 'sha1', 'expired', 'not_yet_valid',
20
+ 'subject', 'key_usage', 'sign_error' (empty when not classified).
21
+ """
22
+
23
+ def __init__(self, message: str, reason: str = '') -> None:
24
+ super().__init__(message)
25
+ self.reason = reason
26
+
27
+
28
+ class ProtocolError(ConrichError):
29
+ """A frame or message could not be parsed or decrypted."""
@@ -0,0 +1,117 @@
1
+ """Event, Dispatcher and EventEmitter (design.md 4.2)."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import queue
6
+ import threading
7
+ from typing import Any, Callable
8
+
9
+ logger = logging.getLogger('conrich.events')
10
+
11
+
12
+ class Event:
13
+ """0.7.x compatible ``event += handler`` object."""
14
+
15
+ def __init__(self) -> None:
16
+ self.listeners: list[Callable[..., Any]] = []
17
+ self._lock = threading.Lock()
18
+
19
+ def __iadd__(self, handler: Callable[..., Any]) -> 'Event':
20
+ with self._lock:
21
+ self.listeners.append(handler)
22
+ return self
23
+
24
+ def __isub__(self, handler: Callable[..., Any]) -> 'Event':
25
+ with self._lock:
26
+ try:
27
+ self.listeners.remove(handler)
28
+ except ValueError:
29
+ pass
30
+ return self
31
+
32
+ def notify(self, *args: Any) -> None:
33
+ with self._lock:
34
+ handlers = list(self.listeners)
35
+ for handler in handlers:
36
+ try:
37
+ handler(*args)
38
+ except Exception: # a broken handler must not stop the others
39
+ logger.exception('event handler raised')
40
+
41
+
42
+ _STOP = object()
43
+
44
+
45
+ class Dispatcher:
46
+ """One daemon thread that runs submitted callables in order."""
47
+
48
+ def __init__(self, name: str) -> None:
49
+ self.name = name
50
+ self._queue: queue.Queue = queue.Queue()
51
+ self._thread: threading.Thread | None = None
52
+ self._lock = threading.Lock()
53
+ self._stopped = False
54
+
55
+ @property
56
+ def running(self) -> bool:
57
+ t = self._thread
58
+ return t is not None and t.is_alive() and not self._stopped
59
+
60
+ def start(self) -> None:
61
+ with self._lock:
62
+ if self._thread is not None and self._thread.is_alive():
63
+ return
64
+ self._stopped = False
65
+ self._thread = threading.Thread(target=self._run, name=f'conrich-dispatch-{self.name}', daemon=True)
66
+ self._thread.start()
67
+
68
+ def submit(self, fn: Callable[[], None]) -> None:
69
+ if self._stopped:
70
+ return
71
+ self._queue.put(fn)
72
+
73
+ def stop(self, timeout: float = 1.0) -> None:
74
+ with self._lock:
75
+ thread = self._thread
76
+ self._stopped = True
77
+ if thread is None or not thread.is_alive():
78
+ return
79
+ self._queue.put(_STOP)
80
+ if thread is not threading.current_thread():
81
+ thread.join(timeout)
82
+
83
+ def _run(self) -> None:
84
+ while True:
85
+ item = self._queue.get()
86
+ if item is _STOP:
87
+ return
88
+ try:
89
+ item()
90
+ except Exception:
91
+ logger.exception('dispatched call raised')
92
+
93
+
94
+ class EventEmitter:
95
+ """Generic listener interface next to the named 0.7.x events."""
96
+
97
+ source = ''
98
+
99
+ def _listeners_list(self) -> list:
100
+ listeners = self.__dict__.get('_event_listeners')
101
+ if listeners is None:
102
+ listeners = self.__dict__['_event_listeners'] = []
103
+ return listeners
104
+
105
+ def add_listener(self, listener: Callable[[dict], None]) -> None:
106
+ self._listeners_list().append(listener)
107
+
108
+ def remove_listener(self, listener: Callable[[dict], None]) -> None:
109
+ self._listeners_list().remove(listener) # ValueError when absent, like list.remove
110
+
111
+ def _emit(self, kind: str, code: str, message: str, data: dict | None = None) -> None:
112
+ event = {'source': self.source, 'kind': kind, 'code': code, 'message': message, 'data': data or {}}
113
+ for listener in list(self._listeners_list()):
114
+ try:
115
+ listener(event)
116
+ except Exception:
117
+ logger.exception('event listener raised')
@@ -0,0 +1,70 @@
1
+ """TCP framing: ``8=Concords|9=<5 digit length><base64 body>`` (design-pure-python.md 2.3, 2.5)."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from typing import Iterator
6
+
7
+ from .errors import ProtocolError
8
+
9
+ logger = logging.getLogger('conrich.framing')
10
+
11
+ HEARTBEAT_PLAIN = '8=Concords|9=00005|35=0'
12
+ IDLE_ACK_PLAIN = '8=Concords|9=00005|35=h'
13
+ _HEADER = b'8=Concords|9='
14
+ _HEADER_LEN = 18
15
+ _MAX_BODY = 1 << 20
16
+
17
+
18
+ def compose_plain(body: str) -> str:
19
+ """Inner message: header + 5 digit byte length (cp950) + body (body starts with '|35=')."""
20
+ return f'8=Concords|9={len(body.encode("cp950")):05d}{body}'
21
+
22
+
23
+ class ConcordsFramer:
24
+ HEADER = _HEADER
25
+
26
+ def __init__(self) -> None:
27
+ self._buf = bytearray()
28
+
29
+ def encode(self, b64: str) -> bytes:
30
+ body = b64.encode('cp950')
31
+ if len(body) > 99999:
32
+ raise ProtocolError('message too long for a 5 digit length field')
33
+ return _HEADER + f'{len(body):05d}'.encode('ascii') + body
34
+
35
+ def feed(self, data: bytes) -> Iterator[str]:
36
+ """Return the complete bodies found so far; partial data stays in the buffer."""
37
+ buf = self._buf
38
+ buf.extend(data)
39
+ out: list[str] = []
40
+ while True:
41
+ idx = buf.find(b'8=Concords|')
42
+ if idx < 0:
43
+ # keep a possible partial header at the end
44
+ keep = len('8=Concords|') - 1
45
+ if len(buf) > keep:
46
+ del buf[:len(buf) - keep]
47
+ break
48
+ if idx > 0:
49
+ logger.warning('skipping %d unexpected byte(s) before a frame', idx)
50
+ del buf[:idx]
51
+ if len(buf) < _HEADER_LEN:
52
+ break
53
+ length_field = bytes(buf[13:_HEADER_LEN])
54
+ if bytes(buf[:13]) != _HEADER or not (length_field.isascii() and length_field.isdigit()) or int(length_field) < 1:
55
+ logger.warning('bad frame header, resynchronising')
56
+ del buf[:1]
57
+ continue
58
+ size = int(length_field)
59
+ if size > _MAX_BODY:
60
+ buf.clear()
61
+ raise ProtocolError('frame body larger than 1 MiB')
62
+ if len(buf) < _HEADER_LEN + size:
63
+ break
64
+ body = bytes(buf[_HEADER_LEN:_HEADER_LEN + size])
65
+ del buf[:_HEADER_LEN + size]
66
+ out.append(body.decode('cp950', errors='replace'))
67
+ return iter(out)
68
+
69
+ def reset(self) -> None:
70
+ self._buf.clear()
conrich/Common/gate.py ADDED
@@ -0,0 +1,65 @@
1
+ """Order safety gate (design-2025.md section 5).
2
+
3
+ Every order path calls ``TradingGate.check()`` before anything is signed or sent.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import os
9
+ import threading
10
+ from typing import Callable
11
+
12
+ from .errors import TradingDisabledError
13
+
14
+ logger = logging.getLogger('conrich.gate')
15
+
16
+ LIVE_ENV = 'CONRICH_ALLOW_LIVE_ORDERS'
17
+
18
+ # Hard switch in the source code: not an environment variable, not a constructor argument.
19
+ # While it is False every order path (live, test host and dry run) raises TradingDisabledError
20
+ # before anything is signed, framed or sent. Only the project owner may change it to True,
21
+ # after explicitly agreeing to it. Tests may monkeypatch it; code must never assign it.
22
+ ORDER_ENABLED = False
23
+
24
+ HARD_OFF_MESSAGE = ('order() is switched off in this build (conrich.Common.gate.ORDER_ENABLED is False). '
25
+ 'Nothing was signed, built or sent.')
26
+
27
+ DISABLED_MESSAGE = ('order() is disabled: pass enable_trading=True to the API constructor. '
28
+ 'Nothing was signed or sent.')
29
+ LIVE_MESSAGE = ('live orders need the environment variable CONRICH_ALLOW_LIVE_ORDERS=1. '
30
+ 'Nothing was signed or sent.')
31
+
32
+
33
+ class TradingGate:
34
+ def __init__(self, *, enable_trading: bool, dry_run: bool, live_target: Callable[[], bool],
35
+ owner: str = 'API') -> None:
36
+ self._enable_trading = bool(enable_trading)
37
+ self._dry_run = bool(dry_run)
38
+ self._live_target = live_target
39
+ self._owner = owner
40
+ self._warned = False
41
+ self._lock = threading.Lock()
42
+
43
+ @property
44
+ def enable_trading(self) -> bool:
45
+ return self._enable_trading
46
+
47
+ @property
48
+ def dry_run(self) -> bool:
49
+ return self._dry_run
50
+
51
+ def check(self, account: str = '') -> None:
52
+ """Raise TradingDisabledError unless an order may proceed (a dry run skips the live check)."""
53
+ if not ORDER_ENABLED: # looked up on every call
54
+ raise TradingDisabledError(HARD_OFF_MESSAGE)
55
+ if not self._enable_trading:
56
+ raise TradingDisabledError(DISABLED_MESSAGE)
57
+ if self._dry_run:
58
+ return
59
+ if self._live_target():
60
+ if os.environ.get(LIVE_ENV) != '1': # read on every call, never cached
61
+ raise TradingDisabledError(LIVE_MESSAGE)
62
+ with self._lock:
63
+ first, self._warned = not self._warned, True
64
+ if first:
65
+ logger.warning('live order enabled for %s (account ****%s)', self._owner, account[-4:])
@@ -0,0 +1,46 @@
1
+ """Argument normalisation shared by the order / query APIs."""
2
+ from __future__ import annotations
3
+
4
+ from decimal import Decimal, InvalidOperation
5
+ from enum import Enum
6
+
7
+ from .errors import OrderError
8
+
9
+
10
+ def enum_value(enum_cls: type[Enum], value, name: str) -> str:
11
+ """Enum member -> .value; anything else is str()-ed and must be a valid value."""
12
+ if isinstance(value, Enum):
13
+ if not isinstance(value, enum_cls):
14
+ raise OrderError(f'{name} 有誤: {value!r}')
15
+ return value.value
16
+ try:
17
+ return enum_cls(str(value)).value
18
+ except ValueError:
19
+ raise OrderError(f'{name} 有誤: {value!r}') from None
20
+
21
+
22
+ def to_int(value, name: str, minimum: int | None = None) -> int:
23
+ if isinstance(value, bool):
24
+ raise OrderError(f'{name} 有誤: {value!r}')
25
+ try:
26
+ number = int(str(value).strip()) if not isinstance(value, int) else value
27
+ except (TypeError, ValueError):
28
+ raise OrderError(f'{name} 有誤: {value!r}') from None
29
+ if minimum is not None and number < minimum:
30
+ raise OrderError(f'{name} 有誤: {value!r}')
31
+ return number
32
+
33
+
34
+ def to_decimal(value, name: str) -> Decimal:
35
+ try:
36
+ number = Decimal(str(value).strip())
37
+ except (InvalidOperation, ValueError):
38
+ raise OrderError(f'{name} 有誤: {value!r}') from None
39
+ if not number.is_finite():
40
+ raise OrderError(f'{name} 有誤: {value!r}')
41
+ return number
42
+
43
+
44
+ def decimal_text(value) -> str:
45
+ """0.7.x: System.Decimal(float(x)).ToString() -> 15 significant digits, no trailing zeros."""
46
+ return format(Decimal(format(float(value), '.15g')).normalize(), 'f')
@@ -0,0 +1,44 @@
1
+ """Turn query answers into list[dict[str, str]] (design.md 4.9). No type conversion."""
2
+ from __future__ import annotations
3
+
4
+ import csv
5
+ import logging
6
+ from typing import Iterable, Sequence
7
+
8
+ logger = logging.getLogger('conrich.records')
9
+
10
+
11
+ def unique_header(header: Sequence[str]) -> list[str]:
12
+ seen: dict[str, int] = {}
13
+ out: list[str] = []
14
+ for name in header:
15
+ count = seen.get(name, 0) + 1
16
+ seen[name] = count
17
+ out.append(name if count == 1 else f'{name}_{count}')
18
+ return out
19
+
20
+
21
+ def _to_dict(cells: Sequence[str], header: Sequence[str]) -> dict[str, str]:
22
+ cells = [c.strip() for c in cells]
23
+ if len(cells) > len(header):
24
+ logger.debug('row has %d columns, header has %d: extra dropped', len(cells), len(header))
25
+ cells = cells[:len(header)] + [''] * (len(header) - len(cells))
26
+ return dict(zip(header, cells))
27
+
28
+
29
+ def rows_to_dicts(rows: Iterable[str], header: Sequence[str], sep: str = ',') -> list[dict[str, str]]:
30
+ return [_to_dict(row.split(sep), header) for row in rows]
31
+
32
+
33
+ def csv_to_dicts(text: str, header: Sequence[str]) -> list[dict[str, str]]:
34
+ out: list[dict[str, str]] = []
35
+ for cells in csv.reader(text.splitlines()):
36
+ if not cells or all(not c.strip() for c in cells):
37
+ continue
38
+ out.append(_to_dict(cells, header))
39
+ return out
40
+
41
+
42
+ def mask_id(id_no: str) -> str:
43
+ """Log-safe ID: first 3 characters, rest '*'."""
44
+ return id_no[:3] + '*' * max(0, len(id_no) - 3)
@@ -0,0 +1,110 @@
1
+ """HTTPS 'BillCenter' query service (design-2025.md 3.2).
2
+
3
+ POST text/plain to ``https://<gateway>/QueryService.aspx`` with a one-line XML body.
4
+ The request body is never logged (it contains the password hash and signatures).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import logging
10
+ import ssl
11
+ import urllib.error
12
+ import urllib.request
13
+ import xml.etree.ElementTree as ET
14
+ from datetime import datetime
15
+ from typing import Callable, Literal, Sequence
16
+
17
+ from .endpoints import is_loopback_url, make_ssl_context
18
+ from .timeutil import fmt_date, fmt_reqtime, now_taipei
19
+
20
+ logger = logging.getLogger('conrich.service')
21
+
22
+ UNEXPECTED = ('999', '非預期錯誤')
23
+ BAD_RESPONSE = ('230', '') # futures: not XML / no respcode (design D18)
24
+
25
+
26
+ def gen_code(svc_type: str, token: str, date: str, time: str) -> str:
27
+ return hashlib.md5((svc_type + token + date + time + 'CONCORDS').encode('utf-8')).hexdigest()
28
+
29
+
30
+ def build_request(token: str, params: Sequence[str], now: datetime) -> str:
31
+ date, time = fmt_date(now), fmt_reqtime(now)
32
+ return (f'<r><svcType>API</svcType><svcToken>{token}</svcToken><reqdate>{date}</reqdate>'
33
+ f'<reqtime>{time}</reqtime><sid></sid><tcode>{gen_code("API", token, date, time)}</tcode>'
34
+ f'<datalist><l>{",".join(params)}</l></datalist></r>')
35
+
36
+
37
+ def parse_response(xml_text: str, product: Literal['stock', 'futures'] = 'stock') -> tuple[str, str]:
38
+ """-> (respcode, content).
39
+
40
+ stock: 000 -> all <l> joined by newline; otherwise <respmsg>; anything odd -> 999.
41
+ futures: 000 -> every <l> followed by newline, trailing newlines stripped; otherwise the
42
+ first <l> text, or the whole text content of the root (.NET InnerText);
43
+ anything odd -> ('230', '').
44
+ """
45
+ if product not in ('stock', 'futures'):
46
+ raise ValueError(f'unknown product: {product!r}')
47
+ bad = UNEXPECTED if product == 'stock' else BAD_RESPONSE
48
+ upper = xml_text.upper()
49
+ if '<!DOCTYPE' in upper or '<!ENTITY' in upper:
50
+ return bad
51
+ try:
52
+ root = ET.fromstring(xml_text)
53
+ except ET.ParseError:
54
+ return bad
55
+ node = root.find('.//respcode')
56
+ if node is None:
57
+ return bad
58
+ code = (node.text or '').strip()
59
+ if product == 'stock':
60
+ if code == '000':
61
+ return code, '\n'.join((n.text or '') for n in root.iter('l'))
62
+ msg = root.find('.//respmsg')
63
+ return code, (msg.text or '') if msg is not None else ''
64
+ rows = [(n.text or '') for n in root.iter('l')]
65
+ if code == '000':
66
+ return code, ''.join(r + '\n' for r in rows).rstrip('\n')
67
+ if rows:
68
+ return code, rows[0]
69
+ return code, ''.join(root.itertext())
70
+
71
+
72
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
73
+ """A redirect would re-send the request body somewhere else; treat it as an error."""
74
+
75
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
76
+ raise urllib.error.HTTPError(req.full_url, code, 'redirect refused', headers, fp)
77
+
78
+
79
+ class ServiceClient:
80
+ def __init__(self, url: str, timeout: float = 60.0, clock: Callable[[], datetime] = now_taipei, *,
81
+ ssl_context: ssl.SSLContext | None = None,
82
+ product: Literal['stock', 'futures'] = 'stock') -> None:
83
+ if product not in ('stock', 'futures'):
84
+ raise ValueError(f'unknown product: {product!r}')
85
+ self.url = url
86
+ self.timeout = timeout
87
+ self.product = product
88
+ self._clock = clock
89
+ self.ssl_context = make_ssl_context(ssl_context)
90
+ handlers: list = [urllib.request.HTTPSHandler(context=self.ssl_context), _NoRedirect]
91
+ if is_loopback_url(url):
92
+ handlers.append(urllib.request.ProxyHandler({}))
93
+ self._opener = urllib.request.build_opener(*handlers)
94
+
95
+ def call(self, token: str, params: Sequence[str]) -> tuple[str, str]:
96
+ """Never raises: network / TLS / HTTP / XML errors give ('999', '非預期錯誤')."""
97
+ body = build_request(token, params, self._clock()).encode('utf-8')
98
+ request = urllib.request.Request(self.url, data=body, method='POST', headers={'Content-Type': 'text/plain'})
99
+ try:
100
+ with self._opener.open(request, timeout=self.timeout) as response:
101
+ text = response.read().decode('utf-8', errors='replace')
102
+ except (urllib.error.URLError, OSError, ValueError) as exc:
103
+ reason = getattr(exc, 'reason', exc)
104
+ if isinstance(reason, ssl.SSLCertVerificationError) or isinstance(exc, ssl.SSLCertVerificationError):
105
+ logger.warning('query %s failed: TLS certificate verification failed (%s); '
106
+ 'pass ssl_context to trust a specific CA', token, reason)
107
+ else:
108
+ logger.warning('query %s failed: %s', token, exc)
109
+ return UNEXPECTED
110
+ return parse_response(text, self.product)