Skip to content

Commit

Permalink
fixed missing ofs in get_ledgers_info; renameing some variables; adde…
Browse files Browse the repository at this point in the history
…d get_balance for spot.user
  • Loading branch information
btschwertfeger committed Oct 13, 2022
1 parent 0bf2c86 commit 6ccd8de
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 26 deletions.
11 changes: 6 additions & 5 deletions examples/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -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____
Expand All @@ -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))
Expand Down Expand Up @@ -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']
# ))


Expand Down
2 changes: 1 addition & 1 deletion kraken/__version__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
VERSION = (0, 5, 2)
VERSION = (0, 5, 3)

__version__ = '.'.join(map(str, VERSION))
9 changes: 5 additions & 4 deletions kraken/base_api/base_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}')
Expand Down Expand Up @@ -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}')

Expand All @@ -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')
18 changes: 14 additions & 4 deletions kraken/spot/trade/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)


39 changes: 33 additions & 6 deletions kraken/spot/user/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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 ----
Expand All @@ -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
Expand Down
11 changes: 5 additions & 6 deletions kraken/spot/websocket/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 6ccd8de

Please sign in to comment.