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,48 @@
|
|
|
1
|
+
|
|
2
|
+
from enum import Enum
|
|
3
|
+
|
|
4
|
+
# 委託種類
|
|
5
|
+
class Action(Enum):
|
|
6
|
+
NEW_ORDER = 'NewOrder' # 新單
|
|
7
|
+
CANCEL_ORDER = 'CancelOrder' # 刪單
|
|
8
|
+
MODIFY_QUANTITY = 'ModifyQty' # 改量
|
|
9
|
+
MODIFY_PRICE = 'ModifyPrice' # 改價
|
|
10
|
+
|
|
11
|
+
# 交易別
|
|
12
|
+
class LotType(Enum):
|
|
13
|
+
ROUND_LOT = 'RoundLot' # 整股
|
|
14
|
+
BLOCK_LOT = 'BlockLot' # 鉅額
|
|
15
|
+
ODD_LOT = 'OddLot' # 零股
|
|
16
|
+
FIX_PRICE = 'FixedPrice' # 定價
|
|
17
|
+
INTRADAY_ODD_LOT = 'IntradayOddLot' # 盤中零股
|
|
18
|
+
|
|
19
|
+
# 委託別
|
|
20
|
+
class OrderType(Enum):
|
|
21
|
+
ORDINARY = 'Ordinary' # 現股
|
|
22
|
+
MARGIN = 'Margin' # 融資
|
|
23
|
+
SHORT = 'Short' # 融券
|
|
24
|
+
LENDING = 'Lending' # 借券
|
|
25
|
+
|
|
26
|
+
# 買賣別
|
|
27
|
+
class Side(Enum):
|
|
28
|
+
BUY = 'Buy' # 買進
|
|
29
|
+
SELL = 'Sell' # 賣出
|
|
30
|
+
|
|
31
|
+
# 現沖註記
|
|
32
|
+
class DayTradeFlag(Enum):
|
|
33
|
+
Y = 'Enable'
|
|
34
|
+
N = 'Unable'
|
|
35
|
+
|
|
36
|
+
# 價格註記(委託方式)
|
|
37
|
+
class PriceFlag(Enum):
|
|
38
|
+
FIX = 'Limit' # 限價
|
|
39
|
+
MARKET = 'Market' # 市價
|
|
40
|
+
LIMIT_UP = 'LimitUp' # 漲停
|
|
41
|
+
LIMIT_DOWN = 'LimitDown' # 跌停
|
|
42
|
+
UNCHANGED = 'Unchange' # 平盤
|
|
43
|
+
|
|
44
|
+
# 委託條件
|
|
45
|
+
class TimeInForce(Enum):
|
|
46
|
+
ROD = 'ROD' # 當盤有效
|
|
47
|
+
IOC = 'IOC' # 立即成交其餘刪除
|
|
48
|
+
FOK = 'FOK' # 全部立即成交否則刪除
|
conrich/Stock/fields.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Stock field tables. HEADERS / TAGS were generated from the former header.json / tag.json
|
|
3
|
+
(tests/fixtures/fields_snapshot.json keeps the originals for comparison)."""
|
|
4
|
+
from enum import Enum
|
|
5
|
+
|
|
6
|
+
# Declared client version (design-pure-python.md 2.8). The 2025 DLL value; format = leading zeros removed.
|
|
7
|
+
API_VERSION = '1.1.2025.321'
|
|
8
|
+
|
|
9
|
+
HEADERS = {'accounts_info': ['分公司代碼', '客戶帳號', '客戶姓名'],
|
|
10
|
+
'current_delivery': ['市場別',
|
|
11
|
+
'交易日期',
|
|
12
|
+
'委託別',
|
|
13
|
+
'買賣別',
|
|
14
|
+
'股票代碼',
|
|
15
|
+
'股票名稱',
|
|
16
|
+
'成交股數',
|
|
17
|
+
'成交價',
|
|
18
|
+
'成交價金',
|
|
19
|
+
'手續費',
|
|
20
|
+
'交易稅',
|
|
21
|
+
'融資金額'],
|
|
22
|
+
'three_days_delivery': ['交易日期', '交割日期', '客戶淨收金額', '客戶淨付金額'],
|
|
23
|
+
'history_delivery': ['市場別',
|
|
24
|
+
'交易日期',
|
|
25
|
+
'委託別',
|
|
26
|
+
'買賣別',
|
|
27
|
+
'股票代碼',
|
|
28
|
+
'股票名稱',
|
|
29
|
+
'成交股數',
|
|
30
|
+
'成交價',
|
|
31
|
+
'成交價金',
|
|
32
|
+
'手續費',
|
|
33
|
+
'交易稅',
|
|
34
|
+
'融資金額',
|
|
35
|
+
'融資自備款',
|
|
36
|
+
'融資利息',
|
|
37
|
+
'融券擔保款',
|
|
38
|
+
'融券保證金',
|
|
39
|
+
'融券手續費',
|
|
40
|
+
'融券利息',
|
|
41
|
+
'應收付金額',
|
|
42
|
+
'空白',
|
|
43
|
+
'空白',
|
|
44
|
+
'委託書號',
|
|
45
|
+
'標借費用',
|
|
46
|
+
'代扣稅款',
|
|
47
|
+
'交易別',
|
|
48
|
+
'來源別',
|
|
49
|
+
'債息',
|
|
50
|
+
'標借利息',
|
|
51
|
+
'沖抵書號'],
|
|
52
|
+
'realized_profit': ['市場別',
|
|
53
|
+
'股票代碼',
|
|
54
|
+
'股票名稱',
|
|
55
|
+
'成交日期',
|
|
56
|
+
'委託別',
|
|
57
|
+
'買賣別',
|
|
58
|
+
'成交股數',
|
|
59
|
+
'成交價',
|
|
60
|
+
'帳面收入',
|
|
61
|
+
'投資成本',
|
|
62
|
+
'自訂投資成本',
|
|
63
|
+
'損益',
|
|
64
|
+
'投資報酬率<%>',
|
|
65
|
+
'委託書號',
|
|
66
|
+
'個股交易稅稅率'],
|
|
67
|
+
'unrealized_profit': ['市場別',
|
|
68
|
+
'股票代碼',
|
|
69
|
+
'股票名稱',
|
|
70
|
+
'委託別',
|
|
71
|
+
'庫存股數',
|
|
72
|
+
'成交均價',
|
|
73
|
+
'平均買進(賣出)成本',
|
|
74
|
+
'投資成本',
|
|
75
|
+
'融資金額',
|
|
76
|
+
'融資自備款',
|
|
77
|
+
'融資利息',
|
|
78
|
+
'融券擔保款',
|
|
79
|
+
'融券保證金',
|
|
80
|
+
'融券手續費',
|
|
81
|
+
'融券利息',
|
|
82
|
+
'現價(市價)',
|
|
83
|
+
'現價(市價)價金',
|
|
84
|
+
'帳面收入',
|
|
85
|
+
'損益',
|
|
86
|
+
'投資報酬率<%>',
|
|
87
|
+
'調整成交價',
|
|
88
|
+
'成交價調整日期',
|
|
89
|
+
'買進(賣出)手續費',
|
|
90
|
+
'個股交易稅稅率'],
|
|
91
|
+
'maintenance_rate': ['市場別',
|
|
92
|
+
'委託別',
|
|
93
|
+
'股票代碼',
|
|
94
|
+
'股票名稱',
|
|
95
|
+
'庫存股數',
|
|
96
|
+
'成交均價',
|
|
97
|
+
'現價',
|
|
98
|
+
'股票現值',
|
|
99
|
+
'未還融資金',
|
|
100
|
+
'融資自備款',
|
|
101
|
+
'融券擔保款',
|
|
102
|
+
'融券保證金',
|
|
103
|
+
'個股維持率',
|
|
104
|
+
'客戶融資餘額',
|
|
105
|
+
'客戶融券餘額',
|
|
106
|
+
'融資保品餘額',
|
|
107
|
+
'融券保品餘額',
|
|
108
|
+
'客戶融資保品餘額',
|
|
109
|
+
'客戶融券保品餘額',
|
|
110
|
+
'資券利息']}
|
|
111
|
+
|
|
112
|
+
TAGS = {'1': '客戶帳號',
|
|
113
|
+
'8': '起始字串',
|
|
114
|
+
'9': '訊息長度',
|
|
115
|
+
'11': '網路單號',
|
|
116
|
+
'35': '訊息種類',
|
|
117
|
+
'37': '委託書號',
|
|
118
|
+
'38': '委託數量',
|
|
119
|
+
'40': '委託方式',
|
|
120
|
+
'41': '原網路單號',
|
|
121
|
+
'44': '委託單價',
|
|
122
|
+
'50': '分公司碼',
|
|
123
|
+
'52': '訊息傳送時間',
|
|
124
|
+
'54': '買賣別',
|
|
125
|
+
'55': '股票代號',
|
|
126
|
+
'56': '市場別',
|
|
127
|
+
'57': '交易別',
|
|
128
|
+
'59': '委託條件',
|
|
129
|
+
'60': '委託日期',
|
|
130
|
+
'10000': '委託來源',
|
|
131
|
+
'10001': '委託別',
|
|
132
|
+
'20000': '客戶端下單IP',
|
|
133
|
+
'20001': '營業員代號',
|
|
134
|
+
'20003': '現賣沖註記',
|
|
135
|
+
'20021': '漲跌停註記',
|
|
136
|
+
'21000': '驗章註記',
|
|
137
|
+
'21001': '簽章明文',
|
|
138
|
+
'21002': '簽章值',
|
|
139
|
+
'21003': '憑證序號',
|
|
140
|
+
'21004': '身分證字號'}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ConnectionWay(Enum):
|
|
145
|
+
"""SocketStatusEvent side. Values as in the DLL enum (Send=0, Receive=1)."""
|
|
146
|
+
Send = 0
|
|
147
|
+
Receive = 1
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Stock message composing / parsing (design-2025.md 3.4, 3.6; design-pure-python.md 2.10, 2.11).
|
|
3
|
+
|
|
4
|
+
All functions are pure. Order composers are added in Phase 5 (design-2025.md 7.2).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
from ..Common import tagvalue
|
|
14
|
+
from ..Common.framing import HEARTBEAT_PLAIN, compose_plain
|
|
15
|
+
from ..Common.signer import SignParts
|
|
16
|
+
from ..Common.timeutil import fmt_date, fmt_timestamp
|
|
17
|
+
from .orders import StockOrderFields
|
|
18
|
+
from .results import ExecutionReport, OrderResult
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger('conrich.stock')
|
|
21
|
+
|
|
22
|
+
__all__ = ['login_plain', 'order_sign_plain', 'order_body', 'register_plain', 'recover_plain', 'heartbeat_plain', 'parse_message',
|
|
23
|
+
'parse_push', 'parse_order_channel', 'PushMessage', 'to_transaction_time', 'to_ct_transaction_time']
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def heartbeat_plain() -> str:
|
|
27
|
+
return HEARTBEAT_PLAIN
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def login_plain(id_no: str, pwd_hash: str, verify_mode: bool, version: str, now: datetime,
|
|
31
|
+
*, sign: SignParts) -> str:
|
|
32
|
+
"""TCP login: 21003 certNo, 21002 signature, 21001 signed plain text sit between 555 and 58."""
|
|
33
|
+
return compose_plain('|' + tagvalue.compose([
|
|
34
|
+
('35', 'A'), ('52', fmt_timestamp(now)), ('553', id_no), ('554', pwd_hash),
|
|
35
|
+
('555', 'Y' if verify_mode else 'N'), ('21003', sign.cert_no), ('21002', sign.signature),
|
|
36
|
+
('21001', sign.plain), ('58', version)]))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def order_sign_plain(f: StockOrderFields) -> str:
|
|
40
|
+
"""Text that is signed: action + branch + account + symbol + side + qty + price condition + price."""
|
|
41
|
+
return f'{f.action}{f.branch}{f.account}{f.symbol}{f.bs}{f.qty}{f.pcnd}{f.price}'
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def order_body(f: StockOrderFields, *, guid: str, now: datetime, sign: SignParts, id_no: str, origin: str = 'Z') -> str:
|
|
45
|
+
"""Complete order message with the ``8=Concords|9=`` header (design-2025.md 3.7)."""
|
|
46
|
+
head = [('35', f.action), ('52', fmt_timestamp(now)), ('60', fmt_date(now)), ('11', '')]
|
|
47
|
+
if f.action != 'I':
|
|
48
|
+
head += [('41', f.orig_net_no), ('37', f.order_id)]
|
|
49
|
+
pairs = head + [
|
|
50
|
+
('50', f.branch), ('1', f.account), ('56', 'T'), ('57', f.lot), ('10001', f.otype), ('55', f.symbol),
|
|
51
|
+
('54', f.bs), ('40', f.ptype), ('59', f.tif), ('38', f.qty), ('44', f.price), ('10000', origin),
|
|
52
|
+
('20000', ''), ('20001', ''), ('20103', guid), ('21000', 'Y'), ('21001', sign.plain), ('21002', sign.signature),
|
|
53
|
+
('21003', sign.cert_no), ('21004', id_no), ('20003', f.day_trade), ('20021', f.pcnd)]
|
|
54
|
+
return compose_plain('|' + tagvalue.compose(pairs))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def register_plain(register_code: str, now: datetime) -> str:
|
|
58
|
+
"""register_code: 'BHNO+CSEQ' of every account joined by ','."""
|
|
59
|
+
return compose_plain('|' + tagvalue.compose([('35', 'r'), ('52', fmt_timestamp(now)), ('20100', register_code)]))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def recover_plain(bhno: str, cseq: str, now: datetime) -> str:
|
|
63
|
+
return compose_plain('|' + tagvalue.compose([
|
|
64
|
+
('35', '2'), ('52', fmt_timestamp(now)), ('50', bhno), ('1', cseq), ('7', '0'), ('16', '0')]))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def parse_message(plain: str) -> dict[str, str]:
|
|
68
|
+
"""Stock parser: a repeated tag stops the parsing (keeps what was parsed)."""
|
|
69
|
+
return tagvalue.parse(plain, duplicate='stop')
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def to_transaction_time(s: str) -> str:
|
|
73
|
+
if len(s) == 18 and s[:4].isdigit():
|
|
74
|
+
return f'{int(s[:4]) - 1911:04d}' + s[4:15]
|
|
75
|
+
return s
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def to_ct_transaction_time(s: str) -> str:
|
|
79
|
+
if len(s) == 15 and s[:4].isdigit():
|
|
80
|
+
return f'{int(s[:4]) + 1911:04d}' + s[4:] + '000'
|
|
81
|
+
return s
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class PushMessage:
|
|
86
|
+
kind: Literal['heartbeat', 'login', 'register', 'recover', 'order_report', 'bulletin', 'unknown',
|
|
87
|
+
'order_accepted', 'order_rejected']
|
|
88
|
+
tags: dict = field(default_factory=dict)
|
|
89
|
+
messages: tuple = () # GeneralEvent / BulletinEvent texts
|
|
90
|
+
result: OrderResult | None = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
_LOT = {'0': 'RoundLot', '2': 'OddLot', '3': 'FixedPrice', '7': 'IntradayOddLot'}
|
|
94
|
+
_OTYPE = {'0': 'Ordinary', '3': 'Margin', '4': 'Short', '5': 'Lending', '6': 'Lending'}
|
|
95
|
+
_PTYPE = {'1': 'Market', '2': 'Limit'}
|
|
96
|
+
_TIF = {'0': 'ROD', '3': 'IOC', '4': 'FOK'}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _report(tags: dict[str, str]) -> OrderResult | None:
|
|
100
|
+
g = lambda k: tags.get(k, '') # noqa: E731
|
|
101
|
+
day_trade = g('20003') == 'Y'
|
|
102
|
+
side = '買進' if g('54') == 'B' else '賣出'
|
|
103
|
+
if side == '賣出' and day_trade:
|
|
104
|
+
side = '現賣沖'
|
|
105
|
+
exec_type = g('150')
|
|
106
|
+
fields = dict(OrigClOrdID=g('41'), OrderID=g('37'), BranchNo=g('50'), Account=g('1'), Symbol=g('55'),
|
|
107
|
+
TransactTime=to_transaction_time(g('60')), CT_TransactionTime=to_ct_transaction_time(g('60')),
|
|
108
|
+
DayTrade='Enable' if day_trade else 'Unable', Side=side,
|
|
109
|
+
OrdLotType=_LOT.get(g('57'), ''), OrdType=_OTYPE.get(g('10001'), ''),
|
|
110
|
+
OrdPriceType=_PTYPE.get(g('40'), ''), TimeInForce=_TIF.get(g('59'), 'ROD'))
|
|
111
|
+
actual = g('20053') or g('38')
|
|
112
|
+
if exec_type in ('8', 'P8'):
|
|
113
|
+
res = dict(ClOrdID=g('11'), ResultType='1', StatusCode=-1, CodeDesc=f'[{g("103")}]: {g("58")}')
|
|
114
|
+
fields.update(ExecType=exec_type, OrderQty=g('38'), ActualOrderQty=actual, Price=g('44'))
|
|
115
|
+
elif exec_type == 'F':
|
|
116
|
+
res = dict(ResultType='1', StatusCode=0)
|
|
117
|
+
fields.update(ExecType='F', LastQty=g('32'), LastPx=g('31'), MatchNo=g('17'))
|
|
118
|
+
elif exec_type in ('0', '4', '5', 'M', 'P0', 'P4'):
|
|
119
|
+
res = dict(ClOrdID=g('11'), ResultType='1', StatusCode=0)
|
|
120
|
+
if '103' in tags:
|
|
121
|
+
res['CodeDesc'] = f'[{tags["103"]}]: {tags.get("58", "")}'
|
|
122
|
+
fields.update(ExecType=exec_type if exec_type in ('P0', 'P4') else g('10002'),
|
|
123
|
+
OrderQty=g('38'), ActualOrderQty=actual, Price=g('44'))
|
|
124
|
+
else:
|
|
125
|
+
# unknown 150: the DLL logs an error and still raises the event with an empty result (FR-ST6)
|
|
126
|
+
logger.error('unknown execution type (150=%s)', exec_type)
|
|
127
|
+
res = dict(ResultType='', StatusCode=0)
|
|
128
|
+
fields.update(ExecType=exec_type, OrderQty=g('38'), ActualOrderQty=actual, Price=g('44'))
|
|
129
|
+
return OrderResult(ExcReport=ExecutionReport(**fields), **res)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def parse_push(plain: str) -> PushMessage:
|
|
133
|
+
"""Messages arriving on the push channel."""
|
|
134
|
+
tags = parse_message(plain)
|
|
135
|
+
kind = tags.get('35')
|
|
136
|
+
if kind is None:
|
|
137
|
+
return PushMessage('unknown', tags)
|
|
138
|
+
if kind == '0':
|
|
139
|
+
return PushMessage('heartbeat', tags)
|
|
140
|
+
if kind == 'A':
|
|
141
|
+
return PushMessage('login', tags)
|
|
142
|
+
if kind == 'r':
|
|
143
|
+
return PushMessage('register', tags)
|
|
144
|
+
if kind == '2':
|
|
145
|
+
if tags.get('82') is not None and tags.get('82') == tags.get('83'):
|
|
146
|
+
return PushMessage('recover', tags, (f'[回補請求]: 作業完成 共 {tags["83"]} 筆',))
|
|
147
|
+
return PushMessage('recover', tags)
|
|
148
|
+
if kind in ('8', '9'):
|
|
149
|
+
result = _report(tags)
|
|
150
|
+
return PushMessage('order_report', tags, (), result) if result is not None else PushMessage('unknown', tags)
|
|
151
|
+
if kind == 'P':
|
|
152
|
+
# The DLL builds an ExecutionReport here but never attaches it to the result.
|
|
153
|
+
if not all(k in tags for k in ('11', '41', '37', '1', '55', '54', '44')):
|
|
154
|
+
return PushMessage('unknown', tags)
|
|
155
|
+
return PushMessage('order_report', tags, (), OrderResult(ResultType='委託回報', ClOrdID=tags['11']))
|
|
156
|
+
if kind == 'C':
|
|
157
|
+
return PushMessage('bulletin', tags, (f'公告主旨:{tags.get("147", "")}', f'公告內文:{tags.get("58", "")}'))
|
|
158
|
+
return PushMessage('unknown', tags)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def parse_order_channel(plain: str) -> PushMessage:
|
|
162
|
+
"""Messages arriving on the order channel (login reply, order acknowledgements)."""
|
|
163
|
+
tags = parse_message(plain)
|
|
164
|
+
kind = tags.get('35')
|
|
165
|
+
if kind == '0':
|
|
166
|
+
return PushMessage('heartbeat', tags)
|
|
167
|
+
if kind == 'A':
|
|
168
|
+
return PushMessage('login', tags)
|
|
169
|
+
if kind == '8':
|
|
170
|
+
if '11' not in tags or '20103' not in tags:
|
|
171
|
+
return PushMessage('unknown', tags)
|
|
172
|
+
if tags['11'] == '0':
|
|
173
|
+
result = OrderResult(ResultType='0', OrderGuid=tags['20103'], StatusCode=-1, CodeDesc=tags.get('20102', ''))
|
|
174
|
+
return PushMessage('order_rejected', tags, (), result)
|
|
175
|
+
return PushMessage('order_accepted', tags, (), OrderResult(ResultType='0', OrderGuid=tags['20103'], ClOrdID=tags['11']))
|
|
176
|
+
if kind in ('I', 'C', 'D', 'P'):
|
|
177
|
+
result = OrderResult(ResultType='0', StatusCode=-1, CodeDesc=tags.get('20102', ''), OrderGuid=tags.get('20103', ''))
|
|
178
|
+
return PushMessage('order_rejected', tags, (), result)
|
|
179
|
+
return PushMessage('unknown', tags)
|
conrich/Stock/orders.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Stock order argument conversion and pre-send checks (design-2025.md 3.7, FR-ST3, FR-ST4).
|
|
3
|
+
|
|
4
|
+
Pure functions: nothing here signs, builds a frame or touches the network.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from decimal import Decimal, InvalidOperation
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
from ..Common.errors import OrderError
|
|
14
|
+
from ..Common.normalize import to_int
|
|
15
|
+
|
|
16
|
+
_ACTION = {'NewOrder': 'I', 'CancelOrder': 'D', 'ModifyQty': 'C', 'ModifyPrice': 'P', 'MofifyPrice': 'P'}
|
|
17
|
+
_LOT = {'RoundLot': '0', 'OddLot': '2', 'FixedPrice': '3', 'IntradayOddLot': '7'}
|
|
18
|
+
_OTYPE = {'Ordinary': '0', 'Margin': '3', 'Short': '4', 'Lending': '5'}
|
|
19
|
+
_SIDE = {'Buy': 'B', 'Sell': 'S'}
|
|
20
|
+
_DAY_TRADE = {'Enable': 'Y', 'Unable': 'N'}
|
|
21
|
+
_PCND = {'Limit': '', 'Market': '', 'LimitUp': 'U', 'LimitDown': 'D', 'Unchange': 'C'}
|
|
22
|
+
_TIF = {'ROD': '0', 'IOC': '3', 'FOK': '4'}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class StockOrderFields:
|
|
27
|
+
action: Literal['I', 'D', 'C', 'P']
|
|
28
|
+
branch: str
|
|
29
|
+
account: str
|
|
30
|
+
lot: str
|
|
31
|
+
otype: str
|
|
32
|
+
symbol: str
|
|
33
|
+
bs: str
|
|
34
|
+
ptype: str
|
|
35
|
+
tif: str
|
|
36
|
+
qty: str
|
|
37
|
+
price: str
|
|
38
|
+
pcnd: str
|
|
39
|
+
day_trade: Literal['Y', 'N']
|
|
40
|
+
orig_net_no: str
|
|
41
|
+
order_id: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _pick(table: dict[str, str], value, name: str) -> str:
|
|
45
|
+
key = value.value if isinstance(value, Enum) else str(value).strip()
|
|
46
|
+
try:
|
|
47
|
+
return table[key]
|
|
48
|
+
except (KeyError, TypeError):
|
|
49
|
+
raise OrderError(f'{name} 有誤: {value!r}') from None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_fields(action, branch_no, account_no, lot_type, order_type, side, day_trade_flag, symbol,
|
|
53
|
+
quantity, price, price_flag, time_in_force, orig_net_no='', order_id='') -> StockOrderFields:
|
|
54
|
+
"""Convert the 0.7.x arguments and run the checks of MsgHelper.SOrderVerification. Raises OrderError."""
|
|
55
|
+
act = _pick(_ACTION, action, 'action')
|
|
56
|
+
branch = str(branch_no).strip()[-1:]
|
|
57
|
+
if not branch:
|
|
58
|
+
raise OrderError('branch_no 有誤: 空白')
|
|
59
|
+
account = str(account_no).strip()
|
|
60
|
+
lot = _pick(_LOT, lot_type, 'lot_type')
|
|
61
|
+
otype = _pick(_OTYPE, order_type, 'order_type')
|
|
62
|
+
bs = _pick(_SIDE, side, 'side')
|
|
63
|
+
day_trade = _pick(_DAY_TRADE, day_trade_flag, 'day_trade_flag')
|
|
64
|
+
pcnd = _pick(_PCND, price_flag, 'price_flag')
|
|
65
|
+
flag_name = price_flag.value if isinstance(price_flag, Enum) else str(price_flag).strip()
|
|
66
|
+
ptype = '1' if flag_name == 'Market' else '2'
|
|
67
|
+
tif = _pick(_TIF, time_in_force, 'time_in_force')
|
|
68
|
+
sym = str(symbol).strip()
|
|
69
|
+
orig, oid = str(orig_net_no).strip(), str(order_id).strip()
|
|
70
|
+
|
|
71
|
+
# quantity: ModifyPrice always sends 0; every other action needs 1 or more
|
|
72
|
+
qty = '0' if act == 'P' else str(to_int(quantity, 'quantity', minimum=1))
|
|
73
|
+
# price: ModifyQty or a price condition (limit up / down / unchanged) sends 0
|
|
74
|
+
price_text = str(price).strip()
|
|
75
|
+
if act == 'C' or pcnd:
|
|
76
|
+
price_text = '0'
|
|
77
|
+
|
|
78
|
+
# ---- SOrderVerification (MsgHelper.cs:181-272), first mismatch wins ----
|
|
79
|
+
if act in ('D', 'C', 'P'):
|
|
80
|
+
if not orig or len(orig) > 6:
|
|
81
|
+
raise OrderError('orig_net_no 有誤: 刪改單必填且最多 6 碼')
|
|
82
|
+
if not oid or len(oid) > 5:
|
|
83
|
+
raise OrderError('order_id 有誤: 刪改單必填且最多 5 碼')
|
|
84
|
+
if len(branch) != 1:
|
|
85
|
+
raise OrderError('branch_no 有誤: 必須 1 碼')
|
|
86
|
+
if not sym or not 4 <= len(sym) <= 6:
|
|
87
|
+
raise OrderError('symbol 有誤: 必須 4 ~ 6 碼')
|
|
88
|
+
if day_trade == 'Y' and bs != 'S':
|
|
89
|
+
raise OrderError('day_trade_flag 有誤: 現沖只能賣出')
|
|
90
|
+
if len(qty) > 8 or not 0 <= int(qty) <= 65535:
|
|
91
|
+
raise OrderError('quantity 有誤: 必須為 1 ~ 65535')
|
|
92
|
+
if pcnd and price_text != '0':
|
|
93
|
+
raise OrderError('price 有誤: 漲跌停或平盤時價格必須為 0')
|
|
94
|
+
if len(price_text) > 7:
|
|
95
|
+
raise OrderError('price 有誤: 最多 7 碼')
|
|
96
|
+
try:
|
|
97
|
+
value = Decimal(price_text)
|
|
98
|
+
except InvalidOperation:
|
|
99
|
+
raise OrderError(f'price 有誤: {price!r}') from None
|
|
100
|
+
if not value.is_finite() or value < 0:
|
|
101
|
+
raise OrderError(f'price 有誤: {price!r}')
|
|
102
|
+
return StockOrderFields(action=act, branch=branch, account=account, lot=lot, otype=otype, symbol=sym, bs=bs,
|
|
103
|
+
ptype=ptype, tif=tif, qty=qty, price=price_text, pcnd=pcnd, day_trade=day_trade,
|
|
104
|
+
orig_net_no=orig, order_id=oid)
|
conrich/Stock/results.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Result objects with the attribute names of the former .NET classes."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class ExecutionReport:
|
|
10
|
+
OrderID: str = ''
|
|
11
|
+
OrigClOrdID: str = ''
|
|
12
|
+
ExecType: str = ''
|
|
13
|
+
Account: str = ''
|
|
14
|
+
Symbol: str = ''
|
|
15
|
+
Side: str = ''
|
|
16
|
+
OrderQty: str = ''
|
|
17
|
+
Price: str = ''
|
|
18
|
+
LastQty: str = '0'
|
|
19
|
+
LastPx: str = '0'
|
|
20
|
+
TransactTime: str = ''
|
|
21
|
+
MatchNo: str = ''
|
|
22
|
+
BranchNo: str = ''
|
|
23
|
+
OrdLotType: str = '' # member name of the old enum: RoundLot / OddLot / FixedPrice, '' = not parsed
|
|
24
|
+
DayTrade: str = 'Unable' # 'Enable' / 'Unable'
|
|
25
|
+
OrdType: str = '' # Ordinary / Margin / Short
|
|
26
|
+
OrdPriceType: str = '' # Market / Limit
|
|
27
|
+
TimeInForce: str = '' # ROD / IOC / FOK
|
|
28
|
+
ActualOrderQty: str = ''
|
|
29
|
+
CT_TransactionTime: str = ''
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict[str, str]:
|
|
32
|
+
"""The keys 0.7.x StockAPI used for its execution-report dict."""
|
|
33
|
+
return {'order_id': self.OrderID, 'orig_net_no': self.OrigClOrdID, 'execute_status': self.ExecType,
|
|
34
|
+
'account_no': self.Account, 'symbol': self.Symbol, 'side': self.Side,
|
|
35
|
+
'quantity': self.OrderQty, 'price': self.Price, 'strike_quantity': self.LastQty,
|
|
36
|
+
'strike_price': self.LastPx, 'transaction_time': self.TransactTime}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class OrderResult:
|
|
41
|
+
ResultType: str = ''
|
|
42
|
+
StatusCode: int = 0
|
|
43
|
+
CodeDesc: str = ''
|
|
44
|
+
OrderGuid: str = ''
|
|
45
|
+
ClOrdID: str = ''
|
|
46
|
+
ExcReport: ExecutionReport | None = field(default=None)
|
|
47
|
+
|
|
48
|
+
def to_dict(self) -> dict:
|
|
49
|
+
out = {'result': self.ResultType, 'status': self.StatusCode, 'desc': self.CodeDesc,
|
|
50
|
+
'order_guid': self.OrderGuid, 'net_no': self.ClOrdID}
|
|
51
|
+
if self.ExcReport is not None:
|
|
52
|
+
out['report'] = self.ExcReport.to_dict()
|
|
53
|
+
return out
|