Use the Kraken account alias and fix broker diagnostics

The dialog advertised the configured alias while orders for any
account but `kraken.spot` were rejected. The console and EMS gave
different reasons, and INFO logs could expose private WS tokens.

Deats,
- Use `Client.fqan` to advertise and check the same account name.
  Check buy, sell and cancel requests before sending a WS frame.
- Give brokerd and EMS the same account or action rejection reason.
  Quote raw console fields with `!r` so readers can distinguish
  Kraken action names, IDs and string volumes from report prose.
  Keep the layout of pretty-printed messages and heartbeat timing.
- Quote the operation and pair in order-send logs. Report private
  subscription results by channel and treat the online greeting
  as routine. Quote rejected exchange text and the type of an
  unexpected reply. Keep token-bearing frames out of these reports.

Also,
- Measure heartbeat intervals from the second heartbeat onward.
  Report public subscription status and log unknown feed messages.
- Identify the asset and pair in zero-balance warnings and report
  the Kraken error when `WithdrawStatus` omits its result.

(this patch was generated in some part by `Codex` using
`GPT-6` (`OpenAI`))

(cherry picked from commit 14099adfd1640e8908dfca5c5e2943a02acd0e43)
wkt/land_kraken_parity_replay
Gud Boi 2026-12-01 17:42:22 -05:00
parent cc9f827fa0
commit 3889ab4db1
4 changed files with 143 additions and 100 deletions

View File

@ -88,7 +88,7 @@ def get_config() -> dict[str, Any]:
) )
if (section := conf.get('kraken')) is None: if (section := conf.get('kraken')) is None:
log.warning( log.warning(
f'No config section found for kraken in {path}' f'No config section found for kraken in {path!r}'
) )
return {} return {}
@ -178,6 +178,14 @@ class Client:
self.conf: dict[str, str] = config self.conf: dict[str, str] = config
self._ws_token: str|None = None 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 @property
def pairs(self) -> dict[str, Pair]: def pairs(self) -> dict[str, Pair]:
@ -416,7 +424,11 @@ class Client:
try: try:
xfers: list[dict] = resp['result'] xfers: list[dict] = resp['result']
except KeyError: 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 [] return []
# eg. resp schema: # eg. resp schema:

View File

