conrich2 1.0.0.dev0__tar.gz

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 (50) hide show
  1. conrich2-1.0.0.dev0/LICENSE +21 -0
  2. conrich2-1.0.0.dev0/MANIFEST.in +16 -0
  3. conrich2-1.0.0.dev0/PKG-INFO +242 -0
  4. conrich2-1.0.0.dev0/README.md +206 -0
  5. conrich2-1.0.0.dev0/conrich/Common/__init__.py +0 -0
  6. conrich2-1.0.0.dev0/conrich/Common/cipher.py +74 -0
  7. conrich2-1.0.0.dev0/conrich/Common/endpoints.py +49 -0
  8. conrich2-1.0.0.dev0/conrich/Common/errors.py +29 -0
  9. conrich2-1.0.0.dev0/conrich/Common/events.py +117 -0
  10. conrich2-1.0.0.dev0/conrich/Common/framing.py +70 -0
  11. conrich2-1.0.0.dev0/conrich/Common/gate.py +65 -0
  12. conrich2-1.0.0.dev0/conrich/Common/normalize.py +46 -0
  13. conrich2-1.0.0.dev0/conrich/Common/records.py +44 -0
  14. conrich2-1.0.0.dev0/conrich/Common/service.py +110 -0
  15. conrich2-1.0.0.dev0/conrich/Common/signer.py +176 -0
  16. conrich2-1.0.0.dev0/conrich/Common/tagvalue.py +47 -0
  17. conrich2-1.0.0.dev0/conrich/Common/timeutil.py +35 -0
  18. conrich2-1.0.0.dev0/conrich/Common/transport.py +171 -0
  19. conrich2-1.0.0.dev0/conrich/Common/version.py +16 -0
  20. conrich2-1.0.0.dev0/conrich/Futures/Futures_README.md +71 -0
  21. conrich2-1.0.0.dev0/conrich/Futures/__init__.py +12 -0
  22. conrich2-1.0.0.dev0/conrich/Futures/base.py +236 -0
  23. conrich2-1.0.0.dev0/conrich/Futures/constant.py +63 -0
  24. conrich2-1.0.0.dev0/conrich/Futures/fields.py +716 -0
  25. conrich2-1.0.0.dev0/conrich/Futures/foreign_futures.py +53 -0
  26. conrich2-1.0.0.dev0/conrich/Futures/futures.py +74 -0
  27. conrich2-1.0.0.dev0/conrich/Futures/messages.py +97 -0
  28. conrich2-1.0.0.dev0/conrich/Futures/session.py +464 -0
  29. conrich2-1.0.0.dev0/conrich/Quote/__init__.py +15 -0
  30. conrich2-1.0.0.dev0/conrich/Quote/event.py +4 -0
  31. conrich2-1.0.0.dev0/conrich/Quote/quote.py +116 -0
  32. conrich2-1.0.0.dev0/conrich/Quote/server.py +10 -0
  33. conrich2-1.0.0.dev0/conrich/Quote/symbols.py +18 -0
  34. conrich2-1.0.0.dev0/conrich/Stock/__init__.py +10 -0
  35. conrich2-1.0.0.dev0/conrich/Stock/constant.py +48 -0
  36. conrich2-1.0.0.dev0/conrich/Stock/fields.py +147 -0
  37. conrich2-1.0.0.dev0/conrich/Stock/messages.py +179 -0
  38. conrich2-1.0.0.dev0/conrich/Stock/orders.py +104 -0
  39. conrich2-1.0.0.dev0/conrich/Stock/results.py +53 -0
  40. conrich2-1.0.0.dev0/conrich/Stock/session.py +373 -0
  41. conrich2-1.0.0.dev0/conrich/Stock/stock.py +279 -0
  42. conrich2-1.0.0.dev0/conrich/__init__.py +38 -0
  43. conrich2-1.0.0.dev0/conrich2.egg-info/PKG-INFO +242 -0
  44. conrich2-1.0.0.dev0/conrich2.egg-info/SOURCES.txt +48 -0
  45. conrich2-1.0.0.dev0/conrich2.egg-info/dependency_links.txt +1 -0
  46. conrich2-1.0.0.dev0/conrich2.egg-info/requires.txt +1 -0
  47. conrich2-1.0.0.dev0/conrich2.egg-info/top_level.txt +1 -0
  48. conrich2-1.0.0.dev0/requirements.txt +6 -0
  49. conrich2-1.0.0.dev0/setup.cfg +4 -0
  50. conrich2-1.0.0.dev0/setup.py +39 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Concords
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ include MANIFEST.in
2
+ include LICENSE
3
+ include README.md
4
+ include setup.py
5
+ include requirements.txt
6
+
7
+ graft conrich
8
+ prune tools
9
+ prune tests
10
+ prune docs
11
+
12
+ global-exclude *.pyc
13
+ global-exclude __pycache__
14
+ global-exclude *.log
15
+ global-exclude *.dll
16
+ global-exclude *.config
@@ -0,0 +1,242 @@
1
+ Metadata-Version: 2.4
2
+ Name: conrich2
3
+ Version: 1.0.0.dev0
4
+ Summary: Unofficial pure Python client for the Concords Securities / Futures trading API (not released by Concords).
5
+ Home-page: https://github.com/phymach
6
+ Author: Leo Wu
7
+ Author-email: phymach@gmail.com
8
+ License: MIT
9
+ Keywords: stock,futures,option,TWSE,TPEX,TAIFEX
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Office/Business :: Financial
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.13
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: cryptography>=42
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: keywords
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: requires-dist
34
+ Dynamic: requires-python
35
+ Dynamic: summary
36
+
37
+ # conrich2
38
+
39
+ ![PyPI](https://img.shields.io/pypi/v/conrich2)
40
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/conrich2)
41
+ ![PyPI - Format](https://img.shields.io/pypi/format/conrich2)
42
+ ![PyPI - License](https://img.shields.io/pypi/l/conrich2)
43
+ ![PyPI - Downloads](https://img.shields.io/pypi/dm/conrich2)
44
+ ![contact](https://img.shields.io/badge/contact-康和證券集團-red)
45
+
46
+ > **非官方聲明**:本套件(PyPI 名稱 `conrich2`)為非官方的純 Python 版本,並非康和證券集團發佈。安裝名稱是 `conrich2`,程式裡仍然使用 `import conrich`。
47
+
48
+ 康和綜合證券程式下單API為純 Python 實作(非官方),直接與康和伺服器通訊,不需要 .NET Framework、pythonnet 或任何 DLL,可在 Windows、Linux、macOS 執行,讓使用者可以輕鬆的運用python執行快速下單。
49
+
50
+ >conrich is a securities, futures, option API, which send orders to Concord Securities Group.
51
+ This package is pure Python (unofficial): it talks to the Concord servers directly, with no .NET Framework, pythonnet or vendor DLL, runs on Windows, Linux and macOS, and requires Python 3.13+.
52
+ This is an unofficial release (PyPI name `conrich2`), not published by Concord Securities Group. Install it with `pip install conrich2`; in code you still `import conrich`.
53
+ It is distributed under the MIT license.
54
+
55
+ - [Installation](#installation)
56
+ - [Preinstall](#preinstall)
57
+ - [Binaries](#binaries)
58
+ - [Quick Starts](#quick-starts)
59
+ - [Login](#login)
60
+ - [Place Order](#place-order)
61
+ - [Stock](#stock)
62
+ - [Futures](#futures)
63
+ - [Foreign Futures](#foreign-futures)
64
+ - [Register Event](#register-event)
65
+ - [Quote](#quote)
66
+ - [Reference](#reference)
67
+
68
+
69
+ ## Installation
70
+ ### Preinstall
71
+ >API usage needs application in advance. In order to use this package, please contact us.
72
+
73
+ ### Binaries
74
+
75
+ simply use pip to install (the import name is still `conrich`)
76
+ ```
77
+ pip install conrich2
78
+ ```
79
+
80
+ ## Quick Starts
81
+ ### Login
82
+ ```python
83
+ from conrich import StockAPI
84
+
85
+ agent = StockAPI()
86
+ agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
87
+ ```
88
+ ```python
89
+ from conrich import FuturesAPI
90
+
91
+ agent = FuturesAPI()
92
+ agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
93
+ ```
94
+ ```python
95
+ from conrich import ForeignFuturesAPI
96
+
97
+ agent = ForeignFuturesAPI()
98
+ agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
99
+ ```
100
+
101
+ ## Place Order
102
+ ### Stock
103
+ ```python
104
+ from conrich.Stock import constant
105
+
106
+ result = agent.order(action = constant.Action.NEW_ORDER.value,
107
+ branch_no = '8450',
108
+ account_no = "YOUR_ACCOUNT",
109
+ lot_type = constant.LotType.ROUND_LOT.value,
110
+ order_type = constant.OrderType.ORDINARY.value,
111
+ side = constant.Side.BUY.value,
112
+ day_trade_flag = constant.DayTradeFlag.N.value,
113
+ symbol = '6016',
114
+ quantity = 1,
115
+ price = 10.0,
116
+ price_flag = constant.PriceFlag.FIX.value,
117
+ time_in_force = constant.TimeInForce.ROD.value)
118
+ ```
119
+ ### Futures
120
+ ```python
121
+ from conrich.Futures import constant
122
+
123
+ result = agent.order(action = constant.Action.NEW_ORDER.value,
124
+ branch_no = 'F029000',
125
+ account_no = "YOUR_ACCOUNT",
126
+ market_type = constant.Market.FUTURES.value,
127
+ compound_type = constant.CompoundType.FUTURES_SINGLE.value,
128
+ commodity = 'TXFI0',
129
+ time_in_force = constant.TimeInForce.ROD.value,
130
+ writeoff = constant.WriteOff.AUTO.value,
131
+ order_type = constant.OrderType.LIMIT.value,
132
+ side = constant.Side.BUY.value,
133
+ quantity = 1,
134
+ price = 12000.00)
135
+ ```
136
+ ### Foreign Futures
137
+ ```python
138
+ agent.order(action=constant.Action.NEW_ORDER.value,
139
+ branch_no = 'F029000',
140
+ account_no = "YOUR_ACCOUNT",
141
+ exchange = 'NYM',
142
+ side1 = constant.Side.BUY.value,
143
+ market_type1 = constant.Market.FUTURES.value,
144
+ commodity1 = 'QM',
145
+ commodity_month1 = '202010',
146
+ strike_price1 = 0,
147
+ put_call1 = constant.PutCall.NONE.value,
148
+ side2 = '',
149
+ market_type2 = '',
150
+ commodity2 = '',
151
+ commodity_month2 = '',
152
+ strike_price2 = 0,
153
+ put_call2 = constant.PutCall.NONE.value,
154
+ order_type = constant.ForeignOrderType.LIMIT.value,
155
+ price = 0,
156
+ price_numerator = 0,
157
+ price_denominator = 0,
158
+ stop_price = 42.95,
159
+ stop_price_numerator = 0,
160
+ stop_price_denominator = 0,
161
+ quantity = 1,
162
+ writeoff = constant.Writeoff.OPEN.value)
163
+ ```
164
+
165
+ ## Register Event
166
+ >If you want to catch order or match report, one can define a function and register
167
+
168
+ ### Stock
169
+ ```python
170
+ def OrderReportHandler(result, msg):
171
+ order_result = {'result' : result.ResultType,
172
+ 'status' : result.StatusCode,
173
+ 'desc' : result.CodeDesc,
174
+ 'order_guid' : result.OrderGuid,
175
+ 'net_no' : result.ClOrdID
176
+ }
177
+
178
+ if result.ResultType=='1':
179
+ report = result.ExcReport
180
+ exe_report = {'order_id' : report.OrderID,
181
+ 'orig_net_no' : report.OrigClOrdID,
182
+ 'execute_status' : report.ExecType,
183
+ 'account_no' : report.Account,
184
+ 'symbol' : report.Symbol,
185
+ 'side' : report.Side,
186
+ 'quantity' : report.OrderQty,
187
+ 'price' : report.Price,
188
+ 'strike_quantity' : report.LastQty,
189
+ 'strike_price' : report.LastPx,
190
+ 'transaction_time' : report.TransactTime}
191
+
192
+ agent.OrderReportEvent += OrderReportHandler
193
+ ```
194
+
195
+ ### Futures
196
+ ```python
197
+ def OrderReportHandler(code, msg):
198
+ dict_msg = dict((agent.msg_tag[k], v) for k,v in [tag.split('=') for tag in msg.split('|')])
199
+ print(dict_msg)
200
+
201
+ agent.OnFOrderReport += OrderReportHandler
202
+ ```
203
+
204
+ ## Quote
205
+ Quotes come from the futures gateway (domestic futures and options only), so log in with `FuturesAPI` first.
206
+ `QuoteAPI` polls `FuturesAPI.quote()` in a background thread and fires `OnQuoteUpdate` when a field changes.
207
+ No 康和金好康 or other Windows program needs to be running, and `QuoteServer` (the old COM based quote server)
208
+ is gone: creating it raises `NotImplementedError`, use `QuoteAPI` instead. `code_convert` still works.
209
+
210
+ >The layout of the quote answer is not verified yet: until it is, the topics are the column names
211
+ `col1`, `col2`, ... of the answer row.
212
+
213
+ ```python
214
+ from datetime import datetime
215
+ from conrich import FuturesAPI, QuoteAPI
216
+ from conrich.Quote import code_convert
217
+
218
+ futures = FuturesAPI(pfx_path='YOUR_CERT.pfx', pfx_password='YOUR_PFX_PASSWORD')
219
+ futures.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
220
+
221
+ def on_quote(commodity, topic, value):
222
+ print('[{}][{}] {}'.format(commodity, topic, value))
223
+
224
+ quote = QuoteAPI(futures, interval=1.0) # interval in seconds, 0.5 or more
225
+ quote.OnQuoteUpdate += on_quote
226
+
227
+ topic1 = code_convert(commodity='TXO', commodity_type='P', strike_price=12500, expire_date=datetime(2020, 10, 18), after_hour=True)
228
+ quote.register_topic(topic1, 'col1')
229
+ topic2 = code_convert(commodity='TX', commodity_type='F', strike_price=0, expire_date=datetime(2020, 10, 18), after_hour=False)
230
+ quote.register_topic(topic2, 'col2')
231
+
232
+ quote.start() # or: with QuoteAPI(futures) as quote: ...
233
+ # ...
234
+ quote.stop()
235
+ ```
236
+
237
+ ## Reference
238
+
239
+ [FuturesAPI](./conrich/Futures/README.md)
240
+
241
+ https://www.concords.com.tw/download/20200318_證券API客戶使用元件及文件.zip
242
+ https://www.concordfutures.com.tw/WebSiteUpload//Files/Document/20200728_期貨API.zip
@@ -0,0 +1,206 @@
1
+ # conrich2
2
+
3
+ ![PyPI](https://img.shields.io/pypi/v/conrich2)
4
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/conrich2)
5
+ ![PyPI - Format](https://img.shields.io/pypi/format/conrich2)
6
+ ![PyPI - License](https://img.shields.io/pypi/l/conrich2)
7
+ ![PyPI - Downloads](https://img.shields.io/pypi/dm/conrich2)
8
+ ![contact](https://img.shields.io/badge/contact-康和證券集團-red)
9
+
10
+ > **非官方聲明**:本套件(PyPI 名稱 `conrich2`)為非官方的純 Python 版本,並非康和證券集團發佈。安裝名稱是 `conrich2`,程式裡仍然使用 `import conrich`。
11
+
12
+ 康和綜合證券程式下單API為純 Python 實作(非官方),直接與康和伺服器通訊,不需要 .NET Framework、pythonnet 或任何 DLL,可在 Windows、Linux、macOS 執行,讓使用者可以輕鬆的運用python執行快速下單。
13
+
14
+ >conrich is a securities, futures, option API, which send orders to Concord Securities Group.
15
+ This package is pure Python (unofficial): it talks to the Concord servers directly, with no .NET Framework, pythonnet or vendor DLL, runs on Windows, Linux and macOS, and requires Python 3.13+.
16
+ This is an unofficial release (PyPI name `conrich2`), not published by Concord Securities Group. Install it with `pip install conrich2`; in code you still `import conrich`.
17
+ It is distributed under the MIT license.
18
+
19
+ - [Installation](#installation)
20
+ - [Preinstall](#preinstall)
21
+ - [Binaries](#binaries)
22
+ - [Quick Starts](#quick-starts)
23
+ - [Login](#login)
24
+ - [Place Order](#place-order)
25
+ - [Stock](#stock)
26
+ - [Futures](#futures)
27
+ - [Foreign Futures](#foreign-futures)
28
+ - [Register Event](#register-event)
29
+ - [Quote](#quote)
30
+ - [Reference](#reference)
31
+
32
+
33
+ ## Installation
34
+ ### Preinstall
35
+ >API usage needs application in advance. In order to use this package, please contact us.
36
+
37
+ ### Binaries
38
+
39
+ simply use pip to install (the import name is still `conrich`)
40
+ ```
41
+ pip install conrich2
42
+ ```
43
+
44
+ ## Quick Starts
45
+ ### Login
46
+ ```python
47
+ from conrich import StockAPI
48
+
49
+ agent = StockAPI()
50
+ agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
51
+ ```
52
+ ```python
53
+ from conrich import FuturesAPI
54
+
55
+ agent = FuturesAPI()
56
+ agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
57
+ ```
58
+ ```python
59
+ from conrich import ForeignFuturesAPI
60
+
61
+ agent = ForeignFuturesAPI()
62
+ agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
63
+ ```
64
+
65
+ ## Place Order
66
+ ### Stock
67
+ ```python
68
+ from conrich.Stock import constant
69
+
70
+ result = agent.order(action = constant.Action.NEW_ORDER.value,
71
+ branch_no = '8450',
72
+ account_no = "YOUR_ACCOUNT",
73
+ lot_type = constant.LotType.ROUND_LOT.value,
74
+ order_type = constant.OrderType.ORDINARY.value,
75
+ side = constant.Side.BUY.value,
76
+ day_trade_flag = constant.DayTradeFlag.N.value,
77
+ symbol = '6016',
78
+ quantity = 1,
79
+ price = 10.0,
80
+ price_flag = constant.PriceFlag.FIX.value,
81
+ time_in_force = constant.TimeInForce.ROD.value)
82
+ ```
83
+ ### Futures
84
+ ```python
85
+ from conrich.Futures import constant
86
+
87
+ result = agent.order(action = constant.Action.NEW_ORDER.value,
88
+ branch_no = 'F029000',
89
+ account_no = "YOUR_ACCOUNT",
90
+ market_type = constant.Market.FUTURES.value,
91
+ compound_type = constant.CompoundType.FUTURES_SINGLE.value,
92
+ commodity = 'TXFI0',
93
+ time_in_force = constant.TimeInForce.ROD.value,
94
+ writeoff = constant.WriteOff.AUTO.value,
95
+ order_type = constant.OrderType.LIMIT.value,
96
+ side = constant.Side.BUY.value,
97
+ quantity = 1,
98
+ price = 12000.00)
99
+ ```
100
+ ### Foreign Futures
101
+ ```python
102
+ agent.order(action=constant.Action.NEW_ORDER.value,
103
+ branch_no = 'F029000',
104
+ account_no = "YOUR_ACCOUNT",
105
+ exchange = 'NYM',
106
+ side1 = constant.Side.BUY.value,
107
+ market_type1 = constant.Market.FUTURES.value,
108
+ commodity1 = 'QM',
109
+ commodity_month1 = '202010',
110
+ strike_price1 = 0,
111
+ put_call1 = constant.PutCall.NONE.value,
112
+ side2 = '',
113
+ market_type2 = '',
114
+ commodity2 = '',
115
+ commodity_month2 = '',
116
+ strike_price2 = 0,
117
+ put_call2 = constant.PutCall.NONE.value,
118
+ order_type = constant.ForeignOrderType.LIMIT.value,
119
+ price = 0,
120
+ price_numerator = 0,
121
+ price_denominator = 0,
122
+ stop_price = 42.95,
123
+ stop_price_numerator = 0,
124
+ stop_price_denominator = 0,
125
+ quantity = 1,
126
+ writeoff = constant.Writeoff.OPEN.value)
127
+ ```
128
+
129
+ ## Register Event
130
+ >If you want to catch order or match report, one can define a function and register
131
+
132
+ ### Stock
133
+ ```python
134
+ def OrderReportHandler(result, msg):
135
+ order_result = {'result' : result.ResultType,
136
+ 'status' : result.StatusCode,
137
+ 'desc' : result.CodeDesc,
138
+ 'order_guid' : result.OrderGuid,
139
+ 'net_no' : result.ClOrdID
140
+ }
141
+
142
+ if result.ResultType=='1':
143
+ report = result.ExcReport
144
+ exe_report = {'order_id' : report.OrderID,
145
+ 'orig_net_no' : report.OrigClOrdID,
146
+ 'execute_status' : report.ExecType,
147
+ 'account_no' : report.Account,
148
+ 'symbol' : report.Symbol,
149
+ 'side' : report.Side,
150
+ 'quantity' : report.OrderQty,
151
+ 'price' : report.Price,
152
+ 'strike_quantity' : report.LastQty,
153
+ 'strike_price' : report.LastPx,
154
+ 'transaction_time' : report.TransactTime}
155
+
156
+ agent.OrderReportEvent += OrderReportHandler
157
+ ```
158
+
159
+ ### Futures
160
+ ```python
161
+ def OrderReportHandler(code, msg):
162
+ dict_msg = dict((agent.msg_tag[k], v) for k,v in [tag.split('=') for tag in msg.split('|')])
163
+ print(dict_msg)
164
+
165
+ agent.OnFOrderReport += OrderReportHandler
166
+ ```
167
+
168
+ ## Quote
169
+ Quotes come from the futures gateway (domestic futures and options only), so log in with `FuturesAPI` first.
170
+ `QuoteAPI` polls `FuturesAPI.quote()` in a background thread and fires `OnQuoteUpdate` when a field changes.
171
+ No 康和金好康 or other Windows program needs to be running, and `QuoteServer` (the old COM based quote server)
172
+ is gone: creating it raises `NotImplementedError`, use `QuoteAPI` instead. `code_convert` still works.
173
+
174
+ >The layout of the quote answer is not verified yet: until it is, the topics are the column names
175
+ `col1`, `col2`, ... of the answer row.
176
+
177
+ ```python
178
+ from datetime import datetime
179
+ from conrich import FuturesAPI, QuoteAPI
180
+ from conrich.Quote import code_convert
181
+
182
+ futures = FuturesAPI(pfx_path='YOUR_CERT.pfx', pfx_password='YOUR_PFX_PASSWORD')
183
+ futures.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
184
+
185
+ def on_quote(commodity, topic, value):
186
+ print('[{}][{}] {}'.format(commodity, topic, value))
187
+
188
+ quote = QuoteAPI(futures, interval=1.0) # interval in seconds, 0.5 or more
189
+ quote.OnQuoteUpdate += on_quote
190
+
191
+ topic1 = code_convert(commodity='TXO', commodity_type='P', strike_price=12500, expire_date=datetime(2020, 10, 18), after_hour=True)
192
+ quote.register_topic(topic1, 'col1')
193
+ topic2 = code_convert(commodity='TX', commodity_type='F', strike_price=0, expire_date=datetime(2020, 10, 18), after_hour=False)
194
+ quote.register_topic(topic2, 'col2')
195
+
196
+ quote.start() # or: with QuoteAPI(futures) as quote: ...
197
+ # ...
198
+ quote.stop()
199
+ ```
200
+
201
+ ## Reference
202
+
203
+ [FuturesAPI](./conrich/Futures/README.md)
204
+
205
+ https://www.concords.com.tw/download/20200318_證券API客戶使用元件及文件.zip
206
+ https://www.concordfutures.com.tw/WebSiteUpload//Files/Document/20200728_期貨API.zip
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."""