From 6ccd8dea4ed8f32906821c1352d938d01b3f9864 Mon Sep 17 00:00:00 2001 From: Benjamin Thomas Schwertfeger Date: Thu, 13 Oct 2022 16:07:26 +0200 Subject: [PATCH] fixed missing ofs in get_ledgers_info; renameing some variables; added get_balance for spot.user --- examples/examples.py | 11 +++++---- kraken/__version__.py | 2 +- kraken/base_api/base_api.py | 9 ++++--- kraken/spot/trade/trade.py | 18 +++++++++++--- kraken/spot/user/user.py | 39 +++++++++++++++++++++++++----- kraken/spot/websocket/websocket.py | 11 ++++----- 6 files changed, 64 insertions(+), 26 deletions(-) diff --git a/examples/examples.py b/examples/examples.py index d21abfab..da36caa8 100644 --- a/examples/examples.py +++ b/examples/examples.py @@ -35,12 +35,12 @@ def main() -> None: # print(user.get_trade_balance())#asset='BTC' # print(user.get_open_orders()) # print(user.get_closed_orders()) - # print(user.get_orders_info(txid='someid')) # or txid='id1,id2,id3' or txid=['id1','id2'] + print(user.get_orders_info(txid='ONNXNP-EHGRS-JTZIOR')) # or txid='id1,id2,id3' or txid=['id1','id2'] # print(user.get_trades_history()) # print(user.get_trades_info(txid='someid')) - print(user.get_open_positions())#txid='someid' + # print(user.get_open_positions())#txid='someid' # print(user.get_ledgers_info())#asset='BTC' or asset='BTC,EUR' or asset=['BTC','EUR'] - # print(user.get_ledgers(id='LNBK7T-BLEFU-C6NGIS')) + # print(user.get_ledgers(id='LIORGR-33NXH-LBUS5Z')) # print(user.get_trade_volume())#pair='BTC/EUR' #____export_report____ @@ -61,7 +61,7 @@ def main() -> None: market = Market(key=key, secret=secret) # print(market.get_assets(assets=['XBT'])) - # print(market.get_tradable_asset_pair(pair=['BTCEUR','DOTEUR'])) + # print(market.get_tradable_asset_pair(pair=['DOTEUR'])) # print(market.get_ticker(pair='BTCUSD')) # print(market.get_ohlc(pair='BTCUSD', interval=5)) # print(market.get_order_book(pair='BTCUSDT', count=10)) @@ -127,8 +127,9 @@ def main() -> None: # timeout=60 # )) + # __ not working # print(trade.cancel_order_batch( - # orders=['OG5V2Y-RYKVL-DT3V3B','OP5V2Y-RYKVL-ET3V3B'] + # orders=['O2JLFP-VYFIW-35ZAAE', 'O523KJ-DO4M2-KAT243', 'OCDIAL-YC66C-DOF7HS', 'OVFPZ2-DA2GV-VBFVVI'] # )) diff --git a/kraken/__version__.py b/kraken/__version__.py index 73364a64..c0166557 100644 --- a/kraken/__version__.py +++ b/kraken/__version__.py @@ -1,3 +1,3 @@ -VERSION = (0, 5, 2) +VERSION = (0, 5, 3) __version__ = '.'.join(map(str, VERSION)) diff --git a/kraken/base_api/base_api.py b/kraken/base_api/base_api.py index 97ab6cfa..3ef73734 100644 --- a/kraken/base_api/base_api.py +++ b/kraken/base_api/base_api.py @@ -51,7 +51,7 @@ def _request(self, method: str, uri: str, timeout: int=10, auth: bool=True, para 'API-Sign': self.get_kraken_signature(f'{self._api_v}{uri}', params) } - headers['User-Agent'] = 'Kraken-Python-SDK' + headers['User-Agent'] = 'python-kraken-sdk' url = f'{self.url}{self._api_v}{uri}' # logging.debug(f'Request to: {url}') @@ -84,7 +84,7 @@ def check_response_data(response_data, return_raw: bool=False): else: if 'error' in data: if len(data.get('error')) == 0 and 'result' in data: return data['result'] - else: raise Exception(f'{response_data.status_code}-{response_data.text}') + else: raise Exception(f'{response_data.status_code} - {response_data.text}') else: return data else: raise Exception(f'{response_data.status_code}-{response_data.text}') @@ -93,5 +93,6 @@ def return_unique_id(self): return ''.join([each for each in str(uuid1()).split('-')]) def _to_str_list(self, a) -> str: - if type(a) == str: a = [a] - return ','.join(a) + if type(a) == str: return a + elif type(a) == list: return ','.join([i for i in a]) + else: raise ValueError('a must be string or list of strings') \ No newline at end of file diff --git a/kraken/spot/trade/trade.py b/kraken/spot/trade/trade.py index 5e7efcc1..68c03b0d 100644 --- a/kraken/spot/trade/trade.py +++ b/kraken/spot/trade/trade.py @@ -61,7 +61,18 @@ def create_order_batch(self, orders: [dict], pair: str, deadline: str=None, vali if deadline != None: params['deadline'] = deadline return self._request('POST', '/private/AddOrderBatch', params=params, do_json=True) - def edit_order(self, txid, pair: str, volume: str=None, price: str=None, price2: str=None, oflags=None, deadline: str=None, cancel_response: bool=None, validate: str=False, userref: int=None) -> dict: + def edit_order(self, + txid: str, + pair: str, + volume: str=None, + price: str=None, + price2: str=None, + oflags=None, + deadline: str=None, + cancel_response: bool=None, + validate: str=False, + userref: int=None + ) -> dict: '''https://docs.kraken.com/rest/#operation/editOrder''' params = { 'txid': txid, @@ -88,12 +99,11 @@ def cancel_all_orders(self) -> dict: def cancel_all_orders_after_x(self, timeout: int) -> dict: '''https://docs.kraken.com/rest/#operation/cancelAllOrdersAfter''' params = { 'timeout': timeout } - return self._request('POST', '/private/CancelAllOrdersAfter') + return self._request('POST', '/private/CancelAllOrdersAfter', params=params) def cancel_order_batch(self, orders: [str]) -> dict: '''https://docs.kraken.com/rest/#operation/cancelOrderBatch''' params = { 'orders': orders } - return self._request('POST', '/private/CancelOrderBatch') - + return self._request('POST', '/private/CancelOrderBatch', params=params) diff --git a/kraken/spot/user/user.py b/kraken/spot/user/user.py index b1c0a5a5..bb868b98 100644 --- a/kraken/spot/user/user.py +++ b/kraken/spot/user/user.py @@ -6,6 +6,33 @@ def get_account_balance(self) -> dict: '''https://docs.kraken.com/rest/#operation/getAccountBalance''' return self._request('POST', '/private/Balance') + def get_balances(self, currency: str) -> dict: + + balance = float(0) + symbol = None + for symbol, value in self.get_account_balance().items(): + if balance != float(0): break + elif sym in [ currency, f'Z{currency}', f'X{currency}' ]: + balance = float(value) + symbol = sym + + available_balance = balance + + for txid, order in self.get_open_orders()['open'].items(): + if sym in order['descr']['pair'][0:len(symbol)]: + if order['descr']['type'] == 'sell': + available_balance -= float(order['vol']) + elif sym in order['descr']['pair'][len(symbol):0]: + if order['descr']['type'] == 'buy': + available_balance -= float(order['vol']) * float(order['descr']['price']) + + return { + 'symbol': symbol, + 'balance': quote_balance, + 'available_balance': base_balance + } + + def get_trade_balance(self, asset=None) -> dict: '''https://docs.kraken.com/rest/#operation/getTradeBalance''' params = {} @@ -31,7 +58,7 @@ def get_closed_orders(self, trades: bool=False, userref: int=None, start: int=No return self._request('POST', '/private/ClosedOrders', params=params) - def get_orders_info(self, txid: str, trades: bool=False, userref: int=None) -> dict: + def get_orders_info(self, txid, trades: bool=False, userref: int=None) -> dict: '''https://docs.kraken.com/rest/#operation/getOrdersInfo''' params = { 'txid': txid, @@ -41,10 +68,10 @@ def get_orders_info(self, txid: str, trades: bool=False, userref: int=None) -> d if userref != None: params['userref'] = userref return self._request('POST', '/private/QueryOrders', params=params) - def get_trades_history(self, type: str='all', trades: bool=False, start: int=None, end: int=None, ofs: int=None) -> dict: + def get_trades_history(self, type_: str='all', trades: bool=False, start: int=None, end: int=None, ofs: int=None) -> dict: '''https://docs.kraken.com/rest/#operation/getTradeHistory''' params = { - 'type': type, + 'type': type_, 'trades': trades } if start != None: params['start'] = start @@ -77,7 +104,7 @@ def get_ledgers_info(self, asset: str='all', aclass: str='currency', type_: str= if type(params['asset']) == list: params['asset'] = self._to_str_list(asset) if start != None: params['start'] = start if end != None: params['end'] = end - if ofs != None: params['ofs'] = None + if ofs != None: params['ofs'] = ofs return self._request('POST', '/private/Ledgers', params=params) def get_ledgers(self, id=None, trades: bool=False) -> dict: @@ -93,7 +120,7 @@ def get_trade_volume(self, pair=None, fee_info: bool=None) -> dict: if fee_info != None: params['fee-info'] = fee_info return self._request('POST', '/private/TradeVolume', params=params) - def request_export_report(self, report: str, description: str, format: str='CSV', fields: str='all', starttm: int=None, endtm: int=None) -> dict: + def request_export_report(self, report: str, description: str, format_: str='CSV', fields: str='all', starttm: int=None, endtm: int=None) -> dict: '''https://docs.kraken.com/rest/#operation/addExport ---- RESPONSE ---- @@ -102,7 +129,7 @@ def request_export_report(self, report: str, description: str, format: str='CSV' params = { 'report': report, 'description': description, - 'format': format, + 'format': format_, 'fields': fields } if starttm != None: params['starttm'] = starttm diff --git a/kraken/spot/websocket/websocket.py b/kraken/spot/websocket/websocket.py index a2a9e71b..c1994c28 100644 --- a/kraken/spot/websocket/websocket.py +++ b/kraken/spot/websocket/websocket.py @@ -104,13 +104,12 @@ async def _reconnect(self): for task in finished: if task.exception(): exception_occur = True - message = f'{task} got an exception {task.exception()}' - message += f'\nTRACEBACK: {traceback.format_exc()}' + message = f'{task} got an exception {task.exception()}\nTRACEBACK: {traceback.format_exc()}' logging.warning(message) - for pt in pending: - logging.warning(f'pending {pt}') - try: pt.cancel() - except asyncio.CancelledError: logging.exception('CancelledError ') + for process in pending: + logging.warning(f'pending {process}') + try: process.cancel() + except asyncio.CancelledError: logging.exception('CancelledError') logging.warning('cancel ok.') await self._callback({ 'ws-error': message }) if exception_occur: break