kaq-quant-common 0.2.11__tar.gz → 0.2.13__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.
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/PKG-INFO +1 -1
- kaq_quant_common-0.2.13/kaq_quant_common/api/rest/api_client_base.py +187 -0
- kaq_quant_common-0.2.13/kaq_quant_common/api/rest/instruction/helper/commission_helper.py +141 -0
- kaq_quant_common-0.2.13/kaq_quant_common/api/rest/instruction/helper/mock_order_helper.py +344 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/helper/order_helper.py +1 -1
- kaq_quant_common-0.2.13/kaq_quant_common/api/rest/instruction/instruction_client.py +288 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/instruction_server_base.py +54 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/models/order.py +1 -1
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/modules/funding_rate_helper.py +4 -2
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/modules/limit_order_helper.py +4 -2
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/pyproject.toml +1 -1
- kaq_quant_common-0.2.11/kaq_quant_common/api/rest/api_client_base.py +0 -42
- kaq_quant_common-0.2.11/kaq_quant_common/api/rest/instruction/instruction_client.py +0 -86
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/README.md +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/common/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/common/api_interface.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/common/auth.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/api_server_base.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/models/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/models/account.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/models/position.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/rest/instruction/models/transfer.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/exchange/models.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/exchange/ws_exchange_client.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/exchange/ws_exchange_server.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/instruction/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/instruction/ws_instruction_client.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/instruction/ws_instruction_server_base.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/models.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/ws_client_base.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/api/ws/ws_server_base.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/ddb_table_monitor.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/http_monitor.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/modules/limit_order_symbol_monitor.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/modules/limit_order_symbol_monitor_group.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/monitor_base.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/monitor_group.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/redis_table_monitor.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/statistics/funding_rate_history_statistics.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/statistics/kline_history_statistics.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/common/ws_wrapper.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/config/config.yaml +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_ddb_pool_stream_read_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_ddb_stream_init_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_ddb_stream_read_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_ddb_stream_write_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_mysql_init_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_mysql_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_postgresql_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_quant_hive_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/resources/kaq_redis_resources.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/__init__.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/dagster_job_check_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/dagster_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/date_util.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/enums_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/error_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/hash_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/log_time_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/logger_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/mytt_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/signal_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/sqlite_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/uuid_utils.py +0 -0
- {kaq_quant_common-0.2.11 → kaq_quant_common-0.2.13}/kaq_quant_common/utils/yml_utils.py +0 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
from typing import Optional, Type, TypeVar, Callable
|
|
2
|
+
import asyncio
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
try:
|
|
8
|
+
import httpx
|
|
9
|
+
HTTPX_AVAILABLE = True
|
|
10
|
+
except ImportError:
|
|
11
|
+
HTTPX_AVAILABLE = False
|
|
12
|
+
|
|
13
|
+
from kaq_quant_common.api.common.auth import get_auth_token
|
|
14
|
+
from kaq_quant_common.utils import logger_utils
|
|
15
|
+
from pydantic import BaseModel
|
|
16
|
+
|
|
17
|
+
R = TypeVar("R", bound=BaseModel)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ApiClientBase:
|
|
21
|
+
"""
|
|
22
|
+
api 客户端
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
# 类级别的共享 event loop 线程
|
|
26
|
+
_shared_loop: Optional[asyncio.AbstractEventLoop] = None
|
|
27
|
+
_shared_loop_thread: Optional[threading.Thread] = None
|
|
28
|
+
_loop_lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
def __init__(self, base_url: str, token: Optional[str] = None):
|
|
31
|
+
self._base_url = base_url.rstrip("/")
|
|
32
|
+
self._token = token if token is not None else get_auth_token()
|
|
33
|
+
self._logger = logger_utils.get_logger(self)
|
|
34
|
+
# 异步客户端(懒加载)
|
|
35
|
+
self._async_client: Optional[httpx.AsyncClient] = None
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def _ensure_shared_loop(cls):
|
|
39
|
+
"""确保共享的 event loop 已创建并运行"""
|
|
40
|
+
if cls._shared_loop is None or not cls._shared_loop.is_running():
|
|
41
|
+
with cls._loop_lock:
|
|
42
|
+
# 双重检查
|
|
43
|
+
if cls._shared_loop is None or not cls._shared_loop.is_running():
|
|
44
|
+
def run_loop():
|
|
45
|
+
"""在后台线程中运行 event loop"""
|
|
46
|
+
cls._shared_loop = asyncio.new_event_loop()
|
|
47
|
+
asyncio.set_event_loop(cls._shared_loop)
|
|
48
|
+
cls._shared_loop.run_forever()
|
|
49
|
+
|
|
50
|
+
cls._shared_loop_thread = threading.Thread(
|
|
51
|
+
target=run_loop,
|
|
52
|
+
daemon=True,
|
|
53
|
+
name="ApiClient-EventLoop"
|
|
54
|
+
)
|
|
55
|
+
cls._shared_loop_thread.start()
|
|
56
|
+
|
|
57
|
+
# 等待 loop 启动
|
|
58
|
+
while cls._shared_loop is None:
|
|
59
|
+
time.sleep(0.01)
|
|
60
|
+
|
|
61
|
+
# 发送请求
|
|
62
|
+
def _make_request(self, method_name: str, request_data: BaseModel, response_model: Type[R]) -> R:
|
|
63
|
+
url = f"{self._base_url}/api/{method_name}"
|
|
64
|
+
headers = {}
|
|
65
|
+
if self._token:
|
|
66
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
67
|
+
try:
|
|
68
|
+
# 发送post请求
|
|
69
|
+
response = requests.post(url, json=request_data.model_dump(), headers=headers or None)
|
|
70
|
+
# 检查响应状态码,如果不成功,则尝试解析错误信息并抛出异常
|
|
71
|
+
if not response.ok:
|
|
72
|
+
try:
|
|
73
|
+
error_data = response.json()
|
|
74
|
+
error_message = error_data.get("error", response.text)
|
|
75
|
+
except ValueError:
|
|
76
|
+
error_message = response.text
|
|
77
|
+
raise requests.exceptions.HTTPError(f"HTTP error occurred: {response.status_code} - {error_message}", response=response)
|
|
78
|
+
# 返回请求结果
|
|
79
|
+
return response_model(**response.json())
|
|
80
|
+
except requests.exceptions.RequestException as e:
|
|
81
|
+
self._logger.error(f"An error occurred: {e}")
|
|
82
|
+
raise
|
|
83
|
+
|
|
84
|
+
# 异步发送请求
|
|
85
|
+
async def _make_request_async(self, method_name: str, request_data: BaseModel, response_model: Type[R]) -> R:
|
|
86
|
+
"""
|
|
87
|
+
异步发送请求
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
method_name: API方法名
|
|
91
|
+
request_data: 请求数据
|
|
92
|
+
response_model: 响应模型
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
响应对象
|
|
96
|
+
"""
|
|
97
|
+
if not HTTPX_AVAILABLE:
|
|
98
|
+
raise RuntimeError("httpx library is required for async requests. Install it with: pip install httpx")
|
|
99
|
+
|
|
100
|
+
url = f"{self._base_url}/api/{method_name}"
|
|
101
|
+
headers = {}
|
|
102
|
+
if self._token:
|
|
103
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
104
|
+
|
|
105
|
+
# 懒加载创建async client
|
|
106
|
+
if self._async_client is None:
|
|
107
|
+
self._async_client = httpx.AsyncClient(timeout=30.0)
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
# 发送异步post请求
|
|
111
|
+
response = await self._async_client.post(
|
|
112
|
+
url,
|
|
113
|
+
json=request_data.model_dump(),
|
|
114
|
+
headers=headers or None
|
|
115
|
+
)
|
|
116
|
+
# 检查响应状态码
|
|
117
|
+
if not response.is_success:
|
|
118
|
+
try:
|
|
119
|
+
error_data = response.json()
|
|
120
|
+
error_message = error_data.get("error", response.text)
|
|
121
|
+
except ValueError:
|
|
122
|
+
error_message = response.text
|
|
123
|
+
raise httpx.HTTPStatusError(
|
|
124
|
+
f"HTTP error occurred: {response.status_code} - {error_message}",
|
|
125
|
+
request=response.request,
|
|
126
|
+
response=response
|
|
127
|
+
)
|
|
128
|
+
# 返回请求结果
|
|
129
|
+
return response_model(**response.json())
|
|
130
|
+
except httpx.HTTPStatusError:
|
|
131
|
+
raise
|
|
132
|
+
except Exception as e:
|
|
133
|
+
self._logger.error(f"An error occurred: {e}")
|
|
134
|
+
raise
|
|
135
|
+
|
|
136
|
+
# 回调方式发送请求
|
|
137
|
+
def _make_request_callback(
|
|
138
|
+
self,
|
|
139
|
+
method_name: str,
|
|
140
|
+
request_data: BaseModel,
|
|
141
|
+
response_model: Type[R],
|
|
142
|
+
on_success: Optional[Callable[[R], None]] = None,
|
|
143
|
+
on_error: Optional[Callable[[Exception], None]] = None
|
|
144
|
+
) -> None:
|
|
145
|
+
"""
|
|
146
|
+
回调方式发送请求,使用共享的 event loop
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
method_name: API方法名
|
|
150
|
+
request_data: 请求数据
|
|
151
|
+
response_model: 响应模型
|
|
152
|
+
on_success: 成功回调,接收响应对象,可选
|
|
153
|
+
on_error: 错误回调,接收异常对象,可选
|
|
154
|
+
"""
|
|
155
|
+
# 确保共享 loop 已启动
|
|
156
|
+
self._ensure_shared_loop()
|
|
157
|
+
|
|
158
|
+
async def _async_task():
|
|
159
|
+
"""异步任务"""
|
|
160
|
+
try:
|
|
161
|
+
result = await self._make_request_async(method_name, request_data, response_model)
|
|
162
|
+
# 调用成功回调(如果提供)
|
|
163
|
+
if on_success:
|
|
164
|
+
on_success(result)
|
|
165
|
+
except Exception as e:
|
|
166
|
+
# 调用错误回调
|
|
167
|
+
if on_error:
|
|
168
|
+
on_error(e)
|
|
169
|
+
else:
|
|
170
|
+
self._logger.error(f"Callback request failed: {e}")
|
|
171
|
+
|
|
172
|
+
# 将任务提交到共享的 event loop
|
|
173
|
+
asyncio.run_coroutine_threadsafe(_async_task(), self._shared_loop)
|
|
174
|
+
|
|
175
|
+
async def close_async(self):
|
|
176
|
+
"""关闭异步客户端连接"""
|
|
177
|
+
if self._async_client is not None:
|
|
178
|
+
await self._async_client.aclose()
|
|
179
|
+
self._async_client = None
|
|
180
|
+
|
|
181
|
+
async def __aenter__(self):
|
|
182
|
+
"""异步上下文管理器入口"""
|
|
183
|
+
return self
|
|
184
|
+
|
|
185
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
186
|
+
"""异步上下文管理器出口"""
|
|
187
|
+
await self.close_async()
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from kaq_quant_common.utils import logger_utils
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CommissionHelper:
|
|
9
|
+
"""手续费助手,用于从Redis加载和获取交易对的手续费率"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, ins_server):
|
|
12
|
+
# 必须放在这里 延迟引入,否则会有循环引用问题
|
|
13
|
+
from kaq_quant_common.api.rest.instruction.instruction_server_base import (
|
|
14
|
+
InstructionServerBase,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
self._server: InstructionServerBase = ins_server
|
|
18
|
+
self._logger = logger_utils.get_logger(self)
|
|
19
|
+
|
|
20
|
+
# 手续费数据缓存
|
|
21
|
+
self._commission_data: Optional[pd.DataFrame] = None
|
|
22
|
+
# 是否已加载
|
|
23
|
+
self._loaded = False
|
|
24
|
+
|
|
25
|
+
def _load_commission_rates(self):
|
|
26
|
+
"""从Redis加载手续费率数据"""
|
|
27
|
+
if self._loaded:
|
|
28
|
+
return
|
|
29
|
+
|
|
30
|
+
redis = self._server._redis
|
|
31
|
+
if redis is None:
|
|
32
|
+
self._logger.warning("Redis未配置,无法加载手续费率")
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
exchange = self._server._exchange
|
|
36
|
+
# 组装Redis key,格式: kaq_{exchange}_futures_commission_rate
|
|
37
|
+
redis_key = f"kaq_{exchange}_futures_commission_rate"
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
self._logger.info(f"Loading commission rates from Redis key: {redis_key}")
|
|
41
|
+
# 从Redis读取list数据
|
|
42
|
+
data_list = redis.lrange(redis_key)
|
|
43
|
+
|
|
44
|
+
if data_list is not None and not data_list.empty:
|
|
45
|
+
self._commission_data = data_list
|
|
46
|
+
self._loaded = True
|
|
47
|
+
self._logger.info(
|
|
48
|
+
f"Successfully loaded {len(self._commission_data)} commission rates"
|
|
49
|
+
)
|
|
50
|
+
else:
|
|
51
|
+
self._logger.warning(f"No commission rate data found in Redis key: {redis_key}")
|
|
52
|
+
except Exception as e:
|
|
53
|
+
self._logger.error(f"Failed to load commission rates from Redis: {e}")
|
|
54
|
+
|
|
55
|
+
def get_taker_commission_rate(self, symbol: str, default_rate: float = 0.0005) -> float:
|
|
56
|
+
"""
|
|
57
|
+
获取指定交易对的taker手续费率
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
symbol: 交易对,如 BTCUSDT
|
|
61
|
+
default_rate: 默认手续费率,如果获取失败则使用该值
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
float: taker手续费率
|
|
65
|
+
"""
|
|
66
|
+
# 如果还没加载,先加载
|
|
67
|
+
if not self._loaded:
|
|
68
|
+
self._load_commission_rates()
|
|
69
|
+
|
|
70
|
+
# 如果还是没有数据,返回默认值
|
|
71
|
+
if self._commission_data is None or self._commission_data.empty:
|
|
72
|
+
self._logger.warning(
|
|
73
|
+
f"Commission data not available, using default rate: {default_rate}"
|
|
74
|
+
)
|
|
75
|
+
return default_rate
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
# 从DataFrame中查找对应的symbol
|
|
79
|
+
matched = self._commission_data[self._commission_data["symbol"] == symbol]
|
|
80
|
+
|
|
81
|
+
if not matched.empty:
|
|
82
|
+
rate = float(matched.iloc[0]["takerCommissionRate"])
|
|
83
|
+
self._logger.debug(f"Found taker commission rate for {symbol}: {rate}")
|
|
84
|
+
return rate
|
|
85
|
+
else:
|
|
86
|
+
self._logger.warning(
|
|
87
|
+
f"Symbol {symbol} not found in commission data, using default rate: {default_rate}"
|
|
88
|
+
)
|
|
89
|
+
return default_rate
|
|
90
|
+
except Exception as e:
|
|
91
|
+
self._logger.error(
|
|
92
|
+
f"Error getting commission rate for {symbol}: {e}, using default rate: {default_rate}"
|
|
93
|
+
)
|
|
94
|
+
return default_rate
|
|
95
|
+
|
|
96
|
+
def get_maker_commission_rate(self, symbol: str, default_rate: float = 0.0002) -> float:
|
|
97
|
+
"""
|
|
98
|
+
获取指定交易对的maker手续费率
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
symbol: 交易对,如 BTCUSDT
|
|
102
|
+
default_rate: 默认手续费率,如果获取失败则使用该值
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
float: maker手续费率
|
|
106
|
+
"""
|
|
107
|
+
# 如果还没加载,先加载
|
|
108
|
+
if not self._loaded:
|
|
109
|
+
self._load_commission_rates()
|
|
110
|
+
|
|
111
|
+
# 如果还是没有数据,返回默认值
|
|
112
|
+
if self._commission_data is None or self._commission_data.empty:
|
|
113
|
+
self._logger.warning(
|
|
114
|
+
f"Commission data not available, using default rate: {default_rate}"
|
|
115
|
+
)
|
|
116
|
+
return default_rate
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
# 从DataFrame中查找对应的symbol
|
|
120
|
+
matched = self._commission_data[self._commission_data["symbol"] == symbol]
|
|
121
|
+
|
|
122
|
+
if not matched.empty:
|
|
123
|
+
rate = float(matched.iloc[0]["makerCommissionRate"])
|
|
124
|
+
self._logger.debug(f"Found maker commission rate for {symbol}: {rate}")
|
|
125
|
+
return rate
|
|
126
|
+
else:
|
|
127
|
+
self._logger.warning(
|
|
128
|
+
f"Symbol {symbol} not found in commission data, using default rate: {default_rate}"
|
|
129
|
+
)
|
|
130
|
+
return default_rate
|
|
131
|
+
except Exception as e:
|
|
132
|
+
self._logger.error(
|
|
133
|
+
f"Error getting commission rate for {symbol}: {e}, using default rate: {default_rate}"
|
|
134
|
+
)
|
|
135
|
+
return default_rate
|
|
136
|
+
|
|
137
|
+
def reload(self):
|
|
138
|
+
"""重新加载手续费率数据"""
|
|
139
|
+
self._loaded = False
|
|
140
|
+
self._commission_data = None
|
|
141
|
+
self._load_commission_rates()
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from kaq_quant_common.api.rest.instruction.models.order import (
|
|
6
|
+
OrderInfo,
|
|
7
|
+
OrderSide,
|
|
8
|
+
OrderStatus,
|
|
9
|
+
PositionStatus,
|
|
10
|
+
)
|
|
11
|
+
from kaq_quant_common.api.rest.instruction.models.position import PositionSide
|
|
12
|
+
from kaq_quant_common.utils import logger_utils, uuid_utils
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MockOrderHelper:
|
|
16
|
+
"""模拟订单助手,用于模拟下单流程,不调用真实交易所API"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, ins_server):
|
|
19
|
+
# 必须放在这里 延迟引入,否则会有循环引用问题
|
|
20
|
+
from kaq_quant_common.api.rest.instruction.instruction_server_base import (
|
|
21
|
+
InstructionServerBase,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
self._server: InstructionServerBase = ins_server
|
|
25
|
+
self._logger = logger_utils.get_logger(self)
|
|
26
|
+
|
|
27
|
+
self._mysql_table_name_order = "kaq_futures_instruction_order"
|
|
28
|
+
self._mysql_table_name_position = "kaq_futures_instruction_position"
|
|
29
|
+
# 当前持仓
|
|
30
|
+
self._redis_key_position = "kaq_futures_instruction_position"
|
|
31
|
+
# 持仓历史
|
|
32
|
+
self._redis_key_position_history = "kaq_futures_instruction_position_history"
|
|
33
|
+
|
|
34
|
+
def _write_position_open_to_redis(
|
|
35
|
+
self,
|
|
36
|
+
position_id: str,
|
|
37
|
+
exchange: str,
|
|
38
|
+
symbol: str,
|
|
39
|
+
position_side,
|
|
40
|
+
coin_quantity: float,
|
|
41
|
+
usdt_quantity: float,
|
|
42
|
+
open_ins_id: str,
|
|
43
|
+
open_price: float,
|
|
44
|
+
open_fee: float,
|
|
45
|
+
open_fee_rate: float,
|
|
46
|
+
open_time: int,
|
|
47
|
+
):
|
|
48
|
+
redis = self._server._redis
|
|
49
|
+
if redis is None:
|
|
50
|
+
return
|
|
51
|
+
data = {
|
|
52
|
+
"id": position_id,
|
|
53
|
+
"exchange": exchange,
|
|
54
|
+
"symbol": symbol,
|
|
55
|
+
"position_side": position_side.value,
|
|
56
|
+
"coin_quantity": coin_quantity,
|
|
57
|
+
"usdt_quantity": usdt_quantity,
|
|
58
|
+
"open_ins_id": open_ins_id,
|
|
59
|
+
"open_price": open_price,
|
|
60
|
+
"open_fee": open_fee,
|
|
61
|
+
"open_fee_rate": open_fee_rate,
|
|
62
|
+
"open_time": open_time,
|
|
63
|
+
"close_ins_id": None,
|
|
64
|
+
"close_price": 0,
|
|
65
|
+
"close_time": 0,
|
|
66
|
+
"status": PositionStatus.OPEN.value,
|
|
67
|
+
# 标识模拟
|
|
68
|
+
"is_mock": True,
|
|
69
|
+
}
|
|
70
|
+
redis.client.hset(self._redis_key_position, position_id, json.dumps(data))
|
|
71
|
+
|
|
72
|
+
def _write_position_close_to_redis(
|
|
73
|
+
self,
|
|
74
|
+
position_id: str,
|
|
75
|
+
exchange: str,
|
|
76
|
+
symbol: str,
|
|
77
|
+
position_side,
|
|
78
|
+
coin_quantity: float,
|
|
79
|
+
usdt_quantity: float,
|
|
80
|
+
open_ins_id: str,
|
|
81
|
+
open_price: float,
|
|
82
|
+
open_fee: float,
|
|
83
|
+
open_fee_rate: float,
|
|
84
|
+
open_time: int,
|
|
85
|
+
close_ins_id: str,
|
|
86
|
+
close_price: float,
|
|
87
|
+
close_fee: float,
|
|
88
|
+
close_fee_rate: float,
|
|
89
|
+
close_time: int,
|
|
90
|
+
):
|
|
91
|
+
redis = self._server._redis
|
|
92
|
+
if redis is None:
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
# 先从 redis 读取现有的 position 数据,获取 funding_rate_records 字段
|
|
96
|
+
funding_rate_records = None
|
|
97
|
+
try:
|
|
98
|
+
existing_position_json = redis.client.hget(
|
|
99
|
+
self._redis_key_position, position_id
|
|
100
|
+
)
|
|
101
|
+
if existing_position_json:
|
|
102
|
+
existing_position = json.loads(existing_position_json)
|
|
103
|
+
if existing_position and "funding_rate_records" in existing_position:
|
|
104
|
+
funding_rate_records = existing_position.get(
|
|
105
|
+
"funding_rate_records"
|
|
106
|
+
)
|
|
107
|
+
except Exception as e:
|
|
108
|
+
# 读取失败不影响后续流程,记录日志
|
|
109
|
+
self._logger.warning(
|
|
110
|
+
f"Failed to get funding_rate_records for position {position_id}: {e}"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
data = {
|
|
114
|
+
"id": position_id,
|
|
115
|
+
"exchange": exchange,
|
|
116
|
+
"symbol": symbol,
|
|
117
|
+
"position_side": position_side.value,
|
|
118
|
+
"coin_quantity": coin_quantity,
|
|
119
|
+
"usdt_quantity": usdt_quantity,
|
|
120
|
+
"open_ins_id": open_ins_id,
|
|
121
|
+
"open_price": open_price,
|
|
122
|
+
"open_fee": open_fee,
|
|
123
|
+
"open_fee_rate": open_fee_rate,
|
|
124
|
+
"open_time": open_time,
|
|
125
|
+
"close_ins_id": close_ins_id,
|
|
126
|
+
"close_price": close_price,
|
|
127
|
+
"close_fee": close_fee,
|
|
128
|
+
"close_fee_rate": close_fee_rate,
|
|
129
|
+
"close_time": close_time,
|
|
130
|
+
"status": PositionStatus.CLOSE.value,
|
|
131
|
+
# 标识模拟
|
|
132
|
+
"is_mock": True,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
# 如果存在 funding_rate_records,添加到 data 中
|
|
136
|
+
if funding_rate_records is not None:
|
|
137
|
+
data["funding_rate_records"] = funding_rate_records
|
|
138
|
+
|
|
139
|
+
redis.client.hdel(self._redis_key_position, position_id)
|
|
140
|
+
redis.client.rpush(self._redis_key_position_history, json.dumps(data))
|
|
141
|
+
|
|
142
|
+
def process_order(
|
|
143
|
+
self,
|
|
144
|
+
order: OrderInfo,
|
|
145
|
+
mock_fill_price: Optional[float] = None,
|
|
146
|
+
mock_fee_rate: float = 0.0005,
|
|
147
|
+
):
|
|
148
|
+
"""
|
|
149
|
+
处理模拟订单
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
order: 订单信息
|
|
153
|
+
mock_fill_price: 模拟成交价格,如果为None则使用订单的target_price
|
|
154
|
+
mock_fee_rate: 模拟手续费率,默认0.05%
|
|
155
|
+
"""
|
|
156
|
+
# 获取交易所
|
|
157
|
+
exchange = self._server._exchange
|
|
158
|
+
|
|
159
|
+
# 记录开始时间
|
|
160
|
+
start_time = time.time()
|
|
161
|
+
|
|
162
|
+
# 执行模拟订单处理
|
|
163
|
+
self._do_process_mock_order(exchange, order, mock_fill_price, mock_fee_rate, start_time)
|
|
164
|
+
|
|
165
|
+
def _do_process_mock_order(
|
|
166
|
+
self,
|
|
167
|
+
exchange: str,
|
|
168
|
+
order: OrderInfo,
|
|
169
|
+
mock_fill_price: Optional[float],
|
|
170
|
+
mock_fee_rate: float,
|
|
171
|
+
start_time: float,
|
|
172
|
+
):
|
|
173
|
+
# 获取mysql
|
|
174
|
+
mysql = self._server._mysql
|
|
175
|
+
|
|
176
|
+
ins_id = order.instruction_id
|
|
177
|
+
order_id = order.order_id
|
|
178
|
+
symbol = order.symbol
|
|
179
|
+
side = order.side
|
|
180
|
+
position_side = order.position_side
|
|
181
|
+
|
|
182
|
+
is_open = True
|
|
183
|
+
side_str = "开仓"
|
|
184
|
+
if position_side == PositionSide.LONG:
|
|
185
|
+
# 多单是正向理解的
|
|
186
|
+
if side == OrderSide.SELL:
|
|
187
|
+
side_str = "平仓"
|
|
188
|
+
is_open = False
|
|
189
|
+
else:
|
|
190
|
+
side_str = "开仓"
|
|
191
|
+
is_open = True
|
|
192
|
+
else:
|
|
193
|
+
# 空单是反向理解的
|
|
194
|
+
if side == OrderSide.SELL:
|
|
195
|
+
side_str = "开仓"
|
|
196
|
+
is_open = True
|
|
197
|
+
else:
|
|
198
|
+
side_str = "平仓"
|
|
199
|
+
is_open = False
|
|
200
|
+
|
|
201
|
+
self._logger.info(
|
|
202
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} step 1. {side_str}模拟挂单 {order_id}"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# 步骤1.挂单成功 插入到订单记录
|
|
206
|
+
current_time = int(time.time() * 1000)
|
|
207
|
+
|
|
208
|
+
if mysql is not None:
|
|
209
|
+
status = OrderStatus.CREATE
|
|
210
|
+
sql = f"""
|
|
211
|
+
INSERT INTO {self._mysql_table_name_order} (ins_id, exchange, symbol, side, position_side, orig_price, orig_coin_quantity, order_id, status, create_time, last_update_time, is_mock)
|
|
212
|
+
VALUES ( '{ins_id}', '{exchange}', '{symbol}', '{side.value}', '{order.position_side.value}', {order.current_price or order.target_price}, {order.quantity}, '{order_id}', '{status.value}', {current_time}, {current_time}, 1 );
|
|
213
|
+
"""
|
|
214
|
+
execute_ret = mysql.execute_sql(sql, True)
|
|
215
|
+
|
|
216
|
+
# 步骤2.模拟成交 - 直接使用模拟价格
|
|
217
|
+
# 如果没有指定模拟成交价,使用订单的当前价格
|
|
218
|
+
avg_price = mock_fill_price if mock_fill_price is not None else order.current_price or order.target_price
|
|
219
|
+
# 成交数量就是订单数量
|
|
220
|
+
executed_qty = order.quantity
|
|
221
|
+
# 计算出usdt数量
|
|
222
|
+
executed_usdt = avg_price * executed_qty
|
|
223
|
+
# 计算手续费
|
|
224
|
+
fee = executed_usdt * mock_fee_rate
|
|
225
|
+
# 费率
|
|
226
|
+
fee_rate = mock_fee_rate
|
|
227
|
+
|
|
228
|
+
# 模拟处理时间(可以立即完成)
|
|
229
|
+
end_time = time.time()
|
|
230
|
+
cost_time = end_time - start_time
|
|
231
|
+
|
|
232
|
+
self._logger.info(
|
|
233
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} step 2. {side_str}模拟订单 {order_id} 成交 耗时 {int(cost_time * 1000)}ms"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
# 步骤3.把最终持仓写进去
|
|
237
|
+
current_time = int(time.time() * 1000)
|
|
238
|
+
|
|
239
|
+
if mysql is None:
|
|
240
|
+
self._logger.warning(
|
|
241
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} 仅操作,没有入库,请设置 mysql!!"
|
|
242
|
+
)
|
|
243
|
+
return
|
|
244
|
+
|
|
245
|
+
status = OrderStatus.FINISH
|
|
246
|
+
# 更新写入最终信息
|
|
247
|
+
sql = f"""
|
|
248
|
+
UPDATE {self._mysql_table_name_order}
|
|
249
|
+
SET price = {avg_price}, coin_quantity = {executed_qty}, usdt_quantity = {executed_usdt}, fee = {fee}, fee_rate = {fee_rate}, status = '{status.value}', last_update_time = {current_time}
|
|
250
|
+
WHERE ins_id = '{ins_id}' AND exchange = '{exchange}' AND symbol = '{symbol}';
|
|
251
|
+
"""
|
|
252
|
+
execute_ret = mysql.execute_sql(sql, True)
|
|
253
|
+
|
|
254
|
+
self._logger.info(
|
|
255
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} step 2. 模拟订单成交 {order_id}, {side_str}价格 {avg_price}, {side_str}数量 {executed_qty}, {side_str}usdt {executed_usdt}"
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
if is_open:
|
|
259
|
+
# 同时插入持仓表
|
|
260
|
+
position_id = uuid_utils.generate_uuid()
|
|
261
|
+
sql = f"""
|
|
262
|
+
INSERT INTO {self._mysql_table_name_position} (id, exchange, symbol, position_side, coin_quantity, usdt_quantity, open_ins_id, open_price, open_fee, open_fee_rate, open_time, status, is_mock)
|
|
263
|
+
VALUES ( '{position_id}', '{exchange}', '{symbol}', '{position_side.value}', '{executed_qty}', '{executed_usdt}', '{ins_id}', '{avg_price}', '{fee}', '{fee_rate}', {current_time}, '{PositionStatus.OPEN.value}', 1 );
|
|
264
|
+
"""
|
|
265
|
+
execute_ret = mysql.execute_sql(sql, True)
|
|
266
|
+
|
|
267
|
+
self._logger.info(
|
|
268
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} step 3. 创建持仓记录 {position_id}"
|
|
269
|
+
)
|
|
270
|
+
try:
|
|
271
|
+
self._write_position_open_to_redis(
|
|
272
|
+
position_id,
|
|
273
|
+
exchange,
|
|
274
|
+
symbol,
|
|
275
|
+
position_side,
|
|
276
|
+
executed_qty,
|
|
277
|
+
executed_usdt,
|
|
278
|
+
ins_id,
|
|
279
|
+
avg_price,
|
|
280
|
+
fee,
|
|
281
|
+
fee_rate,
|
|
282
|
+
current_time,
|
|
283
|
+
)
|
|
284
|
+
except:
|
|
285
|
+
pass
|
|
286
|
+
else:
|
|
287
|
+
# 需要找到对应的持仓记录
|
|
288
|
+
sql = f"""
|
|
289
|
+
SELECT * FROM {self._mysql_table_name_position}
|
|
290
|
+
WHERE exchange = '{exchange}' AND symbol = '{symbol}' AND position_side = '{position_side.value}' AND status = '{PositionStatus.OPEN.value}' AND is_mock = 1
|
|
291
|
+
ORDER BY open_time ASC;
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
# 如果有指定仓位id,就用指定的
|
|
295
|
+
if hasattr(order, "position_id") and order.position_id:
|
|
296
|
+
sql = f"""
|
|
297
|
+
SELECT * FROM {self._mysql_table_name_position}
|
|
298
|
+
WHERE id = '{order.position_id}' AND status = '{PositionStatus.OPEN.value}' AND is_mock = 1
|
|
299
|
+
"""
|
|
300
|
+
self._logger.info(
|
|
301
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} get position by id {order.position_id}"
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
execute_ret = mysql.execute_sql(sql)
|
|
305
|
+
try:
|
|
306
|
+
row = execute_ret.fetchone()
|
|
307
|
+
position_id = row.id
|
|
308
|
+
if position_id is not None:
|
|
309
|
+
# 更新持仓信息
|
|
310
|
+
sql = f"""
|
|
311
|
+
UPDATE {self._mysql_table_name_position}
|
|
312
|
+
SET close_ins_id = '{ins_id}', close_price = {avg_price}, close_fee = '{fee}', close_fee_rate = '{fee_rate}', close_time = {current_time}, status = '{PositionStatus.CLOSE.value}'
|
|
313
|
+
WHERE id = '{position_id}';
|
|
314
|
+
"""
|
|
315
|
+
execute_ret = mysql.execute_sql(sql, True)
|
|
316
|
+
|
|
317
|
+
self._logger.info(
|
|
318
|
+
f"[MOCK] {ins_id}_{exchange}_{symbol} step 3. 更新持仓记录 {position_id}"
|
|
319
|
+
)
|
|
320
|
+
try:
|
|
321
|
+
self._write_position_close_to_redis(
|
|
322
|
+
position_id,
|
|
323
|
+
exchange,
|
|
324
|
+
symbol,
|
|
325
|
+
position_side,
|
|
326
|
+
float(row.coin_quantity),
|
|
327
|
+
float(row.usdt_quantity),
|
|
328
|
+
row.open_ins_id,
|
|
329
|
+
float(row.open_price),
|
|
330
|
+
float(row.open_fee),
|
|
331
|
+
float(row.open_fee_rate),
|
|
332
|
+
int(row.open_time),
|
|
333
|
+
ins_id,
|
|
334
|
+
avg_price,
|
|
335
|
+
fee,
|
|
336
|
+
fee_rate,
|
|
337
|
+
current_time,
|
|
338
|
+
)
|
|
339
|
+
except:
|
|
340
|
+
pass
|
|
341
|
+
except:
|
|
342
|
+
pass
|
|
343
|
+
|
|
344
|
+
return True
|
|
@@ -194,7 +194,7 @@ class OrderHelper:
|
|
|
194
194
|
status = OrderStatus.CREATE
|
|
195
195
|
sql = f"""
|
|
196
196
|
INSERT INTO {self._mysql_table_name_order} (ins_id, exchange, symbol, side, position_side, orig_price, orig_coin_quantity, order_id, status, create_time, last_update_time)
|
|
197
|
-
VALUES ( '{ins_id}', '{exchange}', '{symbol}', '{side.value}', '{order.position_side.value}', {order.target_price}, {order.quantity}, '{order_id}', '{status.value}', {current_time}, {current_time} );
|
|
197
|
+
VALUES ( '{ins_id}', '{exchange}', '{symbol}', '{side.value}', '{order.position_side.value}', {order.current_price or order.target_price}, {order.quantity}, '{order_id}', '{status.value}', {current_time}, {current_time} );
|
|
198
198
|
"""
|
|
199
199
|
execute_ret = mysql.execute_sql(sql, True)
|
|
200
200
|
|