Example #1
0
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"))
Example #2
0
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))
Example #3
0
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))
Example #4
0
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))
Example #5
0
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"))
Example #6
0
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"))
Example #7
0
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"))
Example #8
0
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"))
Example #9
0
def test_asset_pair_short():
    assert 'ETHEUR' == clikraken_utils.asset_pair_short('XETHZEUR')
    assert 'ETHEUR' == clikraken_utils.asset_pair_short('ETHEUR')
    assert 'DASHEUR' == clikraken_utils.asset_pair_short('DASHEUR')
    assert 'DASHXBT' == clikraken_utils.asset_pair_short('DASHXBT')