diff --git a/piker/brokers/kraken/api.py b/piker/brokers/kraken/api.py index c9d8d8ff..b1a932e4 100644 --- a/piker/brokers/kraken/api.py +++ b/piker/brokers/kraken/api.py @@ -88,7 +88,7 @@ def get_config() -> dict[str, Any]: ) if (section := conf.get('kraken')) is None: log.warning( - f'No config section found for kraken in {path}' + f'No config section found for kraken in {path!r}' ) return {} @@ -178,6 +178,14 @@ class Client: self.conf: dict[str, str] = config self._ws_token: str|None = None + @property + def fqan(self) -> str: + ''' + Return the EMS account name for this Kraken key's alias. + + ''' + return f'kraken.{self._key_descr}' + @property def pairs(self) -> dict[str, Pair]: @@ -416,7 +424,11 @@ class Client: try: xfers: list[dict] = resp['result'] except KeyError: - log.exception(f'Kraken suxxx: {resp}') + errors = resp.get('error') + log.exception( + f'Kraken WithdrawStatus returned no result ' + f'for {asset!r}, errors={errors!r}' + ) return [] # eg. resp schema: diff --git a/piker/brokers/kraken/broker.py b/piker/brokers/kraken/broker.py index 92709d78..14d20def 100644 --- a/piker/brokers/kraken/broker.py +++ b/piker/brokers/kraken/broker.py @@ -142,13 +142,15 @@ async def handle_order_requests( ''' # XXX: UGH, let's unify this.. with ``msgspec``!!! + fqan: str = client.fqan msg: dict|Order async for msg in ems_order_stream: log.info(f'Rx order msg:\n{pformat(msg)}') match msg: case { 'action': 'cancel', - }: + 'account': account, + } if account == fqan: cancel = BrokerdCancel(**msg) reqid = ids[cancel.oid] @@ -160,16 +162,18 @@ async def handle_order_requests( # - update dark order quickly after # triggered-submitted and then we have inavlid # value in `reqids2txids` sent over ws.send()?? - log.error('TOO FAST CANCEL/EDIT') + reason: str = ( + f'Cancel before Kraken assigned a txid ' + f'for reqid {reqid!r}' + ) + log.error(reason) toofastedit.add(reqid) reqids2txids[reqid] = reqid await ems_order_stream.send( BrokerdError( oid=msg['oid'], symbol=msg['symbol'], - reason=( - f'Edit too fast:{reqid}, cancelling..' - ), + reason=reason, ) ) @@ -184,9 +188,9 @@ async def handle_order_requests( }) case { - 'account': 'kraken.spot' as account, + 'account': account, 'action': 'buy'|'sell', - }: + } if account == fqan: # validate order = BrokerdOrder(**msg) @@ -199,7 +203,11 @@ async def handle_order_requests( except KeyError: # XXX: not sure if this block ever gets hit now? - log.error('TOO FAST EDIT') + reason = ( + f'Edit before Kraken assigned a txid ' + f'for reqid {reqid!r}, requesting cancel' + ) + log.error(reason) reqids2txids[reqid] = reqid toofastedit.add(reqid) await tractor.pause() @@ -207,9 +215,7 @@ async def handle_order_requests( BrokerdError( oid=msg['oid'], symbol=msg['symbol'], - reason=( - f'TooFastEdit reqid: {reqid}, cancelling..' - ), + reason=reason, ) ) @@ -225,8 +231,8 @@ async def handle_order_requests( reqid = BrokerClient.new_reqid() ids[order.oid] = reqid log.debug( - f"Adding order {reqid}\n" - f'{ids}' + f'Adding order {reqid!r}\n' + f'{ids!r}' ) extra = { 'ordertype': 'limit', @@ -272,7 +278,9 @@ async def handle_order_requests( # validate: 'true', # validity check, nothing more } | extra - log.info(f'Submitting WS order request:\n{pformat(req)}') + log.info( + f'Sending {ep!r} for {pair!r}, reqid={reqid!r}' + ) # NOTE HOWTO, debug order requests # @@ -286,19 +294,22 @@ async def handle_order_requests( case _: account = msg.get('account') - if account != 'kraken.spot': - log.error( - 'This is a kraken account, \ - only a `kraken.spot` selection is valid' + if account != fqan: + reason = ( + f'Invalid Kraken account {account!r}, ' + f'expected {fqan!r}' ) + else: + action = msg.get('action') + reason = f'Invalid Kraken action {action!r}' + + log.error(reason) await ems_order_stream.send( BrokerdError( oid=msg['oid'], - symbol=msg['symbol'], - reason=( - 'Invalid request msg:\n{msg}' - ), + symbol=msg.get('symbol'), + reason=reason, ) ) @@ -337,11 +348,7 @@ async def subscribe( != latest_token ): - log.info( - f'RE-subscribing to WS connection..\n' - f'orig-token: {token!r}\n' - f'latest-token: {latest_token!r}\n' - ) + log.info('Resubscribing with the current Kraken WS token') token = latest_token subnames: set[str] = set() @@ -368,18 +375,21 @@ async def subscribe( with trio.move_on_after(5): while True: msg: dict = await ws.recv_msg() - fmt_msg: str = ppfmt(msg) match msg: + case { + 'event': 'systemStatus', + 'status': 'online', + }: + log.info('Kraken private WebSocket is online') + case { 'event': 'subscriptionStatus', 'status': 'subscribed', 'subscription': sub_opts, - } as msg: - log.info( - f'Sucessful subscribe for {sub_opts}:\n' - f'{pformat(msg)}' - ) - subnames.remove(sub_opts['name']) + }: + name: str = sub_opts['name'] + log.info(f'Kraken subscription active: {name!r}') + subnames.remove(name) if not subnames: break @@ -388,19 +398,23 @@ async def subscribe( 'status': 'error', 'errorMessage': errmsg, 'subscription': sub_opts, - } as msg: - if errmsg: - etype_str, _, ev_msg = errmsg.partition(':') - etype: Type[Exception] = getattr( - api, - etype_str, - RuntimeError, - ) - - exc = etype( - f'{ev_msg}\n' - f'\n' - f'{fmt_msg}' + }: + channel: str|None = sub_opts.get('name') + etype_str: str + ev_msg: str + ( + etype_str, + _, + ev_msg, + ) = errmsg.partition(':') + etype: Type[Exception] = getattr( + api, + etype_str, + RuntimeError, + ) + reason: str = ( + f'Kraken rejected subscription {channel!r}: ' + f'{errmsg!r}' ) # !TODO, for `InvalidSession` we should # attempt retries to resub and ensure all @@ -419,17 +433,22 @@ async def subscribe( continue case _: - log.warning( - f'Unhandled subscription-status,\n' - f'{fmt_msg}' - ) + log.warning(reason) - raise exc + raise etype(reason) + + case {'event': event}: + status = msg.get('status') + log.warning( + f'Unexpected Kraken subscription event ' + f'{event!r}, status={status!r}' + ) case _: + msg_type: str = type(msg).__name__ log.warning( - f'Unknown ws event rxed?\n' - f'{fmt_msg}' + f'Expected a Kraken subscription event, ' + f'received {msg_type!r}' ) yield @@ -537,15 +556,14 @@ async def open_trade_dialog( acctid: str = client._key_descr if not accounts.get(acctid): raise ConfigurationError( - f'No API-key found for account-alias defined as {acctid!r} !\n' + f'No Kraken account entry for key alias {acctid!r}\n' f'\n' - f'Did set a `kraken.accounts.*` entry in your `brokers.toml`?\n' - f'It should look something like,\n' + f'Expected this entry in `brokers.toml`:\n' f'\n' f'[kraken]\n' f'accounts.{acctid} = {acctid!r}\n' ) - fqan: str = f'kraken.{acctid}' + fqan: str = client.fqan # task local msg dialog tracking apiflows = OrderDialogs() @@ -785,7 +803,7 @@ async def handle_order_updates( {'sequence': seq}, ]: log.info( - f'ownTrades update_{seq}:\n' + f'ownTrades update_{seq!r}:\n' f'{pformat(trades_msgs)}' ) trades = { @@ -809,7 +827,9 @@ async def handle_order_updates( # up from our own registry... reqid = reqids2txids.inverse[txid] if not reqid: - log.warning(f'Unknown trade dialog: {txid}') + log.warning( + f'Unknown trade dialog: {txid!r}' + ) action = trade['type'] price = float(trade['price']) @@ -869,7 +889,7 @@ async def handle_order_updates( ]: for order_msg in order_msgs: log.info( - f'`openOrders` msg update_{seq}:\n' + f'`openOrders` msg update_{seq!r}:\n' f'{ppfmt(order_msg)}' ) txid, update_msg = list(order_msg.items())[0] @@ -990,7 +1010,8 @@ async def handle_order_updates( # code here? # - send open order status msg. log.info( - f'Order replaced: {txid}@reqid={reqid}' + f'Order replaced: {txid!r}' + f'@reqid={reqid!r}' ) # we don't do normal msg emission on @@ -1009,7 +1030,7 @@ async def handle_order_updates( if ourreqid is None: log.info( 'Mapping new txid to our reqid:\n' - f'{reqid} -> {txid}' + f'{reqid!r} -> {txid!r}' ) oid = ids.inverse.get(reqid) @@ -1048,8 +1069,9 @@ async def handle_order_updates( # until an edit confirmation # arrives... log.cancel( - f'Received too fast edit {txid}:\n' - f'{update_msg}\n' + 'Received too fast edit ' + f'{txid!r}:\n' + f'{update_msg!r}\n' 'Cancelling order for now!..' ) # call ws api to cancel: @@ -1114,8 +1136,9 @@ async def handle_order_updates( ourreqid = reqids2txids.inverse[txid] assert reqid == ourreqid log.info( - f'openOrders vlm={vlm} Fill for {reqid}:\n' - f'{update_msg}' + f'openOrders vlm={vlm!r} ' + f'Fill for {reqid!r}:\n' + f'{update_msg!r}' ) fill_msg = BrokerdFill( @@ -1136,7 +1159,7 @@ async def handle_order_updates( case _: log.warning( 'Unknown orders msg:\n' - f'{txid}:{order_msg}' + f'{txid!r}:{order_msg!r}' ) # order request status updates @@ -1153,7 +1176,7 @@ async def handle_order_updates( } ): log.info( - f'{etype}:\n' + f'{etype!r}:\n' f'{pformat(msg)}' ) @@ -1166,7 +1189,7 @@ async def handle_order_updates( if not oid: log.warning( 'Unknown order status update?:\n' - f'{event}' + f'{event!r}' ) continue @@ -1178,8 +1201,8 @@ async def handle_order_updates( action = etype.removesuffix('OrderStatus') errmsg = rest['errorMessage'] log.error( - f'Failed to {action} order {reqid}:\n' - f'{errmsg}' + f'Failed to {action!r} order {reqid!r}:\n' + f'{errmsg!r}' ) # if tractor._state.debug_mode(): # await tractor.pause() @@ -1209,7 +1232,9 @@ async def handle_order_updates( # client was editting too quickly # so we instead cancel this order log.cancel( - f'Cancelling {reqid}@{txid} due to:\n {event}') + f'Cancelling {reqid!r}@{txid!r}:\n' + f'{event!r}' + ) await ws.send_msg({ 'event': 'cancelOrder', # 'token': token, @@ -1218,4 +1243,4 @@ async def handle_order_updates( 'txid': [txid], }) case _: - log.warning(f'Unhandled trades update msg: {msg}') + log.warning(f'Unhandled trades update msg: {msg!r}') diff --git a/piker/brokers/kraken/feed.py b/piker/brokers/kraken/feed.py index e0b19a27..bcf13666 100644 --- a/piker/brokers/kraken/feed.py +++ b/piker/brokers/kraken/feed.py @@ -89,18 +89,19 @@ async def stream_messages( though a single async generator. ''' - last_hb: float = 0 + last_hb: float|None = None async for msg in ws: match msg: case {'event': 'heartbeat'}: - now = time.time() - delay = now - last_hb - last_hb = now - + now: float = time.monotonic() # XXX: why tf is this not printing without --tl flag? - log.debug(f"Heartbeat after {delay}") - # print(f"Heartbeat after {delay}") + if last_hb is not None: + delay: float = now - last_hb + log.debug(f'Kraken heartbeat after {delay:.3f}s') + # print(f"Heartbeat after {delay}") + + last_hb = now continue @@ -128,8 +129,8 @@ async def process_data_feed_msgs( 'event': 'subscriptionStatus', } as sub: log.info( - 'WS subscription is active:\n' - f'{sub}' + 'Kraken public WS subscription status:\n' + f'{sub!r}' ) continue @@ -179,12 +180,15 @@ async def process_data_feed_msgs( 'version': ver, }: log.info( - f'Established {ver} ws connection with id: {conid}' + f'Established {ver!r} ws connection ' + f'with id: {conid!r}' ) continue case _: - print(f'UNHANDLED MSG: {msg}') + log.warning( + f'Unhandled Kraken public WS frame: {msg!r}' + ) # yield msg @@ -248,7 +252,9 @@ async def open_history_client( queries += 1 break except DataThrottle: - log.warning(f'kraken OHLC throttle for {symbol}') + log.warning( + f'Kraken OHLC throttle for {symbol!r}' + ) await trio.sleep(1) start_dt = pendulum.from_timestamp(array[0]['time']) @@ -410,6 +416,9 @@ async def stream_quotes( pass case _: - log.warning(f'Unknown WSS message: {typ}, {quote}') + log.warning( + f'Unknown WSS message: {typ!r}, ' + f'{quote!r}' + ) await send_chan.send({topic: quote}) diff --git a/piker/brokers/kraken/ledger.py b/piker/brokers/kraken/ledger.py index f250d246..9507f544 100644 --- a/piker/brokers/kraken/ledger.py +++ b/piker/brokers/kraken/ledger.py @@ -155,13 +155,9 @@ def has_pp( and pos.size ): log.warning( - f'`kraken` account says you have a ZERO ' - f'balance for {bs_mktid}:{pair}\n' - f'but piker seems to think `{pos.size}`\n' - 'This is likely a discrepancy in piker ' - 'accounting if the above number is' - "large,' though it's likely to due lack" - "f tracking xfers fees.." + f'Kraken reports a zero balance for {dst!r}, but ' + f'piker records {pos.size!r} for {pair!r}. ' + f'Untracked transfer fees may explain this.' ) return pos @@ -194,7 +190,8 @@ async def verify_balances( ) ): log.warning( - f'Skipping balance `{dst}`:{size} for position calcs!' + f'Skipping balance {dst!r}:{size!r} ' + f'for position calcs!' ) continue @@ -237,8 +234,8 @@ async def verify_balances( else: raise ValueError( 'Could not find a position pair in ' - 'ledger for likely widthdrawal ' - f'candidate: {dst}' + 'ledger for likely withdrawal ' + f'candidate: {dst!r}' ) # this was likely pos that had a withdrawal @@ -258,7 +255,7 @@ async def verify_balances( symcache=ledger.symcache, ) log.info( - f'Updated {dst} from transfers:\n' + f'Updated {dst!r} from transfers:\n' f'{pformat(updated)}' )