Skip to content

Commit

Permalink
Pass our manually mapped reqid: int to EMS
Browse files Browse the repository at this point in the history
Since we seem to always be able to get back the `reqid`/`userref` value
we send to kraken ws endpoints, we can use this as our brokerd side
order id and avoid all race cases with getting the true `txid` value
that `kraken` assigns (and which changes when you do "edits"
:eyeroll:). This simplifies status updates by allowing our relay loop
just to pass back our generated `.reqid` verbatim and allows responding
with a `BrokerdOrderAck` immediately in the request handler task which
should guarantee there are no further race conditions with the relay
loop and mapping `txid`s from kraken.. and figuring out wtf to do when
they change, etc.
  • Loading branch information
goodboy committed Jul 8, 2022
1 parent 78b9d90 commit 5100036
Showing 1 changed file with 28 additions and 23 deletions.
51 changes: 28 additions & 23 deletions piker/brokers/kraken/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async def handle_order_requests(
log.info(f'Rx order msg:\n{pformat(msg)}')
match msg:
case {
'account': 'kraken.spot',
'account': 'kraken.spot' as account,
'action': action,
} if action in {'buy', 'sell'}:

Expand All @@ -120,7 +120,7 @@ async def handle_order_requests(
reqid = next(counter)
ids[order.oid] = reqid
log.debug(
f"GENERATED ORDER {reqid}\n"
f"Adding order {reqid}\n"
f'{ids}'
)
extra = {
Expand Down Expand Up @@ -149,11 +149,18 @@ async def handle_order_requests(
log.info(f'Submitting WS order request:\n{pformat(req)}')
await ws.send_msg(req)

resp = BrokerdOrderAck(
oid=order.oid, # ems order request id
reqid=reqid, # our custom int mapping
account=account, # piker account
)
await ems_order_stream.send(resp)

# placehold for sanity checking in relay loop
emsflow.setdefault(order.oid, []).append(order)

case {
'account': 'kraken.spot',
'account': 'kraken.spot' as account,
'action': 'cancel',
}:
cancel = BrokerdCancel(**msg)
Expand Down Expand Up @@ -369,6 +376,8 @@ async def handle_order_updates(
case [
trades_msgs,
'ownTrades',
# won't exist for historical values?
# 'userref': reqid,
{'sequence': seq},
]:
# flatten msgs for processing
Expand All @@ -382,8 +391,12 @@ async def handle_order_updates(
}
for tid, trade in trades.items():

# parse-cast
reqid = trade['ordertxid']
# NOTE: try to get the requid sent in the order
# request message if posssible; it may not be
# provided since this sub also returns generic
# historical trade events.
reqid = trade.get('userref', trade['ordertxid'])

action = trade['type']
price = float(trade['price'])
size = float(trade['vol'])
Expand All @@ -392,6 +405,7 @@ async def handle_order_updates(
# send a fill msg for gui update
fill_msg = BrokerdFill(
reqid=reqid,

time_ns=time.time_ns(),

action=action,
Expand Down Expand Up @@ -540,7 +554,7 @@ async def handle_order_updates(
# order state updates
resp = BrokerdStatus(

reqid=txid,
reqid=reqid,
time_ns=time.time_ns(), # cuz why not
account=f'kraken.{acctid}',

Expand Down Expand Up @@ -598,9 +612,10 @@ async def handle_order_updates(
# 'txid': [last.reqid], # txid from submission
# })

msgs.extend(resps)
for resp in resps:
await ems_stream.send(resp.dict())
if resps:
msgs.extend(resps)
for resp in resps:
await ems_stream.send(resp.dict())

case _:
log.warning(f'Unhandled trades update msg: {msg}')
Expand Down Expand Up @@ -635,7 +650,7 @@ def process_status(
resp = BrokerdError(
oid=oid,
# XXX: use old reqid in case it changed?
reqid=last.reqid,
reqid=reqid,
symbol=getattr(last, 'symbol', 'N/A'),

reason=f'Failed {action}:\n{errmsg}',
Expand All @@ -657,12 +672,7 @@ def process_status(
f're-mapped reqid: {reqid}\n'
f'txid: {txid}\n'
)
resp = BrokerdOrderAck(
oid=oid, # ems order request id
reqid=txid, # kraken unique order id
account=last.account, # piker account
)
return [resp], False
return [], False

case {
'event': 'editOrderStatus',
Expand All @@ -680,12 +690,7 @@ def process_status(
f'{descr}'
)
# deliver another ack to update the ems-side `.reqid`.
resp = BrokerdOrderAck(
oid=oid, # ems order request id
reqid=txid, # kraken unique order id
account=last.account, # piker account
)
return [resp], False
return [], False

case {
"event": "cancelOrderStatus",
Expand All @@ -701,7 +706,7 @@ def process_status(
resps: list[MsgUnion] = []
for txid in rest.get('txid', [last.reqid]):
resp = BrokerdStatus(
reqid=txid,
reqid=reqid,
account=last.account,
time_ns=time.time_ns(),
status='cancelled',
Expand Down

0 comments on commit 5100036

Please sign in to comment.