qe-connector 1.0.0__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.
@@ -0,0 +1,561 @@
1
+ Metadata-Version: 2.1
2
+ Name: qe-connector
3
+ Version: 1.0.0
4
+ Summary: This is a lightweight library that works as a connector to Quantum Execute public API.
5
+ Home-page: https://github.com/Quantum-Execute/qe-connector-python
6
+ Author: Quantum-Execute
7
+ License: MIT
8
+ Keywords: Quantum-Execute,Public API
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Financial and Insurance Industry
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ Requires-Dist: requests>=2.31.0
19
+ Requires-Dist: websocket-client>=1.6.3
20
+ Requires-Dist: pycryptodome>=3.15.0
21
+
22
+ # Quantum Execute Python SDK
23
+
24
+ [![Python Version](https://img.shields.io/pypi/pyversions/qe-connector)](https://pypi.org/project/qe-connector/)
25
+ [![PyPI Version](https://img.shields.io/pypi/v/qe-connector)](https://pypi.org/project/qe-connector/)
26
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
27
+
28
+ 这是 Quantum Execute 公共 API 的官方 Python SDK,为开发者提供了一个轻量级、易于使用的接口来访问 Quantum Execute 的交易服务。
29
+
30
+ ## 功能特性
31
+
32
+ - ✅ 完整的 Quantum Execute API 支持
33
+ - ✅ 交易所 API 密钥管理
34
+ - ✅ 主订单创建与管理(TWAP、VWAP 等算法)
35
+ - ✅ 订单查询和成交明细
36
+ - ✅ 多种认证方式支持(HMAC、RSA、Ed25519)
37
+ - ✅ 支持生产环境和测试环境
38
+ - ✅ 异步和同步调用支持
39
+ - ✅ 完善的错误处理和日志记录
40
+
41
+ ## 安装
42
+
43
+ ```bash
44
+ pip install qe-connector
45
+ ```
46
+
47
+ 或者从源码安装:
48
+
49
+ ```bash
50
+ git clone https://github.com/Quantum-Execute/qe-connector-python.git
51
+ cd qe-connector-python
52
+ pip install -e .
53
+ ```
54
+
55
+ ## 快速开始
56
+
57
+ ### 初始化客户端
58
+
59
+ ```python
60
+ from qe.user import User as Client
61
+ import logging
62
+
63
+ # 配置日志(可选)
64
+ logging.basicConfig(level=logging.INFO)
65
+
66
+ # 创建生产环境客户端
67
+ client = Client(
68
+ api_key="your-api-key",
69
+ api_secret="your-api-secret"
70
+ )
71
+
72
+ # 创建测试环境客户端
73
+ client = Client(
74
+ api_key="your-api-key",
75
+ api_secret="your-api-secret",
76
+ base_url="https://testapi.quantumexecute.com"
77
+ )
78
+ ```
79
+
80
+ ### 管理交易所 API
81
+
82
+ #### 列出交易所 API 密钥
83
+
84
+ ```python
85
+ # 获取所有交易所 API 密钥
86
+ apis = client.list_exchange_apis()
87
+ print(f"共有 {apis['total']} 个 API 密钥")
88
+
89
+ for api in apis['items']:
90
+ print(f"账户: {api['accountName']}, 交易所: {api['exchange']}, 状态: {api['status']}")
91
+
92
+ # 带分页和过滤
93
+ apis = client.list_exchange_apis(
94
+ page=1,
95
+ pageSize=10,
96
+ exchange="binance"
97
+ )
98
+ ```
99
+
100
+ #### 添加交易所 API 密钥
101
+
102
+ ```python
103
+ result = client.add_exchange_api(
104
+ accountName="我的币安账户",
105
+ exchange="binance",
106
+ apiKey="your-exchange-api-key",
107
+ apiSecret="your-exchange-api-secret",
108
+ enableTrading=True # 启用交易权限
109
+ )
110
+
111
+ if result['success']:
112
+ print(f"API Key 添加成功,ID: {result['id']}")
113
+ ```
114
+
115
+ ### 创建主订单
116
+
117
+ #### TWAP 订单示例
118
+
119
+ ```python
120
+ # 创建一个 TWAP 订单,在 30 分钟内分批买入价值 $10,000 的 BTC
121
+ response = client.create_master_order(
122
+ algorithm="TWAP",
123
+ algorithmType="TIME_WEIGHTED",
124
+ exchange="binance",
125
+ symbol="BTCUSDT",
126
+ marketType="SPOT",
127
+ side="BUY",
128
+ apiKeyId="your-api-key-id", # 从 list_exchange_apis 获取
129
+ orderNotional=10000, # $10,000 名义价值
130
+ startTime="2024-01-01T10:00:00Z",
131
+ endTime="2024-01-01T10:30:00Z",
132
+ executionDuration="60", # 每 60 秒执行一次
133
+ mustComplete=True, # 必须完成全部订单
134
+ worstPrice=-1, # -1 表示无最差价格限制
135
+ clientId="my-order-001" # 自定义订单 ID
136
+ )
137
+
138
+ if response.get('success'):
139
+ print(f"主订单创建成功,ID: {response['masterOrderId']}")
140
+ ```
141
+
142
+ #### VWAP 订单示例
143
+
144
+ ```python
145
+ # 创建 VWAP 订单,根据市场成交量分布执行
146
+ response = client.create_master_order(
147
+ algorithm="VWAP",
148
+ algorithmType="VOLUME_WEIGHTED",
149
+ exchange="binance",
150
+ symbol="ETHUSDT",
151
+ marketType="SPOT",
152
+ side="SELL",
153
+ apiKeyId="your-api-key-id",
154
+ totalQuantity=5.0, # 卖出 5 ETH
155
+ strategyType="AGGRESSIVE", # 激进策略
156
+ startTime="2024-01-01T09:00:00Z",
157
+ endTime="2024-01-01T17:00:00Z",
158
+ makerRateLimit=0.3, # 最多 30% Maker 订单
159
+ povLimit=0.1, # 最多占市场成交量的 10%
160
+ notes="VWAP 卖出 ETH" # 订单备注
161
+ )
162
+ ```
163
+
164
+ #### 期货订单示例
165
+
166
+ ```python
167
+ # 创建期货 TWAP 订单
168
+ response = client.create_master_order(
169
+ algorithm="TWAP",
170
+ algorithmType="TIME_WEIGHTED",
171
+ exchange="binance",
172
+ symbol="BTCUSDT",
173
+ marketType="FUTURES",
174
+ side="BUY",
175
+ apiKeyId="your-api-key-id",
176
+ totalQuantity=0.1, # 0.1 BTC
177
+ executionDuration="1800", # 30 分钟
178
+ marginType="CROSS", # 全仓模式(或 "ISOLATED" 逐仓)
179
+ reduceOnly=False, # 非只减仓
180
+ worstPrice=55000.0, # 最差价格限制
181
+ upTolerance="0.001", # 向上容差 0.1%
182
+ lowTolerance="0.001", # 向下容差 0.1%
183
+ strictUpBound=True # 严格上限
184
+ )
185
+ ```
186
+
187
+ ### 查询订单
188
+
189
+ #### 查询主订单列表
190
+
191
+ ```python
192
+ # 查询所有主订单
193
+ orders = client.get_master_orders()
194
+
195
+ # 带过滤条件查询
196
+ orders = client.get_master_orders(
197
+ page=1,
198
+ pageSize=20,
199
+ status="ACTIVE", # 活跃订单
200
+ symbol="BTCUSDT",
201
+ startTime="2024-01-01T00:00:00Z",
202
+ endTime="2024-01-31T23:59:59Z"
203
+ )
204
+
205
+ # 打印订单信息
206
+ for order in orders['items']:
207
+ print(f"""
208
+ 订单 ID: {order['masterOrderId']}
209
+ 算法: {order['algorithm']}
210
+ 交易对: {order['symbol']}
211
+ 方向: {order['side']}
212
+ 状态: {order['status']}
213
+ 完成度: {order['completionProgress'] * 100:.2f}%
214
+ 平均价格: {order['averagePrice']}
215
+ 已成交数量: {order['filledQuantity']} / {order['totalQuantity']}
216
+ """)
217
+ ```
218
+
219
+ #### 查询成交明细
220
+
221
+ ```python
222
+ # 查询特定主订单的成交明细
223
+ fills = client.get_order_fills(
224
+ masterOrderId="your-master-order-id",
225
+ page=1,
226
+ pageSize=50
227
+ )
228
+
229
+ # 查询所有成交
230
+ fills = client.get_order_fills(
231
+ symbol="BTCUSDT",
232
+ startTime="2024-01-01T00:00:00Z",
233
+ endTime="2024-01-01T23:59:59Z"
234
+ )
235
+
236
+ # 计算总成交额和手续费
237
+ total_value = 0
238
+ total_fee = 0
239
+
240
+ for fill in fills['items']:
241
+ print(f"""
242
+ 成交时间: {fill['orderCreatedTime']}
243
+ 交易对: {fill['symbol']}
244
+ 方向: {fill['side']}
245
+ 成交价格: {fill['price']}
246
+ 成交数量: {fill['filledQuantity']}
247
+ 成交金额: {fill['filledValue']}
248
+ 手续费: {fill['fee']}
249
+ """)
250
+ total_value += fill['filledValue']
251
+ total_fee += fill['fee']
252
+
253
+ print(f"总成交额: ${total_value:.2f}, 总手续费: ${total_fee:.2f}")
254
+ ```
255
+
256
+ ### 取消订单
257
+
258
+ ```python
259
+ response = client.cancel_master_order(
260
+ masterOrderId="your-master-order-id",
261
+ reason="用户手动取消" # 可选的取消原因
262
+ )
263
+
264
+ if response.get('success'):
265
+ print("订单取消成功")
266
+ else:
267
+ print(f"订单取消失败: {response.get('message')}")
268
+ ```
269
+
270
+ ## 错误处理
271
+
272
+ SDK 提供了详细的错误类型,方便进行精确的错误处理:
273
+
274
+ ```python
275
+ from qe.error import ClientError, APIError
276
+
277
+ try:
278
+ response = client.create_master_order(
279
+ # ... 订单参数
280
+ )
281
+ except APIError as error:
282
+ # API 返回的业务错误
283
+ print(f"API 错误 - 代码: {error.code}, 原因: {error.reason}, 消息: {error.message}")
284
+ print(f"追踪 ID: {error.trace_id}") # 用于技术支持
285
+ except ClientError as error:
286
+ # 客户端错误(如参数错误、网络错误等)
287
+ print(f"客户端错误 - 状态码: {error.status_code}, 错误消息: {error.error_message}")
288
+ except Exception as error:
289
+ # 其他未预期的错误
290
+ print(f"未知错误: {error}")
291
+ ```
292
+
293
+ ## 高级配置
294
+
295
+ ### 配置超时和代理
296
+
297
+ ```python
298
+ client = Client(
299
+ api_key="your-api-key",
300
+ api_secret="your-api-secret",
301
+ timeout=30, # 30 秒超时
302
+ proxies={
303
+ 'https': 'http://proxy.example.com:8080'
304
+ }
305
+ )
306
+ ```
307
+
308
+ ### 使用 RSA 或 Ed25519 签名
309
+
310
+ ```python
311
+ # 使用 RSA 私钥
312
+ with open('private_key.pem', 'r') as f:
313
+ private_key = f.read()
314
+
315
+ client = Client(
316
+ api_key="your-api-key",
317
+ private_key=private_key,
318
+ private_key_pass="your-password" # 如果私钥有密码
319
+ )
320
+
321
+ # 使用 Ed25519 私钥
322
+ with open('ed25519_key.pem', 'r') as f:
323
+ ed25519_key = f.read()
324
+
325
+ client = Client(
326
+ api_key="your-api-key",
327
+ private_key=ed25519_key
328
+ )
329
+ ```
330
+
331
+ ### 显示请求限制使用情况
332
+
333
+ ```python
334
+ client = Client(
335
+ api_key="your-api-key",
336
+ api_secret="your-api-secret",
337
+ show_limit_usage=True,
338
+ show_header=True
339
+ )
340
+
341
+ # API 响应将包含限制信息
342
+ response = client.get_master_orders()
343
+ if isinstance(response, dict) and 'limit_usage' in response:
344
+ print(f"限制使用情况: {response['limit_usage']}")
345
+ print(f"实际数据: {response['data']}")
346
+ ```
347
+
348
+ ### 配置日志
349
+
350
+ ```python
351
+ import logging
352
+ from qe.lib.utils import config_logging
353
+
354
+ # 配置详细日志
355
+ config_logging(logging, logging.DEBUG)
356
+
357
+ # 只记录警告和错误
358
+ config_logging(logging, logging.WARNING)
359
+ ```
360
+
361
+ ## 完整示例
362
+
363
+ ### 完整的交易流程示例
364
+
365
+ ```python
366
+ import logging
367
+ from qe.user import User as Client
368
+ from qe.error import ClientError, APIError
369
+ from qe.lib.utils import config_logging
370
+ import time
371
+
372
+ # 配置日志
373
+ config_logging(logging, logging.INFO)
374
+ logger = logging.getLogger(__name__)
375
+
376
+ # 初始化客户端
377
+ client = Client("your-api-key", "your-api-secret")
378
+
379
+ try:
380
+ # 1. 获取可用的 API 密钥
381
+ apis = client.list_exchange_apis(exchange="binance")
382
+ if not apis['items']:
383
+ logger.error("没有找到可用的币安 API 密钥")
384
+ exit(1)
385
+
386
+ api_key_id = apis['items'][0]['id']
387
+ logger.info(f"使用 API 密钥: {api_key_id}")
388
+
389
+ # 2. 创建 TWAP 订单
390
+ order_response = client.create_master_order(
391
+ algorithm="TWAP",
392
+ algorithmType="TIME_WEIGHTED",
393
+ exchange="binance",
394
+ symbol="BTCUSDT",
395
+ marketType="SPOT",
396
+ side="BUY",
397
+ apiKeyId=api_key_id,
398
+ orderNotional=1000, # $1000
399
+ startTime="2024-01-01T10:00:00Z",
400
+ endTime="2024-01-01T10:10:00Z",
401
+ executionDuration="30", # 每 30 秒执行一次
402
+ mustComplete=True,
403
+ clientId=f"test_order_{int(time.time())}"
404
+ )
405
+
406
+ if not order_response.get('success'):
407
+ logger.error(f"创建订单失败: {order_response.get('message')}")
408
+ exit(1)
409
+
410
+ master_order_id = order_response['masterOrderId']
411
+ logger.info(f"订单创建成功,ID: {master_order_id}")
412
+
413
+ # 3. 监控订单状态
414
+ while True:
415
+ orders = client.get_master_orders(
416
+ page=1,
417
+ pageSize=1,
418
+ status="ACTIVE"
419
+ )
420
+
421
+ if not orders['items']:
422
+ logger.info("订单已完成或取消")
423
+ break
424
+
425
+ order = orders['items'][0]
426
+ logger.info(f"订单进度: {order['completionProgress'] * 100:.2f}%, "
427
+ f"已成交: {order['filledQuantity']}/{order['totalQuantity']}")
428
+
429
+ # 检查是否需要取消
430
+ if order['completionProgress'] > 0.5: # 完成超过 50%
431
+ logger.info("演示:取消订单")
432
+ cancel_response = client.cancel_master_order(
433
+ masterOrderId=master_order_id,
434
+ reason="演示取消"
435
+ )
436
+ if cancel_response.get('success'):
437
+ logger.info("订单已取消")
438
+ break
439
+
440
+ time.sleep(10) # 每 10 秒检查一次
441
+
442
+ # 4. 获取最终成交明细
443
+ fills = client.get_order_fills(masterOrderId=master_order_id)
444
+ logger.info(f"总成交笔数: {fills['total']}")
445
+
446
+ for fill in fills['items']:
447
+ logger.info(f"成交: {fill['side']} {fill['filledQuantity']} {fill['symbol']} "
448
+ f"@ {fill['price']}, 手续费: {fill['fee']}")
449
+
450
+ except APIError as error:
451
+ logger.error(f"API 错误: {error}")
452
+ except ClientError as error:
453
+ logger.error(f"客户端错误: {error}")
454
+ except Exception as error:
455
+ logger.error(f"未知错误: {error}")
456
+ ```
457
+
458
+ ## API 文档
459
+
460
+ 完整的 API 文档请参考 [Quantum Execute API 文档](https://docs.quantumexecute.com)
461
+
462
+ ## 支持的算法类型
463
+
464
+ - **TWAP (Time Weighted Average Price)**: 时间加权平均价格算法
465
+ - **VWAP (Volume Weighted Average Price)**: 成交量加权平均价格算法
466
+ - **POV (Percentage of Volume)**: 成交量百分比算法
467
+ - **IMPLEMENTATION_SHORTFALL**: 执行缺口算法
468
+ - 更多算法类型请参考 API 文档
469
+
470
+ ## 示例代码
471
+
472
+ 更多示例代码请参考 [examples](./examples) 目录:
473
+
474
+ - [添加交易所 API](examples/user/add_exchange_api.py)
475
+ - [创建主订单](examples/user/create_master_order.py)
476
+ - [取消主订单](examples/user/cancel_master_order.py)
477
+ - [查询订单列表](examples/user/get_master_orders.py)
478
+ - [查询成交明细](examples/user/get_order_fills.py)
479
+
480
+ ## 开发和测试
481
+
482
+ ### 安装开发依赖
483
+
484
+ ```bash
485
+ pip install -r requirements/requirements-dev.txt
486
+ ```
487
+
488
+ ### 运行测试
489
+
490
+ ```bash
491
+ python -m pytest tests/
492
+ ```
493
+
494
+ ### 代码格式化
495
+
496
+ ```bash
497
+ black qe/
498
+ flake8 qe/
499
+ ```
500
+
501
+ ## 常见问题
502
+
503
+ ### 1. 如何获取 API 密钥?
504
+
505
+ 请登录 Quantum Execute 平台,在用户设置中创建 API 密钥。确保保管好您的密钥,不要将其提交到版本控制系统中。
506
+
507
+ ### 2. 时间戳错误怎么处理?
508
+
509
+ 如果遇到时间戳相关的错误,可能是您的系统时间与服务器时间不同步。请确保系统时间准确。
510
+
511
+ ### 3. 如何处理大量数据的分页?
512
+
513
+ ```python
514
+ def get_all_orders(client):
515
+ all_orders = []
516
+ page = 1
517
+ page_size = 100
518
+
519
+ while True:
520
+ result = client.get_master_orders(page=page, pageSize=page_size)
521
+ all_orders.extend(result['items'])
522
+
523
+ if len(result['items']) < page_size:
524
+ break
525
+ page += 1
526
+
527
+ return all_orders
528
+ ```
529
+
530
+ ### 4. 如何设置订单的时间?
531
+
532
+ 时间格式使用 ISO 8601 标准,例如:
533
+ - UTC 时间:`2024-01-01T10:00:00Z`
534
+ - 带时区:`2024-01-01T18:00:00+08:00`
535
+
536
+ ## 贡献指南
537
+
538
+ 欢迎提交 Issue 和 Pull Request!请确保:
539
+
540
+ 1. 代码符合 PEP 8 规范
541
+ 2. 添加适当的测试
542
+ 3. 更新相关文档
543
+
544
+ ## 更新日志
545
+
546
+ ### v1.0.0 (2024-01-01)
547
+ - 初始版本发布
548
+ - 支持完整的 Quantum Execute API
549
+ - 支持多种认证方式
550
+ - 完善的错误处理
551
+
552
+ ## 许可证
553
+
554
+ 本项目采用 MIT 许可证 - 详见 [LICENSE](LICENSE) 文件。
555
+
556
+ ## 联系我们
557
+
558
+ - 官网:[https://quantumexecute.com](https://quantumexecute.com)
559
+ - 邮箱:support@quantumexecute.com
560
+ - GitHub:[https://github.com/Quantum-Execute/qe-connector-python](https://github.com/Quantum-Execute/qe-connector-python)
561
+