-
Notifications
You must be signed in to change notification settings - Fork 19
/
user.py
1253 lines (1120 loc) · 43 KB
/
user.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (C) 2023 Benjamin Thomas Schwertfeger
# GitHub: https://github.com/btschwertfeger
#
# (PLR0904): Too many public methods
# ruff: noqa: PLR0904
# pylint: disable=too-many-lines
"""Module that implements the Kraken Spot User client"""
from __future__ import annotations
from decimal import Decimal
from typing import TypeVar
from kraken.base_api import SpotClient, defined, ensure_string
Self = TypeVar("Self")
class User(SpotClient):
"""
Class that implements the Kraken Spot User client
Requires the ``Query funds`` permission in the API key settings.
- https://docs.kraken.com/rest/#tag/Account-Data
- https://docs.kraken.com/rest/#tag/Subaccounts
:param key: Spot API public key (default: ``""``)
:type key: str, optional
:param secret: Spot API secret key (default: ``""``)
:type secret: str, optional
:param url: The URL to access the Kraken API (default:
https://api.kraken.com)
:type url: str, optional
:param proxy: proxy URL, may contain authentication information
:type proxy: str, optional
.. code-block:: python
:linenos:
:caption: Spot User: Create the user client
>>> from kraken.spot import User
>>> user = User() # unauthenticated
>>> auth_user = User(key="api-key", secret="secret-key") # authenticated
.. code-block:: python
:linenos:
:caption: Spot User: Create the user client as context manager
>>> from kraken.spot import User
>>> with User(key="api-key", secret="secret-key") as user:
... print(user.get_account_balances())
"""
def __init__( # nosec: B107
self: User,
key: str = "",
secret: str = "",
url: str = "",
proxy: str | None = None,
) -> None:
super().__init__(key=key, secret=secret, url=url, proxy=proxy)
def __enter__(self: Self) -> Self:
super().__enter__()
return self
def get_account_balance(
self: User,
*,
extra_params: dict | None = None,
) -> dict:
"""
Get the current balances of the user.
Requires the ``Query funds`` permission in the API key settings.
- https://docs.kraken.com/rest/#operation/getAccountBalance
.. code-block:: python
:linenos:
:caption: Spot User: Get the account balances
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_account_balances()
{
'ZUSD': '241983.1415',
'KFEE': '8020.22',
'BCH': '0.0000077100',
'ETHW': '0.0000040',
'XXLM': '0.00000000',
'ZEUR': '0.0000',
'DOT': '32011.21197000',
...
}
"""
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/Balance",
extra_params=extra_params,
)
def get_balances(
self: User,
*,
extra_params: dict | None = None,
) -> dict:
"""
Retrieve the user's asset balances and the the corresponding amount held
by open orders.
Requires the ``Query funds`` permission in the API key settings.
:return: Dictionary containing the ``currency`` as keys, that hold a
dictionary containing the ``balance`` key holding the actual balance
including the value in orders and the ``hold_trade`` key that
represents the amount held in open orders.
:rtype: dict
.. code-block:: python
:linenos:
:caption: Spot User: Get balances
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_balances()
{
'XXLM': {
'balance': '0.00000000', 'hold_trade': '0.00000000'
},
'ZEUR': {
'balance': '500.0000', 'hold_trade': '0.0000'
},
'XXBT': {
'balance': '2.1031709100', 'hold_trade': '0.1401000000'
},
'KFEE': {
'balance': '1407.73', 'hold_trade': '0.00'
},
...
}
"""
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/BalanceEx",
extra_params=extra_params,
)
def get_balance(self: User, currency: str) -> dict:
"""
Returns the balance and available balance of a given currency.
Requires the ``Query funds`` permission in the API key settings.
:param currency: The currency to get the balances from
:type currency: str
:return: Dictionary containing the ``currency`` (currency as string),
``balance`` (including value in orders), and ``available_balance``
(amount that is not in orders)
:rtype: dict
.. code-block:: python
:linenos:
:caption: Spot User: Get balance
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_balance(currency="EUR")
{
'currency': 'ZEUR',
'balance': 6011.2119,
'available_balance': 4999.0619
}
"""
balance: Decimal = Decimal(0)
available_balance: Decimal = Decimal(0)
curr_opts: tuple = (currency, f"Z{currency}", f"X{currency}")
for symbol, data in self.get_balances().items():
if symbol in curr_opts:
currency = symbol
balance = Decimal(data["balance"])
available_balance = balance - Decimal(data["hold_trade"])
break
return {
"currency": currency,
"balance": float(balance),
"available_balance": float(available_balance),
}
def get_trade_balance(
self: User,
asset: str | None = "ZUSD",
*,
extra_params: dict | None = None,
) -> dict:
"""
Get the summary of all collateral balances.
Requires the ``Query funds``, ``Query open orders & trades``, and
``Query closed orders & trades`` permissions in the API key settings.
- https://docs.kraken.com/rest/#operation/getTradeBalance
:param asset: The base asset to determine the balances (default:
``ZUSD``)
:type asset: str, optional
.. code-block:: python
:linenos:
:caption: Spot User: Get the trade balance
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_trade_balance()
{
'eb': '983691.5512', # Equivalent balance - all currencies combined
'tb': '322296.9914', # Trade balance - balance of all equity currencies
'm': '0.0000', # Margin amount of open positions
'uv': '0.0000', # Unexecuted value of partly filled orders/positions
'n': '0.0000', # Unrealized net profit/loss of open positions
'c': '0.0000', # Cost basis of open positions
'v': '0.0000', # Current floating value of open positions
'e': '983691.5512', # Equity ( eb + n )
'mf': '322296.9914' # Free margin ( tb / initial margin ) * 100
}
"""
params: dict = {}
if defined(asset):
params["asset"] = asset
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/TradeBalance",
params=params,
extra_params=extra_params,
)
def get_open_orders(
self: User,
userref: int | None = None,
*,
trades: bool | None = False,
extra_params: dict | None = None,
) -> dict:
"""
Get information about the open orders.
Requires the ``Query open orders & trades`` permission in the API key
settings.
- https://docs.kraken.com/rest/#operation/getOpenOrders
:param userref: Filter the results by user reference id
:type userref: int, optional
:param trades: Include trades related to position or not into the
response (default: ``False``)
:type trades: bool
.. code-block:: python
:linenos:
:caption: Spot User: Get the open orders
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_open_orders()
{
'open': {
'OCUG7Z-4EM5R-7ZCJ47': {
'refid': None,
'userref': 0,
'status':
'open',
'opentm': 1680777427.576083,
'starttm': 0,
'expiretm': 0,
'descr': {
'pair': 'ETHUSD',
'type': 'buy',
'ordertype': 'limit',
'price': '1720.37',
'price2': '0',
'leverage': 'none',
'order': 'buy 0.02000000 ETHUSD @ limit 1720.37',
'close': ''
},
'vol': '0.02000000',
'vol_exec': '0.00000000',
'cost': '0.00000',
'fee': '0.00000',
'price': '0.00000',
'stopprice': '0.00000',
'limitprice': '0.00000',
'misc': '',
'oflags': 'fciq'
},
'OFZP3V-UMMUJ-6HMRMB': {
...
}
}
}
"""
params: dict = {"trades": trades}
if defined(userref):
params["userref"] = userref
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/OpenOrders",
params=params,
extra_params=extra_params,
)
def get_closed_orders(
self: User,
userref: int | None = None,
start: int | None = None,
end: int | None = None,
ofs: int | None = None,
closetime: str | None = "both",
*,
trades: bool | None = False,
extra_params: dict | None = None,
) -> dict:
"""
Get the 50 latest closed (filled or canceled) orders.
Requires the ``Query closed orders & trades`` permission in the API key
settings.
- https://docs.kraken.com/rest/#operation/getClosedOrders
:param userref: Filter the results by user reference id
:type userref: int, optional
:param start: Unix timestamp to start the search from
:type start: int, optional
:param end: Unix timestamp to define the last result to include
:type end: int, optional
:param ofs: Offset for pagination
:type ofs: int, optional
:param closetime: Specify the exact time frame, one of: ``both``,
``open``, ``close`` (default: ``both``)
:type closetime: str, optional
:param trades: Include trades related to position into the response or
not (default: ``False``)
:type trades: bool
.. code-block:: python
:linenos:
:caption: Spot User: Get the closed orders
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_closed_orders()
{
'closed': {
'OBGFYP-XVQNL-P4GMWF': {
'refid': None,
'userref': 0,
'status': 'closed',
'opentm': 1680698929.9052045,
'starttm': 0,
'expiretm': 0,
'descr': {
'pair': 'ETHUSD',
'type': 'buy',
'ordertype': 'limit',
'price': '1860.76',
'price2': '0',
'leverage': 'none',
'order': 'buy 0.02000000 ETHUSD @ limit 1860.76',
'close': ''
},
'vol': '0.02000000',
'vol_exec': '0.02000000',
'cost': '37.21520',
'fee': '0.05954',
'price': '1860.76',
'stopprice': '0.00000',
'limitprice': '0.00000',
'misc': '',
'oflags': 'fciq',
'reason': None,
'closetm': 1680777419.8115675
},
'OAUHYR-YCVK6-P22G6P': {
...
}
}
}
"""
params: dict = {"trades": trades, "closetime": closetime}
if defined(userref):
params["userref"] = userref
if defined(start):
params["start"] = start
if defined(end):
params["end"] = end
if defined(ofs):
params["ofs"] = ofs
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/ClosedOrders",
params=params,
extra_params=extra_params,
)
@ensure_string("txid")
def get_orders_info(
self: User,
txid: list[str] | str,
userref: int | None = None,
*,
trades: bool | None = False,
consolidate_taker: bool | None = True,
extra_params: dict | None = None,
) -> dict:
"""
Get information about one or more orders.
Requires the ``Query open orders & trades`` and ``Query closed orders &
trades`` permissions in the API key settings.
- https://docs.kraken.com/rest/#tag/User-Data/operation/getOrdersInfo
:param txid: A transaction id of a specific order, a list of txids or a
string containing a comma delimited list of txids
:type txid: str | list[str]
:param userref: Filter results by user reference id
:type userref: int, optional
:param trades: Include trades in the result or not (default: ``False``)
:type trades: bool, optional
:param consolidate_taker: Consolidate trades by individual taker trades
(default: ``True``)
:type consolidate_taker: bool, optional
.. code-block:: python
:linenos:
:caption: Spot User: Get order information
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_orders_info(txid="OG5IL4-6AR7I-ZAPZEZ")
{
'OG5IL4-6AR7I-ZAPZEZ': {
'refid': None,
'userref': 0,
'status': 'open',
'opentm': 1680618712.3723278,
'starttm': 0,
'expiretm': 0,
'descr': {
'pair': 'MATICUSD',
'type': 'buy',
'ordertype': 'limit',
'price': '1.0922',
'price2': '0',
'leverage': 'none',
'order': 'buy 45.77910000 MATICUSD @ limit 1.0922',
'close': ''
},
'vol': '45.77910000',
'vol_exec': '0.00000000',
'cost': '0.000000',
'fee': '0.000000',
'price': '0.000000',
'stopprice': '0.000000',
'limitprice': '0.000000',
'misc': '',
'oflags': 'fciq',
'reason': None
}
}
>>> user.get_orders_info(txid=["OAUHYR-YCVK6-P22G6P", "OG5IL4-6AR7I-ZAPZEZ"])
{
'OAUHYR-YCVK6-P22G6P': {
'refid': None,
'userref': 0,
'status': 'canceled',
'opentm': 1680618716.4409518,
'starttm': 0,
'expiretm': 0,
'descr': {
'pair': 'MATICUSD',
'type': 'buy',
'ordertype': 'limit',
'price': '1.0501',
'price2': '0',
'leverage': 'none',
'order': 'buy 47.61450000 MATICUSD @ limit 1.0501',
'close': ''
},
'vol': '47.61450000',
'vol_exec': '0.00000000',
'cost': '0.000000',
'fee': '0.000000',
'price': '0.000000',
'stopprice': '0.000000',
'limitprice': '0.000000',
'misc': '',
'oflags': 'fciq',
'reason': 'User requested',
'closetm': 1680756419.5768735
}
}
"""
params: dict = {
"txid": txid,
"trades": trades,
"consolidate_taker": consolidate_taker,
}
if defined(userref):
params["userref"] = userref
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/QueryOrders",
params=params,
extra_params=extra_params,
)
def get_trades_history( # pylint: disable=too-many-arguments
self: User,
type_: str | None = "all",
start: int | None = None,
end: int | None = None,
ofs: int | None = None,
*,
trades: bool | None = False,
consolidate_taker: bool = True,
ledgers: bool = False,
extra_params: dict | None = None,
) -> dict:
"""
Get information about the latest 50 trades and fills. Can be paginated.
Requires the ``Query closed orders & trades`` permission in the API key
settings.
- https://docs.kraken.com/rest/#operation/getTradeHistory
:param type_: Filter by type of trade, one of: ``all``, ``any
position``, ``closed position``, ``closing position``, and ``no
position`` (default: ``all``)
:type type_: str, optional
:param start: Timestamp or txid to start the search
:type start: int, optional
:param end: Timestamp or txid to define the last included result
:type end: int, optional
:param trades: Include trades related to a position or not (default:
``False``)
:type trades: bool, optional
:param consolidate_taker: Consolidate trades by individual taker trades
(default: ``True``)
:type consolidate_taker: bool
:param ledgers: Include related leger entries for filtered trade
(default: ``False``)
:type ledgers: bool
.. code-block:: python
:linenos:
:caption: Spot User: Get the trade history
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_trades_history()
{
'count': 630,
'trades': {
'TPLJ5E-NONOU-5LH7JL': {
'ordertxid': 'OBGFYP-XVQNL-P4GMWF',
'postxid': 'TKH2SE-M7IF5-CFI7LT',
'pair': 'XETHZUSD',
'time': 1680777419.8115635,
'type': 'buy',
'ordertype': 'limit',
'price': '1860.76000',
'cost': '37.21520',
'fee': '0.05954',
'vol': '0.02000000',
'margin': '0.00000',
'leverage': '0',
'misc': '',
'trade_id': 43914718
},
'TNGMNU-XQSRA-LKCWOK': { ... },
...
}
}
"""
params: dict = {
"type": type_,
"trades": trades,
"ledgers": ledgers,
"consolidate_taker": consolidate_taker,
}
if defined(start):
params["start"] = start
if defined(end):
params["end"] = end
if defined(ofs):
params["ofs"] = ofs
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/TradesHistory",
params=params,
extra_params=extra_params,
)
@ensure_string("txid")
def get_trades_info(
self: User,
txid: str | list[str],
*,
trades: bool | None = False,
extra_params: dict | None = None,
) -> dict:
"""
Get information about specific trades/filled orders. 20 txids can be
queried maximum.
Requires the ``Query open orders & trades`` and ``Query closed orders &
trades`` permission in the API key settings.
- https://docs.kraken.com/rest/#operation/getTradesInfo
:param txid: txid or list of txids or comma delimited list of txids as
string
:type txid: str | list[str]
:param trades: Include trades related to position in result (default:
``False``)
:type trades: bool
.. code-block:: python
:linenos:
:caption: Spot User: Get the historical trade information
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_trades_info(txid="TNGMNU-XQSRA-LKCWOK")
{
'TNGMNU-XQSRA-LKCWOK': {
'ordertxid': 'OHAJCS-ON45W-UIXHT7',
'postxid': 'TKH2SE-M7IF5-CFI7LT',
'pair': 'XETHZUSD',
'time': 1680606470.360982,
'type': 'sell',
'ordertype': 'limit',
'price': '1855.16000',
'cost': '37.10320',
'fee': '0.05937',
'vol': '0.02000000',
'margin': '0.00000',
'leverage': '0',
'misc': '',
'trade_id': 43878042
}
}
"""
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/QueryTrades",
params={
"trades": trades,
"txid": txid,
},
extra_params=extra_params,
)
@ensure_string("txid")
def get_open_positions(
self: User,
txid: str | list[str] | None = None,
consolidation: str | None = "market",
*,
docalcs: bool | None = False,
extra_params: dict | None = None,
) -> dict:
"""
Get information about the open margin positions.
Requires the ``Query open orders & trades`` permission in the API key
settings.
- https://docs.kraken.com/rest/#operation/getOpenPositions
:param txid: Filter by txid or list of txids or comma delimited list of
txids as string
:type txid: str | list[str], optional
:param consolidation: Consolidate positions by market/pair (default:
``market``)
:type consolidation: str, optional
:param docalcs: Include profit and loss calculation into the result
(default: ``False``)
:type docalcs: bool, optional
:return: List of open positions
:rtype: dict
.. code-block:: python
:linenos:
:caption: Spot User: Get the open margin positions
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_open_positions()
{
'TF5GVO-T7ZZ2-6NBKBI': {
'ordertxid': 'O0SFFP-ABH4R-LOLNFG',
'posstatus': 'open',
'pair': 'XXBTZUSD',
'time': 1618748097.12341,
'type': 'buy',
'ordertype': 'limit',
'cost': '801243.52842',
'fee': '208.44527',
'vol': '8.82412861',
'vol_closed': '0.20200000',
'margin': '17234.123968',
'value": '231463.1',
'net": '+134186.9728',
'terms": '0.0100% per 4 hours',
'rollovertm': '1623672637',
'misc': '',
'oflags": ''
}, ...
}
"""
params: dict = {"docalcs": docalcs, "consolidation": consolidation}
if defined(txid):
params["txid"] = txid
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/OpenPositions",
params=params,
extra_params=extra_params,
)
@ensure_string("asset")
def get_ledgers_info(
self: User,
asset: str | list[str] | None = "all",
aclass: str | None = "currency",
type_: str | None = "all",
start: int | None = None,
end: int | None = None,
ofs: int | None = None,
*,
extra_params: dict | None = None,
) -> dict:
"""
Get information about the users ledger entries. 50 results can be
returned at a time.
Requires the ``Query funds`` and ``Query ledger entries`` permissions in
the API key settings.
- https://docs.kraken.com/rest/#operation/getLedgers
:param asset: The asset(s) to filter for (default: ``all``)
:type asset: str | list[str]
:param aclass: The asset class (default: ``currency`` )
:type aclass: str
:param type_: Ledger type, one of: ``all``, ``deposit``, ``withdrawal``,
``trade``, ``margin``, ``rollover``, ``credit``, ``transfer``,
``settled``, ``staking``, and ``sale`` (default: ``all``)
:type type_: str, optional
:param start: Unix timestamp to start the search from
:type start: int, optional
:param end: Unix timestamp to define the last result
:type end: int, optional
:param ofs: Offset for pagination
:type ofs: int, optional
.. code-block:: python
:linenos:
:caption: Spot User: Get ledgers info
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_ledgers_info(asset=["KFEE","EUR","ETH"])
{
'count': 519,
'ledger': {
'LKLSX7-VUXD4-HDLK2P': {
'aclass': 'currency',
'amount': '0.00',
'asset': 'KFEE',
'balance': '8020.22',
'fee': '5.95',
'refid': 'TPLJ5E-NONOU-5LH7JL',
'time': 1680777419.8115911,
'type': 'trade',
'subtype': ''
},
'L4BF6E-FIFW7-6UB2CI': { ... },
...
}
}
"""
params: dict = {"asset": asset, "aclass": aclass, "type": type_}
if defined(start):
params["start"] = start
if defined(end):
params["end"] = end
if defined(ofs):
params["ofs"] = ofs
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/Ledgers",
params=params,
extra_params=extra_params,
)
@ensure_string("id_")
def get_ledgers(
self: User,
id_: str | list[str],
*,
trades: bool | None = False,
extra_params: dict | None = None,
) -> dict:
"""
Get information about specific ledeger entries.
Requires the ``Query funds`` and ``Query ledger entries`` permissions in
the API key settings.
- https://docs.kraken.com/rest/#operation/getLedgersInfo
:param id_: Ledger id as string, list of strings, or comma delimited
list of ledger ids as string
:type id_: str | list[str]
:param trades: Include trades related to a position or not (default:
``False``)
:type trades: bool, optional
.. code-block:: python
:linenos:
:caption: Spot User: Get ledgers
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_ledgers(id_="LKLSX7-VUXD4-HDLK2P")
{
'LKLSX7-VUXD4-HDLK2P': {
'aclass': 'currency',
'amount': '0.00',
'asset': 'FEE',
'balance': '8020.22',
'fee': '5.95',
'refid': 'TPLJ5E-NONOU-5LH7JL',
'time': 1680777419.8115911,
'type': 'trade',
'subtype': ''
}
}
"""
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/QueryLedgers",
params={"trades": trades, "id": id_},
extra_params=extra_params,
)
@ensure_string("pair")
def get_trade_volume(
self: User,
pair: str | list[str] | None = None,
*,
fee_info: bool = True,
extra_params: dict | None = None,
) -> dict:
"""
Get the 30-day user specific trading volume in USD.
Requires the ``Query funds`` permission in the API key settings.
- https://docs.kraken.com/rest/#operation/getTradeVolume
:param pair: Asset pair, list of asset pairs or comma delimited list (as
string) of asset pairs to filter
:type pair: str | list[str], optional
:param fee_info: Include fee information or not (default: ``True``)
:type fee_info: bool, optional
.. code-block:: python
:linenos:
:caption: Spot User: Get the 30-day trade volume
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.get_trade_volume()
{
'currency': 'ZUSD',
'volume': '212220.9741',
'fees': None,
'fees_maker': None
}
>>> u.get_trade_volume(pair="DOTUSD")
{
'currency': 'ZUSD',
'volume': '212243.1210',
'fees': {
'DOTUSD': {
'fee': '0.2200',
'minfee': '0.1000',
'maxfee': '0.2200',
'nextfee': '0.2000',
'tiervolume': '0.0000',
'nextvolume': '250000.0000'
}
},
'fees_maker': {
'DOTUSD': {
'fee': '0.1200',
'minfee': '0.0000',
'maxfee': '0.1200',
'nextfee': '0.1000',
'tiervolume': '0.0000',
'nextvolume': '250000.0000'
}
}
}
"""
params: dict = {"fee-info": fee_info}
if defined(pair):
params["pair"] = pair
return self.request( # type: ignore[return-value]
method="POST",
uri="/0/private/TradeVolume",
params=params,
extra_params=extra_params,
)
@ensure_string("fields")
def request_export_report( # pylint: disable=too-many-arguments
self: User,
report: str,
description: str,
format_: str | None = "CSV",
fields: str | list[str] | None = "all",
starttm: int | None = None,
endtm: int | None = None,
*,
timeout: int | None = 10,
extra_params: dict | None = None,
) -> dict:
"""
Request to export the trades or ledgers of the user.
Requires the ``Export data`` permission. In addition for exporting
trades data the permissions ``Query open orders & trades`` and ``Query
closed orders & trades`` must be set. For exporting ledgers the ``Query
funds`` and ``Query ledger entries`` must be set.
- https://docs.kraken.com/rest/#operation/addExport
:param report: Kind of report, one of: ``trades`` and ``ledgers``
:type report: str
:param format_: The export format of the requesting report, one of
``CSV`` and ``TSV`` (default: ``CSV``)
:type format_: str
:param fields: Fields to include in the report (default: ``all``)
:type fields: str | list[str], optional
:param starttm: Unix timestamp to start
:type starttm: int, optional
:param endtm: Unix timestamp of the last result
:type endtm: int, optional
:param timeout: The timeout for that request (default: ``10``)
:type timeout: int
:return: A dictionary containing the export id
:rtype: dict
.. code-block:: python
:linenos:
:caption: Spot User: Request an report export
>>> from kraken.spot import User
>>> user = User(key="api-key", secret="secret-key")
>>> user.request_export_report(
... report="ledgers", description="myLedgers1", format="CSV"
... )
{ 'id': 'GEHI' }
"""
if report not in {"trades", "ledgers"}:
raise ValueError('`report` must be either "trades" or "ledgers".')
params: dict = {
"report": report,
"description": description,
"format": format_,
"fields": fields,
}
if defined(starttm):
params["starttm"] = starttm
if defined(endtm):
params["endtm"] = endtm