Check Kraken account and subscription diagnostics

The paper selector exposed two different rejection reports for one
order. Exercise the console and EMS paths with the same request.

Tests cover,
- Submit a paper buy and a buy for a foreign Kraken alias. Check
  both reports against the configured alias. Send a foreign cancel
  with an otherwise valid order ID and require zero WS sends.
- Feed an unexpected list, an online greeting and a multiline
  rejection through the private socket. Check the quoted frame
  type, the INFO greeting and the escaped reason in both the
  WARNING and the exception.
- Check the operation, pair and reqid in the order-send log.
  Deliver a rejected edit and verify the console quotes the action
  and exchange text while EMS receives the original reason.
- Include a synthetic token in the rejected frame and check that
  neither the log nor the exception echoes it.

(this patch was generated in some part by `Codex` using
`GPT-6` (`OpenAI`))
wkt/kraken_order_regressions
Gud Boi 2026-12-01 17:45:55 -05:00
parent 06b12d6738
commit b14a45c34a
1 changed files with 161 additions and 16 deletions

View File

@ -241,7 +241,11 @@ def buy(
) )
def cancel(oid: str, reqid: int) -> BrokerdCancel: def cancel(
oid: str,
reqid: int,
account: str = 'kraken.spot',
) -> BrokerdCancel:
''' '''
Build an acknowledged EMS cancel, which carries no symbol. Build an acknowledged EMS cancel, which carries no symbol.
@ -250,7 +254,7 @@ def cancel(oid: str, reqid: int) -> BrokerdCancel:
oid=oid, oid=oid,
reqid=reqid, reqid=reqid,
time_ns=2, time_ns=2,
account='kraken.spot', account=account,
) )
@ -329,16 +333,26 @@ class OrderSession:
Deliver one numbered ``openOrders`` update for an EMS reqid. Deliver one numbered ``openOrders`` update for an EMS reqid.
''' '''
async def updates() -> AsyncIterator[list[object]]: await self.update([
[{txid: {'userref': reqid, 'status': 'open'}}],
'openOrders',
{'sequence': seq},
])
async def update(
self,
frame: WsFrame|list[object],
) -> None:
'''
Deliver one private-channel frame to the live update handler.
'''
async def updates() -> AsyncIterator[WsFrame|list[object]]:
''' '''
Yield a single Kraken v1 private-channel update. Yield the frame and end this receive loop.
''' '''
yield [ yield frame
[{txid: {'userref': reqid, 'status': 'open'}}],
'openOrders',
{'sequence': seq},
]
await broker.handle_order_updates( await broker.handle_order_updates(
client=self.client, client=self.client,
@ -400,27 +414,57 @@ async def test_order_uses_configured_alias(
assert frame['reqid'] == ack.reqid assert frame['reqid'] == ack.reqid
@pytest.mark.parametrize('account', ['paper', 'kraken.other']) @pytest.mark.parametrize(
'account, cancel_order',
[
pytest.param('paper', False, id='paper-buy'),
pytest.param('kraken.spot', False, id='foreign-buy'),
pytest.param('kraken.other', True, id='foreign-cancel'),
],
)
async def test_reject_foreign_account( async def test_reject_foreign_account(
client: api.Client, client: api.Client,
account: str, account: str,
cancel_order: bool,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
''' '''
Reject a buy addressed to another account before any WS send. Reject requests addressed to another account before any WS send.
- A live EMS relay can receive a buy from the paper selector. - A live EMS relay can receive a buy from the paper selector.
Feed that request and an unconfigured alias through the live With ``kraken.swing`` active, submit a paper or foreign buy,
``broker.handle_order_requests()`` with ``kraken.spot`` active. or a symbol-less cancel carrying another account's name.
- Require a ``BrokerdError`` for the original order and zero - The console included source indentation and EMS saw a literal
exchange messages. placeholder. Require one readable reason identifying both
accounts in both reports and zero exchange messages.
''' '''
client._key_descr = 'swing'
client.conf['accounts'] = {'swing': 'swing'}
session: OrderSession = OrderSession(client) session: OrderSession = OrderSession(client)
await session.requests(request(buy('A', account=account))) command: OrderCommand
if cancel_order:
command = cancel('A', reqid=17, account=account)
session.ids['A'] = 17
session.txids[17] = 'KRAKEN-A'
else:
command = buy('A', account=account)
await session.requests(request(command))
session.ems.send.assert_awaited_once() session.ems.send.assert_awaited_once()
error: object = session.ems.send.await_args.args[0] error: object = session.ems.send.await_args.args[0]
assert isinstance(error, BrokerdError) assert isinstance(error, BrokerdError)
assert error.oid == 'A' assert error.oid == 'A'
expected_account: str = 'kraken.swing'
expected: str = (
f'Invalid Kraken account {account!r}, '
f'expected {expected_account!r}'
)
assert error.reason == expected
assert (broker.__name__, logging.ERROR, expected) in (
caplog.record_tuples
)
assert not session.frames() assert not session.frames()
@ -843,5 +887,106 @@ async def test_ready_session_keeps_tokens_out_of_logs(
order: WsFrame order: WsFrame
(order,) = session.frames('addOrder') (order,) = session.frames('addOrder')
assert order['token'] == token assert order['token'] == token
assert (
broker.__name__,
logging.INFO,
"Sending 'addOrder' for 'XBT/USD', reqid=1",
) in caplog.record_tuples
assert FIRST_TOKEN not in caplog.text assert FIRST_TOKEN not in caplog.text
assert NEXT_TOKEN not in caplog.text assert NEXT_TOKEN not in caplog.text
async def test_private_subscription_diagnostics(
client: api.Client,
caplog: pytest.LogCaptureFixture,
) -> None:
'''
Report connection status and rejected private subscriptions.
- The online greeting triggered an unknown-event warning. An
error could copy the whole private reply into a log and an
exception. Send both messages through ``broker.subscribe()``.
- Send an unexpected list and a multiline rejection. Check that
the warning names the frame type and quotes the exchange text
without exposing a token or splitting the reason across lines.
'''
ws: mock.AsyncMock = mock.AsyncMock(spec=NoBsWs)
errmsg: str = 'EGeneral:Permission denied\nretry later'
ws.recv_msg.side_effect = [
[FIRST_TOKEN],
{
'event': 'systemStatus',
'status': 'online',
},
{
'event': 'subscriptionStatus',
'status': 'error',
'subscription': {
'name': 'openOrders',
'token': FIRST_TOKEN,
},
'errorMessage': errmsg,
},
]
exc: pytest.ExceptionInfo[RuntimeError]
with (
caplog.at_level(logging.INFO, logger=broker.__name__),
pytest.raises(RuntimeError) as exc,
):
async with broker.subscribe(ws, client, FIRST_TOKEN):
pytest.fail('Kraken admitted a rejected subscription')
reason: str = str(exc.value)
assert reason == (
"Kraken rejected subscription 'openOrders': "
f'{errmsg!r}'
)
assert (
broker.__name__,
logging.WARNING,
"Expected a Kraken subscription event, received 'list'",
) in caplog.record_tuples
assert (broker.__name__, logging.WARNING, reason) in (
caplog.record_tuples
)
assert (
broker.__name__,
logging.INFO,
'Kraken private WebSocket is online',
) in caplog.record_tuples
assert FIRST_TOKEN not in reason
assert FIRST_TOKEN not in caplog.text
async def test_rejected_order_diagnostics(
client: api.Client,
caplog: pytest.LogCaptureFixture,
) -> None:
'''
Identify the exchange action and its error in the console.
- A rejected edit printed its wire action as ordinary prose.
Deliver an ``editOrderStatus`` with a multiline error through
``broker.handle_order_updates()``.
- Require the quoted action, numeric request ID and escaped
error in the log. EMS receives the original rejection text.
'''
session: OrderSession = OrderSession(client)
session.ids['A'] = 17
errmsg: str = 'EOrder:Invalid price\ncheck tick size'
await session.update({
'event': 'editOrderStatus',
'status': 'error',
'reqid': 17,
'errorMessage': errmsg,
})
assert (
broker.__name__,
logging.ERROR,
f"Failed to 'edit' order 17:\n{errmsg!r}",
) in caplog.record_tuples
session.ems.send.assert_awaited_once()
error: BrokerdError = session.ems.send.await_args.args[0]
assert error.reason == f'Failed edit:\n{errmsg}'