Advertisement
den4ik2003

Untitled

Jan 17th, 2025
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.37 KB | None | 0 0
  1. from LBank.new_v2_inter.MarketMan import MarketMan
  2. from LBank.new_v2_inter.OrderMan import OrderMan
  3. from LBank.AccountMan import AccountMan
  4. from datetime import datetime
  5. import time
  6.  
  7. class Lbank:
  8.     def __init__(self, args, symbol, use_rsa=True):
  9.         if args['memo'] == 'HmacSHA256':
  10.             sign_method = "HmacSHA256"
  11.         else:    
  12.             sign_method = "RSA" if use_rsa else "HmacSHA256"
  13.         self.market = "lbank"
  14.         self.market_client = MarketMan(args['api'], args['secret'], 0, sign_method)
  15.         self.order_client = OrderMan(args['api'], args['secret'], 0, sign_method)
  16.         self.account_client = AccountMan(args['api'], args['secret'], 0, sign_method)
  17.         self.symbol = (symbol[0].lower(), symbol[1].lower(), symbol[2].lower()) + symbol[3:]
  18.         self.last_public_trades = set()
  19.         self.last_private_trades = set()
  20.  
  21.     def get_info(self):
  22.         book = self.market_client.getBookTicker(symbol=self.symbol[0])
  23.         book = book['data'] if 'data' in book else {}
  24.         best = {'ask_price': float(book['askPrice']) if 'askPrice' in book else 0, 'bid_price': float(book['bidPrice']) if 'bidPrice' in book else 0}
  25.         acc = self.account_client.getUserInfo()['data']
  26.         bal = {'base': 0, 'quote': 0}
  27.         for asset in acc['free'].keys():
  28.             if asset == self.symbol[1]:
  29.                 bal['base'] += float(acc['free'][asset])
  30.             elif asset == self.symbol[2]:
  31.                 bal['quote'] += float(acc['free'][asset])
  32.         for asset in acc['freeze'].keys():
  33.             if asset == self.symbol[1]:
  34.                 bal['base'] += float(acc['freeze'][asset])
  35.             elif asset == self.symbol[2]:
  36.                 bal['quote'] += float(acc['freeze'][asset])
  37.         print('finish')
  38.         return {'book': best, 'balance': bal}
  39.  
  40.     def cancel(self, order_id):
  41.         self.order_client.getCancel_orderV2(symbol=self.symbol[0], orderId=order_id)
  42.  
  43.     def proper_round(self, x, precision):
  44.         return f"%.{precision}f" % round(x, precision)
  45.  
  46.     def new_limit_maker(self, price, quantity, is_bid):
  47.         type = 'buy_maker' if is_bid else 'sell_maker'
  48.         try:
  49.             self.order_client.getCreate_order(symbol=self.symbol[0], type=type, price=self.proper_round(price, self.symbol[3]), amount=self.proper_round(quantity, self.symbol[4]))
  50.         except Exception as e:
  51.             print(e)
  52.  
  53.     def new_limit(self, price, quantity, is_bid):
  54.         type = 'buy' if is_bid else 'sell'
  55.         self.order_client.getCreate_order(symbol=self.symbol[0], type=type, price=self.proper_round(price, self.symbol[3]), amount=self.proper_round(quantity, self.symbol[4]))
  56.  
  57.     def get_orders(self):
  58.         try:
  59.             orders = self.order_client.getOrders_info_no_deal(symbol=self.symbol[0], page_length=200, current_page=1)['data']['orders']
  60.         except Exception as e:
  61.             print(e)
  62.             orders = {}
  63.         #print(orders)
  64.         res = {'ask': [], 'bid': []}
  65.         for order in orders:
  66.             if order['type'] == 'sell_maker':
  67.                 res['ask'].append({'id': order['orderId'], 'quantity': float(order['origQty']), 'price': float(order['price'])})
  68.             elif order['type'] == 'buy_maker':
  69.                 res['bid'].append({'id': order['orderId'], 'quantity': float(order['origQty']), 'price': float(order['price'])})
  70.         return res
  71.  
  72.     def get_depth(self):
  73.         depth = self.market_client.getIncrDepth(symbol=self.symbol[0])
  74.         print(depth)
  75.         return dict(zip(depth.keys(), map(lambda z: map(lambda v: list(map(float, v)), z), depth.values())))
  76.  
  77.     def get_new_public_trades(self):
  78.         trades = []
  79.         new_trades = set()
  80.         try:
  81.             response = self.market_client.getTradesV2(symbol=self.symbol[0], size=50)['data']
  82.         except Exception as e:
  83.             print(e)
  84.             return []
  85.         for order in response:
  86.             new_trades.add(order['id'])
  87.             if order['id'] in self.last_public_trades:
  88.                 continue
  89.             trade = {'price': float(order['price']), 'quantity': float(order['qty']), 'side': 'sell' if order['isBuyerMaker'] else 'buy', 'timestamp': int(order['time'])}
  90.             trades.append(trade)
  91.         if len(self.last_public_trades) == 0:
  92.             trades = []
  93.         if len(new_trades) > 0:
  94.             self.last_public_trades = new_trades
  95.         return trades
  96.  
  97.     def get_new_private_trades(self):
  98.         trades = []
  99.         new_trades = set()
  100.         try:
  101.             response = self.order_client.getTransaction_history(symbol=self.symbol[0], startTime=str(datetime.fromtimestamp(int(time.time())-60+8*60*60)))['data']
  102.         except Exception as e:
  103.             print(e)
  104.             return []
  105.         for order in response:
  106.             new_trades.add(order['id'])
  107.             if order['id'] in self.last_private_trades:
  108.                 continue
  109.             trade = {'price': float(order['price']), 'quantity': float(order['qty']), 'side': 'sell' if (order['isBuyer'] == order['isMaker']) else 'buy', 'timestamp': int(order['time'])}
  110.             trades.append(trade)
  111.         if len(self.last_private_trades) == 0:
  112.             trades = []
  113.         if len(new_trades) > 0:
  114.             self.last_private_trades = new_trades
  115.         return trades
  116.  
  117.     def cancel_open_orders(self):
  118.         self.order_client.getCancel_order_by_symbol(symbol=self.symbol[0])
  119.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement