Inline `process_trade_msgs()` into relay loop

notokeninwswrapper
Tyler Goodlet 2022-07-03 11:18:45 -04:00
parent 47777e4192
commit aea7bec2c3
1 changed files with 72 additions and 89 deletions

View File

@ -37,9 +37,13 @@ import wsproto
from piker import pp from piker import pp
from piker.clearing._messages import ( from piker.clearing._messages import (
BrokerdPosition, BrokerdOrder, BrokerdStatus, BrokerdCancel,
BrokerdOrderAck, BrokerdError, BrokerdCancel, BrokerdError,
BrokerdFill, BrokerdFill,
BrokerdOrder,
BrokerdOrderAck,
BrokerdPosition,
BrokerdStatus,
) )
from .api import ( from .api import (
Client, Client,
@ -338,6 +342,7 @@ async def trades_dialogue(
token = resp['result']['token'] token = resp['result']['token']
ws: NoBsWs
async with ( async with (
ctx.open_stream() as ems_stream, ctx.open_stream() as ems_stream,
open_autorecon_ws( open_autorecon_ws(
@ -350,55 +355,78 @@ async def trades_dialogue(
# task for processing inbound requests from ems # task for processing inbound requests from ems
n.start_soon(handle_order_requests, client, ems_stream) n.start_soon(handle_order_requests, client, ems_stream)
# begin trade event processing count: int = 0
async for trade in process_trade_msgs( ledger_txids = {r.tid for r in trans}
ws,
trans, # pass in prior ledger transactions
):
match trade:
# prepare and send a filled status update
case Trade():
filled_msg = BrokerdStatus(
reqid=trade.reqid,
time_ns=time.time_ns(),
account=acc_name, # process and relay trades events to ems
status='filled', # https://docs.kraken.com/websockets/#message-ownTrades
filled=float(trade.size), async for msg in stream_messages(ws):
reason='Order filled by kraken', match msg:
broker_details={ case [
'name': 'kraken', trades_msgs,
'broker_time': trade.broker_time 'ownTrades',
}, {'sequence': seq},
]:
# ensure that we are only processing new trades
assert seq > count
count += 1
# TODO: figure out if kraken gives a count for entries in trades_msgs:
# of how many units of underlying were for tid, msg in entries.items():
# filled. Alternatively we can decrement
# this value ourselves by associating and
# calcing from the diff with the original
# client-side request, see:
# https://github.com/pikers/piker/issues/296
remaining=0,
)
await ems_stream.send(filled_msg.dict())
# send a fill msg for gui update if tid in ledger_txids:
fill_msg = BrokerdFill( log.debug(f'Skipping ledgered {tid}:{msg}')
reqid=trade.reqid, continue
time_ns=time.time_ns(),
action=trade.action, # yield trade
size=float(trade.size), reqid = msg['ordertxid']
price=float(trade.price), action = msg['type']
# TODO: maybe capture more msg data i.e fees? price = float(msg['price'])
broker_details={'name': 'kraken'}, size = float(msg['vol'])
broker_time=float(trade.broker_time) broker_time = float(msg['time'])
)
await ems_stream.send(fill_msg.dict()) filled_msg = BrokerdStatus(
reqid=reqid,
time_ns=time.time_ns(),
account=acc_name,
status='filled',
filled=size,
reason='Order filled by kraken',
broker_details={
'name': 'kraken',
'broker_time': broker_time
},
# TODO: figure out if kraken gives a count
# of how many units of underlying were
# filled. Alternatively we can decrement
# this value ourselves by associating and
# calcing from the diff with the original
# client-side request, see:
# https://github.com/pikers/piker/issues/296
remaining=0,
)
await ems_stream.send(filled_msg.dict())
# send a fill msg for gui update
fill_msg = BrokerdFill(
reqid=reqid,
time_ns=time.time_ns(),
action=action,
size=size,
price=price,
# TODO: maybe capture more msg data
# i.e fees?
broker_details={'name': 'kraken'},
broker_time=broker_time
)
await ems_stream.send(fill_msg.dict())
case _: case _:
log.warning(f'Unhandled trades msg: {trade}') log.warning(f'Unhandled trades msg: {msg}')
await tractor.breakpoint() await tractor.breakpoint()
@ -452,48 +480,3 @@ async def update_ledger(
# normalize to transaction form # normalize to transaction form
records = norm_trade_records(trade_entries) records = norm_trade_records(trade_entries)
return records return records
async def process_trade_msgs(
ws: NoBsWs,
trans: list[pp.Transaction],
):
'''
Parse and pack trades subscription messages, deliver framed
sequences of messages?
Ws api docs:
https://docs.kraken.com/websockets/#message-ownTrades
'''
count: int = 0
ledger_txids = {r.tid for r in trans}
async for msg in stream_messages(ws):
sub = msg[1]
seq = msg[2]['sequence']
# stream sanity checks
assert sub == 'ownTrades'
# ensure that we are only processing new trades
assert seq > count
count += 1
trade_events = msg[0]
for trade_event in trade_events:
for tid, trade_data in trade_event.items():
if tid in ledger_txids:
continue
trade = Trade(
reqid=msg['ordertxid'],
action=msg['type'],
price=msg['price'],
size=msg['vol'],
broker_time=msg['time']
)
yield trade