1
0

Compare commits

...

3 Commits

Author SHA1 Message Date
ffc95d8f99
partisia blockchain double registers wip
Some checks failed
Python Ruff Code Quality / ruff (push) Failing after 22s
Run Python tests (through Pytest) / Test (push) Successful in 30s
Verify Python project can be installed, loaded and have version checked / Test (push) Successful in 26s
2024-12-23 00:08:12 +01:00
6e3c9a117b
Rework kraken to use ledger 2024-12-22 05:44:51 +01:00
e4f73342a1
Kraken now supports double registers 2024-12-22 04:48:31 +01:00
4 changed files with 159 additions and 34 deletions

View File

@ -3,11 +3,13 @@
import datetime
import logging
from decimal import Decimal
from collections.abc import Iterator
import fin_defs
import krakenex
from .data import (
Depo,
DepoFetcher,
DepoSingle,
DepositDetails,
@ -64,24 +66,114 @@ class KrakenDepoFetcher(DepoFetcher):
def _get_withdrawals(self) -> list[WithdrawalDetails]:
raise NotImplementedError("_get_withdrawals is a work in progress")
raise NotImplementedError("work in progress")
"""
json = self.client.query_private('WithdrawStatus',data={'start':1})
results = []
for v in json['result']:
asset = parse_asset_from_ticker(v['asset'])
results.append(WithdrawalDetails(
withdrawn=fin_defs.AssetAmount(asset, Decimal(v['amount'])),
fee=fin_defs.AssetAmount(asset, Decimal(v['fee'])),
executed_time = datetime.datetime.fromtimestamp(v['time'],tz=datetime.UTC),
raw_details = v,
))
return results
"""
def _get_deposits(self) -> list[DepositDetails]:
raise NotImplementedError("_get_deposits is a work in progress")
raise NotImplementedError("work in progress")
"""
json = self.client.query_private('DepositStatus',data={'start':1})
print(json)
results = []
for v in json['result']:
asset = parse_asset_from_ticker(v['asset'])
results.append(DepositDetails(
deposit=fin_defs.AssetAmount(asset, Decimal(v['amount'])),
fee=fin_defs.AssetAmount(asset, Decimal(v['fee'])),
executed_time = datetime.datetime.fromtimestamp(v['time'],tz=datetime.UTC),
raw_details = v,
))
return results
"""
def _get_historic_spot_orders(self) -> Iterator[TradeOrderDetails]:
raise NotImplementedError("_get_historic_spot_orders is a work in progress")
raise NotImplementedError("work in progress")
"""
json = self.client.query_private('ClosedOrders',data={'start':1})
for order_id, v in json['result']['closed'].items():
assert v['descr']['pair'] == 'USDTEUR', 'Only sell USDT for EUR is supported'
assert v['descr']['type'] == 'sell', 'Only sell USDT for EUR is supported'
asset_input = fin_defs.USDT
asset_output = fin_defs.EUR
yield TradeOrderDetails(
input =fin_defs.AssetAmount(asset_input, Decimal(v['vol_exec'])),
output =fin_defs.AssetAmount(asset_output, Decimal(v['cost'])),
fee = fin_defs.AssetAmount(asset_output, Decimal(v['fee'])),
executed_time = datetime.datetime.fromtimestamp(v['closetm'],tz=datetime.UTC),
order_id=order_id,
raw_order_details= v,
)
del order_id, v
"""
def _get_double_registers(self) -> list[DoubleRegister]:
double_registers: list[DoubleRegister] = []
double_registers += self._get_deposits()
double_registers += self._get_withdrawals()
double_registers += self._get_historic_spot_orders()
double_registers.sort(key=lambda x: x.executed_time)
return double_registers
json = self.client.query_private('Ledgers',data={'start':1})
return list(parse_from_ledger(json['result']['ledger'].values()))
def parse_asset_from_ticker(ticker: str) -> fin_defs.Asset:
account = ticker.removesuffix('.HOLD')
if account == 'ZEUR':
return fin_defs.EUR
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

@ -13,7 +13,14 @@ import fin_defs
import requests
from frozendict import frozendict
from .data import DepoFetcher, DepoGroup, DepoSingle
from .data import (
DepoFetcher,
DepoGroup,
DepoSingle,
DepositDetails,
DoubleRegister,
WithdrawalDetails,
)
logger = logging.getLogger(__name__)
@ -179,3 +186,16 @@ class PartisiaBlockchainAccountDepoFetcher(DepoFetcher):
balances.update_time,
[depo_mpc, depo_byoc],
)
def _get_withdrawals(self) -> list[WithdrawalDetails]:
raise UnsupportedOperationException("TODO")
def _get_deposits(self) -> list[DepositDetails]:
raise UnsupportedOperationException("TODO")
def _get_double_registers(self) -> list[DoubleRegister]:
double_registers: list[DoubleRegister] = []
double_registers += self._get_deposits()
double_registers += self._get_withdrawals()
double_registers.sort(key=lambda x: x.executed_time)
return double_registers

View File

@ -9,13 +9,40 @@ needs_secrets = pytest.mark.skipif(
reason='Secret kraken_USERNAME required',
)
@needs_secrets
def test_get_depo():
fetcher = fin_depo.defi_kraken.KrakenDepoFetcher(
def get_fetcher():
return fin_depo.defi_kraken.KrakenDepoFetcher(
secrets.KRAKEN_KEY,
secrets.KRAKEN_SECRET,
)
depo = fetcher.get_depo()
@needs_secrets
def test_get_depo():
"""Can inspect depository."""
depo = get_fetcher().get_depo()
assert isinstance(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
def test_get_double_registers():
double_registers = get_fetcher()._get_double_registers()
assert len(double_registers) > 0

View File

@ -28,7 +28,7 @@ def get_fetcher() -> fin_depo.defi_kucoin.KucoinDepoFetcher:
@needs_secrets
def test_get_depo():
"""Can inspect kucoin depository."""
"""Can inspect depository."""
depo = get_fetcher().get_depo()
assert isinstance(depo, fin_depo.data.DepoGroup)
@ -36,25 +36,11 @@ def test_get_depo():
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
def test_get_double_registers():
double_registers = get_fetcher()._get_double_registers()
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