@ -142,13 +142,15 @@ async def handle_order_requests(
''' '''
# XXX: UGH, let's unify this.. with ``msgspec``!!! # XXX: UGH, let's unify this.. with ``msgspec``!!!
fqan: str = client.fqan
msg: dict|Order msg: dict|Order
async for msg in ems_order_stream: async for msg in ems_order_stream:
log.info(f'Rx order msg:\n{pformat(msg)}') log.info(f'Rx order msg:\n{pformat(msg)}')
match msg: match msg:
case { case {
'action': 'cancel', 'action': 'cancel',
}: 'account': account,
} if account == fqan:
cancel = BrokerdCancel(**msg) cancel = BrokerdCancel(**msg)
reqid = ids[cancel.oid] reqid = ids[cancel.oid]
@ -160,16 +162,18 @@ async def handle_order_requests(
# - update dark order quickly after # - update dark order quickly after
# triggered-submitted and then we have inavlid # triggered-submitted and then we have inavlid
# value in `reqids2txids` sent over ws.send()?? # 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) toofastedit.add(reqid)
reqids2txids[reqid] = reqid reqids2txids[reqid] = reqid
await ems_order_stream.send( await ems_order_stream.send(
BrokerdError( BrokerdError(
oid=msg['oid'], oid=msg['oid'],
symbol=msg['symbol'], symbol=msg['symbol'],
reason=( reason=reason,
f'Edit too fast:{reqid}, cancelling..'
),
) )
) )
@ -184,9 +188,9 @@ async def handle_order_requests(
}) })
case { case {
'account': 'kraken.spot' as account, 'account': account,
'action': 'buy'|'sell', 'action': 'buy'|'sell',
}: } if account == fqan:
# validate # validate
order = BrokerdOrder(**msg) order = BrokerdOrder(**msg)
@ -199,7 +203,11 @@ async def handle_order_requests(
except KeyError: except KeyError:
# XXX: not sure if this block ever gets hit now? # 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 reqids2txids[reqid] = reqid
toofastedit.add(reqid) toofastedit.add(reqid)
await tractor.pause() await tractor.pause()
@ -207,9 +215,7 @@ async def handle_order_requests(
BrokerdError( BrokerdError(
oid=msg['oid'], oid=msg['oid'],
symbol=msg['symbol'], symbol=msg['symbol'],
reason=( reason=reason,
f'TooFastEdit reqid: {reqid}, cancelling..'
),
) )
) )
@ -225,8 +231,8 @@ async def handle_order_requests(
reqid = BrokerClient.new_reqid() reqid = BrokerClient.new_reqid()
ids[order.oid] = reqid ids[order.oid] = reqid
log.debug( log.debug(
f"Adding order {reqid}\n" f'Adding order {reqid!r}\n'
f'{ids}' f'{ids!r}'
) )
extra = { extra = {
'ordertype': 'limit', 'ordertype': 'limit',
@ -272,7 +278,9 @@ async def handle_order_requests(
# validate: 'true', # validity check, nothing more # validate: 'true', # validity check, nothing more
} | extra } | 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 # NOTE HOWTO, debug order requests
# #
@ -286,19 +294,22 @@ async def handle_order_requests(
case _: case _:
account = msg.get('account') account = msg.get('account')
if account != 'kraken.spot': if account != fqan:
log.error( reason = (
'This is a kraken account, \ f'Invalid Kraken account {account!r}, '
only a `kraken.spot` selection is valid' f'expected {fqan!r}'
) )
else:
action = msg.get('action')
reason = f'Invalid Kraken action {action!r}'
log.error(reason)
await ems_order_stream.send( await ems_order_stream.send(
BrokerdError( BrokerdError(
oid=msg['oid'], oid=msg['oid'],
symbol=msg['symbol'], symbol=msg.get('symbol'),
reason=( reason=reason,
'Invalid request msg:\n{msg}'
),
) )
) )
@ -337,11 +348,7 @@ async def subscribe(
!= !=
latest_token latest_token
): ):
log.info( log.info('Resubscribing with the current Kraken WS token')
f'RE-subscribing to WS connection..\n'
f'orig-token: {token!r}\n'
f'latest-token: {latest_token!r}\n'
)
token = latest_token token = latest_token
subnames: set[str] = set() subnames: set[str] = set()
@ -368,18 +375,21 @@ async def subscribe(
with trio.move_on_after(5): with trio.move_on_after(5):
while True: while True:
msg: dict = await ws.recv_msg() msg: dict = await ws.recv_msg()
fmt_msg: str = ppfmt(msg)
match msg: match msg:
case {
'event': 'systemStatus',
'status': 'online',
}:
log.info('Kraken private WebSocket is online')
case { case {
'event': 'subscriptionStatus', 'event': 'subscriptionStatus',
'status': 'subscribed', 'status': 'subscribed',
'subscription': sub_opts, 'subscription': sub_opts,
} as msg: }:
log.info( name: str = sub_opts['name']
f'Sucessful subscribe for {sub_opts}:\n' log.info(f'Kraken subscription active: {name!r}')
f'{pformat(msg)}' subnames.remove(name)
)
subnames.remove(sub_opts['name'])
if not subnames: if not subnames:
break break
@ -388,19 +398,23 @@ async def subscribe(
'status': 'error', 'status': 'error',
'errorMessage': errmsg, 'errorMessage': errmsg,
'subscription': sub_opts, 'subscription': sub_opts,
} as msg: }:
if errmsg: channel: str|None = sub_opts.get('name')
etype_str, _, ev_msg = errmsg.partition(':') etype_str: str
ev_msg: str
(
etype_str,
_,
ev_msg,
) = errmsg.partition(':')
etype: Type[Exception] = getattr( etype: Type[Exception] = getattr(
api, api,
etype_str, etype_str,
RuntimeError, RuntimeError,
) )
reason: str = (
exc = etype( f'Kraken rejected subscription {channel!r}: '
f'{ev_msg}\n' f'{errmsg!r}'
f'\n'
f'{fmt_msg}'
) )
# !TODO, for `InvalidSession` we should # !TODO, for `InvalidSession` we should
# attempt retries to resub and ensure all # attempt retries to resub and ensure all
@ -419,17 +433,22 @@ async def subscribe(
continue continue
case _: case _:
log.warning(reason)
raise etype(reason)
case {'event': event}:
status = msg.get('status')
log.warning( log.warning(
f'Unhandled subscription-status,\n' f'Unexpected Kraken subscription event '
f'{fmt_msg}' f'{event!r}, status={status!r}'
) )
raise exc
case _: case _:
msg_type: str = type(msg).__name__
log.warning( log.warning(
f'Unknown ws event rxed?\n' f'Expected a Kraken subscription event, '
f'{fmt_msg}' f'received {msg_type!r}'
) )
yield yield
@ -537,15 +556,14 @@ async def open_trade_dialog(
acctid: str = client._key_descr acctid: str = client._key_descr
if not accounts.get(acctid): if not accounts.get(acctid):
raise ConfigurationError( 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'\n'
f'Did set a `kraken.accounts.*` entry in your `brokers.toml`?\n' f'Expected this entry in `brokers.toml`:\n'
f'It should look something like,\n'
f'\n' f'\n'
f'[kraken]\n' f'[kraken]\n'
f'accounts.{acctid} = {acctid!r}\n' f'accounts.{acctid} = {acctid!r}\n'
) )
fqan: str = f'kraken.{acctid}' fqan: str = client.fqan
# task local msg dialog tracking # task local msg dialog tracking
apiflows = OrderDialogs() apiflows = OrderDialogs()
@ -785,7 +803,7 @@ async def handle_order_updates(
{'sequence': seq}, {'sequence': seq},
]: ]:
log.info( log.info(
f'ownTrades update_{seq}:\n' f'ownTrades update_{seq!r}:\n'
f'{pformat(trades_msgs)}' f'{pformat(trades_msgs)}'
) )
trades = { trades = {
@ -809,7 +827,9 @@ async def handle_order_updates(
# up from our own registry... # up from our own registry...
reqid = reqids2txids.inverse[txid] reqid = reqids2txids.inverse[txid]
if not reqid: if not reqid:
log.warning(f'Unknown trade dialog: {txid}') log.warning(
f'Unknown trade dialog: {txid!r}'
)
action = trade['type'] action = trade['type']
price = float(trade['price']) price = float(trade['price'])
@ -869,7 +889,7 @@ async def handle_order_updates(
]: ]:
for order_msg in order_msgs: for order_msg in order_msgs:
log.info( log.info(
f'`openOrders` msg update_{seq}:\n' f'`openOrders` msg update_{seq!r}:\n'
f'{ppfmt(order_msg)}' f'{ppfmt(order_msg)}'
) )
txid, update_msg = list(order_msg.items())[0] txid, update_msg = list(order_msg.items())[0]
@ -990,7 +1010,8 @@ async def handle_order_updates(
# code here? # code here?
# - send open order status msg. # - send open order status msg.
log.info( 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 # we don't do normal msg emission on
@ -1009,7 +1030,7 @@ async def handle_order_updates(
if ourreqid is None: if ourreqid is None:
log.info( log.info(
'Mapping new txid to our reqid:\n' 'Mapping new txid to our reqid:\n'
f'{reqid} -> {txid}' f'{reqid!r} -> {txid!r}'
) )
oid = ids.inverse.get(reqid) oid = ids.inverse.get(reqid)
@ -1048,8 +1069,9 @@ async def handle_order_updates(
# until an edit confirmation # until an edit confirmation
# arrives... # arrives...
log.cancel( log.cancel(
f'Received too fast edit {txid}:\n' 'Received too fast edit '
f'{update_msg}\n' f'{txid!r}:\n'
f'{update_msg!r}\n'
'Cancelling order for now!..' 'Cancelling order for now!..'
) )
# call ws api to cancel: # call ws api to cancel:
@ -1114,8 +1136,9 @@ async def handle_order_updates(
ourreqid = reqids2txids.inverse[txid] ourreqid = reqids2txids.inverse[txid]
assert reqid == ourreqid assert reqid == ourreqid
log.info( log.info(
f'openOrders vlm={vlm} Fill for {reqid}:\n' f'openOrders vlm={vlm!r} '
f'{update_msg}' f'Fill for {reqid!r}:\n'
f'{update_msg!r}'
) )
fill_msg = BrokerdFill( fill_msg = BrokerdFill(
@ -1136,7 +1159,7 @@ async def handle_order_updates(
case _: case _:
log.warning( log.warning(
'Unknown orders msg:\n' 'Unknown orders msg:\n'
f'{txid}:{order_msg}' f'{txid!r}:{order_msg!r}'
) )
# order request status updates # order request status updates
@ -1153,7 +1176,7 @@ async def handle_order_updates(
} }
): ):
log.info( log.info(
f'{etype}:\n' f'{etype!r}:\n'
f'{pformat(msg)}' f'{pformat(msg)}'
) )
@ -1166,7 +1189,7 @@ async def handle_order_updates(
if not oid: if not oid:
log.warning( log.warning(
'Unknown order status update?:\n' 'Unknown order status update?:\n'
f'{event}' f'{event!r}'
) )
continue continue
@ -1178,8 +1201,8 @@ async def handle_order_updates(
action = etype.removesuffix('OrderStatus') action = etype.removesuffix('OrderStatus')
errmsg = rest['errorMessage'] errmsg = rest['errorMessage']
log.error( log.error(
f'Failed to {action} order {reqid}:\n' f'Failed to {action!r} order {reqid!r}:\n'
f'{errmsg}' f'{errmsg!r}'
) )
# if tractor._state.debug_mode(): # if tractor._state.debug_mode():
# await tractor.pause() # await tractor.pause()
@ -1209,7 +1232,9 @@ async def handle_order_updates(
# client was editting too quickly # client was editting too quickly
# so we instead cancel this order # so we instead cancel this order
log.cancel( log.cancel(
f'Cancelling {reqid}@{txid} due to:\n {event}') f'Cancelling {reqid!r}@{txid!r}:\n'
f'{event!r}'
)
await ws.send_msg({ await ws.send_msg({
'event': 'cancelOrder', 'event': 'cancelOrder',
# 'token': token, # 'token': token,
@ -1218,4 +1243,4 @@ async def handle_order_updates(
'txid': [txid], 'txid': [txid],
}) })
case _: case _:
log.warning(f'Unhandled trades update msg: {msg}') log.warning(f'Unhandled trades update msg: {msg!r}')

View File

@ -89,19 +89,20 @@ async def stream_messages(
though a single async generator. though a single async generator.
''' '''
last_hb: float = 0 last_hb: float|None = None
async for msg in ws: async for msg in ws:
match msg: match msg:
case {'event': 'heartbeat'}: case {'event': 'heartbeat'}:
now = time.time() now: float = time.monotonic()
delay = now - last_hb
last_hb = now
# XXX: why tf is this not printing without --tl flag? # XXX: why tf is this not printing without --tl flag?
log.debug(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}") # print(f"Heartbeat after {delay}")
last_hb = now
continue continue
case _: case _:
@ -128,8 +129,8 @@ async def process_data_feed_msgs(
'event': 'subscriptionStatus', 'event': 'subscriptionStatus',
} as sub: } as sub:
log.info( log.info(
'WS subscription is active:\n' 'Kraken public WS subscription status:\n'
f'{sub}' f'{sub!r}'
) )
continue continue
@ -179,12 +180,15 @@ async def process_data_feed_msgs(
'version': ver, 'version': ver,
}: }:
log.info( log.info(
f'Established {ver} ws connection with id: {conid}' f'Established {ver!r} ws connection '
f'with id: {conid!r}'
) )
continue continue
case _: case _:
print(f'UNHANDLED MSG: {msg}') log.warning(
f'Unhandled Kraken public WS frame: {msg!r}'
)
# yield msg # yield msg
@ -248,7 +252,9 @@ async def open_history_client(
queries += 1 queries += 1
break break
except DataThrottle: except DataThrottle:
log.warning(f'kraken OHLC throttle for {symbol}') log.warning(
f'Kraken OHLC throttle for {symbol!r}'
)
await trio.sleep(1) await trio.sleep(1)
start_dt = pendulum.from_timestamp(array[0]['time']) start_dt = pendulum.from_timestamp(array[0]['time'])
@ -410,6 +416,9 @@ async def stream_quotes(
pass pass
case _: 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}) await send_chan.send({topic: quote})

View File

@ -155,13 +155,9 @@ def has_pp(
and pos.size and pos.size
): ):
log.warning( log.warning(
f'`kraken` account says you have a ZERO ' f'Kraken reports a zero balance for {dst!r}, but '
f'balance for {bs_mktid}:{pair}\n' f'piker records {pos.size!r} for {pair!r}. '
f'but piker seems to think `{pos.size}`\n' f'Untracked transfer fees may explain this.'
'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.."
) )
return pos return pos
@ -194,7 +190,8 @@ async def verify_balances(
) )
): ):
log.warning( log.warning(
f'Skipping balance `{dst}`:{size} for position calcs!' f'Skipping balance {dst!r}:{size!r} '
f'for position calcs!'
) )
continue continue
@ -237,8 +234,8 @@ async def verify_balances(
else: else:
raise ValueError( raise ValueError(
'Could not find a position pair in ' 'Could not find a position pair in '
'ledger for likely widthdrawal ' 'ledger for likely withdrawal '
f'candidate: {dst}' f'candidate: {dst!r}'
) )
# this was likely pos that had a withdrawal # this was likely pos that had a withdrawal
@ -258,7 +255,7 @@ async def verify_balances(
symcache=ledger.symcache, symcache=ledger.symcache,
) )
log.info( log.info(
f'Updated {dst} from transfers:\n' f'Updated {dst!r} from transfers:\n'
f'{pformat(updated)}' f'{pformat(updated)}'
) )