piker/tests/providers/test_kraken_order_control.py

848 lines
25 KiB
Python
Raw Normal View History

'''
Offline regressions for Kraken private startup and order control.
'''
from collections import Counter
from collections.abc import AsyncIterator
import contextlib
from decimal import Decimal
import itertools
import logging
from pathlib import Path
from typing import Literal
from unittest import mock
from bidict import bidict
import httpx
import pytest
import tractor
import trio
from trio.testing import MockClock
from piker import config
from piker.brokers import kraken
from piker.brokers.kraken import (
api,
broker,
)
from piker.clearing import OrderDialogs
from piker.clearing._messages import (
BrokerdCancel,
BrokerdError,
BrokerdOrder,
BrokerdOrderAck,
)
from piker.data._symcache import SymbologyCache
from piker.data._web_bs import NoBsWs
pytestmark = pytest.mark.anyio
PRIVATE_CHANNELS: tuple[str, str] = ('ownTrades', 'openOrders')
HANDSHAKE_WATCHDOG_S: float = 30
WS_REPLY_BUFFER_SIZE: int = 16
FIRST_TOKEN: str = 'test-expired-token'
NEXT_TOKEN: str = 'test-renewed-token'
# Kraken sends heterogeneous JSON objects. `subscription_key()`
# checks the fields used to match a subscribe request to its reply.
type WsFrame = dict[str, object]
type SubscriptionStatus = Literal['subscribed', 'error']
type SubscriptionReplies = dict[tuple[str, str], SubscriptionStatus]
type KrakenConfig = dict[str, str|dict[str, str]]
type OrderCommand = BrokerdOrder|BrokerdCancel
@pytest.fixture
def anyio_backend() -> tuple[str, dict[str, MockClock]]:
'''
Advance Trio deadlines immediately when all tasks are blocked.
'''
return 'trio', {'clock': MockClock(autojump_threshold=0)}
@pytest.fixture
def token_endpoint() -> mock.AsyncMock:
'''
Supply the initial and renewed REST tokens to the Kraken client.
'''
return mock.AsyncMock(side_effect=[
{'result': {'token': FIRST_TOKEN}},
{'result': {'token': NEXT_TOKEN}},
])
@pytest.fixture
def client(
monkeypatch: pytest.MonkeyPatch,
token_endpoint: mock.AsyncMock,
) -> api.Client:
'''
Isolate the Kraken client and its broker-assigned order IDs.
- Supply REST replies while exercising the real token cache in
``api.Client.get_ws_token()``.
- Give ``broker.BrokerClient.new_reqid()`` a fresh
``BrokerClient.counter`` and ``BrokerClient._table`` per case.
'''
client: api.Client = api.Client(
config={'accounts': {'spot': 'spot'}},
httpx_client=mock.AsyncMock(spec=httpx.AsyncClient),
key_descr='spot',
)
monkeypatch.setattr(client, 'endpoint', token_endpoint)
monkeypatch.setattr(broker.BrokerClient, '_table', set())
monkeypatch.setattr(
broker.BrokerClient,
'counter',
itertools.count(1),
)
return client
@pytest.mark.parametrize(
('settings', 'result'),
[
pytest.param(None, 'paper', id='credential-free'),
pytest.param(
{'src_fiat': 'usd', 'accounts': {'swing': 'swing'}},
'kraken.swing',
id='configured-alias',
),
pytest.param(
{'accounts': {'swing': 'swing'}},
'src_fiat',
id='missing-source-fiat',
),
pytest.param({'src_fiat': 'usd'}, 'accounts', id='no-table'),
pytest.param(
{'src_fiat': 'usd', 'accounts': 'swing'},
'accounts',
id='malformed-table',
),
pytest.param(
{'src_fiat': 'usd', 'accounts': {'spot': 'spot'}},
'swing',
id='alias-mismatch',
),
],
)
async def test_trade_dialog_account(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
settings: KrakenConfig|None,
result: str,
) -> None:
'''
Exercise credential-free and authenticated trade-dialog startup.
- A missing or malformed ``kraken.accounts`` table reached
``accounts.get()`` in ``broker.open_trade_dialog()``. Pass each
config through ``api.get_client()`` with a temporary ledger.
- Capture the EMS startup reply at ``tractor.Context.started()``
for paper and the configured alias. Invalid settings must name
the field or alias before the first private REST call.
'''
conf: KrakenConfig = {}
if settings is not None:
conf = {
**settings,
'key_descr': 'swing',
'api_key': 'fake',
'secret': 'fake',
}
monkeypatch.setattr(config, '_config_dir', tmp_path)
monkeypatch.setattr(api, 'get_config', lambda: conf)
monkeypatch.setattr(
httpx.AsyncClient,
'send',
mock.AsyncMock(side_effect=AssertionError(
'Kraken trade-dialog test attempted HTTP transport I/O'
)),
)
monkeypatch.setattr(api.Client, 'get_assets', mock.AsyncMock())
monkeypatch.setattr(
api.Client,
'get_mkt_pairs',
mock.AsyncMock(),
)
private: mock.AsyncMock = mock.AsyncMock(side_effect=[
{'result': {'trades': {}, 'count': 0}},
{'result': {}},
])
monkeypatch.setattr(api.Client, 'endpoint', private)
monkeypatch.setattr(broker, 'get_console_log', lambda **_: None)
cache: SymbologyCache = SymbologyCache(
mod=kraken,
fp=tmp_path / 'symcache',
)
monkeypatch.setattr(
broker,
'open_symcache',
lambda _: contextlib.nullcontext(cache),
)
monkeypatch.setattr(
broker,
'open_cached_client',
lambda _: api.get_client(),
)
ctx: mock.AsyncMock = mock.AsyncMock(spec=tractor.Context)
class Started(Exception):
'''
Stop at the startup reply before opening a private socket.
'''
ctx.started.side_effect = Started
if result in ('paper', 'kraken.swing'):
with pytest.raises(Started):
await broker.open_trade_dialog(ctx)
if result == 'paper':
ctx.started.assert_awaited_once_with('paper')
private.assert_not_awaited()
else:
ctx.started.assert_awaited_once_with(([], [result]))
else:
with pytest.raises(config.ConfigurationError, match=result):
await broker.open_trade_dialog(ctx)
ctx.started.assert_not_awaited()
private.assert_not_awaited()
def buy(
oid: str,
symbol: str = 'xbtusd.spot',
account: str = 'kraken.spot',
price: str = '10',
reqid: int|None = None,
) -> BrokerdOrder:
'''
Build the same broker request that EMS sends for a limit buy.
'''
return BrokerdOrder(
oid=oid,
account=account,
time_ns=1,
symbol=symbol,
price=Decimal(price),
reqid=reqid,
size=1.0,
action='buy',
)
def cancel(oid: str, reqid: int) -> BrokerdCancel:
'''
Build an acknowledged EMS cancel, which carries no symbol.
'''
return BrokerdCancel(
oid=oid,
reqid=reqid,
time_ns=2,
account='kraken.spot',
)
async def request(
command: OrderCommand,
) -> AsyncIterator[OrderCommand]:
'''
Deliver a single request on an otherwise idle EMS stream.
'''
yield command
class OrderSession:
'''
Run Kraken's request and update handlers against one EMS dialog.
- ``OrderSession.ids`` maps EMS order IDs to local request IDs.
``OrderSession.txids`` maps those to exchange IDs. Both use
``OrderSession.pending`` for deferred request IDs.
- Each yield to ``OrderSession.requests()`` lets the request
handler finish one EMS command before the test supplies the
next command or calls ``OrderSession.opened()``.
'''
def __init__(self, client: api.Client) -> None:
'''
Isolate both streams and order-ID namespaces for one dialog.
'''
self.client: api.Client = client
self.ws: mock.AsyncMock = mock.AsyncMock(spec=NoBsWs)
self.ems: mock.MagicMock = mock.MagicMock(
spec=tractor.MsgStream,
)
self.ids: bidict[str, int] = bidict()
self.txids: bidict[int, str] = bidict()
self.pending: set[int] = set()
self.flows: OrderDialogs = OrderDialogs(_flows={})
async def requests(
self,
commands: AsyncIterator[OrderCommand],
) -> None:
'''
Deliver EMS requests in wire format, in the supplied order.
'''
async def messages() -> AsyncIterator[dict[str, object]]:
'''
Convert typed commands to the maps received over IPC.
'''
cmd: OrderCommand
async for cmd in commands:
yield cmd.to_dict()
self.ems.__aiter__.side_effect = messages
await broker.handle_order_requests(
ws=self.ws,
client=self.client,
ems_order_stream=self.ems,
apiflows=self.flows,
ids=self.ids,
reqids2txids=self.txids,
toofastedit=self.pending,
)
async def opened(
self,
reqid: int,
txid: str,
seq: int,
) -> None:
'''
Deliver one numbered ``openOrders`` update for an EMS reqid.
'''
async def updates() -> AsyncIterator[list[object]]:
'''
Yield a single Kraken v1 private-channel update.
'''
yield [
[{txid: {'userref': reqid, 'status': 'open'}}],
'openOrders',
{'sequence': seq},
]
await broker.handle_order_updates(
client=self.client,
ws=self.ws,
ws_stream=updates(),
ems_stream=self.ems,
apiflows=self.flows,
ids=self.ids,
reqids2txids=self.txids,
toofastedit=self.pending,
acnt=None,
ledger=None,
acctid='spot',
acc_name='kraken.spot',
)
def frames(self, event: str|None = None) -> list[WsFrame]:
'''
Return outbound WS frames in send order, optionally by event.
'''
frames: list[WsFrame] = []
args: tuple[WsFrame]
_kwargs: dict[str, object]
for args, _kwargs in self.ws.send_msg.await_args_list:
frame: WsFrame = args[0]
if event is None or frame['event'] == event:
frames.append(frame)
return frames
@pytest.mark.parametrize('alias', ['spot', 'swing'])
async def test_order_uses_configured_alias(
client: api.Client,
alias: str,
) -> None:
'''
Exercise order submission for the alias advertised by brokerd.
- An account could pass startup but lose every buy to a literal
``kraken.spot`` matcher in ``broker.handle_order_requests()``.
- Send one buy for the configured account. Its EMS ack and sole
WS submission must carry the same local request ID.
'''
client._key_descr = alias
client.conf['accounts'] = {alias: alias}
account: str = f'kraken.{alias}'
session: OrderSession = OrderSession(client)
await session.requests(request(buy('A', account=account)))
ack: object = session.ems.send.await_args.args[0]
assert isinstance(ack, BrokerdOrderAck)
assert (ack.oid, ack.account) == ('A', account)
frame: WsFrame
(frame,) = session.frames()
assert frame['event'] == 'addOrder'
assert frame['reqid'] == ack.reqid
@pytest.mark.parametrize('account', ['paper', 'kraken.other'])
async def test_reject_foreign_account(
client: api.Client,
account: str,
) -> None:
'''
Reject a buy addressed to another account before any WS send.
- A live EMS relay can receive a buy from the paper selector.
Feed that request and an unconfigured alias through the live
``broker.handle_order_requests()`` with ``kraken.spot`` active.
- Require a ``BrokerdError`` for the original order and zero
exchange messages.
'''
session: OrderSession = OrderSession(client)
await session.requests(request(buy('A', account=account)))
session.ems.send.assert_awaited_once()
error: object = session.ems.send.await_args.args[0]
assert isinstance(error, BrokerdError)
assert error.oid == 'A'
assert not session.frames()
@pytest.mark.parametrize(
'edit_first',
[False, True],
ids=['early-cancel', 'early-edit-then-cancel'],
)
async def test_cancel_waits_for_own_exchange_id(
client: api.Client,
monkeypatch: pytest.MonkeyPatch,
edit_first: bool,
) -> None:
'''
Resolve an early EMS edit or cancel against its own Kraken txid.
- ``broker.handle_order_requests()`` used a local reqid as a
txid on early edit and read a missing symbol on early cancel.
Submit two buys and request A's cancel before either opens.
- Deliver B's open first, then A's twice, between EMS messages.
Exactly one cancel after A opens proves timing and target.
'''
session: OrderSession = OrderSession(client)
pause: mock.AsyncMock = mock.AsyncMock()
monkeypatch.setattr(tractor, 'pause', pause)
async def commands() -> AsyncIterator[OrderCommand]:
'''
Interleave exchange updates between individual EMS requests.
'''
yield buy('A')
yield buy('B', 'etheur.spot')
reqid_a: int = session.ids['A']
reqid_b: int = session.ids['B']
if edit_first:
yield buy('A', price='11', reqid=reqid_a)
yield cancel('A', reqid_a)
assert reqid_a not in session.txids
await session.opened(reqid_b, 'KRAKEN-B', 1)
added_a: WsFrame
added_b: WsFrame
added_a, added_b = session.frames()
assert added_a['event'] == added_b['event'] == 'addOrder'
await session.opened(reqid_a, 'KRAKEN-A', 2)
await session.opened(reqid_a, 'KRAKEN-A', 3)
await session.requests(commands())
added_a: WsFrame
added_b: WsFrame
canceled: WsFrame
(
added_a,
added_b,
canceled,
) = session.frames()
assert added_a['reqid'] != added_b['reqid']
assert canceled['event'] == 'cancelOrder'
assert canceled['reqid'] == added_a['reqid']
assert canceled['txid'] == ['KRAKEN-A']
assert added_b['reqid'] == session.ids['B']
assert session.txids[session.ids['B']] == 'KRAKEN-B'
assert not session.pending
pause.assert_not_awaited()
async def test_edit_and_cancel_after_open(
client: api.Client,
) -> None:
'''
Keep acknowledged edits and cancels bound to their order.
- ``broker.handle_order_requests()`` reused the last buy's pair.
Open B on a different pair, then edit A in the same handler.
- Deliver A's replacement txid before its cancel. Check the edit
uses A's original ID and pair and the cancel uses its new ID.
'''
session: OrderSession = OrderSession(client)
async def commands() -> AsyncIterator[OrderCommand]:
'''
Acknowledge both adds, then replace and cancel A.
'''
yield buy('A')
yield buy('B', 'etheur.spot')
reqid_a: int = session.ids['A']
await session.opened(reqid_a, 'ORIGINAL-A', 1)
await session.opened(session.ids['B'], 'KRAKEN-B', 2)
yield buy('A', price='11', reqid=reqid_a)
await session.opened(reqid_a, 'REPLACEMENT-A', 3)
yield cancel('A', reqid_a)
await session.requests(commands())
added_a: WsFrame
added_b: WsFrame
edited: WsFrame
canceled: WsFrame
(
added_a,
added_b,
edited,
canceled,
) = session.frames()
assert added_a['event'] == added_b['event'] == 'addOrder'
assert edited['event'] == 'editOrder'
assert edited['orderid'] == 'ORIGINAL-A'
assert edited['pair'] == added_a['pair'] == 'XBT/USD'
assert edited['price'] == '11'
assert canceled['event'] == 'cancelOrder'
assert canceled['txid'] == ['REPLACEMENT-A']
assert edited['reqid'] == canceled['reqid'] == added_a['reqid']
assert added_b['reqid'] == session.ids['B']
assert session.txids[session.ids['B']] == 'KRAKEN-B'
async def test_duplicate_open_consumes_pending_cancel(
client: api.Client,
) -> None:
'''
Consume a deferred cancel on the first openOrders update.
- Repeated open notifications used to send a second cancel.
Seed ``OrderSession.pending`` as if EMS already deferred A.
- Drive ``broker.handle_order_updates()`` with B, A and A again.
Check the cancel frame and removal of the pending request.
'''
session: OrderSession = OrderSession(client)
session.ids.update({'A': 17, 'B': 23})
session.pending.add(17)
await session.opened(23, 'KRAKEN-B', 1)
assert not session.frames()
await session.opened(17, 'KRAKEN-A', 2)
await session.opened(17, 'KRAKEN-A', 3)
frames: list[WsFrame] = session.frames()
assert len(frames) == 1
canceled: WsFrame = frames[0]
assert canceled['event'] == 'cancelOrder'
assert canceled['reqid'] == 17
assert canceled['txid'] == ['KRAKEN-A']
assert not session.pending
def subscription_key(frame: WsFrame) -> tuple[str, str]:
'''
Read the token and channel name from a Kraken subscribe frame.
'''
token: str
name: str
match frame:
case {
'subscription': {
'token': str() as token,
'name': str() as name,
},
}:
return token, name
raise AssertionError(
'Kraken subscribe requires string token and name fields'
)
def private_peer(
ws: mock.AsyncMock,
replies: SubscriptionReplies,
) -> set[str]:
'''
Simulate Kraken's private subscription replies on a test socket.
- Match each outbound subscribe against a (token, channel) entry
in ``replies``. A missing entry leaves the request unanswered.
- Add a channel to the returned set only when ``ws.recv_msg()``
delivers a positive acknowledgement to ``broker.subscribe()``.
'''
send: trio.MemorySendChannel[tuple[str, SubscriptionStatus]]
receive: trio.MemoryReceiveChannel[
tuple[str, SubscriptionStatus]
]
send, receive = trio.open_memory_channel[
tuple[str, SubscriptionStatus]
](WS_REPLY_BUFFER_SIZE)
active: set[str] = set()
async def respond(frame: WsFrame) -> None:
'''
Queue a Kraken v1 status only for a scripted subscribe.
'''
if frame['event'] != 'subscribe':
return
token: str
name: str
token, name = subscription_key(frame)
key: tuple[str, str] = (token, name)
status: SubscriptionStatus|None = replies.get(key)
if status is not None:
await send.send((name, status))
async def recv() -> WsFrame:
'''
Deliver the next scripted reply and record active channels.
'''
name: str
status: SubscriptionStatus
name, status = await receive.receive()
ack: WsFrame = {
'event': 'subscriptionStatus',
'channelName': name,
'subscription': {'name': name},
'status': status,
}
if status == 'error':
ack['errorMessage'] = 'ESession:Invalid session'
else:
active.add(name)
return ack
ws.send_msg.side_effect = respond
ws.recv_msg.side_effect = recv
return active
@pytest.mark.parametrize(
'already_active',
[False, True],
ids=['both-outstanding', 'one-outstanding'],
)
async def test_renew_private_subscriptions(
client: api.Client,
token_endpoint: mock.AsyncMock,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
already_active: bool,
) -> None:
'''
Resume both private subscriptions after a stale-token rejection.
- ``broker.subscribe()`` renewed the token, entered PDB and
waited for replies to requests it never resent. Acknowledge
outstanding channels only when they subscribe with a new token.
- Check both acks before sending a cancel for an existing order.
Inspect wire tokens, the exact submissions, and diagnostics.
'''
session: OrderSession = OrderSession(client)
pause: mock.AsyncMock = mock.AsyncMock()
monkeypatch.setattr(tractor, 'pause', pause)
caplog.set_level(logging.INFO, logger=broker.__name__)
replies: SubscriptionReplies = {
(FIRST_TOKEN, 'openOrders'): 'error',
(NEXT_TOKEN, 'ownTrades'): 'subscribed',
(NEXT_TOKEN, 'openOrders'): 'subscribed',
}
if already_active:
replies[
FIRST_TOKEN,
'ownTrades',
] = 'subscribed'
active: set[str] = private_peer(session.ws, replies)
await session.requests(request(buy('A')))
reqid: int = session.ids['A']
await session.opened(reqid, 'KRAKEN-A', 1)
with trio.fail_after(HANDSHAKE_WATCHDOG_S):
async with broker.subscribe(session.ws, client, FIRST_TOKEN):
assert active == set(PRIVATE_CHANNELS)
await session.requests(request(cancel('A', reqid)))
expected: list[tuple[str, str]] = [
(FIRST_TOKEN, 'ownTrades'),
(FIRST_TOKEN, 'openOrders'),
(NEXT_TOKEN, 'openOrders'),
]
if not already_active:
expected.append((NEXT_TOKEN, 'ownTrades'))
subscriptions: Counter[tuple[str, str]] = Counter()
orders: list[WsFrame] = []
frame: WsFrame
for frame in session.frames():
if frame['event'] == 'subscribe':
subscriptions[subscription_key(frame)] += 1
elif frame['event'] != 'unsubscribe':
orders.append(frame)
assert subscriptions == Counter(expected)
add: WsFrame
canceled: WsFrame
add, canceled = orders
assert (add['event'], add['token']) == ('addOrder', FIRST_TOKEN)
assert (canceled['event'], canceled['token']) == (
'cancelOrder',
NEXT_TOKEN,
)
assert canceled['txid'] == ['KRAKEN-A']
assert token_endpoint.await_count == 2
assert FIRST_TOKEN not in caplog.text
assert NEXT_TOKEN not in caplog.text
pause.assert_not_awaited()
@pytest.mark.parametrize(
'reject',
[False, True],
ids=['missing-ack', 'rejected-twice'],
)
async def test_incomplete_handshake_blocks_orders(
client: api.Client,
token_endpoint: mock.AsyncMock,
monkeypatch: pytest.MonkeyPatch,
reject: bool,
) -> None:
'''
Keep order control closed after an incomplete private handshake.
- The deadline in ``broker.subscribe()`` could release the order
handler with just one channel. Withhold the ``openOrders`` ack
or reject that channel again after renewal.
- Trio's ``MockClock`` advances when the peer stops replying.
Require startup to raise before the separate test watchdog and
verify a second rejection uses up the single allowed renewal.
'''
session: OrderSession = OrderSession(client)
pause: mock.AsyncMock = mock.AsyncMock()
monkeypatch.setattr(tractor, 'pause', pause)
replies: SubscriptionReplies = {
(FIRST_TOKEN, 'ownTrades'): 'subscribed',
}
if reject:
token: str
for token in (FIRST_TOKEN, NEXT_TOKEN):
replies[
token,
'openOrders',
] = 'error'
active: set[str] = private_peer(session.ws, replies)
with trio.fail_after(HANDSHAKE_WATCHDOG_S):
with pytest.raises((
api.BrokerError,
RuntimeError,
ConnectionError,
trio.TooSlowError,
TimeoutError,
)):
async with broker.subscribe(
session.ws,
client,
FIRST_TOKEN,
):
pytest.fail('Incomplete handshake admitted orders')
assert active == {'ownTrades'}
assert token_endpoint.await_count == (2 if reject else 1)
if reject:
tokens: list[str] = []
frame: WsFrame
for frame in session.frames('subscribe'):
name: str
token, name = subscription_key(frame)
if name == 'openOrders':
tokens.append(token)
assert tokens == [FIRST_TOKEN, NEXT_TOKEN]
pause.assert_not_awaited()
@pytest.mark.parametrize(
'renewed',
[False, True],
ids=['initial-token', 'cached-renewal'],
)
async def test_ready_session_keeps_tokens_out_of_logs(
client: api.Client,
caplog: pytest.LogCaptureFixture,
renewed: bool,
) -> None:
'''
Keep tokens off the console during startup and order submission.
- ``broker.subscribe()`` and ``broker.handle_order_requests()``
printed tokens. Complete a healthy handshake with the initial
token or a newer one already held by ``api.Client``.
- Submit a buy and verify its wire token. Capture the broker's
INFO records across both operations and check for either token.
'''
session: OrderSession = OrderSession(client)
token: str = await client.get_ws_token()
if renewed:
token = await client.get_ws_token(force_renewal=True)
replies: SubscriptionReplies = {
(token, 'ownTrades'): 'subscribed',
(token, 'openOrders'): 'subscribed',
}
active: set[str] = private_peer(session.ws, replies)
with caplog.at_level(logging.INFO, logger=broker.__name__):
async with broker.subscribe(session.ws, client, FIRST_TOKEN):
assert active == set(PRIVATE_CHANNELS)
await session.requests(request(buy('A')))
order: WsFrame
(order,) = session.frames('addOrder')
assert order['token'] == token
assert FIRST_TOKEN not in caplog.text
assert NEXT_TOKEN not in caplog.text