Drop wacky if block logic, while loop, handle errors and prep for async batching

notokeninwswrapper
Tyler Goodlet 2022-06-29 17:21:45 -04:00
parent d3caad6e11
commit 9106d13dfe
1 changed files with 39 additions and 28 deletions

View File

@ -21,6 +21,7 @@ Kraken web API wrapping.
from contextlib import asynccontextmanager as acm from contextlib import asynccontextmanager as acm
from dataclasses import field from dataclasses import field
from datetime import datetime from datetime import datetime
import itertools
from typing import ( from typing import (
Any, Any,
Optional, Optional,
@ -28,7 +29,8 @@ from typing import (
) )
import time import time
import trio # import trio
# import tractor
import pendulum import pendulum
import asks import asks
from fuzzywuzzy import process as fuzzy from fuzzywuzzy import process as fuzzy
@ -213,37 +215,46 @@ class Client:
async def get_trades( async def get_trades(
self, self,
data: dict[str, Any] = {}
) -> dict[str, Any]: ) -> dict[str, Any]:
data['ofs'] = 0 '''
# Grab all trade history Get the trades (aka cleared orders) history from the rest endpoint:
# https://docs.kraken.com/rest/#operation/getTradeHistory https://docs.kraken.com/rest/#operation/getTradeHistory
# Kraken uses 'ofs' to refer to the offset
while True: '''
resp = await self.endpoint('TradesHistory', data) ofs = 0
# grab the first 50 trades trades_by_id: dict[str, Any] = {}
if data['ofs'] == 0:
trades = resp['result']['trades'] for i in itertools.count():
# load the next 50 trades using dict constructor
# for speed # increment 'ofs' pagination offset
elif data['ofs'] == 50: ofs = i*50
trades = dict(trades, **resp['result']['trades'])
# catch the end of the trades resp = await self.endpoint(
elif resp['result']['trades'] == {}: 'TradesHistory',
{'ofs': ofs},
)
# get up to 50 results
try:
by_id = resp['result']['trades']
except KeyError:
err = resp['error']
raise BrokerError(err)
trades_by_id.update(by_id)
if (
len(by_id) < 50
):
# we know we received the max amount of
# trade results so there may be more history.
# catch the end of the trades
count = resp['result']['count'] count = resp['result']['count']
break break
# update existing dict if num trades exceeds 100
else:
trades.update(resp['result']['trades'])
# increment the offset counter
data['ofs'] += 50
# To avoid exceeding API rate limit in case of a lot of trades
await trio.sleep(1)
# make sure you grabbed all the trades # santity check on update
assert count == len(trades.values()) assert count == len(trades_by_id.values())
return trades_by_id
return trades
async def submit_limit( async def submit_limit(
self, self,