Advertisement
Guest User

Untitled

a guest
Mar 5th, 2018
940
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.03 KB | None | 0 0
  1. # python3.4
  2.  
  3. ' Wrapper for Common PyBitshares DEX Algo Trading API Calls '
  4.  
  5. # data is in easy to quant float / list of floats / dict of floats format
  6.  
  7.     # buy / sell / cancel
  8.     # outstanding orders
  9.     # account balance for pair
  10.     # complete account balance
  11.     # orderbook
  12.     # last_price
  13.     # account value
  14.     # latency
  15.  
  16. # if no price / amount specified executes market order buy/sell
  17. # if no expiration specified default is 3.2 years
  18. # cancels all outstanding orders in market
  19.  
  20. ' BTS: litepresence1 '
  21.  
  22. # http://docs.pybitshares.com
  23. from bitshares.market import Market
  24. from bitshares.account import Account
  25. from bitshares import BitShares
  26. from bitshares.blockchain import Blockchain
  27. import time
  28.  
  29.  
  30. ACCOUNT = Account("")
  31. PASS_PHRASE = ""
  32.  
  33. BitCURRENCY = 'OPEN.BTC'
  34. BitASSET = 'BTS'
  35. BitPAIR = BitASSET + ":" + BitCURRENCY
  36. MARKET = Market(BitPAIR, bitshares_instance=BitShares(nodes()))
  37. CHAIN = Blockchain(bitshares_instance=BitShares(
  38.     nodes()), mode='head')
  39.  
  40. SATOSHI = 0.00000001
  41. ANTISAT = 1 / SATOSHI
  42.  
  43. def nodes():  # Public Nodes List
  44.  
  45.     nodes = [
  46.         'wss://b.mrx.im/ws',
  47.         'wss://bitshares.openledger.info/ws',
  48.         'wss://bitshares.dacplay.org:8089/ws',
  49.         'wss://dele-puppy.com/ws',
  50.         'wss://eu.openledger.info/ws',
  51.         'wss://bit.btsabc.org/ws',
  52.         'wss://eu.openledger.info/ws',
  53.         'wss://dexnode.net/ws',
  54.         'wss://ws.gdex.top',
  55.         'wss://kc-us-dex.xeldal.com/ws',
  56.         'wss://bts.ai.la/ws',
  57.         'wss://btsza.co.za:8091/ws',
  58.         'wss://japan.bitshares.apasia.tech/ws',
  59.         'wss://api.bts.blckchnd.com',
  60.         'wss://bitshares-api.wancloud.io/ws',
  61.         'wss://eu.nodes.bitshares.ws',
  62.         'wss://bitshares.crypto.fans/ws',
  63.         'wss://dex.rnglab.org',
  64.         'wss://bitshares.openledger.info/ws',
  65.         'wss://ws.winex.pro',
  66.         'wss://sg.nodes.bitshares.ws',
  67.         'wss://us.nodes.bitshares.ws',
  68.         'wss://bitshares.apasia.tech/ws',
  69.         'wss://openledger.hk/ws',
  70.         'wss://bitshares.dacplay.org/ws',
  71.     ]
  72.     return nodes
  73.  
  74. def dex(  # Public AND Private API Bitshares
  75.         command, amount=ANTISAT, price=None,
  76.         depth=1, expiration=ANTISAT):
  77.  
  78.     MARKET.bitshares.wallet.unlock(PASS_PHRASE)
  79.     ACCOUNT.refresh()
  80.  
  81.     if command == 'buy':
  82.  
  83.         # buy relentlessly until satisfied or currency exhausted
  84.         print(('Bitshares API', command))
  85.         if price is None:
  86.             price = ANTISAT
  87.         print(('buying', amount, 'at', price))
  88.         attempt = 1
  89.         currency = float(ACCOUNT.balance(BitCURRENCY))
  90.         if amount > 0.998 * currency * price:
  91.             amount = 0.998 * currency * price
  92.         if amount > 0:
  93.             while attempt:
  94.                 try:
  95.                     details = (MARKET.buy(price, amount, expiration))
  96.                     print (details)
  97.                     attempt = 0
  98.                 except:
  99.                     print(("buy attempt %s failed" % attempt))
  100.                     attempt += 1
  101.                     if attempt > 10:
  102.                         print ('buy aborted')
  103.                         return
  104.                     pass
  105.         else:
  106.             print('no currency to buy')
  107.  
  108.     if command == 'sell':
  109.  
  110.         # sell relentlessly until satisfied or assets exhausted
  111.         expiration = 86400 * 7
  112.         print(('Bitshares API', command))
  113.         if price is None:
  114.             price = SATOSHI
  115.         print(('selling', amount, 'at', price))
  116.         attempt = 1
  117.         assets = float(ACCOUNT.balance(BitASSET))
  118.         if amount > 0.998 * assets:
  119.             amount = 0.998 * assets
  120.         if amount > 0:
  121.             while attempt:
  122.                 try:
  123.                     details = (MARKET.sell(price, amount, expiration))
  124.                     print (details)
  125.                     attempt = 0
  126.                 except:
  127.                     print(("sell attempt %s failed" % attempt))
  128.                     attempt += 1
  129.                     if attempt > 10:
  130.                         print ('sell aborted')
  131.                         return
  132.                     pass
  133.         else:
  134.             print('no assets to sell')
  135.  
  136.     if command == 'cancel':
  137.  
  138.         # cancel all orders in this MARKET relentlessly until satisfied
  139.         print(('Bitshares API', command))  
  140.         orders = MARKET.accountopenorders()
  141.         print((len(orders), 'open orders to cancel'))
  142.         if len(orders):
  143.             attempt = 1  
  144.             order_list = []      
  145.             for order in orders:
  146.                 order_list.append(order['id'])
  147.             while attempt:
  148.                 try:
  149.                     details = MARKET.cancel(order_list)
  150.                     print (details)
  151.                     attempt = 0
  152.                 except:
  153.                     print((attempt, 'cancel failed', order_list))
  154.                     attempt += 1
  155.                     if attempt > 10:
  156.                         print ('cancel aborted')
  157.                         return
  158.                     pass    
  159.  
  160.     if command == 'orders':
  161.  
  162.         # dictionary of open orders in traditional format:
  163.         # orderNumber, orderType, market, amount, price
  164.         print(('Bitshares API', command))
  165.         orders = []
  166.         for order in MARKET.accountopenorders():
  167.             orderNumber = order['id']
  168.             asset = order['base']['symbol']
  169.             currency = order['quote']['symbol']
  170.             amount = float(order['base'])
  171.             price = float(order['price'])
  172.             orderType = 'buy'
  173.             if asset == BitASSET:
  174.                 orderType = 'sell'
  175.                 price = 1 / price
  176.             orders.append({'orderNumber': orderNumber,
  177.                            'orderType': orderType,
  178.                            'market': BitPAIR, 'amount': amount,
  179.                            'price': price})
  180.         for o in orders:
  181.             print (o)
  182.         if len(orders) == 0:
  183.             print ('no open orders')
  184.         return orders
  185.  
  186.     if command == 'market_balances':
  187.  
  188.         # dictionary of currency and assets in this MARKET
  189.         print(('Bitshares API', command))
  190.         currency = float(ACCOUNT.balance(BitCURRENCY))
  191.         assets = float(ACCOUNT.balance(BitASSET))
  192.         balances = {'currency': currency, 'assets': assets}
  193.         print (balances)
  194.         return balances
  195.  
  196.     if command == 'complete_balances':
  197.  
  198.         # dictionary of ALL account balances
  199.         print(('Bitshares API', command))
  200.         raw = list(ACCOUNT.balances)
  201.         balances = {}
  202.         for i in range(len(raw)):
  203.             balances[raw[i]['symbol']] = float(raw[i]['amount'])
  204.         print (balances)
  205.         return balances
  206.  
  207.     if command == 'book':
  208.  
  209.         # dictionary of 4 lists containing bid/ask volume/price
  210.         print(('Bitshares API', command))
  211.         raw = MARKET.orderbook(limit=depth)
  212.         bids = raw['bids']
  213.         asks = raw['asks']
  214.         bidp = [float(bids[i]['price']) for i in range(len(bids))]
  215.         bidv = [float(bids[i]['quote']) for i in range(len(bids))]
  216.         askp = [float(asks[i]['price']) for i in range(len(asks))]
  217.         askv = [float(asks[i]['quote']) for i in range(len(asks))]
  218.         book = {'bidp': bidp, 'bidv': bidv, 'askp': askp, 'askv': askv}
  219.         # print(book)
  220.         print(('ask', ('%.8f' % book['askp'][0])))  # lowest ask price
  221.         print(('bid', ('%.8f' % book['bidp'][0])))  # highest bid price
  222.         # print(book['bidv'][0]) #highest bid volume
  223.         # print(book['askv'][0]) #lowest ask volume
  224.         return book
  225.  
  226.     if command == 'last':
  227.  
  228.         # the most recent transation in this MARKET
  229.         print(('Bitshares API', command))
  230.         raw = MARKET.ticker()['latest']
  231.         price = float(raw)
  232.         # print (price)
  233.         return price
  234.  
  235.     if command == 'account_value':
  236.  
  237.         # dictionary account value in BTS BTC and USD
  238.         print(('Bitshares API', command))
  239.         raw = list(ACCOUNT.balances)
  240.         balances = {}
  241.         for i in range(len(raw)):
  242.             balances[raw[i]['symbol']] = float(raw[i]['amount'])
  243.         btc_value = 0
  244.         for asset, amount in list(balances.items()):
  245.             market_pair = 'OPEN.BTC:' + asset
  246.             market = Market(market_pair)
  247.             price = float(market.ticker()['latest'])
  248.             try:
  249.                 value = amount / price
  250.             except:
  251.                 value = 0
  252.             if value < 0.0001:
  253.                 value = 0
  254.             else:
  255.                 if asset != 'USD':
  256.                     price = 1 / (price + SATOSHI)
  257.                 print((('%.4f' % value), 'OPEN.BTC', ('%.2f' % amount),
  258.                        asset, '@', ('%.8f' % price)))
  259.                 btc_value += value
  260.  
  261.         market_pair = 'OPEN.BTC:USD'
  262.         market = Market(market_pair)
  263.         price = float(market.ticker()['latest'])
  264.         usd_value = btc_value * price
  265.         market_pair = 'OPEN.BTC:BTS'
  266.         market = Market(market_pair)
  267.         price = float(market.ticker()['latest'])
  268.         bts_value = btc_value * price
  269.         print((('%.2f' % bts_value), 'BTS',
  270.              ('%.4f' % btc_value), 'OPEN.BTC',
  271.              ('%.2f' % usd_value), 'bitUSD'))
  272.         return bts_value, btc_value, usd_value
  273.  
  274.     if command == 'blocktime':
  275.  
  276.         current_block = CHAIN.get_current_block_num()
  277.         blocktime = CHAIN.block_time(current_block)
  278.         blocktimestamp = CHAIN.block_timestamp(current_block) - 18000
  279.         now = time.time()
  280.         latency = now - blocktimestamp
  281.         print(('block               :', current_block))
  282.         # print(('blocktime           :', blocktime))
  283.         # print(('stamp               :', blocktimestamp))
  284.         # print(('ctime(stamp)        :', time.ctime(blocktimestamp)))
  285.         # print(('now                 :', now))
  286.         print(('dex_rate latency    :', ('%.2f' % latency)))
  287.         return current_block, blocktimestamp, latency
  288.  
  289.  
  290.  
  291. '''
  292. dex('buy')
  293. dex('sell')
  294. dex('orders')
  295. dex('cancel')
  296. dex('market_balances')
  297. dex('complete_balances')
  298. dex('last')
  299. dex('book')
  300. dex('account_value')
  301. dex('blocktime')
  302. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement