Skip to content

Instantly share code, notes, and snippets.

@veox
Created October 18, 2017 17:00
Show Gist options
  • Save veox/c71c42bf4c6260785d1c214e86c04e37 to your computer and use it in GitHub Desktop.
Save veox/c71c42bf4c6260785d1c214e86c04e37 to your computer and use it in GitHub Desktop.
Kraken request scheduling / 502 glitching
#!/usr/bin/env ipython
# This file is NOT YET part of krakenex.
# Licensed under the Simplified BSD license. See `examples/LICENSE.txt`.
# Place a simple buy/sell limit order.
from decimal import Decimal as D
import pprint
from time import time
import krakenex
def now():
return D(time())
def main():
k = krakenex.API()
k.load_key('kraken-trade.key')
before = now()
response = k.query_private('AddOrder', {'pair': 'XMRXBT', 'type': 'buy', 'ordertype': 'limit',
'price': '0.01175', 'volume': '1', 'userref': '0'})
after = now()
print('# response')
pprint.pprint(response)
print('# roundtrip', after - before, 'seconds')
return
if __name__ == '__main__':
main()
#!/usr/bin/env python
# This file is part of krakenex.
# Licensed under the Simplified BSD license. See `examples/LICENSE.txt`.
# Get balance available for trading/withdrawal (not on orders).
#
# NOTE: Assumes regular orders. Margin positions are not taken into account!
#
# FIXME: Also shows how current krakenex usage has too much sugar.
from decimal import Decimal as D
import pprint
import time
import krakenex
k = krakenex.API()
k.load_key('kraken-monitor.key')
balance = k.query_private('Balance')
orders = k.query_private('OpenOrders')
balance = balance['result']
orders = orders['result']
newbalance = dict()
for currency in balance:
# remove first symbol ('Z' or 'X'), but not for GNO
newname = currency[1:] if len(currency) == 4 else currency
newbalance[newname] = D(balance[currency]) # type(balance[currency]) == str
balance = newbalance
for _, o in orders['open'].items():
# remaining volume in base currency
volume = D(o['vol']) - D(o['vol_exec'])
# extract for less typing
descr = o['descr']
# order price
price = D(descr['price'])
pair = descr['pair']
base = pair[:3]
quote = pair[3:]
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
print('#', time.ctime())
for k, v in balance.items():
# convert to string for printing
if v == D('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)
veox@localhost% ./print-available-balances.py
# Wed Oct 18 19:17:11 2017
EUR <snip>
XBT 0.0144076056
<snip>

Note the balance.


veox@localhost% ./add-order.py
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
/home/veox/src/python3-krakenex/examples/add-order.py in <module>()
     31 
     32 if __name__ == '__main__':
---> 33     main()

/home/veox/src/python3-krakenex/examples/add-order.py in main()
     21     before = now()
     22     response = k.query_private('AddOrder', {'pair': 'XMRXBT', 'type': 'buy', 'ordertype': 'limit',
---> 23                                             'price': '0.01175', 'volume': '1', 'userref': '0'})
     24     after = now()
     25 

/home/veox/.local/lib/python3.6/site-packages/krakenex/api.py in query_private(self, method, data)
    167         }
    168 
--> 169         return self._query(urlpath, data, headers)
    170 
    171     def _nonce(self):

/home/veox/.local/lib/python3.6/site-packages/krakenex/api.py in _query(self, urlpath, data, headers)
    120 
    121         if self.response.status_code not in (200, 201, 202):
--> 122             self.response.raise_for_status()
    123 
    124         return self.response.json()

/usr/lib/python3.6/site-packages/requests/models.py in raise_for_status(self)
    933 
    934         if http_error_msg:
--> 935             raise HTTPError(http_error_msg, response=self)
    936 
    937     def close(self):

HTTPError: 502 Server Error: Bad Gateway for url: https://api.kraken.com/0/private/AddOrder

The query failed with a HTTP 502 error.


veox@localhost% ./print-available-balances.py
# Wed Oct 18 19:19:31 2017
EUR <snip>
XBT 0.0144076056
<snip>

Balance remains same as before.


veox@localhost% ./print-available-balances.py
# Wed Oct 18 19:19:44 2017
EUR <snip>
XBT 0.0026576056
<snip>

Several seconds later, the query that 502'ed has gone through!

@veox
Copy link
Author

veox commented Oct 18, 2017

The general approach is non-graceful: should be reusing the session, i.e. should have a single script. Not sure if that would hinder the demonstration, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment