def get_ledgers(args): """Get ledgers info""" # If id is specified, then query just that if args.id: api_params = { 'id': args.id, } lg = query_api('private', 'QueryLedgers', api_params, args) else: # Parameters to pass to the API api_params = { } if args.asset: # We do not user DEFAULT_ASSET HERE as this param is optional api_params.update({'asset': args.asset}) if args.type: api_params.update({'type': args.type}) if args.start: api_params.update({'start': args.start}) if args.end: api_params.update({'end': args.end}) if args.ofs: api_params.update({'ofs': args.ofs}) res = query_api('private', 'Ledgers', api_params, args) # extract list of ledgers from API results lg = res['ledger'] lg_list = [] for refid, item in lg.items(): # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function asset_dict = OrderedDict() asset_dict['id'] = refid asset_dict['refid'] = item['refid'] asset_dict['time'] = format_timestamp(int(item['time'])) asset_dict['type'] = item['type'] # Remove leading Z or X from item pair if it is of length 4 asset_dict['asset'] = item['asset'][1:] \ if len(item['asset']) == 4 and item['asset'][0] in ['Z', 'X'] else item['asset'] asset_dict['aclass'] = item['aclass'] asset_dict['amount'] = float(item['amount']) asset_dict['fee'] = float(item['fee']) asset_dict['balance'] = float(item['balance']) lg_list.append(asset_dict) if not lg_list: return # sort by date lg_list = sorted(lg_list, key=lambda odict: odict['time']) if args.csv: print(csv(lg_list, headers="keys")) else: print(tabulate(lg_list, headers="keys"))
def get_ledgers(args): """Get ledgers info""" # If id is specified, then query just that if args.id: api_params = { 'id': args.id, } lg = query_api('private', 'QueryLedgers', api_params, args) else: # Parameters to pass to the API api_params = {} if args.asset: # We do not user DEFAULT_ASSET HERE as this param is optional api_params.update({'asset': args.asset}) if args.type: api_params.update({'type': args.type}) if args.start: api_params.update({'start': args.start}) if args.end: api_params.update({'end': args.end}) if args.ofs: api_params.update({'ofs': args.ofs}) res = query_api('private', 'Ledgers', api_params, args) # extract list of ledgers from API results lg = res['ledger'] lg_list = [] for refid, item in lg.items(): # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function asset_dict = OrderedDict() asset_dict['id'] = refid asset_dict['refid'] = item['refid'] asset_dict['time'] = format_timestamp(int(item['time'])) asset_dict['type'] = item['type'] # Remove leading Z or X from item pair if it is of length 4 asset_dict['asset'] = item['asset'][1:] \ if len(item['asset']) == 4 and item['asset'][0] in ['Z', 'X'] else item['asset'] asset_dict['aclass'] = item['aclass'] asset_dict['amount'] = float(item['amount']) asset_dict['fee'] = float(item['fee']) asset_dict['balance'] = float(item['balance']) lg_list.append(asset_dict) if not lg_list: return # sort by date lg_list = sorted(lg_list, key=lambda odict: odict['time']) if args.csv: print(csv(lg_list, headers="keys")) else: print(tabulate(lg_list, headers="keys"))
def list_open_positions(args): """List open positions.""" # Parameters to pass to the API api_params = { 'docalcs': 'true', } res = query_api('private', 'OpenPositions', api_params, args) pos_list = [] for order in res.values(): pos = OrderedDict() pos['ordertxid'] = order['ordertxid'] pos['opening time'] = datetime.fromtimestamp(order['time']) pos['type'] = order['type'] pos['volume'] = order['vol'] pos['pair'] = order['pair'] pos['ordertype'] = order['ordertype'] pos['cost'] = order['cost'] pos['fee'] = order['fee'] pos['margin'] = order['margin'] pos['value'] = order['value'] pos['profit/loss'] = order['net'] pos['rollover time'] = datetime.fromtimestamp(int(order['rollovertm'])) pos['rollover terms'] = order['terms'] pos_list.append(pos) print(tabulate(pos_list, headers="keys"))
def get_deposit_methods(args=None): """Get deposit methods.""" # Parameters to pass to the API api_params = { 'asset': args.asset, } res = query_api('private', 'DepositMethods', api_params, args) m_list = [] for method in res: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function method_dict = OrderedDict() # Remove leading Z or X from asset pair if it is of length 4 method_dict['asset'] = args.asset[1:] if len(args.asset) == 4 and args.asset[0] in ['Z', 'X'] else args.asset method_dict['method'] = method['method'] method_dict['fee'] = method['fee'] method_dict['limit'] = method['limit'] method_dict['gen-address'] = method['gen-address'] m_list.append(method_dict) if not m_list: return # Sort alphabetically m_list = sorted(m_list, key=lambda method_dict: '{}{}'.format(method_dict['asset'], method_dict['method'])) if args.csv: print(csv(m_list, headers="keys")) else: print(tabulate(m_list, headers="keys"))
def get_balance(args=None): """Get user balance.""" # Parameters to pass to the API api_params = {} res = query_api('private', 'Balance', api_params, args) bal_list = [] for asset in res: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function asset_dict = OrderedDict() # Remove leading Z or X from asset pair if it is of length 4 asset_dict['asset'] = asset[1:] if len( asset) == 4 and asset[0] in ['Z', 'X'] else asset asset_dict['balance'] = res[asset] bal_list.append(asset_dict) if not bal_list: return # Sort alphabetically bal_list = sorted(bal_list, key=lambda asset_dict: asset_dict['asset']) if args.csv: print(csv(bal_list, headers="keys")) else: print(tabulate(bal_list, headers="keys"))
def list_open_positions(args): """List open positions.""" # Parameters to pass to the API api_params = { 'docalcs': 'true', } res = query_api('private', 'OpenPositions', api_params, args) pos_list = [] for order in res.values(): pos = OrderedDict() pos['ordertxid'] = order['ordertxid'] pos['opening time'] = datetime.fromtimestamp(order['time']) pos['type'] = order['type'] pos['volume'] = order['vol'] pos['pair'] = order['pair'] pos['ordertype'] = order['ordertype'] pos['cost'] = order['cost'] pos['fee'] = order['fee'] pos['margin'] = order['margin'] pos['value'] = order['value'] pos['profit/loss'] = order['net'] pos['rollover time'] = datetime.fromtimestamp(int(order['rollovertm'])) pos['rollover terms'] = order['terms'] pos_list.append(pos) print(tabulate(pos_list, headers="keys"))
def asset_pairs(args): """Get available asset pairs.""" # Parameters to pass to the API api_params = {} res = query_api('public', 'AssetPairs', api_params, args) # initialize a list to store the parsed assets pairs assetlist = [] for assetpair in res: if assetpair.endswith('.d'): continue ad = OrderedDict() ad['Pair'] = assetpair ad['Alt Name'] = res[assetpair]['altname'] ad['Base'] = res[assetpair]['base'] ad['Quote'] = res[assetpair]['quote'] assetlist.append(ad) if args.csv: print(csv(assetlist, headers="keys")) else: print(tabulate(assetlist, headers='keys')) print('--- Total: {} pairs'.format(len(assetlist)))
def place_order(args): """Place an order.""" # Parameters to pass to the API api_params = { 'pair': args.pair, 'type': args.type, 'ordertype': args.ordertype, 'volume': args.volume, 'starttm': args.starttm, 'expiretm': args.expiretm, 'leverage': args.leverage, } if gv.TRADING_AGREEMENT == 'agree': api_params['trading_agreement'] = 'agree' if args.ordertype == 'limit': if args.price is None: logger.error('For limit orders, the price must be given!') return else: api_params['price'] = args.price elif args.ordertype == 'market': if args.price is not None: logger.warn('price is ignored for market orders!') check_trading_agreement() if args.userref: api_params['userref'] = args.userref oflags = [] # order flags if args.ordertype == 'limit': if not args.nopost: # for limit orders, by default set post-only order flag oflags.append('post') if args.viqc: oflags.append('viqc') if oflags: api_params['oflags'] = ','.join(oflags) if args.validate: api_params['validate'] = 'true' res = query_api('private', 'AddOrder', api_params, args) descr = res.get('descr') odesc = descr.get('order', 'No description available!') print(odesc) txid = res.get('txid') if not txid: if args.validate: logger.info('Validating inputs only. Order not submitted!') else: logger.warn('Order was NOT successfully added!') else: for tx in txid: print(tx)
def asset_pairs(args): """Get available asset pairs.""" # Parameters to pass to the API api_params = {} res = query_api('public', 'AssetPairs', api_params, args) # initialize a list to store the parsed assets pairs assetlist = [] for assetpair in res: if assetpair.endswith('.d'): continue ad = OrderedDict() ad['Pair'] = assetpair ad['Alt Name'] = res[assetpair]['altname'] ad['Base'] = res[assetpair]['base'] ad['Quote'] = res[assetpair]['quote'] assetlist.append(ad) if args.csv: print(csv(assetlist, headers="keys")) else: print(tabulate(assetlist, headers='keys')) print('--- Total: {} pairs'.format(len(assetlist)))
def place_order(args): """Place an order.""" # Parameters to pass to the API api_params = { 'pair': args.pair, 'type': args.type, 'ordertype': args.ordertype, 'volume': args.volume, 'starttm': args.starttm, 'expiretm': args.expiretm, 'leverage': args.leverage, } if gv.TRADING_AGREEMENT == 'agree': api_params['trading_agreement'] = 'agree' if args.ordertype == 'limit': if args.price is None: logger.error('For limit orders, the price must be given!') return else: api_params['price'] = args.price elif args.ordertype == 'market': if args.price is not None: logger.warn('price is ignored for market orders!') check_trading_agreement() if args.userref: api_params['userref'] = args.userref oflags = [] # order flags if args.ordertype == 'limit': # for limit orders, always set post only order flag oflags.append('post') if args.viqc: oflags.append('viqc') if oflags: api_params['oflags'] = ','.join(oflags) if args.validate: api_params['validate'] = 'true' res = query_api('private', 'AddOrder', api_params, args) descr = res.get('descr') odesc = descr.get('order', 'No description available!') print(odesc) txid = res.get('txid') if not txid: if args.validate: logger.info('Validating inputs only. Order not submitted!') else: logger.warn('Order was NOT successfully added!') else: for tx in txid: print(tx)
def ticker(args): """Get currency ticker information.""" # Parameters to pass to the API api_params = { 'pair': args.pair, } res = query_api('public', 'Ticker', api_params, args) # the list will contain one OrderedDict containing # the parser ticker info per asset pair ticker_list = [] for pair in res: # extract the results for the current pair pair_res = res[pair] # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function pticker = OrderedDict() pticker['pair'] = asset_pair_short(pair) pticker['last'] = pair_res['c'][0] # price only pticker['high'] = pair_res['h'][1] # last 24h pticker['low'] = pair_res['l'][1] # last 24h pticker['vol'] = pair_res['v'][1] # last 24h pticker['wavg'] = pair_res['p'][1] # last 24h # calculate an estimate of the traded volume in quoted currency # for the last 24h: Volume x Average price quote_val = Decimal(pticker['vol']) * Decimal(pticker['wavg']) unit_prefix = '' if quote_val >= 10e6: quote_val = quote_val / Decimal(1e6) unit_prefix = 'M' elif quote_val >= 10e3: quote_val = quote_val / Decimal(1e3) unit_prefix = 'k' pticker['vol value'] = str(round(quote_val)) + ' ' + unit_prefix + pticker['pair'][-3:] # get the price only pticker['ask'] = pair_res['a'][0] pticker['bid'] = pair_res['b'][0] ticker_list.append(pticker) if not ticker_list: return ticker_list = sorted(ticker_list, key=lambda pticker: pticker['pair']) if args.csv: print(csv(ticker_list, headers="keys")) else: print(tabulate(ticker_list, headers="keys"))
def depth(args): """Get market depth information.""" # Parameters to pass to the API api_params = {'pair': args.pair, 'count': args.count} res = query_api('public', 'Depth', api_params, args) depth_dict = {'asks': [], 'bids': []} depth_label = {'asks': "Ask", 'bids': "Bid"} shortpair = asset_pair_short(args.pair) # dtype is 'asks' or 'bids' for dtype in depth_dict: # extract the array of market depth from the api results dlist = res[args.pair][dtype] # build a column label depending on the asset pair and dtype price_label = shortpair + " " + depth_label[dtype] for delem in dlist: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function dentry = OrderedDict() dentry[price_label] = delem[0] dentry["Volume"] = delem[1] dentry["Age"] = humanize_timestamp(delem[2]) depth_dict[dtype].append(dentry) if not dlist: continue # sort by price descending depth_dict[dtype] = reversed( sorted(depth_dict[dtype], key=lambda dentry: Decimal(dentry[price_label]))) if args.csv: output = [] for dtype in depth_dict.keys(): for o in depth_dict[dtype]: it = OrderedDict() it['dtype'] = dtype for k, v in o.items(): if len(k.split(' ')) > 1: # key has a space, this is the "price_label" column -> "XABCZDEF Ask" it['pair'] = k.split(' ')[0] # keep only "XABCZDEF" it['price'] = v else: # the other columns don't contain a space it[k] = v output += [it] print(csv(output, headers="keys")) else: asks_table = tabulate(depth_dict['asks'], headers="keys") bids_table = tabulate(depth_dict['bids'], headers="keys") print("{}\n\n{}".format(asks_table, bids_table))
def list_open_orders(args): """List open orders.""" # Parameters to pass to the API api_params = { # TODO } if args.txid: api_params.update({'txid': args.txid}) res_ol = query_api('private', 'QueryOrders', api_params, args) else: res = query_api('private', 'OpenOrders', api_params, args) # extract list of orders from API results res_ol = res['open'] # the parsing is done in an helper function ol = parse_order_res(res_ol, ['open']) # filter and sort orders by price in each category for otype in ol: # filter orders based on currency pair if 'pair' in args and args.pair: ol[otype] = [ odict for odict in ol[otype] if (odict['pair'] in [args.pair, asset_pair_short(args.pair)] or args.pair == 'all') ] # sort orders by price ol[otype] = sorted(ol[otype], key=lambda odict: Decimal(odict['price'])) # final list is concatenation of buy orders followed by sell orders ol_all = ol['buy'] + ol['sell'] if not ol_all: return if args.csv: print(csv(ol_all, headers="keys")) else: print(tabulate(ol_all, headers="keys"))
def ohlc(args): """Get OHLC data for asset pairs for various minute intervals: 1 (default), 5, 15, 30, 60, 240, 1440, 10800, 21600.""" # Parameters to pass to the API api_params = { 'pair': args.pair, } if args.since: api_params['since'] = args.since if args.interval: api_params['interval'] = interval = args.interval else: interval = 1 res = query_api('public', 'OHLC', api_params, args) results = res[args.pair] last_id = res['last'] # initialize a list to store the parsed ohlc data ohlclist = [] for period in results: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function ohlcdict = OrderedDict() ohlcdict["Time"] = format_timestamp(period[0]) ohlcdict["Open"] = period[1] ohlcdict["High"] = period[2] ohlcdict["Low"] = period[3] ohlcdict["Close"] = period[4] ohlcdict["VWAP"] = period[5] ohlcdict["Volume"] = period[6] ohlcdict["Count"] = period[7] ohlclist.append(ohlcdict) if not ohlclist: return # Reverse trade list to have the most recent interval at the top ohlclist = ohlclist[::-1] if args.csv: print(csv(ohlclist[:args.count], headers="keys")) else: print('Asset pair: ' + asset_pair_short(args.pair)) print('Interval: ' + str(interval) + 'm\n') print(tabulate(ohlclist[:args.count], headers="keys") + '\n') print('Last ID = {}'.format(last_id))
def ohlc(args): """Get OHLC data for asset pairs for various minute intervals: 1 (default), 5, 15, 30, 60, 240, 1440, 10800, 21600.""" # Parameters to pass to the API api_params = { 'pair': args.pair, } if args.since: api_params['since'] = args.since if args.interval: api_params['interval'] = interval = args.interval else: interval = 1 res = query_api('public', 'OHLC', api_params, args) results = res[args.pair] last_id = res['last'] # initialize a list to store the parsed ohlc data ohlclist = [] for period in results: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function ohlcdict = OrderedDict() ohlcdict["Time"] = format_timestamp(period[0]) ohlcdict["Open"] = period[1] ohlcdict["High"] = period[2] ohlcdict["Low"] = period[3] ohlcdict["Close"] = period[4] ohlcdict["VWAP"] = period[5] ohlcdict["Volume"] = period[6] ohlcdict["Count"] = period[7] ohlclist.append(ohlcdict) if not ohlclist: return # Reverse trade list to have the most recent interval at the top ohlclist = ohlclist[::-1] if args.csv: print(csv(ohlclist[:args.count], headers="keys")) else: print('Asset pair: ' + asset_pair_short(args.pair)) print('Interval: ' + str(interval) + 'm\n') print(tabulate(ohlclist[:args.count], headers="keys") + '\n') print('Last ID = {}'.format(last_id))
def list_open_orders(args): """List open orders.""" # Parameters to pass to the API api_params = { # TODO } if args.txid: api_params.update({'txid': args.txid}) res_ol = query_api('private', 'QueryOrders', api_params, args) else: res = query_api('private', 'OpenOrders', api_params, args) # extract list of orders from API results res_ol = res['open'] # the parsing is done in an helper function ol = parse_order_res(res_ol, ['open']) # filter and sort orders by price in each category for otype in ol: # filter orders based on currency pair if 'pair' in args and args.pair: ol[otype] = [odict for odict in ol[otype] if (odict['pair'] in [args.pair, asset_pair_short(args.pair)] or args.pair == 'all')] # sort orders by price ol[otype] = sorted(ol[otype], key=lambda odict: Decimal(odict['price'])) # final list is concatenation of buy orders followed by sell orders ol_all = ol['buy'] + ol['sell'] if not ol_all: return if args.csv: print(csv(ol_all, headers="keys")) else: print(tabulate(ol_all, headers="keys"))
def list_closed_orders(args): """List closed orders.""" # Parameters to pass to the API api_params = { # TODO } if args.txid: api_params.update({'txid': args.txid}) res_ol = query_api('private', 'QueryOrders', api_params, args) else: res = query_api('private', 'ClosedOrders', api_params, args) # extract list of orders from API results res_ol = res['closed'] # the parsing is done in an helper function ol = parse_order_res(res_ol, ['closed', 'canceled']) # merge order types in one list ol = ol['buy'] + ol['sell'] # filter out orders with zero volume executed ol = [odict for odict in ol if Decimal(odict['vol_exec']) > 0] if 'pair' in args and args.pair: ol = [odict for odict in ol if odict['pair'] in [args.pair, asset_pair_short(args.pair)]] if not ol: return # sort by date ol = sorted(ol, key=lambda odict: odict['closing_date']) if args.csv: print(csv(ol, headers="keys")) else: print(tabulate(ol, headers="keys"))
def get_deposit_addresses(args=None): """Get deposit addresses.""" # Parameters to pass to the API api_params = { 'asset': args.asset, 'method': args.method, } if args.new: api_params['new'] = args.new res = query_api('private', 'DepositAddresses', api_params, args) if not res: return if args.one: # Get preferably not used addresses addresses = [a for a in res if a.get('new', False)] or res print(addresses[0]['address']) return addresses_list = [] for address in res: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function asset_dict = OrderedDict() # Remove leading Z or X from asset pair if it is of length 4 asset_dict['asset'] = args.asset[1:] if len( args.asset) == 4 and args.asset[0] in ['Z', 'X'] else args.asset asset_dict['address'] = address['address'] asset_dict['new'] = address.get('new', False) asset_dict['expiretm'] = \ int(address.get('expiretm', 0)) > 0 and format_timestamp(int(address.get('expiretm', 0))) or '' addresses_list.append(asset_dict) if not addresses_list: return # sort by expiretm addresses_list = sorted(addresses_list, key=lambda odict: odict['expiretm']) if args.csv: print(csv(addresses_list, headers="keys")) else: print(tabulate(addresses_list, headers="keys"))
def get_deposit_addresses(args=None): """Get deposit addresses.""" # Parameters to pass to the API api_params = { 'asset': args.asset, 'method': args.method, } if args.new: api_params['new'] = args.new res = query_api('private', 'DepositAddresses', api_params, args) if not res: return if args.one: # Get preferably not used addresses addresses = [a for a in res if a.get('new', False)] or res print(addresses[0]['address']) return addresses_list = [] for address in res: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function asset_dict = OrderedDict() # Remove leading Z or X from asset pair if it is of length 4 asset_dict['asset'] = args.asset[1:] if len(args.asset) == 4 and args.asset[0] in ['Z', 'X'] else args.asset asset_dict['address'] = address['address'] asset_dict['new'] = address.get('new', False) asset_dict['expiretm'] = \ int(address.get('expiretm', 0)) > 0 and format_timestamp(int(address.get('expiretm', 0))) or '' addresses_list.append(asset_dict) if not addresses_list: return # sort by expiretm addresses_list = sorted(addresses_list, key=lambda odict: odict['expiretm']) if args.csv: print(csv(addresses_list, headers="keys")) else: print(tabulate(addresses_list, headers="keys"))
def cancel_order(args): """Cancel an open order.""" for order_id in args.order_ids: # Parameters to pass to the API api_params = { 'txid': order_id, } res = query_api('private', 'CancelOrder', api_params, args) count = res.get('count') pending = res.get('pending') if count: print('{} - count: {}'.format(order_id, count)) if pending: logger.info('{} - order(s) is/are pending cancellation!'.format(order_id))
def cancel_order(args): """Cancel an open order.""" for order_id in args.order_ids: # Parameters to pass to the API api_params = { 'txid': order_id, } res = query_api('private', 'CancelOrder', api_params, args) count = res.get('count') pending = res.get('pending') if count: print('{} - count: {}'.format(order_id, count)) if pending: logger.info( '{} - order(s) is/are pending cancellation!'.format(order_id))
def get_trade_balance(args=None): """Get user trade balance.""" # Parameters to pass to the API api_params = {} res = query_api('private', 'TradeBalance', api_params, args) tbal_list = [ ['equivalent balance', res.get('eb', 'n/a')], ['trade balance', res.get('tb', 'n/a')], ['margin amount of open positions', res.get('m', 'n/a')], ['cost basis of open positions', res.get('c', 'n/a')], ['current floating valuation of open positions', res.get('v', 'n/a')], ['equity', res.get('e', 'n/a')], ['free margin', res.get('mf', 'n/a')], ['margin level', res.get('ml', 'n/a')], ['unrealized net profit/loss of open positions', res.get('n', 'n/a')], ] print(tabulate(tbal_list))
def get_trade_balance(args=None): """Get user trade balance.""" # Parameters to pass to the API api_params = {} res = query_api('private', 'TradeBalance', api_params, args) tbal_list = [ ['equivalent balance', res['eb']], ['trade balance', res['tb']], ['margin amount of open positions', res['m']], ['cost basis of open positions', res['c']], ['current floating valuation of open positions', res['v']], ['equity', res['e']], ['free margin', res['mf']], ['margin level', res['ml']], ['unrealized net profit/loss of open positions', res['n']], ] print(tabulate(tbal_list))
def get_deposit_methods(args=None): """Get deposit methods.""" # Parameters to pass to the API api_params = { 'asset': args.asset, } res = query_api('private', 'DepositMethods', api_params, args) m_list = [] for method in res: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function method_dict = OrderedDict() # Remove leading Z or X from asset pair if it is of length 4 method_dict['asset'] = args.asset[1:] if len( args.asset) == 4 and args.asset[0] in ['Z', 'X'] else args.asset method_dict['method'] = method['method'] method_dict['fee'] = method['fee'] method_dict['limit'] = method['limit'] method_dict['gen-address'] = method['gen-address'] m_list.append(method_dict) if not m_list: return # Sort alphabetically m_list = sorted(m_list, key=lambda method_dict: '{}{}'.format( method_dict['asset'], method_dict['method'])) if args.csv: print(csv(m_list, headers="keys")) else: print(tabulate(m_list, headers="keys"))
def last_trades(args): """Get last trades.""" _, quote_currency = base_quote_short_from_asset_pair(args.pair) # Parameters to pass to the API api_params = { 'pair': args.pair, } if args.since: api_params['since'] = args.since res = query_api('public', 'Trades', api_params, args) results = res[args.pair] last_id = res['last'] # initialize a list to store the parsed trades tlist = [] # mappings ttype_label = {'b': 'buy', 's': 'sell'} otype_label = {'l': 'limit', 'm': 'market'} for trade in results: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function tdict = OrderedDict() tdict["Trade type"] = ttype_label.get(trade[3], 'unknown') tdict["Order type"] = otype_label.get(trade[4], 'unknown') tdict["Price"] = trade[0] tdict["Volume"] = trade[1] tdict["Age"] = humanize_timestamp(trade[2]) # tdict["Misc"] = trade[5] tlist.append(tdict) if not tlist: return # Reverse trade list to have the most recent trades at the top tlist = tlist[::-1] if args.csv: print(csv(tlist[:args.count], headers="keys")) else: print(tabulate(tlist[:args.count], headers="keys") + '\n') # separate the trades based on their type sell_trades = [x for x in tlist if x["Trade type"] == "sell"] buy_trades = [x for x in tlist if x["Trade type"] == "buy"] last_sell = sell_trades[0] last_buy = buy_trades[0] lt = [ ["", "Price (" + quote_currency + ")", "Volume", "Age"], [ "Last Sell", last_sell["Price"], last_sell["Volume"], last_sell["Age"] ], [ "Last Buy", last_buy["Price"], last_buy["Volume"], last_buy["Age"] ], ] print(tabulate(lt, headers="firstrow") + '\n') print('Last ID = {}'.format(last_id))
def trades(args): """Get trades history or Query trades info""" # Parameters to pass to the API api_params = { # TODO: trades param } if args.type: api_params.update({'type': args.type}) if args.start: api_params.update({'start': args.start}) if args.end: api_params.update({'end': args.end}) if args.ofs: api_params.update({'ofs': args.ofs}) if args.id: api_params.update({ 'txid': args.id, }) res_trades = query_api('private', 'QueryTrades', api_params, args) else: res = query_api('private', 'TradesHistory', api_params, args) # extract list of orders from API results res_trades = res['trades'] # put all in a list tl = [] for trade_id, trade_data in res_trades.items(): trade_data.update({'tradeid': trade_id}) tl += [trade_data] # filter orders based on currency pair if 'pair' in args and args.pair: tl = [td for td in tl if (td['pair'] in [args.pair, asset_pair_short(args.pair)] or args.pair == 'all')] # Lets get some order and filter some unnecessary fields tl2 = [] for trade_data in tl: trade_dict = OrderedDict() trade_dict['txid'] = trade_data['tradeid'] trade_dict['time'] = format_timestamp(int(trade_data['time'])) trade_dict['pair'] = trade_data['pair'][1:] if len(trade_data['pair']) == 4 and \ trade_data['pair'][0] in ['Z', 'X'] else trade_data['pair'] trade_dict['type'] = trade_data['type'] trade_dict['ordertype'] = trade_data['ordertype'] trade_dict['vol'] = trade_data['vol'] trade_dict['price'] = trade_data['price'] trade_dict['cost'] = trade_data['cost'] trade_dict['fee'] = trade_data['fee'] trade_dict['margin'] = trade_data['margin'] trade_dict['ordertxid'] = trade_data['ordertxid'] trade_dict['misc'] = trade_data['misc'] tl2.append(trade_dict) # sort orders by time tl2 = sorted(tl2, key=lambda x: x['time']) if not tl2: return if args.csv: print(csv(tl2, headers="keys")) else: print(tabulate(tl2, headers="keys"))
def last_trades(args): """Get last trades.""" _, quote_currency = base_quote_short_from_asset_pair(args.pair) # Parameters to pass to the API api_params = { 'pair': args.pair, } if args.since: api_params['since'] = args.since res = query_api('public', 'Trades', api_params, args) results = res[args.pair] last_id = res['last'] # initialize a list to store the parsed trades tlist = [] # mappings ttype_label = {'b': 'buy', 's': 'sell'} otype_label = {'l': 'limit', 'm': 'market'} for trade in results: # Initialize an OrderedDict to garantee the column order # for later use with the tabulate function tdict = OrderedDict() tdict["Trade type"] = ttype_label.get(trade[3], 'unknown') tdict["Order type"] = otype_label.get(trade[4], 'unknown') tdict["Price"] = trade[0] tdict["Volume"] = trade[1] tdict["Age"] = humanize_timestamp(trade[2]) # tdict["Misc"] = trade[5] tlist.append(tdict) if not tlist: return # Reverse trade list to have the most recent trades at the top tlist = tlist[::-1] if args.csv: print(csv(tlist[:args.count], headers="keys")) else: print(tabulate(tlist[:args.count], headers="keys") + '\n') # separate the trades based on their type sell_trades = [x for x in tlist if x["Trade type"] == "sell"] buy_trades = [x for x in tlist if x["Trade type"] == "buy"] last_sell = sell_trades[0] last_buy = buy_trades[0] lt = [ ["", "Price (" + quote_currency + ")", "Volume", "Age"], ["Last Sell", last_sell["Price"], last_sell["Volume"], last_sell["Age"]], ["Last Buy", last_buy["Price"], last_buy["Volume"], last_buy["Age"]], ] print(tabulate(lt, headers="firstrow") + '\n') print('Last ID = {}'.format(last_id))