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/Futures/base.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Shared part of FuturesAPI / ForeignFuturesAPI (pure Python)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import ssl
|
|
7
|
+
import threading
|
|
8
|
+
from typing import Any
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
|
|
11
|
+
from ..Common import tagvalue
|
|
12
|
+
from ..Common.endpoints import LIVE_HOST, TEST_HOST, gateway_for, is_loopback_url
|
|
13
|
+
from ..Common.events import Dispatcher, Event, EventEmitter
|
|
14
|
+
from ..Common.gate import TradingGate
|
|
15
|
+
from ..Common.records import csv_to_dicts, unique_header
|
|
16
|
+
from ..Common.signer import Signer
|
|
17
|
+
from ..Common.timeutil import to_yyyymmdd
|
|
18
|
+
from . import fields
|
|
19
|
+
from .messages import MarketSpec
|
|
20
|
+
from .session import FuturesSession
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger('conrich.futures')
|
|
23
|
+
|
|
24
|
+
_KINDS = ('general', 'error', 'bulletin', 'order_report')
|
|
25
|
+
_SUFFIX = {'general': 'GeneralReport', 'error': 'ErrorReport', 'bulletin': 'BulletinReport', 'order_report': 'OrderReport'}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FuturesBaseAPI(EventEmitter):
|
|
29
|
+
spec: MarketSpec
|
|
30
|
+
|
|
31
|
+
def __init__(self, debug: bool = False, *, pfx_path=None, pfx_password=None, enable_trading: bool = False,
|
|
32
|
+
dry_run: bool = False, ssl_context: ssl.SSLContext | None = None) -> None:
|
|
33
|
+
for kind in _KINDS:
|
|
34
|
+
setattr(self, self.spec.event_prefix + _SUFFIX[kind], Event()) # handler(code, msg)
|
|
35
|
+
self.OnBulletinReport = Event() # handler(code, msg); same arguments as On(F|FF)BulletinReport
|
|
36
|
+
self.source = self.spec.source
|
|
37
|
+
self.debug = debug
|
|
38
|
+
self.host = TEST_HOST if debug else LIVE_HOST
|
|
39
|
+
self.api_version = fields.API_VERSION
|
|
40
|
+
self.msg_tag = fields.TAGS
|
|
41
|
+
self.last_code = ''
|
|
42
|
+
self.last_order: dict[str, str] = {}
|
|
43
|
+
self.last_order_preview = ''
|
|
44
|
+
self.ssl_context = ssl_context
|
|
45
|
+
self._signer = Signer(pfx_path, pfx_password) if pfx_path is not None else None
|
|
46
|
+
self._gate = TradingGate(enable_trading=enable_trading, dry_run=dry_run, live_target=lambda: self._is_live_target(),
|
|
47
|
+
owner=type(self).__name__)
|
|
48
|
+
# test hooks (not documented): point the API at a local fake server
|
|
49
|
+
self.service_url: str | None = None
|
|
50
|
+
self.ports_override: dict[str, int] | None = None
|
|
51
|
+
self.idle: tuple[float, float, float] = (5.0, 5.0, 12.5) # (check every, ack after, drop after) seconds
|
|
52
|
+
self.heartbeat_interval = 30.0
|
|
53
|
+
self._session: FuturesSession | None = None
|
|
54
|
+
self._dispatcher: Dispatcher | None = None
|
|
55
|
+
self._lock = threading.Lock()
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def enable_trading(self) -> bool:
|
|
59
|
+
return self._gate.enable_trading
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def dry_run(self) -> bool:
|
|
63
|
+
return self._gate.dry_run
|
|
64
|
+
|
|
65
|
+
def _is_live_target(self) -> bool:
|
|
66
|
+
if self.debug:
|
|
67
|
+
return False
|
|
68
|
+
if self.service_url is not None and is_loopback_url(self.service_url):
|
|
69
|
+
return False
|
|
70
|
+
return True
|
|
71
|
+
|
|
72
|
+
def _gateway(self) -> str:
|
|
73
|
+
if self.service_url is not None:
|
|
74
|
+
return urlsplit(self.service_url).hostname or self.host
|
|
75
|
+
return gateway_for(self.host)
|
|
76
|
+
|
|
77
|
+
# ------------------------------------------------------------------ events
|
|
78
|
+
def _on_report(self, kind: str, code: str, msg: str) -> None:
|
|
79
|
+
"""Runs on the dispatcher thread: named event first, then generic listeners."""
|
|
80
|
+
getattr(self, self.spec.event_prefix + _SUFFIX[kind]).notify(code, msg)
|
|
81
|
+
if kind == 'bulletin':
|
|
82
|
+
self.OnBulletinReport.notify(code, msg)
|
|
83
|
+
data = tagvalue.parse(msg) if kind in ('order_report', 'bulletin') else {}
|
|
84
|
+
self._emit(kind, code, msg, data)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def is_login(self) -> bool:
|
|
88
|
+
s = self._session
|
|
89
|
+
return bool(s and s.logged_in)
|
|
90
|
+
|
|
91
|
+
# ------------------------------------------------------------------ session
|
|
92
|
+
def login(self, id_no: str = '', pwd: str = '', branch_no: str = '', account_no: str = '', timeout: float = 10.0) -> bool:
|
|
93
|
+
self.logout()
|
|
94
|
+
self._dispatcher = Dispatcher(self.spec.source)
|
|
95
|
+
self._dispatcher.start()
|
|
96
|
+
session = FuturesSession(self.spec, self._gateway(), self.api_version, self._dispatcher, self._on_report,
|
|
97
|
+
self._signer, self._gate, service_url=self.service_url,
|
|
98
|
+
ssl_context=self.ssl_context, ports_override=self.ports_override,
|
|
99
|
+
heartbeat_interval=self.heartbeat_interval, idle=self.idle)
|
|
100
|
+
self._session = session
|
|
101
|
+
ok = session.login(id_no, pwd, branch_no, account_no, timeout)
|
|
102
|
+
self.last_code = session.last_code if not ok else '102'
|
|
103
|
+
logger.info('[Login] %s (%s)', ok, self.last_code)
|
|
104
|
+
if not ok:
|
|
105
|
+
self.logout()
|
|
106
|
+
return ok
|
|
107
|
+
|
|
108
|
+
def logout(self) -> None:
|
|
109
|
+
session, self._session = self._session, None
|
|
110
|
+
if session is not None:
|
|
111
|
+
code, msg = session.logout()
|
|
112
|
+
logger.debug('[Logout] (%s) %s', code, msg)
|
|
113
|
+
if self._dispatcher is not None:
|
|
114
|
+
self._dispatcher.stop()
|
|
115
|
+
self._dispatcher = None
|
|
116
|
+
|
|
117
|
+
close = logout
|
|
118
|
+
|
|
119
|
+
def __enter__(self):
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
def __exit__(self, *exc: Any) -> None:
|
|
123
|
+
self.logout()
|
|
124
|
+
|
|
125
|
+
def __del__(self) -> None:
|
|
126
|
+
try:
|
|
127
|
+
self.logout()
|
|
128
|
+
except Exception:
|
|
129
|
+
pass
|
|
130
|
+
|
|
131
|
+
def _check_code(self) -> str:
|
|
132
|
+
s = self._session
|
|
133
|
+
return s.check_connect()[0] if s is not None else '210'
|
|
134
|
+
|
|
135
|
+
def check_multi_login(self) -> bool:
|
|
136
|
+
s = self._session
|
|
137
|
+
return bool(s and s.multi)
|
|
138
|
+
|
|
139
|
+
def account_info(self) -> list[dict[str, str]]:
|
|
140
|
+
s = self._session
|
|
141
|
+
if s is None or not s.accounts:
|
|
142
|
+
return []
|
|
143
|
+
return csv_to_dicts('\n'.join(s.accounts), unique_header(fields.HEADERS[self.spec.header_key]['account_info']))
|
|
144
|
+
|
|
145
|
+
# ------------------------------------------------------------------ queries
|
|
146
|
+
def _bhno(self, branch_no: str) -> str:
|
|
147
|
+
return str(branch_no)[-3:]
|
|
148
|
+
|
|
149
|
+
def _raw(self, token: str, params: list[str], need_account: tuple[str, str] | None = None) -> tuple[str, str]:
|
|
150
|
+
"""-> (code, msg). Account check first (the DLL answers 999 for an account it does not know)."""
|
|
151
|
+
s = self._session
|
|
152
|
+
if need_account is not None:
|
|
153
|
+
if s is None or not s.check_account(*need_account):
|
|
154
|
+
return '999', '該查詢帳號未授權'
|
|
155
|
+
elif s is None:
|
|
156
|
+
return '999', '非預期錯誤'
|
|
157
|
+
for value in params:
|
|
158
|
+
if any(ch in value for ch in '<&,'):
|
|
159
|
+
raise ValueError(f'illegal character in query parameter {value!r}')
|
|
160
|
+
code, msg = s.query(token, params)
|
|
161
|
+
self.last_code = code
|
|
162
|
+
return code, msg
|
|
163
|
+
|
|
164
|
+
def _table(self, token: str, params: list[str], header_name: str,
|
|
165
|
+
account: tuple[str, str] | None = None) -> list[dict[str, str]]:
|
|
166
|
+
code, msg = self._raw(token, params, account)
|
|
167
|
+
if code != '000':
|
|
168
|
+
logger.warning('[%s] (%s) %s', token, code, fields.RETURN_CODES.get(code, ''))
|
|
169
|
+
return []
|
|
170
|
+
return csv_to_dicts(msg, unique_header(fields.HEADERS[self.spec.header_key][header_name]))
|
|
171
|
+
|
|
172
|
+
def get_commodity(self) -> list[dict[str, str]]:
|
|
173
|
+
return self._table(self._tok('commodity'), [], 'get_commodity')
|
|
174
|
+
|
|
175
|
+
def get_commodity_by_month(self) -> list[dict[str, str]]:
|
|
176
|
+
return self._table(self._tok('commodity_ym'), [], 'get_commodity_by_month')
|
|
177
|
+
|
|
178
|
+
def order_recover(self, branch_no: str, account_no: str, seq_start: int = 0, seq_end: int = 0) -> str:
|
|
179
|
+
"""Ask the report channel to replay reports. Returns the DLL return code ('124' = sent)."""
|
|
180
|
+
s = self._session
|
|
181
|
+
if s is None:
|
|
182
|
+
return '210'
|
|
183
|
+
code, msg = s.recover(self._bhno(branch_no), account_no, seq_start, seq_end)
|
|
184
|
+
logger.debug('[OrderRecover] (%s) %s', code, fields.RETURN_CODES.get(code, ''))
|
|
185
|
+
return code
|
|
186
|
+
|
|
187
|
+
_QUERY_ORDER = { # (record_type, period) -> (type column, history flag)
|
|
188
|
+
('Order', 'Today'): '0', ('Deal', 'Today'): '2', ('Order', 'History'): '0', ('Deal', 'History'): '2'}
|
|
189
|
+
|
|
190
|
+
def query_order(self, branch_no: str, account_no: str, record_type: str, period: str,
|
|
191
|
+
start_date=None, end_date=None) -> tuple[str, str]:
|
|
192
|
+
if (record_type, period) not in self._QUERY_ORDER:
|
|
193
|
+
raise ValueError(f'record_type / period 有誤: {record_type!r}, {period!r}')
|
|
194
|
+
kind = self._QUERY_ORDER[(record_type, period)]
|
|
195
|
+
bhno = self._bhno(branch_no)
|
|
196
|
+
if period == 'Today':
|
|
197
|
+
token, params = self._tok('t_order'), [bhno, account_no, '0', kind]
|
|
198
|
+
else:
|
|
199
|
+
if start_date is None or end_date is None:
|
|
200
|
+
raise ValueError('History 需要 start_date 與 end_date')
|
|
201
|
+
token = self._tok('h_order')
|
|
202
|
+
params = [bhno, account_no, '0', to_yyyymmdd(start_date), to_yyyymmdd(end_date), kind]
|
|
203
|
+
code, msg = self._raw(token, params, (bhno, account_no))
|
|
204
|
+
logger.debug('[%s][%s] (%s) %s', record_type, period, code, fields.RETURN_CODES.get(code, ''))
|
|
205
|
+
return code, msg
|
|
206
|
+
|
|
207
|
+
def offset(self, branch_no: str, account_no: str) -> list[dict[str, str]]:
|
|
208
|
+
bhno = self._bhno(branch_no)
|
|
209
|
+
return self._table(self._tok('offset'), [bhno, account_no], 'offset', (bhno, account_no))
|
|
210
|
+
|
|
211
|
+
def offset_history(self, branch_no: str, account_no: str, start_date, end_date) -> list[dict[str, str]]:
|
|
212
|
+
bhno = self._bhno(branch_no)
|
|
213
|
+
params = [bhno, account_no, to_yyyymmdd(start_date), to_yyyymmdd(end_date)] # 4 parameters since 2025
|
|
214
|
+
return self._table(self._tok('offset_history'), params, 'offset_history', (bhno, account_no))
|
|
215
|
+
|
|
216
|
+
def deposit(self, branch_no: str, account_no: str) -> list[dict[str, str]]:
|
|
217
|
+
bhno = self._bhno(branch_no)
|
|
218
|
+
return self._table(self._tok('deposit'), [bhno, account_no], 'deposit', (bhno, account_no))
|
|
219
|
+
|
|
220
|
+
def deposit_history(self, branch_no: str, account_no: str, start_date, end_date) -> list[dict[str, str]]:
|
|
221
|
+
bhno = self._bhno(branch_no)
|
|
222
|
+
return self._table(self._tok('deposit_history'), [bhno, account_no, to_yyyymmdd(start_date), to_yyyymmdd(end_date)],
|
|
223
|
+
'deposit_history', (bhno, account_no))
|
|
224
|
+
|
|
225
|
+
def position_index(self, branch_no: str, account_no: str) -> list[dict[str, str]]:
|
|
226
|
+
bhno = self._bhno(branch_no)
|
|
227
|
+
return self._table(self._tok('position_index'), [bhno, account_no], 'position_index', (bhno, account_no))
|
|
228
|
+
|
|
229
|
+
def _tok(self, name: str) -> str:
|
|
230
|
+
raise NotImplementedError
|
|
231
|
+
|
|
232
|
+
# ------------------------------------------------------------------ trading
|
|
233
|
+
def _send_order(self, fields_) -> str:
|
|
234
|
+
"""Shared order flow (design-2025.md 8.2). The gate is always asked first."""
|
|
235
|
+
self._gate.check()
|
|
236
|
+
raise NotImplementedError('futures order() is implemented in Phase 6 / 7')
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
|
|
2
|
+
from enum import Enum
|
|
3
|
+
|
|
4
|
+
# 委託種類
|
|
5
|
+
class Action(Enum):
|
|
6
|
+
NEW_ORDER = 'OrderNew' # 新單
|
|
7
|
+
CANCEL_ORDER = 'OrderDelete' # 刪單
|
|
8
|
+
MODIFY_QUANTITY = 'OrderChangeQty' # 改量
|
|
9
|
+
MODIFY_PRICE = 'OrderChangePrice' # 改價
|
|
10
|
+
|
|
11
|
+
class Market(Enum):
|
|
12
|
+
FUTURES = 'F' # 期貨
|
|
13
|
+
OPTION = 'O' # 選擇權
|
|
14
|
+
|
|
15
|
+
# 單複式別
|
|
16
|
+
class CompoundType(Enum):
|
|
17
|
+
FUTURES_SINGLE = '1' # 期貨單式
|
|
18
|
+
OPTION_SINGLE = '2' # 選擇權單式
|
|
19
|
+
OPTION_COMBINE = '3' # 選擇權複式
|
|
20
|
+
FUTURES_COMBINE = '4' # 期貨複式
|
|
21
|
+
|
|
22
|
+
# 委託條件
|
|
23
|
+
class TimeInForce(Enum):
|
|
24
|
+
ROD = 'R' # 當盤有效
|
|
25
|
+
IOC = 'I' # 立即成交其餘刪除
|
|
26
|
+
FOK = 'F' # 全部立即成交否則刪除
|
|
27
|
+
|
|
28
|
+
# 沖銷別(開平倉碼)
|
|
29
|
+
class WriteOff(Enum):
|
|
30
|
+
OPEN = '0' # 開倉
|
|
31
|
+
CLOSE = '1' # 平倉
|
|
32
|
+
DAY_TRADE = '2' # 期貨當沖
|
|
33
|
+
AUTO = '' # 自動
|
|
34
|
+
|
|
35
|
+
# 委託別
|
|
36
|
+
class OrderType(Enum):
|
|
37
|
+
MARKET = 'M' # 市價
|
|
38
|
+
LIMIT = 'L' # 限價
|
|
39
|
+
MWP = 'P' # 一定範圍市價
|
|
40
|
+
|
|
41
|
+
# 外期委託方式
|
|
42
|
+
class ForeignOrderType(Enum):
|
|
43
|
+
MARKET = 'MKT' # 市價
|
|
44
|
+
LIMIT = 'LMT' # 限價
|
|
45
|
+
LINIT = 'LMT' # 舊拼字(0.7.x),Enum 別名,與 LIMIT 是同一個成員
|
|
46
|
+
STOP = 'STP' # 停損市價
|
|
47
|
+
STOP_LIMIT = 'SWL' # 停損限價
|
|
48
|
+
|
|
49
|
+
# 買賣別
|
|
50
|
+
class Side(Enum):
|
|
51
|
+
BUY = 'B' # 買進
|
|
52
|
+
SELL = 'S' # 賣出
|
|
53
|
+
|
|
54
|
+
class PutCall(Enum):
|
|
55
|
+
NONE = 'N' # 期貨
|
|
56
|
+
PUT = 'P' # 賣權
|
|
57
|
+
CALL = 'C' # 買權
|
|
58
|
+
|
|
59
|
+
# 當沖碼
|
|
60
|
+
class DayTradeFlag(Enum):
|
|
61
|
+
Y = 'Y' # 當沖
|
|
62
|
+
N = 'N' # 非當沖
|
|
63
|
+
|