openfund-core 0.0.4__py3-none-any.whl → 1.0.5__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.
- core/Exchange.py +533 -0
- core/main.py +23 -0
- core/smc/SMCBase.py +130 -0
- core/smc/SMCFVG.py +86 -0
- core/smc/SMCLiquidity.py +7 -0
- core/smc/SMCOrderBlock.py +280 -0
- core/smc/SMCPDArray.py +75 -0
- core/smc/SMCStruct.py +296 -0
- core/smc/__init__.py +0 -0
- core/utils/OPTools.py +30 -0
- openfund_core-1.0.5.dist-info/METADATA +48 -0
- openfund_core-1.0.5.dist-info/RECORD +15 -0
- {openfund_core-0.0.4.dist-info → openfund_core-1.0.5.dist-info}/WHEEL +1 -1
- openfund_core-1.0.5.dist-info/entry_points.txt +3 -0
- openfund/core/__init__.py +0 -14
- openfund/core/api_tools/__init__.py +0 -16
- openfund/core/api_tools/binance_futures_tools.py +0 -23
- openfund/core/api_tools/binance_tools.py +0 -26
- openfund/core/api_tools/enums.py +0 -539
- openfund/core/base_collector.py +0 -72
- openfund/core/base_tool.py +0 -58
- openfund/core/factory.py +0 -97
- openfund/core/openfund_old/continuous_klines.py +0 -153
- openfund/core/openfund_old/depth.py +0 -92
- openfund/core/openfund_old/historical_trades.py +0 -123
- openfund/core/openfund_old/index_info.py +0 -67
- openfund/core/openfund_old/index_price_kline.py +0 -118
- openfund/core/openfund_old/klines.py +0 -95
- openfund/core/openfund_old/klines_qrr.py +0 -103
- openfund/core/openfund_old/mark_price.py +0 -121
- openfund/core/openfund_old/mark_price_klines.py +0 -122
- openfund/core/openfund_old/ticker_24hr_price_change.py +0 -99
- openfund/core/pyopenfund.py +0 -85
- openfund/core/services/um_futures_collector.py +0 -142
- openfund/core/sycu_exam/__init__.py +0 -1
- openfund/core/sycu_exam/exam.py +0 -19
- openfund/core/sycu_exam/random_grade_cplus.py +0 -440
- openfund/core/sycu_exam/random_grade_web.py +0 -404
- openfund/core/utils/time_tools.py +0 -25
- openfund_core-0.0.4.dist-info/LICENSE +0 -201
- openfund_core-0.0.4.dist-info/METADATA +0 -67
- openfund_core-0.0.4.dist-info/RECORD +0 -30
- {openfund/core/openfund_old → core}/__init__.py +0 -0
core/Exchange.py
ADDED
@@ -0,0 +1,533 @@
|
|
1
|
+
import logging
|
2
|
+
import time
|
3
|
+
import ccxt
|
4
|
+
import pandas as pd
|
5
|
+
|
6
|
+
|
7
|
+
from decimal import Decimal
|
8
|
+
from core.utils.OPTools import OPTools
|
9
|
+
from ccxt.base.exchange import ConstructorArgs
|
10
|
+
|
11
|
+
|
12
|
+
class Exchange:
|
13
|
+
BUY_SIDE = 'buy'
|
14
|
+
SELL_SIDE = 'sell'
|
15
|
+
LONG_KEY = 'long'
|
16
|
+
SHORT_KEY = 'short'
|
17
|
+
SIDE_KEY = 'side'
|
18
|
+
SYMBOL_KEY = 'symbol'
|
19
|
+
ENTRY_PRICE_KEY = 'entryPrice'
|
20
|
+
MARK_PRICE_KEY = 'markPrice'
|
21
|
+
CONTRACTS_KEY = 'contracts'
|
22
|
+
def __init__(self, config:ConstructorArgs, exchangeKey:str = "okx",) :
|
23
|
+
# 配置交易所
|
24
|
+
self.exchange = getattr(ccxt, exchangeKey)(config)
|
25
|
+
self.logger = logging.getLogger(__name__)
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
def getMarket(self, symbol:str):
|
30
|
+
# 配置交易对
|
31
|
+
self.exchange.load_markets()
|
32
|
+
|
33
|
+
return self.exchange.market(symbol)
|
34
|
+
|
35
|
+
def get_tick_size(self,symbol) -> Decimal:
|
36
|
+
|
37
|
+
market = self.getMarket(symbol)
|
38
|
+
if market and 'precision' in market and 'price' in market['precision']:
|
39
|
+
return OPTools.toDecimal(market['precision']['price'])
|
40
|
+
else:
|
41
|
+
raise ValueError(f"{symbol}: 无法从市场数据中获取价格精度")
|
42
|
+
|
43
|
+
def amount_to_precision(self,symbol, contract_size):
|
44
|
+
return self.exchange.amount_to_precision(symbol, contract_size)
|
45
|
+
|
46
|
+
def get_position_mode(self):
|
47
|
+
|
48
|
+
try:
|
49
|
+
# 假设获取账户持仓模式的 API
|
50
|
+
response = self.exchange.private_get_account_config()
|
51
|
+
data = response.get('data', [])
|
52
|
+
if data and isinstance(data, list):
|
53
|
+
# 取列表的第一个元素(假设它是一个字典),然后获取 'posMode'
|
54
|
+
position_mode = data[0].get('posMode', 'single') # 默认值为单向
|
55
|
+
|
56
|
+
return position_mode
|
57
|
+
else:
|
58
|
+
|
59
|
+
return 'single' # 返回默认值
|
60
|
+
except Exception as e:
|
61
|
+
error_message = f"Error fetching position mode: {e}"
|
62
|
+
self.logger.error(error_message)
|
63
|
+
raise Exception(error_message)
|
64
|
+
|
65
|
+
def set_leverage(self,symbol, leverage, mgnMode='isolated',posSide=None):
|
66
|
+
try:
|
67
|
+
# 设置杠杆
|
68
|
+
params = {
|
69
|
+
# 'instId': instId,
|
70
|
+
'leverage': leverage,
|
71
|
+
'marginMode': mgnMode
|
72
|
+
}
|
73
|
+
if posSide:
|
74
|
+
params['side'] = posSide
|
75
|
+
|
76
|
+
self.exchange.set_leverage(leverage, symbol=symbol, params=params)
|
77
|
+
self.logger.info(f"{symbol} Successfully set leverage to {leverage}x")
|
78
|
+
except Exception as e:
|
79
|
+
error_message = f"{symbol} Error setting leverage: {e}"
|
80
|
+
self.logger.error(error_message)
|
81
|
+
raise Exception(error_message)
|
82
|
+
# 获取价格精度
|
83
|
+
def get_precision_length(self,symbol) -> int:
|
84
|
+
tick_size = self.get_tick_size(symbol)
|
85
|
+
return len(f"{tick_size:.15f}".rstrip('0').split('.')[1]) if '.' in f"{tick_size:.15f}" else 0
|
86
|
+
|
87
|
+
def format_price(self, symbol, price:Decimal) -> str:
|
88
|
+
precision = self.get_precision_length(symbol)
|
89
|
+
return f"{price:.{precision}f}"
|
90
|
+
|
91
|
+
def convert_contract(self, symbol, amount, price:Decimal, direction='cost_to_contract'):
|
92
|
+
"""
|
93
|
+
进行合约与币的转换
|
94
|
+
:param symbol: 交易对符号,如 'BTC/USDT:USDT'
|
95
|
+
:param amount: 输入的数量,可以是合约数量或币的数量
|
96
|
+
:param direction: 转换方向,'amount_to_contract' 表示从数量转换为合约,'cost_to_contract' 表示从金额转换为合约
|
97
|
+
:return: 转换后的数量
|
98
|
+
"""
|
99
|
+
|
100
|
+
# 获取合约规模
|
101
|
+
market_contractSize = OPTools.toDecimal(self.getMarket(symbol)['contractSize'])
|
102
|
+
amount = OPTools.toDecimal(amount)
|
103
|
+
if direction == 'amount_to_contract':
|
104
|
+
contract_size = amount / market_contractSize
|
105
|
+
elif direction == 'cost_to_contract':
|
106
|
+
contract_size = amount / price / market_contractSize
|
107
|
+
else:
|
108
|
+
raise Exception(f"{symbol}:{direction} 是无效的转换方向,请输入 'amount_to_contract' 或 'cost_to_contract'。")
|
109
|
+
|
110
|
+
return self.amount_to_precision(symbol, contract_size)
|
111
|
+
|
112
|
+
|
113
|
+
def cancel_all_orders(self, symbol):
|
114
|
+
max_retries = 3
|
115
|
+
retry_count = 0
|
116
|
+
|
117
|
+
while retry_count < max_retries:
|
118
|
+
try:
|
119
|
+
# 获取所有未完成订单
|
120
|
+
params = {
|
121
|
+
# 'instId': instId
|
122
|
+
}
|
123
|
+
open_orders = self.exchange.fetch_open_orders(symbol=symbol, params=params)
|
124
|
+
|
125
|
+
# 批量取消所有订单
|
126
|
+
if open_orders:
|
127
|
+
order_ids = [order['id'] for order in open_orders]
|
128
|
+
self.exchange.cancel_orders(order_ids, symbol, params=params)
|
129
|
+
|
130
|
+
self.logger.debug(f"{symbol}: {order_ids} 挂单取消成功.")
|
131
|
+
else:
|
132
|
+
self.logger.debug(f"{symbol}: 无挂单.")
|
133
|
+
return True
|
134
|
+
|
135
|
+
except Exception as e:
|
136
|
+
retry_count += 1
|
137
|
+
if retry_count == max_retries:
|
138
|
+
error_message = f"{symbol} 取消挂单失败(重试{retry_count}次): {str(e)}"
|
139
|
+
self.logger.error(error_message)
|
140
|
+
raise Exception(error_message)
|
141
|
+
else:
|
142
|
+
self.logger.warning(f"{symbol} 取消挂单失败,正在进行第{retry_count}次重试: {str(e)}")
|
143
|
+
time.sleep(0.1) # 重试前等待0.1秒
|
144
|
+
|
145
|
+
def cancel_all_algo_orders(self, symbol, attachType=None) -> bool:
|
146
|
+
"""_summary_
|
147
|
+
|
148
|
+
Args:
|
149
|
+
symbol (_type_): _description_
|
150
|
+
attachType (_type_, optional): "TP"|"SL". Defaults to None.
|
151
|
+
"""
|
152
|
+
|
153
|
+
params = {
|
154
|
+
"ordType": "conditional",
|
155
|
+
}
|
156
|
+
try:
|
157
|
+
orders = self.fetch_open_orders(symbol=symbol,params=params)
|
158
|
+
except Exception as e:
|
159
|
+
error_message = f"!!{symbol} : Error fetching open orders: {e}"
|
160
|
+
self.logger.error(error_message)
|
161
|
+
raise Exception(error_message)
|
162
|
+
|
163
|
+
|
164
|
+
if len(orders) == 0:
|
165
|
+
self.logger.debug(f"{symbol} 未设置策略订单列表。")
|
166
|
+
return True
|
167
|
+
|
168
|
+
algo_ids = []
|
169
|
+
if attachType and attachType == 'SL':
|
170
|
+
algo_ids = [order['id'] for order in orders if order['stopLossPrice'] and order['stopLossPrice'] > 0.0 ]
|
171
|
+
elif attachType and attachType == 'TP':
|
172
|
+
algo_ids = [order['id'] for order in orders if order['takeProfitPrice'] and order['takeProfitPrice'] > 0.0]
|
173
|
+
else :
|
174
|
+
algo_ids = [order['id'] for order in orders ]
|
175
|
+
|
176
|
+
if len(algo_ids) == 0 :
|
177
|
+
self.logger.debug(f"{symbol} 未设置策略订单列表。")
|
178
|
+
return True
|
179
|
+
|
180
|
+
max_retries = 3
|
181
|
+
retry_count = 0
|
182
|
+
|
183
|
+
while retry_count < max_retries:
|
184
|
+
try:
|
185
|
+
params = {
|
186
|
+
"algoId": algo_ids,
|
187
|
+
"trigger": 'trigger'
|
188
|
+
}
|
189
|
+
rs = self.exchange.cancel_orders(ids=algo_ids, symbol=symbol, params=params)
|
190
|
+
|
191
|
+
return len(rs) > 0
|
192
|
+
|
193
|
+
except Exception as e:
|
194
|
+
retry_count += 1
|
195
|
+
if retry_count == max_retries:
|
196
|
+
error_message = f"!!{symbol} : Error cancelling order {algo_ids}: {e}"
|
197
|
+
self.logger.error(error_message)
|
198
|
+
raise Exception(error_message)
|
199
|
+
|
200
|
+
self.logger.warning(f"{symbol} : Error cancelling order {algo_ids}: {str(e)}")
|
201
|
+
time.sleep(0.1) # 重试前等待0.1秒
|
202
|
+
def place_algo_orders(self, symbol, position, price: Decimal, order_type, sl_or_tp='SL', params={}) -> bool:
|
203
|
+
"""
|
204
|
+
下单
|
205
|
+
Args:
|
206
|
+
symbol: 交易对
|
207
|
+
position: 仓位
|
208
|
+
price: 下单价格
|
209
|
+
order_type: 订单类型
|
210
|
+
"""
|
211
|
+
# 计算下单数量
|
212
|
+
amount = abs(position[self.CONTRACTS_KEY])
|
213
|
+
|
214
|
+
if amount <= 0:
|
215
|
+
self.logger.warning(f"{symbol}: amount is 0 for {symbol}")
|
216
|
+
return
|
217
|
+
|
218
|
+
# 止损单逻辑
|
219
|
+
adjusted_price = self.format_price(symbol, price)
|
220
|
+
|
221
|
+
# 默认市价止损,委托价格为-1时,执行市价止损。
|
222
|
+
sl_params = {
|
223
|
+
**params,
|
224
|
+
'slTriggerPx':adjusted_price ,
|
225
|
+
'slOrdPx':'-1', # 委托价格为-1时,执行市价止损
|
226
|
+
# 'slOrdPx' : adjusted_price,
|
227
|
+
'slTriggerPxType':'last',
|
228
|
+
'tdMode':position['marginMode'],
|
229
|
+
'sz': str(amount),
|
230
|
+
'cxlOnClosePos': True,
|
231
|
+
'reduceOnly':True,
|
232
|
+
}
|
233
|
+
|
234
|
+
tp_params = {
|
235
|
+
**params,
|
236
|
+
'tpTriggerPx':adjusted_price,
|
237
|
+
'tpOrdPx' : adjusted_price,
|
238
|
+
'tpOrdKind': 'condition',
|
239
|
+
'tpTriggerPxType':'last',
|
240
|
+
'tdMode':position['marginMode'],
|
241
|
+
'sz': str(amount),
|
242
|
+
'cxlOnClosePos': True,
|
243
|
+
'reduceOnly':True
|
244
|
+
}
|
245
|
+
|
246
|
+
order_params = sl_params if sl_or_tp == 'SL' else tp_params
|
247
|
+
# order_params.update(params)
|
248
|
+
|
249
|
+
if order_type == 'limit' and sl_or_tp =='SL':
|
250
|
+
order_params['slOrdPx'] = adjusted_price
|
251
|
+
|
252
|
+
orderSide = self.BUY_SIDE if position[self.SIDE_KEY] == self.SHORT_KEY else self.SELL_SIDE # 和持仓反向相反下单
|
253
|
+
|
254
|
+
order = {
|
255
|
+
'symbol': symbol,
|
256
|
+
'side': orderSide,
|
257
|
+
'type': order_type,
|
258
|
+
'amount': amount,
|
259
|
+
'price': adjusted_price,
|
260
|
+
'params': order_params
|
261
|
+
}
|
262
|
+
|
263
|
+
max_retries = 3
|
264
|
+
retry_count = 0
|
265
|
+
self.logger.debug(f"{symbol} : Pre Algo Order placed: {order} ")
|
266
|
+
while retry_count < max_retries:
|
267
|
+
try:
|
268
|
+
|
269
|
+
self.exchange.create_order(
|
270
|
+
**order
|
271
|
+
# symbol=symbol,
|
272
|
+
# type=order_type,
|
273
|
+
# price=adjusted_price,
|
274
|
+
# side=orderSide,
|
275
|
+
# amount=amount,
|
276
|
+
# params=order_params
|
277
|
+
)
|
278
|
+
|
279
|
+
break
|
280
|
+
|
281
|
+
except ccxt.NetworkError as e:
|
282
|
+
# 处理网络相关错误
|
283
|
+
retry_count += 1
|
284
|
+
self.logger.warning(f"{symbol} : 设置止盈止损时发生网络错误,正在进行第{retry_count}次重试: {str(e)}")
|
285
|
+
time.sleep(0.1) # 重试前等待1秒
|
286
|
+
continue
|
287
|
+
except ccxt.ExchangeError as e:
|
288
|
+
# 处理交易所API相关错误
|
289
|
+
retry_count += 1
|
290
|
+
self.logger.warning(f"{symbol} : 设置止盈止损单时发生交易所错误,正在进行第{retry_count}次重试: {str(e)}")
|
291
|
+
time.sleep(0.1)
|
292
|
+
continue
|
293
|
+
except Exception as e:
|
294
|
+
# 处理其他未预期的错误
|
295
|
+
retry_count += 1
|
296
|
+
self.logger.warning(f"{symbol} : 设置止盈止损单时发生未知错误,正在进行第{retry_count}次重试: {str(e)}")
|
297
|
+
time.sleep(0.1)
|
298
|
+
continue
|
299
|
+
|
300
|
+
if retry_count >= max_retries:
|
301
|
+
# 重试次数用完仍未成功设置止损单
|
302
|
+
error_message = f"!! {symbol}: 设置止盈止损单时重试次数用完仍未成功设置成功。 "
|
303
|
+
self.logger.error(error_message)
|
304
|
+
raise Exception(error_message)
|
305
|
+
self.logger.debug(f"{symbol} : --------- ++ Order placed done. --------")
|
306
|
+
return True
|
307
|
+
|
308
|
+
|
309
|
+
def place_order(self, symbol, price: Decimal, amount_usdt, side, leverage=20, order_type='limit', params={}) -> bool:
|
310
|
+
"""
|
311
|
+
下单
|
312
|
+
Args:
|
313
|
+
symbol: 交易对
|
314
|
+
price: 下单价格
|
315
|
+
amount_usdt: 下单金额
|
316
|
+
side: 下单方向
|
317
|
+
order_type: 订单类型
|
318
|
+
"""
|
319
|
+
# 格式化价格
|
320
|
+
adjusted_price = self.format_price(symbol, price)
|
321
|
+
|
322
|
+
if amount_usdt <= 0:
|
323
|
+
self.logger.warning(f"{symbol}: amount_usdt must be greater than 0")
|
324
|
+
return
|
325
|
+
|
326
|
+
pos_side = self.LONG_KEY if side == self.BUY_SIDE else self.SHORT_KEY
|
327
|
+
|
328
|
+
# 设置杠杆
|
329
|
+
self.set_leverage(symbol=symbol, leverage=leverage, mgnMode='isolated',posSide=pos_side)
|
330
|
+
# 20250220 SWAP类型计算合约数量
|
331
|
+
contract_size = self.convert_contract(symbol=symbol, price = OPTools.toDecimal(adjusted_price) ,amount=amount_usdt)
|
332
|
+
|
333
|
+
order_params = {
|
334
|
+
**params,
|
335
|
+
"tdMode": 'isolated',
|
336
|
+
"side": side,
|
337
|
+
"ordType": order_type,
|
338
|
+
"sz": contract_size,
|
339
|
+
"px": adjusted_price
|
340
|
+
}
|
341
|
+
|
342
|
+
# # 模拟盘(demo_trading)需要 posSide
|
343
|
+
# if self.is_demo_trading == 1 :
|
344
|
+
# params["posSide"] = pos_side
|
345
|
+
|
346
|
+
order = {
|
347
|
+
'symbol': symbol,
|
348
|
+
'side': side,
|
349
|
+
'type': order_type,
|
350
|
+
'amount': contract_size,
|
351
|
+
'price': adjusted_price,
|
352
|
+
'params': order_params
|
353
|
+
}
|
354
|
+
|
355
|
+
max_retries = 3
|
356
|
+
retry_count = 0
|
357
|
+
|
358
|
+
while retry_count < max_retries:
|
359
|
+
try:
|
360
|
+
# 使用ccxt创建订单
|
361
|
+
self.logger.debug(f"{symbol} : Pre Order placed: {order} ")
|
362
|
+
order_result = self.exchange.create_order(
|
363
|
+
**order
|
364
|
+
# symbol=symbol,
|
365
|
+
# type='limit',
|
366
|
+
# side=side,
|
367
|
+
# amount=amount_usdt,
|
368
|
+
# price=float(adjusted_price),
|
369
|
+
# params=params
|
370
|
+
)
|
371
|
+
except ccxt.NetworkError as e:
|
372
|
+
# 处理网络相关错误
|
373
|
+
retry_count += 1
|
374
|
+
self.logger.warning(f"{symbol} : 设置下单时发生网络错误,正在进行第{retry_count}次重试: {str(e)}")
|
375
|
+
time.sleep(0.1) # 重试前等待1秒
|
376
|
+
continue
|
377
|
+
except ccxt.ExchangeError as e:
|
378
|
+
# 处理交易所API相关错误
|
379
|
+
retry_count += 1
|
380
|
+
self.logger.warning(f"{symbol} : 设置下单时发生交易所错误,正在进行第{retry_count}次重试: {str(e)}")
|
381
|
+
time.sleep(0.1)
|
382
|
+
continue
|
383
|
+
except Exception as e:
|
384
|
+
# 处理其他未预期的错误
|
385
|
+
retry_count += 1
|
386
|
+
self.logger.warning(f"{symbol} : 设置下单时发生未知错误,正在进行第{retry_count}次重试: {str(e)}")
|
387
|
+
time.sleep(0.1)
|
388
|
+
continue
|
389
|
+
if retry_count >= max_retries:
|
390
|
+
# 重试次数用完仍未成功设置止损单
|
391
|
+
error_message = f"!! {symbol}: 设置止盈止损单时重试次数用完仍未成功设置成功。 "
|
392
|
+
self.logger.error(error_message)
|
393
|
+
raise Exception(error_message)
|
394
|
+
self.logger.debug(f"{symbol} : --------- ++ Order placed done. --------")
|
395
|
+
return True
|
396
|
+
|
397
|
+
def fetch_position(self, symbol):
|
398
|
+
"""_summary_
|
399
|
+
|
400
|
+
Args:
|
401
|
+
symbol (_type_): _description_
|
402
|
+
|
403
|
+
Returns:
|
404
|
+
_type_: _description_
|
405
|
+
"""
|
406
|
+
|
407
|
+
max_retries = 3
|
408
|
+
retry_count = 0
|
409
|
+
|
410
|
+
while retry_count < max_retries:
|
411
|
+
try:
|
412
|
+
position = self.exchange.fetch_position(symbol=symbol)
|
413
|
+
if position :
|
414
|
+
# self.logger.debug(f"{symbol} 有持仓合约数: {position['contracts']}")
|
415
|
+
return position
|
416
|
+
return None
|
417
|
+
except Exception as e:
|
418
|
+
retry_count += 1
|
419
|
+
if retry_count == max_retries:
|
420
|
+
error_message = f"!!{symbol} 获取持仓失败(重试{retry_count}次): {str(e)}"
|
421
|
+
self.logger.error(error_message)
|
422
|
+
raise Exception(error_message)
|
423
|
+
|
424
|
+
self.logger.warning(f"{symbol} 检查持仓失败,正在进行第{retry_count}次重试: {str(e)}")
|
425
|
+
time.sleep(0.1) # 重试前等待0.1秒
|
426
|
+
|
427
|
+
def fetch_positions(self):
|
428
|
+
"""_summary_
|
429
|
+
Returns:
|
430
|
+
_type_: _description_
|
431
|
+
"""
|
432
|
+
max_retries = 3
|
433
|
+
retry_count = 0
|
434
|
+
|
435
|
+
while retry_count < max_retries:
|
436
|
+
try:
|
437
|
+
positions = self.exchange.fetch_positions()
|
438
|
+
return positions
|
439
|
+
except Exception as e:
|
440
|
+
retry_count += 1
|
441
|
+
if retry_count == max_retries:
|
442
|
+
error_message = f"!! 获取持仓列表失败(重试{retry_count}次): {str(e)}"
|
443
|
+
self.logger.error(error_message)
|
444
|
+
raise Exception(error_message)
|
445
|
+
|
446
|
+
self.logger.warning(f"获取持仓列表失败,正在进行第{retry_count}次重试: {str(e)}")
|
447
|
+
time.sleep(0.1) # 重试前等待0.1秒
|
448
|
+
|
449
|
+
def fetch_open_orders(self,symbol,params={}):
|
450
|
+
max_retries = 3
|
451
|
+
retry_count = 0
|
452
|
+
|
453
|
+
while retry_count < max_retries:
|
454
|
+
try:
|
455
|
+
orders = self.exchange.fetch_open_orders(symbol=symbol,params=params)
|
456
|
+
return orders
|
457
|
+
|
458
|
+
except Exception as e:
|
459
|
+
retry_count += 1
|
460
|
+
if retry_count == max_retries:
|
461
|
+
error_message = f"{symbol} : fetching open orders(retry {retry_count} times): {str(e)}"
|
462
|
+
self.logger.error(error_message)
|
463
|
+
raise Exception(error_message)
|
464
|
+
|
465
|
+
self.logger.warning(f"{symbol} : Error fetching open orders: {str(e)}")
|
466
|
+
time.sleep(0.1) # 重试前等待0.1秒
|
467
|
+
def get_market_price(self, symbol) -> Decimal:
|
468
|
+
"""
|
469
|
+
获取最新价格
|
470
|
+
Args:
|
471
|
+
symbol: 交易对
|
472
|
+
"""
|
473
|
+
max_retries = 3
|
474
|
+
retry_count = 0
|
475
|
+
|
476
|
+
while retry_count < max_retries:
|
477
|
+
try:
|
478
|
+
ticker = self.exchange.fetch_ticker(symbol)
|
479
|
+
if ticker and 'last' in ticker:
|
480
|
+
return OPTools.toDecimal(ticker['last'])
|
481
|
+
else:
|
482
|
+
raise Exception(f"{symbol} : Unexpected response structure or missing 'last' price")
|
483
|
+
except Exception as e:
|
484
|
+
retry_count += 1
|
485
|
+
if retry_count == max_retries:
|
486
|
+
error_message = f"{symbol} 获取最新价格失败(重试{retry_count}次): {str(e)}"
|
487
|
+
self.logger.error(error_message)
|
488
|
+
raise Exception(error_message)
|
489
|
+
|
490
|
+
def get_historical_klines(self, symbol, bar='15m', limit=300, after:str=None, params={}):
|
491
|
+
"""
|
492
|
+
获取历史K线数据
|
493
|
+
Args:
|
494
|
+
symbol: 交易对
|
495
|
+
bar: K线周期
|
496
|
+
limit: 数据条数
|
497
|
+
after: 之后时间,格式为 "2025-05-21 23:00:00+08:00"
|
498
|
+
"""
|
499
|
+
|
500
|
+
params = {
|
501
|
+
**params,
|
502
|
+
# 'instId': instId,
|
503
|
+
}
|
504
|
+
since = None
|
505
|
+
if after:
|
506
|
+
since = self.exchange.parse8601(after)
|
507
|
+
limit = None
|
508
|
+
if since:
|
509
|
+
params['paginate'] = True
|
510
|
+
|
511
|
+
klines = self.exchange.fetch_ohlcv(symbol, timeframe=bar,since=since, limit=limit, params=params)
|
512
|
+
# if 'data' in response and len(response['data']) > 0:
|
513
|
+
if klines :
|
514
|
+
# return response['data']
|
515
|
+
return klines
|
516
|
+
else:
|
517
|
+
raise Exception(f"{symbol} : Unexpected response structure or missing candlestick data")
|
518
|
+
|
519
|
+
def get_historical_klines_df(self, symbol, bar='15m', limit=300, after:str=None, params={}) -> pd.DataFrame:
|
520
|
+
klines = self.get_historical_klines(symbol, bar=bar, limit=limit, after=after, params=params)
|
521
|
+
return self.format_klines(klines)
|
522
|
+
|
523
|
+
def format_klines(self, klines) -> pd.DataFrame:
|
524
|
+
"""_summary_
|
525
|
+
格式化K线数据
|
526
|
+
Args:
|
527
|
+
klines (_type_): _description_
|
528
|
+
"""
|
529
|
+
klines_df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
530
|
+
# 转换时间戳为日期时间
|
531
|
+
klines_df['timestamp'] = pd.to_datetime(klines_df['timestamp'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Asia/Shanghai')
|
532
|
+
|
533
|
+
return klines_df
|
core/main.py
ADDED
@@ -0,0 +1,23 @@
|
|
1
|
+
import logging
|
2
|
+
from pyfiglet import Figlet
|
3
|
+
|
4
|
+
def main():
|
5
|
+
|
6
|
+
# import importlib.metadata
|
7
|
+
# package_name = __package__ or "openfund-core"
|
8
|
+
# version = importlib.metadata.version("openfund-core")
|
9
|
+
|
10
|
+
# 创建日志记录器并设置输出到屏幕
|
11
|
+
logger = logging.getLogger(__name__)
|
12
|
+
console_handler = logging.StreamHandler()
|
13
|
+
logger.addHandler(console_handler)
|
14
|
+
# # 设置日志级别为INFO
|
15
|
+
logger.setLevel(logging.INFO)
|
16
|
+
|
17
|
+
f = Figlet(font="standard") # 字体可选(如 "block", "bubble")
|
18
|
+
logger.info(f"\n{f.renderText("OpenFund Core")}")
|
19
|
+
|
20
|
+
|
21
|
+
|
22
|
+
if __name__ == "__main__":
|
23
|
+
main()
|
core/smc/SMCBase.py
ADDED
@@ -0,0 +1,130 @@
|
|
1
|
+
from decimal import Decimal
|
2
|
+
import logging
|
3
|
+
import pandas as pd
|
4
|
+
import numpy as np
|
5
|
+
from core.utils.OPTools import OPTools
|
6
|
+
|
7
|
+
class SMCBase(object):
|
8
|
+
HIGH_COL = "high"
|
9
|
+
LOW_COL = "low"
|
10
|
+
CLOSE_COL = "close"
|
11
|
+
OPEN_COL = "open"
|
12
|
+
VOLUME_COL = "volume"
|
13
|
+
AMOUNT_COL = "amount"
|
14
|
+
TIMESTAMP_COL = "timestamp"
|
15
|
+
ATR_COL = "atr"
|
16
|
+
|
17
|
+
BUY_SIDE = "buy"
|
18
|
+
SELL_SIDE = "sell"
|
19
|
+
|
20
|
+
|
21
|
+
def __init__(self):
|
22
|
+
self.logger = logging.getLogger(__name__)
|
23
|
+
|
24
|
+
@staticmethod
|
25
|
+
def check_columns(df: pd.DataFrame, required_columns: list) -> bool:
|
26
|
+
"""
|
27
|
+
检查DataFrame是否包含指定的列
|
28
|
+
参数:
|
29
|
+
df (pd.DataFrame): 要检查的DataFrame
|
30
|
+
columns (list): 要检查的列名列表
|
31
|
+
返回:
|
32
|
+
bool: 如果DataFrame包含所有指定的列,则返回True;否则返回False
|
33
|
+
"""
|
34
|
+
has_pass = all(col in df.columns for col in required_columns)
|
35
|
+
if not has_pass:
|
36
|
+
raise ValueError(f"DataFrame必须包含列: {required_columns}")
|
37
|
+
return has_pass
|
38
|
+
|
39
|
+
@staticmethod
|
40
|
+
def toDecimal(value, precision:int=None) -> Decimal:
|
41
|
+
return OPTools.toDecimal(value, precision)
|
42
|
+
|
43
|
+
@staticmethod
|
44
|
+
def get_precision_length(value) -> int:
|
45
|
+
return len(f"{value:.15f}".rstrip('0').split('.')[1]) if '.' in f"{value:.15f}" else 0
|
46
|
+
|
47
|
+
@staticmethod
|
48
|
+
def calculate_atr(df, period=14, multiplier=2):
|
49
|
+
"""
|
50
|
+
计算增强版ATR指标,等效于Pine Script中的 ta.highest(ta.atr(200),200)*2
|
51
|
+
|
52
|
+
参数:
|
53
|
+
df: 包含OHLCV数据的DataFrame
|
54
|
+
period: ATR计算周期,默认200
|
55
|
+
multiplier: 放大倍数,默认2
|
56
|
+
|
57
|
+
返回:
|
58
|
+
增强版ATR序列
|
59
|
+
"""
|
60
|
+
# df = data.copy()
|
61
|
+
# 计算真实波幅(TR)
|
62
|
+
high = df[SMCBase.HIGH_COL]
|
63
|
+
low = df[SMCBase.LOW_COL]
|
64
|
+
close = df[SMCBase.CLOSE_COL]
|
65
|
+
|
66
|
+
close_prev = close.shift(1)
|
67
|
+
tr = pd.DataFrame({
|
68
|
+
'tr1': high - low,
|
69
|
+
'tr2': abs(high - close_prev),
|
70
|
+
'tr3': abs(low - close_prev)
|
71
|
+
}).max(axis=1)
|
72
|
+
|
73
|
+
# 计算ATR (使用简单移动平均)
|
74
|
+
atr = tr.rolling(window=period, min_periods=1).mean()
|
75
|
+
|
76
|
+
# 计算ATR的N周期最大值
|
77
|
+
max_atr = atr.rolling(window=period, min_periods=1).max()
|
78
|
+
|
79
|
+
|
80
|
+
# 应用放大倍数
|
81
|
+
enhanced_atr = max_atr * multiplier
|
82
|
+
|
83
|
+
return enhanced_atr
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
|
88
|
+
def calculate_atr_with_smoothing(df, length=14, smoothing='RMA'):
|
89
|
+
"""
|
90
|
+
计算ATR (Average True Range) 指标
|
91
|
+
|
92
|
+
参数:
|
93
|
+
df (pd.DataFrame): 包含OHLCV数据的DataFrame,需包含列:['high', 'low', 'close']
|
94
|
+
length (int): 计算周期,默认为14
|
95
|
+
smoothing (str): 平滑方法,支持 'RMA', 'SMA', 'EMA', 'WMA',默认为 'RMA'
|
96
|
+
|
97
|
+
返回:
|
98
|
+
pd.Series: ATR值序列
|
99
|
+
"""
|
100
|
+
# 确保数据包含所需的列
|
101
|
+
required_columns = [SMCBase.HIGH_COL, SMCBase.LOW_COL, SMCBase.CLOSE_COL]
|
102
|
+
SMCBase.check_columns(df, required_columns)
|
103
|
+
|
104
|
+
# 计算真实波幅 (TR)
|
105
|
+
high_low = df[SMCBase.HIGH_COL] - df[SMCBase.LOW_COL]
|
106
|
+
high_close = (df[SMCBase.HIGH_COL] - df[SMCBase.CLOSE_COL].shift()).abs()
|
107
|
+
low_close = (df[SMCBase.LOW_COL] - df[SMCBase.CLOSE_COL].shift()).abs()
|
108
|
+
|
109
|
+
# 计算TR列,取三个值中的最大值
|
110
|
+
tr = pd.concat([high_low, high_close, low_close], axis=1).max(axis=1)
|
111
|
+
|
112
|
+
# Apply smoothing
|
113
|
+
if smoothing == 'RMA':
|
114
|
+
# RMA is approximately an EMA with alpha = 1/length
|
115
|
+
atr = tr.ewm(alpha=1/length, adjust=False).mean()
|
116
|
+
elif smoothing == 'SMA':
|
117
|
+
atr = tr.rolling(window=length).mean()
|
118
|
+
elif smoothing == 'EMA':
|
119
|
+
atr = tr.ewm(span=length, adjust=False).mean()
|
120
|
+
elif smoothing == 'WMA':
|
121
|
+
# WMA implementation
|
122
|
+
weights = pd.Series(range(1, length+1))
|
123
|
+
def wma(series):
|
124
|
+
return (series * weights).sum() / weights.sum()
|
125
|
+
atr = tr.rolling(window=length).apply(wma)
|
126
|
+
else:
|
127
|
+
raise ValueError("Invalid smoothing method. Use 'RMA', 'SMA', 'EMA', or 'WMA'")
|
128
|
+
|
129
|
+
return atr
|
130
|
+
|