Beispiel #1
0
async def order_conditional_close():
    kraken = asynckrakenex.API()
    kraken.load_key('test-kraken.key')
    try:
        response = await kraken.query_private(
            'AddOrder',
            {
                'pair': 'XXBTZEUR',
                'type': 'buy',
                'ordertype': 'limit',
                'price': '1',
                'volume': '1',
                # `ordertype`, `price`, `price2` are valid
                'close[ordertype]': 'limit',
                'close[price]': '9001',
                # Only validate!
                'validate': 'true',
                # these will be ignored!
                'close[pair]': 'XXBTZEUR',
                'close[type]': 'sell',
                'close[volume]': '1'
            })
        print(response)
    finally:
        await kraken.close()
Beispiel #2
0
async def print_depth():
    kraken = asynckrakenex.API()
    try:
        response = await kraken.query_public('Depth', {
            'pair': 'XXBTZUSD',
            'count': '10'
        })
        pprint.pprint(response)
    except HTTPError as e:
        print(str(e))
    finally:
        await kraken.close()
Beispiel #3
0
async def print_available_balances():
    k = asynckrakenex.API()
    k.load_key('test-kraken.key')

    balance = await k.query_private('Balance')
    orders = await k.query_private('OpenOrders')

    balance = balance['result']
    orders = orders['result']

    new_balance = dict()
    for currency in balance:
        # remove first symbol ('Z' or 'X'), but not for GNO or DASH
        new_name = currency[1:] if len(
            currency) == 4 and currency != "DASH" else currency
        new_balance[new_name] = Dec(
            balance[currency])  # type(balance[currency]) == str
    balance = new_balance

    for _, o in orders['open'].items():
        # remaining volume in base currency
        volume = Dec(o['vol']) - Dec(o['vol_exec'])

        # extract for less typing
        descr = o['descr']

        # order price
        price = Dec(descr['price'])

        pair = descr['pair']
        base = pair[:3] if pair != "DASHEUR" else "DASH"
        quote = pair[3:] if pair != "DASHEUR" else "EUR"

        type_ = descr['type']
        if type_ == 'buy':
            # buying for quote - reduce quote balance
            balance[quote] -= volume * price
        elif type_ == 'sell':
            # selling base - reduce base balance
            balance[base] -= volume

    for k, v in balance.items():
        # convert to string for printing
        if v == Dec('0'):
            s = '0'
        else:
            s = str(v)
        # remove trailing zeros (remnant of being decimal)
        s = s.rstrip('0').rstrip('.') if '.' in s else s
        #
        print(k, s)
Beispiel #4
0
async def print_open_positions():
    # configure api
    k = asynckrakenex.API()
    k.load_key('test-kraken.key')

    # prepare request
    req_data = {'docalcs': 'true'}
    try:
        # query servers
        start = await k.query_public('Time')
        open_positions = await k.query_private('OpenPositions', req_data)
        end = await k.query_public('Time')
        latency = end['result']['unixtime'] - start['result']['unixtime']

        # parse result
        b, c = 0, 0

        for order in open_positions['result']:
            coin = order["pair"]
            if coin == 'XETHZUSD':
                b += (float(order['vol']))
            elif coin == 'XXBTZUSD':
                c += (float(order['vol']))

        n_errors = len(open_positions['error'])
        total = len(open_positions['result'])

        msg = """
            error counts: {n_errors}
            latency: {latency}

            open orders
                eth: {b}
                btc: {c}
                total: {total}
            """
        print(
            msg.format(n_errors=n_errors,
                       total=total,
                       b=b,
                       c=c,
                       latency=latency))
    finally:
        await k.close()
Beispiel #5
0
async def log_ohlc():
    pair = 'XETHZEUR'
    # NOTE: for the (default) 1-minute granularity, the API seems to provide
    # data up to 12 hours old only!
    since = str(1499000000) # UTC 2017-07-02 12:53:20

    k = asynckrakenex.API()

    def now():
        return decimal.Decimal(time.time())

    def lineprint(msg, targetlen = 72):
        line = '-'*5 + ' '
        line += str(msg)

        l = len(line)
        if l < targetlen:
            trail = ' ' + '-'*(targetlen-l-1)
            line += trail

        print(line)
        return

    while True:
        lineprint(now())

        before = now()
        ret = await k.query_public('OHLC', data = {'pair': pair, 'since': since})
        after = now()

        # comment out to track the same "since"
        #since = ret['result']['last']

        # TODO: don't repeat-print if list too short
        bars = ret['result'][pair]
        for b in bars[:5]: print(b)
        print('...')
        for b in bars[-5:]: print(b)

        lineprint(after - before)

        time.sleep(20)
Beispiel #6
0
#!/usr/bin/env python3

# This file is part of asynckrakenex.
# Licensed under the Simplified BSD license. See `examples/LICENSE.txt`.

# Demonstrate use of json_options().

from types import SimpleNamespace

import asynckrakenex

kraken = asynckrakenex.API().json_options(
    object_hook=lambda kv: SimpleNamespace(**kv))
response = kraken.query_public('Time')

if response.error:
    print('error:', response.error)
else:
    result = response.result
    print('unixtime:', result.unixtime)
    print('rfc1123:', result.rfc1123)
Beispiel #7
0
    return datetime.datetime.fromtimestamp(nix_time).strftime('%m, %d, %Y')


# return formated Trades History request data
def data(start, end, ofs):
    req_data = {
        'type': 'all',
        'trades': 'true',
        'start': str(date_nix(start)),
        'end': str(date_nix(end)),
        'ofs': str(ofs)
    }
    return req_data


k = asynckrakenex.API()
k.load_key('kraken.key')

data = []
count = 0
# the maximum r
for i in range(6, 11):
    start_date = datetime.datetime(2016, i + 1, 1)
    end_date = datetime.datetime(2016, i + 2, 29)
    th = k.query_private('TradesHistory', data(start_date, end_date, 1))
    print(th['error'])
    time.sleep(.1)
    print(th)
    th_error = th['error']
    if int(th['result']['count']) > 0:
        count += th['result']['count']