openfund-core 1.0.1__tar.gz → 1.0.7__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: openfund-core
3
- Version: 1.0.1
3
+ Version: 1.0.7
4
4
  Summary: Openfund-core.
5
5
  Requires-Python: >=3.9,<4.0
6
6
  Classifier: Programming Language :: Python :: 3
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "openfund-core"
3
- version = "1.0.1"
3
+ version = "1.0.7"
4
4
  description = "Openfund-core."
5
5
  authors = []
6
6
  readme = "README.md"
@@ -0,0 +1,592 @@
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_position_mode(self) -> str:
36
+
37
+ try:
38
+ # 假设获取账户持仓模式的 API
39
+ response = self.exchange.private_get_account_config()
40
+ data = response.get('data', [])
41
+ if data and isinstance(data, list):
42
+ # 取列表的第一个元素(假设它是一个字典),然后获取 'posMode'
43
+ position_mode = data[0].get('posMode', 'single') # 默认值为单向
44
+
45
+ return position_mode
46
+ else:
47
+
48
+ return 'single' # 返回默认值
49
+ except Exception as e:
50
+ error_message = f"Error fetching position mode: {e}"
51
+ self.logger.error(error_message)
52
+ raise Exception(error_message)
53
+
54
+ def get_tick_size(self,symbol) -> Decimal:
55
+
56
+ market = self.getMarket(symbol)
57
+ if market and 'precision' in market and 'price' in market['precision']:
58
+ return OPTools.toDecimal(market['precision']['price'])
59
+ else:
60
+ raise ValueError(f"{symbol}: 无法从市场数据中获取价格精度")
61
+
62
+ def amount_to_precision(self,symbol, contract_size):
63
+ return self.exchange.amount_to_precision(symbol, contract_size)
64
+
65
+
66
+
67
+ def set_leverage(self,symbol, leverage, mgnMode='isolated',posSide=None):
68
+ try:
69
+ # 设置杠杆
70
+ params = {
71
+ # 'instId': instId,
72
+ 'leverage': leverage,
73
+ 'marginMode': mgnMode
74
+ }
75
+ if posSide:
76
+ params['side'] = posSide
77
+
78
+ self.exchange.set_leverage(leverage, symbol=symbol, params=params)
79
+ self.logger.info(f"{symbol} Successfully set leverage to {leverage}x")
80
+ except Exception as e:
81
+ error_message = f"{symbol} Error setting leverage: {e}"
82
+ self.logger.error(error_message)
83
+ raise Exception(error_message)
84
+ # 获取价格精度
85
+ def get_precision_length(self,symbol) -> int:
86
+ tick_size = self.get_tick_size(symbol)
87
+ return len(f"{tick_size:.15f}".rstrip('0').split('.')[1]) if '.' in f"{tick_size:.15f}" else 0
88
+
89
+ def format_price(self, symbol, price:Decimal) -> str:
90
+ precision = self.get_precision_length(symbol)
91
+ return f"{price:.{precision}f}"
92
+
93
+ def convert_contract(self, symbol, amount, price:Decimal, direction='cost_to_contract'):
94
+ """
95
+ 进行合约与币的转换
96
+ :param symbol: 交易对符号,如 'BTC/USDT:USDT'
97
+ :param amount: 输入的数量,可以是合约数量或币的数量
98
+ :param direction: 转换方向,'amount_to_contract' 表示从数量转换为合约,'cost_to_contract' 表示从金额转换为合约
99
+ :return: 转换后的数量
100
+ """
101
+
102
+ # 获取合约规模
103
+ market_contractSize = OPTools.toDecimal(self.getMarket(symbol)['contractSize'])
104
+ amount = OPTools.toDecimal(amount)
105
+ if direction == 'amount_to_contract':
106
+ contract_size = amount / market_contractSize
107
+ elif direction == 'cost_to_contract':
108
+ contract_size = amount / price / market_contractSize
109
+ else:
110
+ raise Exception(f"{symbol} : {direction} 是无效的转换方向,请输入 'amount_to_contract' 或 'cost_to_contract'。")
111
+
112
+ return self.amount_to_precision(symbol, contract_size)
113
+
114
+ def close_position(self, symbol, position, params={}) -> dict:
115
+
116
+ amount = abs(float(position['contracts']))
117
+
118
+ if amount <= 0:
119
+ self.logger.warning(f"{symbol}: position contracts must be greater than 0")
120
+ return
121
+
122
+ max_retries = 3
123
+ retry_count = 0
124
+ while retry_count < max_retries:
125
+
126
+ try:
127
+ side = position[self.SIDE_KEY]
128
+ self.logger.debug(f"{symbol}: Preparing to close position, side= {side}, amount={amount}")
129
+ position_mode = self.get_position_mode() # 获取持仓模式
130
+ if position_mode == 'long_short_mode':
131
+ # 在双向持仓模式下,指定平仓方向
132
+ # pos_side = 'long' if side == 'long' else 'short'
133
+ pos_side = side
134
+ else:
135
+ # 在单向模式下,不指定方向
136
+ pos_side = 'net'
137
+ orderSide = 'buy' if side == 'long' else 'sell'
138
+
139
+ td_mode = position['marginMode']
140
+ params = {
141
+ 'mgnMode': td_mode,
142
+ 'posSide': pos_side,
143
+ # 当市价全平时,平仓单是否需要自动撤销,默认为false. false:不自动撤单 true:自动撤单
144
+ 'autoCxl': 'true',
145
+ **params
146
+
147
+ }
148
+
149
+ # 发送平仓请求并获取返回值
150
+ order = self.exchange.close_position(
151
+ symbol=symbol,
152
+ side=orderSide,
153
+ params=params
154
+ )
155
+
156
+ self.logger.info(f"{symbol} Close position response : {order}")
157
+ return order
158
+
159
+ except Exception as e:
160
+
161
+ retry_count += 1
162
+ if retry_count == max_retries:
163
+ error_message = f"{symbol} Error closing position : {str(e)}"
164
+ self.logger.error(error_message)
165
+ raise Exception(error_message)
166
+ else:
167
+ self.logger.warning(f"{symbol} 平仓失败,正在进行第{retry_count}次重试: {str(e)}")
168
+ time.sleep(0.1) # 重试前等待0.1秒
169
+
170
+
171
+ def cancel_all_orders(self, symbol):
172
+ max_retries = 3
173
+ retry_count = 0
174
+
175
+ while retry_count < max_retries:
176
+ try:
177
+ # 获取所有未完成订单
178
+ params = {
179
+ # 'instId': instId
180
+ }
181
+ open_orders = self.exchange.fetch_open_orders(symbol=symbol, params=params)
182
+
183
+ # 批量取消所有订单
184
+ if open_orders:
185
+ order_ids = [order['id'] for order in open_orders]
186
+ self.exchange.cancel_orders(order_ids, symbol, params=params)
187
+
188
+ self.logger.debug(f"{symbol}: {order_ids} 挂单取消成功.")
189
+ else:
190
+ self.logger.debug(f"{symbol}: 无挂单.")
191
+ return True
192
+
193
+ except Exception as e:
194
+ retry_count += 1
195
+ if retry_count == max_retries:
196
+ error_message = f"{symbol} 取消挂单失败(重试{retry_count}次): {str(e)}"
197
+ self.logger.error(error_message)
198
+ raise Exception(error_message)
199
+ else:
200
+ self.logger.warning(f"{symbol} 取消挂单失败,正在进行第{retry_count}次重试: {str(e)}")
201
+ time.sleep(0.1) # 重试前等待0.1秒
202
+
203
+ def cancel_all_algo_orders(self, symbol, attachType=None) -> bool:
204
+ """_summary_
205
+
206
+ Args:
207
+ symbol (_type_): _description_
208
+ attachType (_type_, optional): "TP"|"SL". Defaults to None.
209
+ """
210
+
211
+ params = {
212
+ "ordType": "conditional",
213
+ }
214
+ try:
215
+ orders = self.fetch_open_orders(symbol=symbol,params=params)
216
+ except Exception as e:
217
+ error_message = f"!!{symbol} : Error fetching open orders: {e}"
218
+ self.logger.error(error_message)
219
+ raise Exception(error_message)
220
+
221
+
222
+ if len(orders) == 0:
223
+ self.logger.debug(f"{symbol} 未设置策略订单列表。")
224
+ return True
225
+
226
+ algo_ids = []
227
+ if attachType and attachType == 'SL':
228
+ algo_ids = [order['id'] for order in orders if order['stopLossPrice'] and order['stopLossPrice'] > 0.0 ]
229
+ elif attachType and attachType == 'TP':
230
+ algo_ids = [order['id'] for order in orders if order['takeProfitPrice'] and order['takeProfitPrice'] > 0.0]
231
+ else :
232
+ algo_ids = [order['id'] for order in orders ]
233
+
234
+ if len(algo_ids) == 0 :
235
+ self.logger.debug(f"{symbol} 未设置策略订单列表。")
236
+ return True
237
+
238
+ max_retries = 3
239
+ retry_count = 0
240
+
241
+ while retry_count < max_retries:
242
+ try:
243
+ params = {
244
+ "algoId": algo_ids,
245
+ "trigger": 'trigger'
246
+ }
247
+ rs = self.exchange.cancel_orders(ids=algo_ids, symbol=symbol, params=params)
248
+
249
+ return len(rs) > 0
250
+
251
+ except Exception as e:
252
+ retry_count += 1
253
+ if retry_count == max_retries:
254
+ error_message = f"!!{symbol} : Error cancelling order {algo_ids}: {e}"
255
+ self.logger.error(error_message)
256
+ raise Exception(error_message)
257
+
258
+ self.logger.warning(f"{symbol} : Error cancelling order {algo_ids}: {str(e)}")
259
+ time.sleep(0.1) # 重试前等待0.1秒
260
+ def place_algo_orders(self, symbol, position, price: Decimal, order_type, sl_or_tp='SL', params={}) -> bool:
261
+ """
262
+ 下单
263
+ Args:
264
+ symbol: 交易对
265
+ position: 仓位
266
+ price: 下单价格
267
+ order_type: 订单类型
268
+ """
269
+ # 计算下单数量
270
+ amount = abs(position[self.CONTRACTS_KEY])
271
+
272
+ if amount <= 0:
273
+ self.logger.warning(f"{symbol}: amount is 0 for {symbol}")
274
+ return
275
+
276
+ # 止损单逻辑
277
+ adjusted_price = self.format_price(symbol, price)
278
+
279
+ # 默认市价止损,委托价格为-1时,执行市价止损。
280
+ sl_params = {
281
+ **params,
282
+ 'slTriggerPx':adjusted_price ,
283
+ 'slOrdPx':'-1', # 委托价格为-1时,执行市价止损
284
+ # 'slOrdPx' : adjusted_price,
285
+ 'slTriggerPxType':'last',
286
+ 'tdMode':position['marginMode'],
287
+ 'sz': str(amount),
288
+ 'cxlOnClosePos': True,
289
+ 'reduceOnly':True,
290
+ }
291
+
292
+ tp_params = {
293
+ **params,
294
+ 'tpTriggerPx':adjusted_price,
295
+ 'tpOrdPx' : adjusted_price,
296
+ 'tpOrdKind': 'condition',
297
+ 'tpTriggerPxType':'last',
298
+ 'tdMode':position['marginMode'],
299
+ 'sz': str(amount),
300
+ 'cxlOnClosePos': True,
301
+ 'reduceOnly':True
302
+ }
303
+
304
+ order_params = sl_params if sl_or_tp == 'SL' else tp_params
305
+ # order_params.update(params)
306
+
307
+ if order_type == 'limit' and sl_or_tp =='SL':
308
+ order_params['slOrdPx'] = adjusted_price
309
+
310
+ orderSide = self.BUY_SIDE if position[self.SIDE_KEY] == self.SHORT_KEY else self.SELL_SIDE # 和持仓反向相反下单
311
+
312
+ order = {
313
+ 'symbol': symbol,
314
+ 'side': orderSide,
315
+ 'type': order_type,
316
+ 'amount': amount,
317
+ 'price': adjusted_price,
318
+ 'params': order_params
319
+ }
320
+
321
+ max_retries = 3
322
+ retry_count = 0
323
+ self.logger.info(f"{symbol} : Pre Algo Order placed: {order} ")
324
+ while retry_count < max_retries:
325
+ try:
326
+
327
+ self.exchange.create_order(
328
+ **order
329
+ # symbol=symbol,
330
+ # type=order_type,
331
+ # price=adjusted_price,
332
+ # side=orderSide,
333
+ # amount=amount,
334
+ # params=order_params
335
+ )
336
+
337
+ break
338
+
339
+ except ccxt.NetworkError as e:
340
+ # 处理网络相关错误
341
+ retry_count += 1
342
+ self.logger.warning(f"{symbol} : 设置止盈止损时发生网络错误,正在进行第{retry_count}次重试: {str(e)}")
343
+ time.sleep(0.1) # 重试前等待1秒
344
+ continue
345
+ except ccxt.ExchangeError as e:
346
+ # 处理交易所API相关错误
347
+ retry_count += 1
348
+ self.logger.warning(f"{symbol} : 设置止盈止损单时发生交易所错误,正在进行第{retry_count}次重试: {str(e)}")
349
+ time.sleep(0.1)
350
+ continue
351
+ except Exception as e:
352
+ # 处理其他未预期的错误
353
+ retry_count += 1
354
+ self.logger.warning(f"{symbol} : 设置止盈止损单时发生未知错误,正在进行第{retry_count}次重试: {str(e)}")
355
+ time.sleep(0.1)
356
+ continue
357
+
358
+ if retry_count >= max_retries:
359
+ # 重试次数用完仍未成功设置止损单
360
+ error_message = f"!! {symbol}: 设置止盈止损单时重试次数用完仍未成功设置成功。 "
361
+ self.logger.error(error_message)
362
+ raise Exception(error_message)
363
+ self.logger.debug(f"{symbol} : --------- ++ Order placed done. --------")
364
+ return True
365
+
366
+
367
+ def place_order(self, symbol, price: Decimal, amount_usdt, side, leverage=20, order_type='limit', params={}) -> bool:
368
+ """
369
+ 下单
370
+ Args:
371
+ symbol: 交易对
372
+ price: 下单价格
373
+ amount_usdt: 下单金额
374
+ side: 下单方向
375
+ order_type: 订单类型
376
+ """
377
+ # 格式化价格
378
+ adjusted_price = self.format_price(symbol, price)
379
+
380
+ if amount_usdt <= 0:
381
+ self.logger.warning(f"{symbol}: amount_usdt must be greater than 0")
382
+ return
383
+
384
+ pos_side = self.LONG_KEY if side == self.BUY_SIDE else self.SHORT_KEY
385
+
386
+ # 设置杠杆
387
+ self.set_leverage(symbol=symbol, leverage=leverage, mgnMode='isolated',posSide=pos_side)
388
+ # 20250220 SWAP类型计算合约数量
389
+ contract_size = self.convert_contract(symbol=symbol, price = OPTools.toDecimal(adjusted_price) ,amount=amount_usdt)
390
+
391
+ order_params = {
392
+ **params,
393
+ "tdMode": 'isolated',
394
+ "side": side,
395
+ "ordType": order_type,
396
+ "sz": contract_size,
397
+ "px": adjusted_price
398
+ }
399
+
400
+ # # 模拟盘(demo_trading)需要 posSide
401
+ # if self.is_demo_trading == 1 :
402
+ # params["posSide"] = pos_side
403
+
404
+ order = {
405
+ 'symbol': symbol,
406
+ 'side': side,
407
+ 'type': order_type,
408
+ 'amount': contract_size,
409
+ 'price': adjusted_price,
410
+ 'params': order_params
411
+ }
412
+
413
+ max_retries = 3
414
+ retry_count = 0
415
+
416
+ self.logger.info(f"{symbol} : Pre Order placed: {order} ")
417
+
418
+ while retry_count < max_retries:
419
+ try:
420
+ # 使用ccxt创建订单
421
+ order_result = self.exchange.create_order(
422
+ **order
423
+ # symbol=symbol,
424
+ # type='limit',
425
+ # side=side,
426
+ # amount=amount_usdt,
427
+ # price=float(adjusted_price),
428
+ # params=params
429
+ )
430
+ except ccxt.NetworkError as e:
431
+ # 处理网络相关错误
432
+ retry_count += 1
433
+ self.logger.warning(f"{symbol} : 下单时发生网络错误,正在进行第{retry_count}次重试: {str(e)}")
434
+ time.sleep(0.1) # 重试前等待1秒
435
+ continue
436
+ except ccxt.ExchangeError as e:
437
+ # 处理交易所API相关错误
438
+ retry_count += 1
439
+ self.logger.warning(f"{symbol} : 下单时发生交易所错误,正在进行第{retry_count}次重试: {str(e)}")
440
+ time.sleep(0.1)
441
+ continue
442
+ except Exception as e:
443
+ # 处理其他未预期的错误
444
+ retry_count += 1
445
+ self.logger.warning(f"{symbol} : 下单时发生未知错误,正在进行第{retry_count}次重试: {str(e)}")
446
+ time.sleep(0.1)
447
+ continue
448
+ if retry_count >= max_retries:
449
+ # 重试次数用完仍未成功设置止损单
450
+ error_message = f"!! {symbol}: 下单时重试次数用完仍未成功设置成功。 "
451
+ self.logger.error(error_message)
452
+ raise Exception(error_message)
453
+ self.logger.debug(f"{symbol} : --------- ++ Order placed done. --------")
454
+ return True
455
+
456
+ def fetch_position(self, symbol):
457
+ """_summary_
458
+
459
+ Args:
460
+ symbol (_type_): _description_
461
+
462
+ Returns:
463
+ _type_: _description_
464
+ """
465
+
466
+ max_retries = 3
467
+ retry_count = 0
468
+
469
+ while retry_count < max_retries:
470
+ try:
471
+ position = self.exchange.fetch_position(symbol=symbol)
472
+ if position :
473
+ # self.logger.debug(f"{symbol} 有持仓合约数: {position['contracts']}")
474
+ return position
475
+ return None
476
+ except Exception as e:
477
+ retry_count += 1
478
+ if retry_count == max_retries:
479
+ error_message = f"!!{symbol} 获取持仓失败(重试{retry_count}次): {str(e)}"
480
+ self.logger.error(error_message)
481
+ raise Exception(error_message)
482
+
483
+ self.logger.warning(f"{symbol} 检查持仓失败,正在进行第{retry_count}次重试: {str(e)}")
484
+ time.sleep(0.1) # 重试前等待0.1秒
485
+
486
+ def fetch_positions(self):
487
+ """_summary_
488
+ Returns:
489
+ _type_: _description_
490
+ """
491
+ max_retries = 3
492
+ retry_count = 0
493
+
494
+ while retry_count < max_retries:
495
+ try:
496
+ positions = self.exchange.fetch_positions()
497
+ return positions
498
+ except Exception as e:
499
+ retry_count += 1
500
+ if retry_count == max_retries:
501
+ error_message = f"!! 获取持仓列表失败(重试{retry_count}次): {str(e)}"
502
+ self.logger.error(error_message)
503
+ raise Exception(error_message)
504
+
505
+ self.logger.warning(f"获取持仓列表失败,正在进行第{retry_count}次重试: {str(e)}")
506
+ time.sleep(0.1) # 重试前等待0.1秒
507
+
508
+ def fetch_open_orders(self,symbol,params={}):
509
+ max_retries = 3
510
+ retry_count = 0
511
+
512
+ while retry_count < max_retries:
513
+ try:
514
+ orders = self.exchange.fetch_open_orders(symbol=symbol,params=params)
515
+ return orders
516
+
517
+ except Exception as e:
518
+ retry_count += 1
519
+ if retry_count == max_retries:
520
+ error_message = f"{symbol} : fetching open orders(retry {retry_count} times): {str(e)}"
521
+ self.logger.error(error_message)
522
+ raise Exception(error_message)
523
+
524
+ self.logger.warning(f"{symbol} : Error fetching open orders: {str(e)}")
525
+ time.sleep(0.1) # 重试前等待0.1秒
526
+ def get_market_price(self, symbol) -> Decimal:
527
+ """
528
+ 获取最新价格
529
+ Args:
530
+ symbol: 交易对
531
+ """
532
+ max_retries = 3
533
+ retry_count = 0
534
+
535
+ while retry_count < max_retries:
536
+ try:
537
+ ticker = self.exchange.fetch_ticker(symbol)
538
+ if ticker and 'last' in ticker:
539
+ return OPTools.toDecimal(ticker['last'])
540
+ else:
541
+ raise Exception(f"{symbol} : Unexpected response structure or missing 'last' price")
542
+ except Exception as e:
543
+ retry_count += 1
544
+ if retry_count == max_retries:
545
+ error_message = f"{symbol} 获取最新价格失败(重试{retry_count}次): {str(e)}"
546
+ self.logger.error(error_message)
547
+ raise Exception(error_message)
548
+
549
+ def get_historical_klines(self, symbol, bar='15m', limit=300, after:str=None, params={}):
550
+ """
551
+ 获取历史K线数据
552
+ Args:
553
+ symbol: 交易对
554
+ bar: K线周期
555
+ limit: 数据条数
556
+ after: 之后时间,格式为 "2025-05-21 23:00:00+08:00"
557
+ """
558
+
559
+ params = {
560
+ **params,
561
+ # 'instId': instId,
562
+ }
563
+ since = None
564
+ if after:
565
+ since = self.exchange.parse8601(after)
566
+ limit = None
567
+ if since:
568
+ params['paginate'] = True
569
+
570
+ klines = self.exchange.fetch_ohlcv(symbol, timeframe=bar,since=since, limit=limit, params=params)
571
+ # if 'data' in response and len(response['data']) > 0:
572
+ if klines :
573
+ # return response['data']
574
+ return klines
575
+ else:
576
+ raise Exception(f"{symbol} : Unexpected response structure or missing candlestick data")
577
+
578
+ def get_historical_klines_df(self, symbol, bar='15m', limit=300, after:str=None, params={}) -> pd.DataFrame:
579
+ klines = self.get_historical_klines(symbol, bar=bar, limit=limit, after=after, params=params)
580
+ return self.format_klines(klines)
581
+
582
+ def format_klines(self, klines) -> pd.DataFrame:
583
+ """_summary_
584
+ 格式化K线数据
585
+ Args:
586
+ klines (_type_): _description_
587
+ """
588
+ klines_df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
589
+ # 转换时间戳为日期时间
590
+ klines_df['timestamp'] = pd.to_datetime(klines_df['timestamp'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Asia/Shanghai')
591
+
592
+ return klines_df