1
0

Rework kraken to use ledger

This commit is contained in:
Jon Michael Aanes 2024-12-22 05:44:51 +01:00
parent e4f73342a1
commit 6e3c9a117b
Signed by: Jmaa
SSH Key Fingerprint: SHA256:Ab0GfHGCblESJx7JRE4fj4bFy/KRpeLhi41y4pF3sNA
2 changed files with 69 additions and 27 deletions

View File

@ -66,7 +66,9 @@ class KrakenDepoFetcher(DepoFetcher):
def _get_withdrawals(self) -> list[WithdrawalDetails]: def _get_withdrawals(self) -> list[WithdrawalDetails]:
json = self.client.query_private('WithdrawStatus') raise NotImplementedError("work in progress")
"""
json = self.client.query_private('WithdrawStatus',data={'start':1})
results = [] results = []
for v in json['result']: for v in json['result']:
asset = parse_asset_from_ticker(v['asset']) asset = parse_asset_from_ticker(v['asset'])
@ -77,9 +79,13 @@ class KrakenDepoFetcher(DepoFetcher):
raw_details = v, raw_details = v,
)) ))
return results return results
"""
def _get_deposits(self) -> list[DepositDetails]: def _get_deposits(self) -> list[DepositDetails]:
json = self.client.query_private('DepositStatus') raise NotImplementedError("work in progress")
"""
json = self.client.query_private('DepositStatus',data={'start':1})
print(json)
results = [] results = []
for v in json['result']: for v in json['result']:
asset = parse_asset_from_ticker(v['asset']) asset = parse_asset_from_ticker(v['asset'])
@ -90,9 +96,12 @@ class KrakenDepoFetcher(DepoFetcher):
raw_details = v, raw_details = v,
)) ))
return results return results
"""
def _get_historic_spot_orders(self) -> Iterator[TradeOrderDetails]: def _get_historic_spot_orders(self) -> Iterator[TradeOrderDetails]:
json = self.client.query_private('ClosedOrders') raise NotImplementedError("work in progress")
"""
json = self.client.query_private('ClosedOrders',data={'start':1})
for order_id, v in json['result']['closed'].items(): for order_id, v in json['result']['closed'].items():
assert v['descr']['pair'] == 'USDTEUR', 'Only sell USDT for EUR is supported' assert v['descr']['pair'] == 'USDTEUR', 'Only sell USDT for EUR is supported'
assert v['descr']['type'] == 'sell', 'Only sell USDT for EUR is supported' assert v['descr']['type'] == 'sell', 'Only sell USDT for EUR is supported'
@ -107,17 +116,64 @@ class KrakenDepoFetcher(DepoFetcher):
raw_order_details= v, raw_order_details= v,
) )
del order_id, v del order_id, v
"""
def _get_double_registers(self) -> list[DoubleRegister]: def _get_double_registers(self) -> list[DoubleRegister]:
double_registers: list[DoubleRegister] = [] json = self.client.query_private('Ledgers',data={'start':1})
double_registers += self._get_deposits() return list(parse_from_ledger(json['result']['ledger'].values()))
double_registers += self._get_withdrawals()
double_registers += self._get_historic_spot_orders()
double_registers.sort(key=lambda x: x.executed_time)
return double_registers
def parse_asset_from_ticker(ticker: str) -> fin_defs.Asset: def parse_asset_from_ticker(ticker: str) -> fin_defs.Asset:
account = ticker.removesuffix('.HOLD') account = ticker.removesuffix('.HOLD')
if account == 'ZEUR': if account == 'ZEUR':
return fin_defs.EUR return fin_defs.EUR
return fin_defs.WELL_KNOWN_SYMBOLS[account] return fin_defs.WELL_KNOWN_SYMBOLS[account]
def parse_from_ledger(ledger_items: list[dict[str,str]]) -> Iterator:
collected_items = {}
for item in ledger_items:
collected_items.setdefault(item['refid'], []).append(item)
for refid, items in collected_items.items():
print(refid, items)
assert len(items) <= 2
if items[0]['type'] == 'deposit':
assert len(items) == 1
asset = parse_asset_from_ticker(items[0]['asset'])
yield DepositDetails(
deposit = fin_defs.AssetAmount(asset, Decimal(items[0]['amount'])),
fee = fin_defs.AssetAmount(asset, Decimal(items[0]['fee'])),
executed_time = datetime.datetime.fromtimestamp(items[0]['time'],tz=datetime.UTC),
raw_details = items[0],
)
elif items[0]['type'] == 'withdrawal':
assert len(items) == 1
asset = parse_asset_from_ticker(items[0]['asset'])
yield WithdrawalDetails(
withdrawn = -fin_defs.AssetAmount(asset, Decimal(items[0]['amount'])),
fee = fin_defs.AssetAmount(asset, Decimal(items[0]['fee'])),
executed_time = datetime.datetime.fromtimestamp(items[0]['time'],tz=datetime.UTC),
raw_details = items[0],
)
else:
assert len(items) == 2, items
assert items[0]['type'] in {'receive', 'trade'}
assert items[1]['type'] in {'spend', 'trade'}
assert float(items[0]['amount']) > 0
assert float(items[1]['amount']) < 0
asset_input = parse_asset_from_ticker(items[1]['asset'])
asset_output = parse_asset_from_ticker(items[0]['asset'])
input = -fin_defs.AssetAmount(asset_input, Decimal(items[1]['amount']))
output = fin_defs.AssetAmount(asset_output, Decimal(items[0]['amount']))
fee_of_input = fin_defs.AssetAmount(asset_input, Decimal(items[1]['fee']))
fee_of_output = fin_defs.AssetAmount(asset_output, Decimal(items[0]['fee']))
details = TradeOrderDetails(
input = input,
output = output,
fee = fee_of_input if fee_of_input.amount != 0 else fee_of_output,
executed_time = datetime.datetime.fromtimestamp(items[1]['time'],tz=datetime.UTC),
order_id = refid,
raw_order_details = items[0],
)
yield details

View File

@ -36,25 +36,11 @@ def test_get_depo():
assert isinstance(nested_depo, fin_depo.data.DepoSingle) assert isinstance(nested_depo, fin_depo.data.DepoSingle)
@needs_secrets
def test_get_withdrawals():
withdrawals = get_fetcher()._get_withdrawals()
assert len(withdrawals) > 0
@needs_secrets
def test_get_deposits():
deposits = get_fetcher()._get_deposits()
assert len(deposits) > 0
@needs_secrets
def test_get_historic_spot_orders():
orders = get_fetcher()._get_historic_spot_orders()
assert next(orders)
@needs_secrets @needs_secrets
def test_get_double_registers(): def test_get_double_registers():
double_registers = get_fetcher()._get_double_registers() double_registers = get_fetcher()._get_double_registers()
assert len(double_registers) > 0 assert len(double_registers) > 0
for item in double_registers:
print(item)
assert item.input.amount > 0 if item.input else None
assert item.output.amount > 0 if item.output else None