Spot REST

class kraken.spot.User(key: str = '', secret: str = '', url: str = '')

Bases: KrakenSpotBaseAPI

Class that implements the Kraken Spot User client

Requires the Query funds permission in the API key settings.

Parameters:
  • key (str, optional) – Spot API public key (default: "")

  • secret (str, optional) – Spot API secret key (default: "")

  • url (str, optional) – The URL to access the Kraken API (default: https://api.kraken.com)

Spot User: Create the user client
1>>> from kraken.spot import User
2>>> user = User() # unauthenticated
3>>> auth_user = User(key="api-key", secret="secret-key") # authenticated
Spot User: Create the user client as context manager
1>>> from kraken.spot import User
2>>> with User(key="api-key", secret="secret-key") as user:
3...     print(user.get_account_balances())
account_transfer(asset: str, amount: str | float, from_: str, to_: str, *, extra_params: dict | None = None) dict

Transfer funds between master and subaccounts. This is currently only available for institutional clients and must be called by the master account.

Parameters:
  • asset (str) – The asset to transfer

  • amount (str | float) – The amount of that asset to transfer

  • from (str) – The source account (IIBAN)

  • to (str) – The destination account (IIBAN)

Returns:

Success or failure

Return type:

dict

Spot User: Transfer funds between accounts
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.account_transfer(
 4...     "asset": "XBT",
 5...     "amount": 1.0,
 6...     "from": "ABCD 1234 EFGH 5678"
 7...     "to": "IJKL 0987 MNOP 6543"
 8... )
 9{
10    'result': {
11        'transfer_id': 'TOH3AS2-LPCWR8-JDQGEU',
12        'status': 'complete'
13    }
14}
create_subaccount(username: str, email: str, *, extra_params: dict | None = None) dict

Create a subaccount for trading. This is currently only available for institutional clients.

Parameters:
  • username (str) – The username for the new subaccount

  • email (str) – The E-Mail address for the new subaccount

Returns:

Success or failure

Return type:

dict

Spot User: Create a subaccount
1>>> from kraken.spot import User
2>>> user = User(key="api-key", secret="secret-key")
3>>> user.create_subaccount(username="user", email="user@domain.com")
4{ 'result': True }
delete_export_report(id_: str, type_: str | None = 'delete', *, extra_params: dict | None = None) dict

Delete a report from the Kraken server.

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.

Parameters:
  • id (str) – The id of the report

  • type (str, optional) – The type of the export, one of: cancel and delete (default: delete)

Returns:

Success or failure

Return type:

dict

Spot User: Delete or cancel the report
1>>> from kraken.spot import User
2>>> user = User(key="api-key", secret="secret-key")
3>>> user.delete_export_report(id_="GEHI", type_="delete")
4{ 'delete': True }
get_account_balance(*, extra_params: dict | None = None) dict

Get the current balances of the user.

Requires the Query funds permission in the API key settings.

Spot User: Get the account balances
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_account_balances()
 4{
 5    'ZUSD': '241983.1415',
 6    'KFEE': '8020.22',
 7    'BCH': '0.0000077100',
 8    'ETHW': '0.0000040',
 9    'XXLM': '0.00000000',
10    'ZEUR': '0.0000',
11    'DOT': '32011.21197000',
12    ...
13}
get_balance(currency: str) dict

Returns the balance and available balance of a given currency.

Requires the Query funds permission in the API key settings.

Parameters:

currency (str) – The currency to get the balances from

Returns:

Dictionary containing the currency (currency as string), balance (including value in orders), and available_balance (amount that is not in orders)

Return type:

dict

Spot User: Get balance
1>>> from kraken.spot import User
2>>> user = User(key="api-key", secret="secret-key")
3>>> user.get_balance(currency="EUR")
4{
5    'currency': 'ZEUR',
6    'balance': 6011.2119,
7    'available_balance': 4999.0619
8}
get_balances(*, 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.

Returns:

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.

Return type:

dict

Spot User: Get balances
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_balances()
 4{
 5    'XXLM': {
 6        'balance': '0.00000000', 'hold_trade': '0.00000000'
 7    },
 8    'ZEUR': {
 9        'balance': '500.0000', 'hold_trade': '0.0000'
10    },
11    'XXBT': {
12        'balance': '2.1031709100', 'hold_trade': '0.1401000000'
13    },
14    'KFEE': {
15        'balance': '1407.73', 'hold_trade': '0.00'
16    },
17    ...
18}
get_closed_orders(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.

Parameters:
  • userref (int, optional) – Filter the results by user reference id

  • start (int, optional) – Unix timestamp to start the search from

  • end (int, optional) – Unix timestamp to define the last result to include

  • ofs (int, optional) – Offset for pagination

  • closetime (str, optional) – Specify the exact time frame, one of: both, open, close (default: both)

  • trades (bool) – Include trades related to position into the response or not (default: False)

Spot User: Get the closed orders
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_closed_orders()
 4{
 5    'closed': {
 6        'OBGFYP-XVQNL-P4GMWF': {
 7            'refid': None,
 8            'userref': 0,
 9            'status': 'closed',
10            'opentm': 1680698929.9052045,
11            'starttm': 0,
12            'expiretm': 0,
13            'descr': {
14                'pair': 'ETHUSD',
15                'type': 'buy',
16                'ordertype': 'limit',
17                'price': '1860.76',
18                'price2': '0',
19                'leverage': 'none',
20                'order': 'buy 0.02000000 ETHUSD @ limit 1860.76',
21                'close': ''
22            },
23            'vol': '0.02000000',
24            'vol_exec': '0.02000000',
25            'cost': '37.21520',
26            'fee': '0.05954',
27            'price': '1860.76',
28            'stopprice': '0.00000',
29            'limitprice': '0.00000',
30            'misc': '',
31            'oflags': 'fciq',
32            'reason': None,
33            'closetm': 1680777419.8115675
34        },
35        'OAUHYR-YCVK6-P22G6P': {
36            ...
37        }
38    }
39}
get_export_report_status(report: str, *, extra_params: dict | None = None) dict

Get the status of the current pending report.

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.

Parameters:

report (str) – Kind of report, one of: trades, ledgers

Returns:

Information about the pending report

Return type:

list[dict]

Example
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> response = user.request_export_report(
 4...     report="ledgers", description="myLedgers1", format="CSV"
 5... )
 6{ 'id': 'GEHI' }
 7>>> user.get_export_report_status(report="ledgers")
 8[
 9    {
10        'id': 'GEHI',
11        'descr': 'myLedgers1',
12        'format': 'CSV',
13        'report': 'ledgers',
14        'status': 'Queued',
15        'aclass': 'currency',
16        'fields': 'all',
17        'asset': 'all',
18        'subtype': 'all',
19        'starttm': '1680307200',
20        'endtm': '1680855267',
21        'createdtm': '1680855267',
22        'expiretm': '1682064867',
23        'completedtm': '0',
24        'datastarttm': '1680307200',
25        'dataendtm': '1680855267',
26        'flags': '0'
27    }
28]
get_ledgers(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.

Parameters:
  • id (str | list[str]) – Ledger id as string, list of strings, or comma delimited list of ledger ids as string

  • trades (bool, optional) – Include trades related to a position or not (default: False)

Spot User: Get ledgers
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_ledgers(id_="LKLSX7-VUXD4-HDLK2P")
 4{
 5    'LKLSX7-VUXD4-HDLK2P': {
 6        'aclass': 'currency',
 7        'amount': '0.00',
 8        'asset': 'FEE',
 9        'balance': '8020.22',
10        'fee': '5.95',
11        'refid': 'TPLJ5E-NONOU-5LH7JL',
12        'time': 1680777419.8115911,
13        'type': 'trade',
14        'subtype': ''
15    }
16}
get_ledgers_info(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.

Parameters:
  • asset (str | list[str]) – The asset(s) to filter for (default: all)

  • aclass (str) – The asset class (default: currency )

  • type (str, optional) – Ledger type, one of: all, deposit, withdrawal, trade, margin, rollover, credit, transfer, settled, staking, and sale (default: all)

  • start (int, optional) – Unix timestamp to start the search from

  • end (int, optional) – Unix timestamp to define the last result

  • ofs (int, optional) – Offset for pagination

Spot User: Get ledgers info
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_ledgers_info(asset=["KFEE","EUR","ETH"])
 4{
 5    'count': 519,
 6    'ledger': {
 7        'LKLSX7-VUXD4-HDLK2P': {
 8            'aclass': 'currency',
 9            'amount': '0.00',
10            'asset': 'KFEE',
11            'balance': '8020.22',
12            'fee': '5.95',
13            'refid': 'TPLJ5E-NONOU-5LH7JL',
14            'time': 1680777419.8115911,
15            'type': 'trade',
16            'subtype': ''
17        },
18        'L4BF6E-FIFW7-6UB2CI': { ... },
19        ...
20    }
21}
get_open_orders(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.

Parameters:
  • userref (int, optional) – Filter the results by user reference id

  • trades (bool) – Include trades related to position or not into the response (default: False)

Spot User: Get the open orders
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_open_orders()
 4{
 5    'open': {
 6        'OCUG7Z-4EM5R-7ZCJ47': {
 7            'refid': None,
 8            'userref': 0,
 9            'status':
10            'open',
11            'opentm': 1680777427.576083,
12            'starttm': 0,
13            'expiretm': 0,
14            'descr': {
15                'pair': 'ETHUSD',
16                'type': 'buy',
17                'ordertype': 'limit',
18                'price': '1720.37',
19                'price2': '0',
20                'leverage': 'none',
21                'order': 'buy 0.02000000 ETHUSD @ limit 1720.37',
22                'close': ''
23            },
24            'vol': '0.02000000',
25            'vol_exec': '0.00000000',
26            'cost': '0.00000',
27            'fee': '0.00000',
28            'price': '0.00000',
29            'stopprice': '0.00000',
30            'limitprice': '0.00000',
31            'misc': '',
32            'oflags': 'fciq'
33        },
34        'OFZP3V-UMMUJ-6HMRMB': {
35            ...
36        }
37    }
38}
get_open_positions(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.

Parameters:
  • txid (str | list[str], optional) – Filter by txid or list of txids or comma delimited list of txids as string

  • consolidation (str, optional) – Consolidate positions by market/pair (default: market)

  • docalcs (bool, optional) – Include profit and loss calculation into the result (default: False)

Returns:

List of open positions

Return type:

dict

Spot User: Get the open margin positions
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_open_positions()
 4{
 5    'TF5GVO-T7ZZ2-6NBKBI': {
 6        'ordertxid': 'O0SFFP-ABH4R-LOLNFG',
 7        'posstatus': 'open',
 8        'pair': 'XXBTZUSD',
 9        'time': 1618748097.12341,
10        'type': 'buy',
11        'ordertype': 'limit',
12        'cost': '801243.52842',
13        'fee': '208.44527',
14        'vol': '8.82412861',
15        'vol_closed': '0.20200000',
16        'margin': '17234.123968',
17        'value": '231463.1',
18        'net": '+134186.9728',
19        'terms": '0.0100% per 4 hours',
20        'rollovertm': '1623672637',
21        'misc': '',
22        'oflags": ''
23    }, ...
24}
get_orders_info(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.

Parameters:
  • txid (str | list[str]) – A transaction id of a specific order, a list of txids or a string containing a comma delimited list of txids

  • userref (int, optional) – Filter results by user reference id

  • trades (bool, optional) – Include trades in the result or not (default: False)

  • consolidate_taker (bool, optional) – Consolidate trades by individual taker trades (default: True)

Spot User: Get order information
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_orders_info(txid="OG5IL4-6AR7I-ZAPZEZ")
 4{
 5    'OG5IL4-6AR7I-ZAPZEZ': {
 6        'refid': None,
 7        'userref': 0,
 8        'status': 'open',
 9        'opentm': 1680618712.3723278,
10        'starttm': 0,
11        'expiretm': 0,
12        'descr': {
13            'pair': 'MATICUSD',
14            'type': 'buy',
15            'ordertype': 'limit',
16            'price': '1.0922',
17            'price2': '0',
18            'leverage': 'none',
19            'order': 'buy 45.77910000 MATICUSD @ limit 1.0922',
20            'close': ''
21        },
22        'vol': '45.77910000',
23        'vol_exec': '0.00000000',
24        'cost': '0.000000',
25        'fee': '0.000000',
26        'price': '0.000000',
27        'stopprice': '0.000000',
28        'limitprice': '0.000000',
29        'misc': '',
30        'oflags': 'fciq',
31        'reason': None
32    }
33}
34>>> user.get_orders_info(txid=["OAUHYR-YCVK6-P22G6P", "OG5IL4-6AR7I-ZAPZEZ"])
35{
36    'OAUHYR-YCVK6-P22G6P': {
37        'refid': None,
38        'userref': 0,
39        'status': 'canceled',
40        'opentm': 1680618716.4409518,
41        'starttm': 0,
42        'expiretm': 0,
43        'descr': {
44            'pair': 'MATICUSD',
45            'type': 'buy',
46            'ordertype': 'limit',
47            'price': '1.0501',
48            'price2': '0',
49            'leverage': 'none',
50            'order': 'buy 47.61450000 MATICUSD @ limit 1.0501',
51            'close': ''
52        },
53        'vol': '47.61450000',
54        'vol_exec': '0.00000000',
55        'cost': '0.000000',
56        'fee': '0.000000',
57        'price': '0.000000',
58        'stopprice': '0.000000',
59        'limitprice': '0.000000',
60        'misc': '',
61        'oflags': 'fciq',
62        'reason': 'User requested',
63        'closetm': 1680756419.5768735
64    }
65}
get_trade_balance(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.

Parameters:

asset (str, optional) – The base asset to determine the balances (default: ZUSD)

Spot User: Get the trade balance
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_trade_balance()
 4{
 5    'eb': '983691.5512', # Equivalent balance - all currencies combined
 6    'tb': '322296.9914', # Trade balance - balance of all equity currencies
 7    'm': '0.0000',       # Margin amount of open positions
 8    'uv': '0.0000',      # Unexecuted value of partly filled orders/positions
 9    'n': '0.0000',       # Unrealized net profit/loss of open positions
10    'c': '0.0000',       # Cost basis of open positions
11    'v': '0.0000',       # Current floating value of open positions
12    'e': '983691.5512',  # Equity ( eb + n )
13    'mf': '322296.9914'  # Free margin ( tb / initial margin ) * 100
14}
get_trade_volume(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.

Parameters:
  • pair (str | list[str], optional) – Asset pair, list of asset pairs or comma delimited list (as string) of asset pairs to filter

  • fee_info (bool, optional) – Include fee information or not (default: True)

Spot User: Get the 30-day trade volume
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_trade_volume()
 4{
 5    'currency': 'ZUSD',
 6    'volume': '212220.9741',
 7    'fees': None,
 8    'fees_maker': None
 9}
10>>> u.get_trade_volume(pair="DOTUSD")
11{
12    'currency': 'ZUSD',
13    'volume': '212243.1210',
14    'fees': {
15        'DOTUSD': {
16            'fee': '0.2200',
17            'minfee': '0.1000',
18            'maxfee': '0.2200',
19            'nextfee': '0.2000',
20            'tiervolume': '0.0000',
21            'nextvolume': '250000.0000'
22        }
23    },
24    'fees_maker': {
25        'DOTUSD': {
26            'fee': '0.1200',
27            'minfee': '0.0000',
28            'maxfee': '0.1200',
29            'nextfee': '0.1000',
30            'tiervolume': '0.0000',
31            'nextvolume': '250000.0000'
32        }
33    }
34}
get_trades_history(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.

Parameters:
  • type (str, optional) – Filter by type of trade, one of: all, any position, closed position, closing position, and no position (default: all)

  • start (int, optional) – Timestamp or txid to start the search

  • end (int, optional) – Timestamp or txid to define the last included result

  • trades (bool, optional) – Include trades related to a position or not (default: False)

  • consolidate_taker (bool) – Consolidate trades by individual taker trades (default: True)

  • ledgers (bool) – Include related leger entries for filtered trade (default: False)

Spot User: Get the trade history
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_trades_history()
 4{
 5    'count': 630,
 6    'trades': {
 7        'TPLJ5E-NONOU-5LH7JL': {
 8            'ordertxid': 'OBGFYP-XVQNL-P4GMWF',
 9            'postxid': 'TKH2SE-M7IF5-CFI7LT',
10            'pair': 'XETHZUSD',
11            'time': 1680777419.8115635,
12            'type': 'buy',
13            'ordertype': 'limit',
14            'price': '1860.76000',
15            'cost': '37.21520',
16            'fee': '0.05954',
17            'vol': '0.02000000',
18            'margin': '0.00000',
19            'leverage': '0',
20            'misc': '',
21            'trade_id': 43914718
22        },
23        'TNGMNU-XQSRA-LKCWOK': { ... },
24        ...
25    }
26}
get_trades_info(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.

Parameters:
  • txid (str | list[str]) – txid or list of txids or comma delimited list of txids as string

  • trades (bool) – Include trades related to position in result (default: False)

Spot User: Get the historical trade information
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> user.get_trades_info(txid="TNGMNU-XQSRA-LKCWOK")
 4{
 5    'TNGMNU-XQSRA-LKCWOK': {
 6        'ordertxid': 'OHAJCS-ON45W-UIXHT7',
 7        'postxid': 'TKH2SE-M7IF5-CFI7LT',
 8        'pair': 'XETHZUSD',
 9        'time': 1680606470.360982,
10        'type': 'sell',
11        'ordertype': 'limit',
12        'price': '1855.16000',
13        'cost': '37.10320',
14        'fee': '0.05937',
15        'vol': '0.02000000',
16        'margin': '0.00000',
17        'leverage': '0',
18        'misc': '',
19        'trade_id': 43878042
20    }
21}
request_export_report(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.

Parameters:
  • report (str) – Kind of report, one of: trades and ledgers

  • format (str) – The export format of the requesting report, one of CSV and TSV (default: CSV)

  • fields (str | list[str], optional) – Fields to include in the report (default: all)

  • starttm (int, optional) – Unix timestamp to start

  • endtm (int, optional) – Unix timestamp of the last result

  • timeout (int) – The timeout for that request (default: 10)

Returns:

A dictionary containing the export id

Return type:

dict

Spot User: Request an report export
1>>> from kraken.spot import User
2>>> user = User(key="api-key", secret="secret-key")
3>>> user.request_export_report(
4...     report="ledgers", description="myLedgers1", format="CSV"
5... )
6{ 'id': 'GEHI' }
retrieve_export(id_: str, timeout: int = 10, *, extra_params: dict | None = None) dict

Retrieve the requested report export.

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.

Parameters:
  • id (str) – Id of the report that was requested

  • timeout (int, optional) – Timeout for that request, default: 10 seconds

Returns:

The response - a zipped report

Return type:

requests.Response

Spot User: Save the exported report to CSV
 1>>> from kraken.spot import User
 2>>> user = User(key="api-key", secret="secret-key")
 3>>> response = user.request_export_report(
 4...     report="ledgers", description="myLedgers1", format="CSV"
 5... )
 6{ 'id': 'GEHI' }
 7>>> ledgers_data = user.retrieve_export(id_=response["id"])
 8>>> with open("myExport.zip", "wb") as file:
 9...     for chunk in ledgers_data.iter_content(chunk_size=512):
10...         if chunk:
11...             file.write(chunk)
property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

class kraken.spot.Market(key: str = '', secret: str = '', url: str = '')

Bases: KrakenSpotBaseAPI

Class that implements the Kraken Spot Market client. Can be used to access the Kraken Spot market data.

Parameters:
  • key (str, optional) – Spot API public key (default: "")

  • secret (str, optional) – Spot API secret key (default: "")

  • url (str, optional) – Alternative URL to access the Kraken API (default: https://api.kraken.com)

Spot Market: Create the market client
1>>> from kraken.spot import Market
2>>> market = Market() # unauthenticated
3>>> auth_market = Market(key="api-key", secret="secret-key") # authenticated
Spot Market: Create the market client as context manager
1>>> from kraken.spot import Market
2>>> with Market() as market:
3...     print(market.get_assets())
get_asset_pairs(pair: str | list[str] | None = None, info: str | None = None, *, extra_params: dict | None = None) dict

Get information about a single or multiple asset/currency pair(s). If pair is left blank, all currency pairs will be returned.

This function uses caching. Run get_asset_pairs.cache_clear() to clear.

Parameters:
  • pair (str | list[str], optional) – Filter by asset pair(s)

  • info (str, optional) – Filter by info, can be one of: info (all info), leverage (leverage info), fees (fee info), and margin (margin info)

Returns:

Information about the asset pair

Return type:

dict

Spot Market: Get information about tradeable asset pairs
 1>>> from kraken.spot import Market
 2>>> Market().get_asset_pairs(pair="XBTUSD")
 3{
 4    'XXBTZUSD': {
 5        'altname': 'XBTUSD',
 6        'wsname': 'XBT/USD',
 7        'aclass_base': 'currency',
 8        'base': 'XXBT',
 9        'aclass_quote': 'currency',
10        'quote': 'ZUSD',
11        'lot': 'unit',
12        'cost_decimals': 5,
13        'pair_decimals': 1,
14        'lot_decimals': 8,
15        'lot_multiplier': 1,
16        'leverage_buy': [2, 3, 4, 5],
17        'leverage_sell': [2, 3, 4, 5],
18        'fees': [
19            [0, 0.26], [50000, 0.24], [100000, 0.22],
20            [250000, 0.2], [500000, 0.18], [1000000, 0.16],
21            [2500000, 0.14], [5000000, 0.12], [10000000, 0.1]
22        ],
23        'fees_maker': [
24            [0, 0.16], [50000, 0.14], [100000, 0.12],
25            [250000, 0.1], [500000, 0.08], [1000000, 0.06],
26            [2500000, 0.04], [5000000, 0.02], [10000000, 0.0]
27        ],
28        'fee_volume_currency': 'ZUSD',
29        'margin_call': 80,
30        'margin_stop': 40,
31        'ordermin': '0.0001',
32        'costmin': '0.5',
33        'tick_size': '0.1',
34        'status': 'online',
35        'long_position_limit': 270,
36        'short_position_limit': 180
37    }
38}
get_assets(assets: str | list[str] | None = None, aclass: str | None = None, *, extra_params: dict | None = None) dict

Get information about one or more assets. If assets is not specified, all assets will be returned.

This function uses caching. Run get_assets.cache_clear() to clear.

Parameters:
  • assets (str | list[str], optional) – Filter by asset(s)

  • aclass (str, optional) – Filter by asset class

Returns:

Information about the requested assets

Return type:

dict

Spot Market: Get information about the available assets
 1>>> from kraken.spot import Market
 2>>> market = Market()
 3>>> market.get_assets(assets="DOT")
 4{
 5    'DOT': {
 6        'aclass': 'currency',
 7        'altname': 'DOT',
 8        'decimals': 10,
 9        'display_decimals': 8,
10        'collateral_value': 0.9,
11        'status': 'enabled'
12    }
13}
14>>> market.get_assets(assets=["MATIC", "XBT"]) # same as market.get_assets(assets="MATIC,XBT"])
15    'MATIC': {
16        'aclass': 'currency',
17        'altname': 'MATIC',
18        'decimals': 10,
19        'display_decimals': 5,
20        'collateral_value': 0.7,
21        'status': 'enabled'
22    },
23    'XXBT': {
24        'aclass': 'currency',
25        'altname': 'XBT',
26        'decimals': 10,
27        'display_decimals': 5,
28        'collateral_value': 1.0,
29        'status': 'enabled'
30    }
31}
get_ohlc(pair: str, interval: int | str = 1, since: str | int | None = None, *, extra_params: dict | None = None) dict

Get the open, high, low, and close data for a specific trading pair. Returns at max 720 time steps per request.

Parameters:
  • pair (str) – The pair to get the ohlc from

  • interval (str | int, optional) – the Interval in minutes (default: 1)

  • since (int | str, optional) – Timestamp to start from (default: None)

Returns:

The OHLC data of a given asset pair

Return type:

dict

Spot Market: Get the OHLC data
 1>>> from kraken.spot import Market
 2>>> Market().get_ohlc(pair="XBTUSD")
 3{
 4    "XXBTZUSD": [
 5        [
 6            1680671100,
 7            "28488.9",
 8            "28489.0",
 9            "28488.8",
10            "28489.0",
11            "28488.9",
12            "1.03390376",
13            8
14        ], ...
15    ]
16}
get_order_book(pair: str, count: int | None = 100, *, extra_params: dict | None = None) dict

Get the current orderbook of a specified trading pair.

Parameters:
  • pair (str) – The pair to get the orderbook from

  • count (int, optional) – Number of asks and bids, must be one of {1..500} (default: 100)

Returns:

Return type:

dict

Spot Market: Get the orderbook
 1>>> from kraken.spot import Market
 2>>> Market().get_order_book(pair="XBTUSD", count=2)
 3{
 4    'XXBTZUSD': {
 5        'asks': [
 6            ['28000.00000', '1.091', 1680714417],
 7            ['28001.00000', '0.001', 1680714413]
 8        ],
 9        'bids': [
10            ['27999.90000', '2.240', 1680714419],
11            ['27999.50000', '0.090', 1680714418]
12        ]
13    }
14}
get_recent_spreads(pair: str, since: str | int | None = None, *, extra_params: dict | None = None) dict

Get the latest spreads for a specific trading pair.

Parameters:
  • pair (str) – Pair to get the recent spreads

  • since (str | int, optional) – Filter trades since given timestamp (default: None)

Returns:

The last n spreads of the asset pair

Return type:

dict

Spot Market: Get the recent spreads
 1>>> from kraken.spot import Market
 2>>> Market().get_recent_spreads(pair="XBTUSD")
 3{
 4    "XXBTZUSD": [
 5        [1680714601, "28015.00000", "28019.40000"],
 6        [1680714601, "28015.00000", "28017.00000"],
 7        [1680714601, "28015.00000", "28016.90000"],
 8        ...
 9    ]
10}
get_recent_trades(pair: str, since: str | int | None = None, count: int | None = None, *, extra_params: dict | None = None) dict

Get the latest trades for a specific trading pair (up to 1000).

Parameters:
  • pair (str) – Pair to get the recent trades

  • since (str | int, optional) – Filter trades since given timestamp (default: None)

  • count (int, optional) – The max number of results

Returns:

The last public trades (up to 1000 results)

Return type:

dict

Spot Market: Get the recent trades
 1>>> from kraken.spot import Market
 2>>> Market().get_recent_trades(pair="XBTUSD")
 3{
 4    "XXBTZUSD": [
 5        ["27980.90000", "0.00071054", 1680712703.2524643, "b", "l", "", 57811127],
 6        ["27981.00000", "0.03180000", 1680712715.1806278, "b", "l", "", 57811128],
 7        ["27980.90000", "0.00010000", 1680712715.469506, "s", "m", "", 57811129],
 8        ...
 9    ]
10}
get_system_status(*, extra_params: dict | None = None) dict

Returns the system status of the Kraken Spot API.

Returns:

Success or failure

Return type:

dict

Spot Market: Get the Kraken API system status
1>>> from kraken.spot import Market
2>>> Market().get_system_status()
3{'status': 'online', 'timestamp': '2023-04-05T17:12:31Z'}
get_ticker(pair: str | list[str] | None = None, *, extra_params: dict | None = None) dict

Returns all tickers if pair is not specified - else just the ticker of the pair. Multiple pairs can be specified.

https://docs.kraken.com/rest/#operation/getTickerInformation

Parameters:

pair (str | list[str], optional) – Filter by pair(s)

Returns:

The ticker(s) including ask, bid, close, volume, vwap, high, low, todays open and more

Return type:

dict

Spot Market: Get the ticker(s)
 1>>> from kraken.spot import Market
 2>>> Market().get_ticker(pair="XBTUSD")
 3{
 4    'XXBTZUSD': {
 5        'a': ['27948.00000', '3', '3.000'],      # ask
 6        'b': ['27947.90000', '1', '1.000'],      # bid
 7        'c': ['27947.90000', '0.00842808'],      # last trade close, lot volume
 8        'v': ['3564.58017484', '4138.93906134'], # volume today and last 24h
 9        'p': ['28351.31431', '28329.55480'],     # vwap today and last 24h
10        't': [33574, 43062],                     # number of trades today and last 24h
11        'l': ['27813.10000', '27813.10000'],     # low today and last 24h
12        'h': ['28792.30000', '28792.30000'],     # high today and last 24
13        'o': '28173.00000'                       # today's opening price
14    }
15}
property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

class kraken.spot.Trade(key: str = '', secret: str = '', url: str = '')

Bases: KrakenSpotBaseAPI

Class that implements the Kraken Trade Spot client.

Parameters:
  • key (str, optional) – Spot API public key (default: "")

  • secret (str, optional) – Spot API secret key (default: "")

  • url (str, optional) – The URL to access the Kraken API (default: https://api.kraken.com)

Spot Trade: Create the trade client
1>>> from kraken.spot import Trade
2>>> trade = Trade() # unauthenticated
3>>> auth_trade = Trade(key="api-key", secret="secret-key") # authenticated
Spot Trade: Create the trade client as context manager
1>>> from kraken.spot import Trade
2>>> with Trade(key="api-key", secret="secret-key") as trade:
3...     print(trade.create_order(...))
cancel_all_orders(*, extra_params: dict | None = None) dict

Cancel all open orders.

Requires the Cancel/close orders permission in the API key settings.

Returns:

Success or failure - Number of closed orders

Return type:

dict

Spot Trade: Cancel all open orders
1>>> from kraken.spot import Trade
2>>> trade = Trade(key="api-key", secret="secret-key")
3>>> trade.cancel_all_orders()
4{ 'count': 2 }
cancel_all_orders_after_x(timeout: int = 0, *, extra_params: dict | None = None) dict

Cancel all orders after a timeout. This can be used as Dead Man’s Switch.

Requires the Create and modify orders permission in the API key settings.

Parameters:

timeout (int, optional) – Optional The timeout in seconds, deactivate by passing the default: 0

Returns:

Current time and trigger time

Return type:

dict

Spot Trade: Set the Death Man’s Switch
1>>> from kraken.spot import Trade
2>>> trade = Trade(key="api-key", secret="secret-key")
3>>> trade.cancel_all_orders_after_x(timeout=60)
4{
5    'currentTime': '2023-04-06T06:51:56Z',
6    'triggerTime': '2023-04-06T06:52:56Z'
7}
cancel_order(txid: str, *, extra_params: dict | None = None) dict

Cancel a specific order by txid. Instead of a transaction id a user reference id can be passed.

Requires the Cancel/close orders permission in the API key settings.

Parameters:

txid (str) – Transaction id or comma delimited list of user reference ids to cancel.

Returns:

Success or failure - Number of closed orders

Return type:

dict

Spot Trade: Cancel an order
1>>> from kraken.spot import Trade
2>>> trade = Trade(key="api-key", secret="secret-key")
3>>> trade.cancel_order(txid="OAUHYR-YCVK6-P22G6P")
4{ 'count': 1 }
cancel_order_batch(orders: list[str | int], *, extra_params: dict | None = None) dict

Cancel a a list of orders by txid or userref

Requires the Cancel/close orders permission in the API key settings.

Parameters:

orders (list[str | int]) – List of orders to cancel

Returns:

Success or failure - Number of closed orders

Return type:

dict

Spot Trade: Cancel multiple orders
1>>> from kraken.spot import Trade
2>>> trade = Trade(key="api-key", secret="secret-key")
3>>> trade.cancel_order_batch(
4...     orders=["OG5IL4-6AR7I-ZAPZEZ", "OAUHYR-YCVK6-P22G6P"]
5... )
6{ count': 2 }
create_order(ordertype: str, side: str, pair: str, volume: str | float, price: str | float | None = None, price2: str | float | None = None, trigger: str | None = None, leverage: str | None = None, stptype: str | None = 'cancel-newest', oflags: str | list[str] | None = None, timeinforce: str | None = None, displayvol: str | None = None, starttm: str | None = '0', expiretm: str | None = None, close_ordertype: str | None = None, close_price: str | float | None = None, close_price2: str | float | None = None, deadline: str | None = None, userref: int | None = None, *, truncate: bool = False, reduce_only: bool | None = False, validate: bool = False, extra_params: dict | None = None) dict

Create a new order and place it on the market.

Requires the Create and modify orders permission in the API key settings.

Parameters:
  • ordertype (str) – The kind of the order, one of: market, limit, take-profit, stop-loss-limit, take-profit-limit and settle-position (see: https://support.kraken.com/hc/en-us/sections/200577136-Order-types)

  • side (str) – buy or sell

  • pair (str) – The asset to trade

  • volume (str | float) – The volume of the position to create

  • price (str | float, optional) – The limit price for limit orders and the trigger price for orders with ordertype one of stop-loss, stop-loss-limit, take-profit, and take-profit-limit

  • price2 (str | float, optional) –

    The limit price for stop-loss-limit and take-profit-limit orders The price2 can also be set to absolute or relative changes.

    • Prefixed using + or - defines the change in the quote asset

    • Prefixed by # is the same as + or - but the sign is set automatically

    • The percentage sign (%) can be used to define relative changes.

  • trigger (str, optional) – What triggers the position of stop-loss, stop-loss-limit, take-profit, and take-profit-limit orders. Will also be used for associated conditional close orders. Kraken will use last if nothing is specified.

  • leverage (str | float, optional) – The leverage

  • stptype (str, optional) – Define what cancels the order, one of cancel-newest, cancel-oldest, cancel-both (default: cancel-newest)

  • oflags (str | list[str], optional) – Order flags like post, fcib, fciq, nomp, viqc (see the referenced Kraken documentation for more information)

  • timeinforce (str, optional) – how long the order remains in the orderbook, one of: GTC, IOC, GTD (see the referenced Kraken documentation for more information)

  • displayvol (str | float, optional) – Define how much of the volume is visible in the orderbook (iceberg)

  • starttim (str, optional) – Unix timestamp or seconds defining the start time (default: "0")

  • expiretm (str, optional) – Unix timestamp or time in seconds defining the expiration of the order, (default: "0" - i.e., no expiration)

  • close_ordertype (str, optional) – Conditional close order type, one of: limit, stop-loss, take-profit, stop-loss-limit, take-profit-limit (see the referenced Kraken documentation for more information)

  • close_price (str | float, optional) – Conditional close price

  • close_price2 (str | float, optional) – The price2 for the conditional order - see the price2 parameter description

  • deadline (str, optional) – RFC3339 timestamp + {0..60} seconds that defines when the matching engine should reject the order.

  • truncate (bool, optional) – If enabled: round the price and volume to Kraken’s maximum allowed decimal places. See https://support.kraken.com/hc/en-us/articles/4521313131540 fore more information about decimals.

  • reduce_only (bool, optional) – Reduce existing orders (default: False)

  • validate (bool, optional) – Validate the order without placing on the market (default: False)

  • userref (int, optional) – User reference id for example to group orders

Raises:

ValueError – If input is not correct

Returns:

The transaction id

Return type:

dict

Spot Trade: Create a market order
 1>>> from kraken.spot import Trade
 2>>> trade = Trade(key="api-key", secret="secret-key")
 3>>> trade.create_order(
 4...     ordertype="market",
 5...     side="buy",
 6...     pair="XBTUSD",
 7...     volume="0.0001"
 8... )
 9{
10    'txid': ['TNGMNU-XQSRA-LKCWOK'],
11    'descr': {
12        'order': 'buy 4.00000000 XBTUSD @ limit 23000.0'
13    }
14}
Spot Trade: Create limit order
 1>>> from kraken.spot import Trade
 2>>> trade = Trade(key="api-key", secret="secret-key")
 3>>> trade.create_order(
 4...     ordertype="limit",
 5...     side="buy",
 6...     pair="XBTUSD",
 7...     volume=4,
 8...     price=23000,
 9...     expiretm=121,
10...     displayvol=0.5,
11...     oflags=["post", "fcib"]
12... )
13{
14    'txid': ['TPPI2H-CUZZ2-EQR2IE'],
15    'descr': {
16        'order': 'buy 4.0000 XBTUSD @ limit 23000.0'
17    }
18}
Spot Trade: Create a stop loss order
 1>>> from kraken.spot import Trade
 2>>> trade = Trade(key="api-key", secret="secret-key")
 3>>> trade.create_order(
 4...     ordertype="stop-loss",
 5...     pair="XBTUSD",
 6...     volume=20,
 7...     price=22000,
 8...     side="buy",
 9... )
10{
11    'txid': ['THNUL1-8ZAS5-EEF3A8'],
12    'descr': {
13        'order': 'buy 20.00000000 XBTUSD @ stop loss 22000.0'
14    }
15}
Spot Trade: Create stop-loss-limit and take-profit-limit orders
 1''' When the price hits $25000:
 2   1. A limit buy order will be placed at $24000 with 2x leverage.
 3   2. When the limit order gets closed/filled at $24000 The
 4      stop-loss-limit part is done and the tale-profit-limit part
 5      begins.
 6   3. When the price hits $27000 a limit order will be placed at
 7      $26800 to sell 1.2 BTC. This ensures that the asset will be
 8      sold for $26800 or better.
 9''' >>> from kraken.spot import Trade >>> trade =
10Trade(key="api-key", secret="secret-key") >>> from datetime import
11datetime, timedelta, timezone >>> deadline = ( ...
12datetime.now(timezone.utc) + timedelta(seconds=20) ... ).isoformat()
13>>> trade.create_order( ...     ordertype="stop-loss-limit", ...
14pair="XBTUSD", ...     side="buy", ...     volume=1.2, ...
15price=24000, ...     price2=25000, ...     validate=True, # just
16validate the input, do not place on the market ...
17trigger="last", ...     timeinforce="GTC", ...     leverage=4, ...
18deadline=deadline, ...     close_ordertype="take-profit-limit", ...
19close_price=27000, ...     close_price2=26800, ... ) {
20    'descr': {
21        'order': 'buy 0.00100000 XBTUSD @ stop loss 24000.0 -> limit
22        25000.0 with 2:1 leverage', 'close': 'close position @ take
23        profit 27000.0 -> limit 26800.0'
24    }
25}
26
27''' The price2 and close_price2 can also be set to absolute or
28relative changes.
29    * Prefixed using "+" or "-" defines the change in the quote
30      asset
31    * Prefixed by # is the same as "+" and "-" but the sign is set
32      automatically
33    * The the percentage sign "%" can be used to define relative
34      changes.
35''' >>> trade.create_order( ...     ordertype="stop-loss-limit", ...
36pair="XBTUSD", ...     side="buy", ...     volume=1.2, ...
37price=24000, ...     price2="+1000", ...     validate=True, ...
38trigger="last", ...     timeinforce="GTC", ...
39close_ordertype="take-profit-limit", ...     close_price=27000, ...
40close_price2="#2%", ... ) {
41    'descr': {
42        'order': 'buy 0.00100000 XBTUSD @ stop loss 24000.0 -> limit
43        +1000.0', 'close': 'close position @ take profit 27000.0 ->
44        limit -2.0000%'
45    }
46}
create_order_batch(orders: list[dict], pair: str, deadline: str | None = None, *, validate: bool = False, extra_params: dict | None = None) dict

Create a batch of max 15 orders for a specific asset pair.

Requires the Create and modify orders permission in the API key settings.

Parameters:
  • orders (list[dict]) – Dictionary of order objects (see the referenced Kraken documentation for more information)

  • pair (str) – Asset pair to place the orders for

  • deadline (str, optional) – RFC3339 timestamp + {0..60} seconds that defines when the matching engine should reject the order.

  • validate (bool, optional) – Validate the orders without placing them. (default: False)

Returns:

Information about the placed orders

Return type:

dict

Spot Trade: Create a batch order
 1>>> from kraken.spot import Trade
 2>>> trade = Trade(key="api-key", secret="secret-key")
 3>>> trade.create_order_batch(orders=[
 4...         {
 5...             "close": {
 6...                 "ordertype": "stop-loss-limit",
 7...                 "price": 21000,
 8...                 "price2": 20000,
 9...             },
10...             "ordertype": "limit",
11...             "price": 25000,
12...             "timeinforce": "GTC",
13...             "type": "buy",
14...             "userref": 16861348843,
15...             "volume": 1,
16...         },
17...         {
18...             "ordertype": "limit",
19...             "price": 1000000,
20...             "timeinforce": "GTC",
21...             "type": "sell",
22...             "userref": 16861348843,
23...             "volume": 2,
24...         },
25...     ],
26...     pair="BTC/USD"
27... )
28{
29    'orders': [{
30        'order': 'buy 1 BTCUSD @ limit 25000',
31        'txid': 'O5TLGX-DKKTU-WKRAZ5',
32        'close': 'close position @ stop loss 21000.0 -> limit 20000.0'
33    }, {
34        'order': "sell 2 BTCUSD @ limit 1000000',
35        'txid': 'OBGFYP-XVQNL-P4GMWF'
36    }]
37}
edit_order(txid: str, pair: str, volume: str | float | None = None, price: str | float | None = None, price2: str | float | None = None, oflags: str | None = None, deadline: str | None = None, cancel_response: bool | None = None, userref: int | None = None, *, truncate: bool = False, validate: bool = False, extra_params: dict | None = None) dict

Edit an open order.

Requires the Create and modify orders permission in the API key settings.

Parameters:
  • txid (str) – The txid of the order to edit

  • pair (str) – The asset pair of the order

  • volume (str | float, optional) – Set a new volume

  • price (str | float, optional) – Set a new price

  • price2 (str | float, optional) – Set a new second price

  • oflags (str | list[str], optional) – Order flags like post, fcib, fciq, nomp, viqc (see the referenced Kraken documentation for more information)

  • deadline (string) – (see the referenced Kraken documentation for more information)

  • cancel_response (bool, optional) – See the referenced Kraken documentation for more information

  • truncate (bool, optional) – If enabled: round the price and volume to Kraken’s maximum allowed decimal places. See https://support.kraken.com/hc/en-us/articles/4521313131540 fore more information about decimals.

  • validate (bool, optional) – Validate the order without placing on the market (default: False)

  • userref (int) – User reference id for example to group orders

Returns:

Success or failure

Return type:

dict

Spot Trade: Modify an order
 1>>> from kraken.spot import Trade
 2>>> trade = Trade(key="api-key", secret="secret-key")
 3>>> trade.edit_order(txid="OBGFYP-XVQNL-P4GMWF",
 4...     volume=0.75,
 5...     pair="XBTUSD",
 6...     price=1250000
 7... )
 8{
 9    'status': 'ok',
10    'txid': 'OFVXHJ-KPQ3B-VS7ELA',
11    'originaltxid': 'OBGFYP-XVQNL-P4GMWF',
12    'volume': '0.75',
13    'price': '1250000',
14    'orders_cancelled': 1,
15    'descr': {
16        'order': 'sell 0.75 XXBTZUSD @ limit 1250000'
17    }
18}
property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

truncate(amount: Decimal | float | str, amount_type: str, pair: str) str

Kraken only allows volume and price amounts to be specified with a specific number of decimal places, and these vary depending on the currency pair used.

This function converts an amount of a specific type and pair to a string that uses the correct number of decimal places.

This function uses caching. Run truncate.clear_cache() to clear.

Parameters:
  • amount (Decimal | float | str) – The floating point number to represent

  • amount_type (str) – What the amount represents. Either "price" or "volume"

  • pair (str) – The currency pair the amount is in reference to.

Raises:
  • ValueError – If the amount_type is price and the price is less than the costmin.

  • ValueError – If the amount_type is volume and the volume is less than the ordermin.

  • ValueError – If no valid amount_type was passed.

Returns:

A string representation of the amount.

Return type:

str

Spot Trade: Truncate
 1>>> print(trade.truncate(
 2...     amount=0.123456789,
 3...     amount_type="volume",
 4...     pair="XBTUSD"
 5... ))
 60.12345678
 7
 8>>> print(trade.truncate(
 9...     amount=21123.12849829993,
10...     amount_type="price",
11...     pair="XBTUSD")
12... ))
1321123.1
14
15>>> print(trade.truncate(
16...     amount=0.1,
17...     amount_type="volume",
18...     pair="XBTUSD"
19... ))
200.10000000
21
22>>> print(trade.truncate(
23...     amount=21123,
24...     amount_type="price",
25...     pair="XBTUSD"
26... ))
2721123.0
class kraken.spot.Funding(key: str = '', secret: str = '', url: str = '')

Bases: KrakenSpotBaseAPI

Class that implements the Spot Funding client. Currently there are no funding endpoints that could be accesses without authentication.

Parameters:
  • key (str, optional) – Spot API public key (default: "")

  • secret (str, optional) – Spot API secret key (default: "")

  • url (str, optional) – Alternative URL to access the Kraken API (default: https://api.kraken.com)

Spot Funding: Create the funding client
1>>> from kraken.spot import Funding
2>>> funding = Funding() # unauthenticated
3>>> auth_funding = Funding(key="api-key", secret="secret-key") # authenticated
Spot Funding: Create the funding client as context manager
1>>> from kraken.spot import Funding
2>>> with Funding(key="api-key", secret="secret-key") as funding:
3...     print(funding.get_deposit_methods(asset="XLM"))
cancel_withdraw(asset: str, refid: str, *, extra_params: dict | None = None) dict

Cancel a requested withdraw. This will only be successful if the withdraw is not being processed so far.

Requires the Withdraw funds API key permissions.

Parameters:
  • asset (str) – Asset of the pending withdraw

  • refid (str) – The reference ID returned the withdraw was requested

Returns:

Success or failure

Return type:

dict

Spot Funding: Cancel Withdraw
1>>> from kraken.spot import Funding
2>>> funding = Funding(key="api-key", secret="secret-key")
3>>> funding.cancel_withdraw(asset="DOT", refid="I7KGS6-UFMTTQ-AGBSO6T")
4{ 'result': True }
get_deposit_address(asset: str, method: str, *, new: bool | None = False, extra_params: dict | None = None) list[dict]

Get the deposit addresses for a specific asset. New deposit addresses can be generated.

Requires the Deposit funds API key permission.

Parameters:
  • asset (str) – Asset being deposited

  • method (str) – Deposit method name

  • new (bool, optional) – Generate a new deposit address (default: False)

Returns:

The user and asset specific deposit addresses

Return type:

list[dict]

Spot Funding: Get the available deposit addresses
 1>>> from kraken.spot import Funding
 2>>> funding = Funding(key="api-key", secret="secret-key")
 3>>> funding.get_deposit_address(asset="XLM", method="Stellar XLM")
 4[
 5    {
 6        'address': 'GA5XIGA5C7QTPTWXQHY6MCJRMTRZDOSHR6EFIBNDQTCQHG262N4GGKTM',
 7        'expiretm': '0',
 8        'new': True,
 9        'tag': '1668814718654064928'
10    }, {
11        'address': 'GA5XIGA5C7QTPTWXQHY6MCJRMTRZDOSHR6EFIBNDQTCQHG262N4GGKTM',
12        'expiretm': '0',
13        'new': True,
14        'tag': '1668815609618044006'
15    },  ...
16]
get_deposit_methods(asset: str, *, extra_params: dict | None = None) list[dict]

Get the available deposit methods for a specific asset.

Parameters:

asset (str) – Asset being deposited

Returns:

List of available deposit methods of the asset

Return type:

list[dict]

Spot Funding: Get the available deposit methods
 1>>> from kraken.spot import Funding
 2>>> funding = Funding(key="api-key", secret="secret-key")
 3>>> funding.get_deposit_methods(asset="XLM")
 4[
 5    {
 6        'method': 'Stellar XLM',
 7        'limit': False,
 8        'gen-address': True
 9    }, {
10        'method': 'Stellar XLM Multi',
11        'limit': False,
12        'gen-address': True
13    }
14]
get_recent_deposits_status(asset: str | None = None, method: str | None = None, start: str | None = None, end: str | None = None, cursor: bool | str = False, *, extra_params: dict | None = None) list[dict] | dict

Get information about the recent deposit status. The look back period is 90 days and only the last 25 deposits will be returned.

Requires the Query funds and Deposit funds API key permissions.

Parameters:
  • asset (str, optional) – Filter by asset

  • method (str, optional) – Filter by deposit method

  • start (str, optional) – Start timestamp

  • end (str, optional) – End timestamp

  • cursor (bool | str, default: False) – If bool: dis-/enable paginated responses; if str: cursor for next page

Returns:

The user specific deposit history

Return type:

list[dict] | dict

Spot Funding: Get the recent deposit status
 1>>> from kraken.spot import Funding
 2>>> funding = Funding(key="api-key", secret="secret-key")
 3>>> funding.get_recent_deposits_status()
 4[
 5    {
 6        'method': 'Bank Frick (SEPA)',
 7        'aclass': 'currency',
 8        'asset': 'ZEUR',
 9        'refid': 'QDFN2EK-XMFWQ4-GPB7SG',
10        'txid': '7702226',
11        'info': 'NTSBDEB1XXX',
12        'amount': '1000.0000',
13        'fee': '0.0000',
14        'time': 1680245166,
15        'status': 'Success'
16    }, {
17        'method': 'Bank Frick (SEPA)',
18        'aclass': 'currency',
19        'asset': 'ZEUR',
20        'refid': 'QDFO35O-O4IU7K-ZEP77Y',
21        'txid': '7559797',
22        'info': 'NTSBDEB1XXX',
23        'amount': '500.0000',
24        'fee': '0.0000',
25        'time': 1677827980,
26        'status': 'Success'
27    }, {
28        'method': 'Ethereum (ERC20)',
29        'aclass': 'currency',
30        'asset': 'XETH',
31        'refid': 'Q5QTWMS-GXER37-ZI4IH6',
32        'txid': '0x2abb04dafd3caed53d4f2912651391c53b912cc4bca1f8b30d09a5cebec5c2d6',
33        'info': '0x35be16f2340c97c02c0cf4dcd9279f2eaa4a0980',
34        'amount': '0.0119328120',
35        'fee': '0.0000000000',
36        'time': 1672901534,
37        'status': 'Success'
38    }, ...
39]
get_recent_withdraw_status(asset: str | None = None, method: str | None = None, start: str | None = None, end: str | None = None, cursor: str | bool | None = None, *, extra_params: dict | None = None) list[dict]

Get information about the recent withdraw status, including withdraws of the past 90 days but at max 500 results.

Parameters:
  • asset (str, optional) – Filter withdraws by asset (default: None)

  • method (str, optional) – Filter by withdraw method (default: None)

  • start (str, optional) – Filter by start timestamp

  • end (str, optional) – Filter by end timestamp

  • cursor (str | bool, optional) – en-/disable paginated responses via True/False or define the page as str.

Returns:

Withdrawal information

Return type:

list[dict]

Get the recent withdraw status
 1>>> from kraken.spot import Funding
 2>>> funding = Funding(key="api-key", secret="secret-key")
 3>>> funding.get_recent_withdraw_status()
 4[
 5    {
 6        'method': 'Polkadot',
 7        'aclass': 'currency',
 8        'asset': 'DOT',
 9        'refid': 'XXXXXX-XXXXXX-HLDRM5',
10        'txid': '0x51d9d13ade1c31a138dae81b845f091d1a6cf2e3c1c36d9cf4f7baf905c483e4',
11        'info': '16LrqRXyhjBCSfA6kKrdqxPKrZoMEUtmoW4nkx5ZhA374Bp3',
12        'amount': '94.39581164',
13        'fee': '0.05000000',
14        'time': 1677816733,
15        'status': 'Success'
16    }, ...
17]
get_withdrawal_info(asset: str, key: str, amount: str | float, *, extra_params: dict | None = None) dict

Get information about a possible withdraw, including fee and limit information. The key must be the name of the key defined in the account. You can add a new key for any asset listed on Kraken here: https://www.kraken.com/u/funding/withdraw.

Requires the Query funds and Withdraw funds API key permissions.

Parameters:
  • asset (str) – Asset to withdraw

  • key (str) – Withdrawal key name as set up in the user account

  • amount (str | float) – The amount to withdraw

Returns:

Information about a possible withdraw including the fee and amount.

Return type:

dict

Spot Funding: Get withdrawal information
 1>>> from kraken.spot import Funding
 2>>> funding = Funding(key="api-key", secret="secret-key")
 3>>> funding.get_withdrawal_info(
 4...     asset="DOT",
 5...     key="MyPolkadotWallet",
 6...     amount="4"
 7... )
 8{
 9    'method': 'Polkadot',
10    'limit': '4.49880000',
11    'amount': '3.95000000',
12    'fee': '0.05000000'
13}
property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

wallet_transfer(asset: str, from_: str, to_: str, amount: str | float, *, extra_params: dict | None = None) dict

Transfer assets between the Spot and Futures wallet.

Requires the Withdraw funds API key permissions.

Parameters:
  • asset (str) – Asset to transfer

  • from (str) – The wallet to withdraw from

  • to (str) – The wallet to deposit to

  • amount (str | float) – The amount to transfer

Returns:

The reference id

Return type:

dict

Spot Funding: Wallet Transfer
1>>> from kraken.spot import Funding
2>>> funding = Funding(key="api-key", secret="secret-key")
3>>> funding.wallet_transfer(
4...     asset="XBT",
5...     from_="Spot Wallet",
6...     to_="Futures Wallet",
7...     amount=0.01
8... )
9{ 'refid': "ANS1EE5-SKACR4-PENGVP" }
withdraw_addresses(asset: str | None = None, aclass: str | None = None, method: str | None = None, key: str | None = None, verified: bool | None = None, *, extra_params: dict | None = None) dict

Returns the list of available withdrawal addresses for that user.

Requires the Funds permissions - Query and Funds permissions - Withdraw API key permissions.

Parameters:
  • asset (Optional[str]) – Filter by asset

  • aclass (Optional[str]) – Filter by asset class (default: currency)

  • method (Optional[str]) – Filter by method

  • key (Optional[str]) – Filter by key

  • verified (Optional[str]) – List only addresses which are confirmed via E-Mail

Returns:

List of available addresses for withdrawal

Return type:

list[dict]

withdraw_funds(asset: str, key: str, amount: str | float, max_fee: str | None = None, *, extra_params: dict | None = None) dict

Create a new withdraw. The key must be the name of the withdraw key defined in the withdraw section of the Kraken WebUI.

Requires the Withdraw funds API key permissions.

Parameters:
  • asset (str) – Asset to withdraw

  • key (str) – Withdrawal key name as set up in the account

  • amount (str | float) – The amount to withdraw

  • max_fee (str) – Fail withdraw if the fee will be higher than the specified max_fee.

Returns:

The reference id of the withdraw

Return type:

dict

Spot Funding: Withdraw Funds
1>>> from kraken.spot import Funding
2>>> funding = Funding(key="api-key", secret="secret-key")
3>>> funding.withdraw_funds(
4...    asset="DOT",
5...    key="MyPolkadotWallet"
6...    amount=4
7... )
8{ 'refid': 'I7KGS6-UFMTTQ-AGBSO6T'}
withdraw_methods(asset: str | None = None, aclass: str | None = None, network: str | None = None, *, extra_params: dict | None = None) dict

Returns the list of available withdraw methods for that user.

Requires the Funds permissions - Query and Funds permissions - Withdraw API key permissions.

Parameters:
  • asset (Optional[str]) – Filter by asset

  • aclass (Optional[str]) – Filter by asset class (default: currency)

  • network (Optional[str]) – Filter by network

Returns:

List of available withdraw methods

Return type:

list[dict]

class kraken.spot.Earn(key: str = '', secret: str = '', url: str = '')

Bases: KrakenSpotBaseAPI

Class that implements the Kraken Spot Earn client. Currently there are no earn endpoints that could be accesses without authentication. The earn endpoints replace the past staking endpoints.

Parameters:
  • key (str, optional) – Spot API public key (default: "")

  • secret (str, optional) – Spot API secret key (default: "")

  • url (str, optional) – Alternative URL to access the Kraken API (default: https://api.kraken.com)

Spot Earn: Create the Earn client
1>>> from kraken.spot import Earn
2>>> earn = Earn() # unauthenticated
3>>> auth_earn = Earn(key="api-key", secret="secret-key") # authenticated
Spot Earn: Create the earn client as context manager
1>>> from kraken.spot import Earn
2>>> with Earn(key="api-key", secret="secret-key") as earn:
3...     print(earn.stake_asset(asset="XLM", amount=200, method="Lumen Staked"))
allocate_earn_funds(amount: str | float, strategy_id: str, *, extra_params: dict | None = None) bool

Allocate funds according to the defined strategy.

Requires the Earn Funds API key permission

Parameters:
Spot Earn: Allocate funds
1>>> from kraken.earn import Earn
2>>> earn = Earn(key="api-key", secret="secret-key")
3>>> earn.allocate_earn_funds(
4...     amount=2000,
5...     strategy_id="ESRFUO3-Q62XD-WIOIL7"
6... )
7True
deallocate_earn_funds(amount: str | float, strategy_id: str, *, extra_params: dict | None = None) bool

Deallocate funds according to the defined strategy.

Requires the Earn Funds API key permission

Parameters:
Spot Earn: Deallocate funds
1>>> from kraken.earn import Earn
2>>> earn = Earn(key="api-key", secret="secret-key")
3>>> earn.deallocate_earn_funds(
4...     amount=2000,
5...     strategy_id="ESRFUO3-Q62XD-WIOIL7"
6... )
7True
get_allocation_status(strategy_id: str, *, extra_params: dict | None = None) dict

Retrieve the status of the last allocation request.

Requires the Earn Funds or Query Funds API key permission.

Parameters:

strategy_id (str) – Identifier of th chosen earn strategy (see kraken.spot.Earn.list_earn_strategies())

Spot Earn: Allocation Status
1>>> from kraken.earn import Earn
2>>> earn = Earn(key="api-key", secret="secret-key")
3>>> earn.get_allocation_status(
4...     strategy_id="ESRFUO3-Q62XD-WIOIL7"
5... )
6{'pending': False}
get_deallocation_status(strategy_id: str, *, extra_params: dict | None = None) dict

Retrieve the status of the last deallocation request.

Requires the Earn Funds or Query Funds API key permission.

Parameters:

strategy_id (str) – Identifier of th chosen earn strategy (see kraken.spot.Earn.list_earn_strategies())

Spot Earn: Deallocation Status
1>>> from kraken.earn import Earn
2>>> earn = Earn(key="api-key", secret="secret-key")
3>>> earn.get_deallocation_status(
4...     strategy_id="ESRFUO3-Q62XD-WIOIL7"
5... )
6{'pending': False}
list_earn_allocations(ascending: str | None = None, hide_zero_allocations: str | None = None, converted_asset: str | None = None, *, extra_params: dict | None = None) dict

List the user’s allocations.

Requires the Query Funds API key permission.

(March 9, 2024): The endpoint is not fully implemented on the side of Kraken. Some errors may happen.

Parameters:
  • ascending (bool, optional) – Sort ascending, defaults to False

  • hide_zero_allocations (bool, optional) – Hide past allocations without balance, defaults to False

  • coverted_asset (str, optional) – Currency to express the value of the allocated asset, defaults to None

Spot Earn: List Earn Allocations
 1>>> from kraken.earn import Earn
 2>>> earn = Earn(key="api-key", secret="secret-key")
 3>>> earn.list_earn_allocations(asset="DOT")
 4{
 5"converted_asset": "USD",
 6    "total_allocated": "49.2398",
 7    "total_rewarded": "0.0675",
 8    "next_cursor": "2",
 9    "items": [{
10        "strategy_id": "ESDQCOL-WTZEU-NU55QF",
11        "native_asset": "ETH",
12        "amount_allocated": {},
13        "total_rewarded": {}
14    }]
15}
list_earn_strategies(asset: str | None = None, limit: int | None = None, lock_type: list[str] | None = None, cursor: bool | None = None, ascending: bool | None = None, *, extra_params: dict | None = None) dict

List the available earn strategies as well as additional information.

Requires an API key but no special permission set.

(March 9, 2024): The endpoint is not fully implemented on the side of Kraken. Some errors may happen.

Parameters:
  • asset (Optional[str], optional) – Asset to filter for, defaults to None

  • limit (Optional[int], optional) – Items per page, defaults to None

  • lock_type (Optional[list[str]], optional) – Filter strategies by lock type (flex, bounded, timed, instant), defaults to None

  • cursor (Optional[bool], optional) – Page ID, defaults to None

  • ascending (bool, optional) – Sort ascending, defaults to False

Spot Earn: List Earn Strategies
 1>>> from kraken.earn import Earn
 2>>> earn = Earn(key="api-key", secret="secret-key")
 3>>> earn.list_earn_strategies(asset="DOT")
 4{
 5    "next_cursor": None,
 6    "items": [
 7        {
 8            "id": "ESMWVX6-JAPVY-23L3CV",
 9            "asset": "DOT",
10            "lock_type": {
11                "type": "bonded",
12                "payout_frequency": 604800,
13                "bonding_period": 0,
14                "bonding_period_variable": False,
15                "bonding_rewards": False,
16                "unbonding_period": 2419200,
17                "unbonding_period_variable": False,
18                "unbonding_rewards": False,
19                "exit_queue_period": 0,
20            },
21            "apr_estimate": {"low": "15.0000", "high": "21.0000"},
22            "user_min_allocation": "0.01",
23            "allocation_fee": "0.0000",
24            "deallocation_fee": "0.0000",
25            "auto_compound": {"type": "enabled"},
26            "yield_source": {"type": "staking"},
27            "can_allocate": True,
28            "can_deallocate": True,
29            "allocation_restriction_info": [],
30        },
31        {
32            "id": "ESRFUO3-Q62XD-WIOIL7",
33            "asset": "DOT",
34            "lock_type": {"type": "instant", "payout_frequency": 604800},
35            "apr_estimate": {"low": "7.0000", "high": "11.0000"},
36            "user_min_allocation": "0.01",
37            "allocation_fee": "0.0000",
38            "deallocation_fee": "0.0000",
39            "auto_compound": {"type": "enabled"},
40            "yield_source": {"type": "staking"},
41            "can_allocate": True,
42            "can_deallocate": True,
43            "allocation_restriction_info": [],
44        },
45    ],
46}
property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

class kraken.spot.Staking(key: str = '', secret: str = '', url: str = '')

Bases: KrakenSpotBaseAPI

Deprecated since version v2.2.0.

Class that implements the Kraken Spot Staking client. Currently there are no staking endpoints that could be accesses without authentication.

Parameters:
  • key (str, optional) – Spot API public key (default: "")

  • secret (str, optional) – Spot API secret key (default: "")

  • url (str, optional) – Alternative URL to access the Kraken API (default: https://api.kraken.com)

  • sandbox (bool, optional) – Use the sandbox (not supported for Spot trading so far, default: False)

Spot Staking: Create the staking client
1>>> from kraken.spot import Staking
2>>> staking = Staking() # unauthenticated
3>>> auth_staking = Staking(key="api-key", secret="secret-key") # authenticated
Spot Staking: Create the staking client as context manager
1>>> from kraken.spot import Staking
2>>> with Staking(key="api-key", secret="secret-key") as staking:
3...     print(staking.stake_asset(asset="XLM", amount=200, method="Lumen Staked"))
get_pending_staking_transactions(*, extra_params: dict | None = None) list[dict]

Deprecated since version v2.2.0.

Get the list of pending staking transactions of the user.

Requires the Withdraw funds and Query funds API key permissions.

Returns:

List of pending staking transactions

Return type:

list[dict]

Spot Staking: Get the pending staking transactions
 1>>> from kraken.spot import Staking
 2>>> staking = Staking(key="api-key", secret="secret-key")
 3>>> staking.get_pending_staking_transactions()
 4[
 5    {
 6        'method': 'polkadot-staked',
 7        'aclass': 'currency',
 8        'asset': 'DOT.S',
 9        'refid': 'BOG5AE5-KSCNR4-VPNPEV',
10        'amount': '1982.17316',
11        'fee': '0.00000000',
12        'time': 1623653613,
13        'status': 'Initial',
14        'type': 'bonding'
15    }, ...
16]
list_stakeable_assets(*, extra_params: dict | None = None) list[dict]

Deprecated since version v2.2.0.

Get a list of stakeable assets. Only assets that the user is able to stake will be shown.

Requires the Withdraw funds and Query funds API key permissions.

https://docs.kraken.com/rest/#operation/getStakingAssetInfo

Returns:

Information for all assets that can be staked on Kraken

Return type:

list[dict]

Spot Staking: List the stakeable assets
 1>>> from kraken.spot import Staking
 2>>> staking = Staking(key="api-key", secret="secret-key")
 3>>> staking.list_stakeable_assets()
 4[
 5    {
 6        "method": "polkadot-staked",
 7        "asset": "DOT",
 8        "staking_asset": "DOT.S",
 9        "rewards": {
10            "type": "percentage",
11            "reward": "7-11"
12        },
13        "on_chain": True,
14        "can_stake": True,
15        "can_unstake": True,
16        "minimum_amount": {
17            "staking": "0.0000000100",
18            "unstaking": "0.0000000100"
19        }
20    }, {
21        "method": "polygon-staked",
22        "asset": "MATIC",
23        "staking_asset": "MATIC.S",
24        "rewards": {
25            "type": "percentage",
26            "reward": "1-2"
27        },
28        "on_chain": True,
29        "can_stake": True,
30        "can_unstake": True,
31        "minimum_amount": {
32            "staking": "0.0000000000",
33            "unstaking": "0.0000000000"
34        }
35    }, ...
36]
list_staking_transactions(*, extra_params: dict | None = None) list[dict]

Deprecated since version v2.2.0.

List the last 1000 staking transactions of the past 90 days.

Requires the Query funds API key permission.

Returns:

List of historical staking transactions

Return type:

list[dict]

Spot Staking: List the historical staking transactions
 1>>> from kraken.spot import Staking
 2>>> staking = Staking(key="api-key", secret="secret-key")
 3>>> staking.list_staking_transactions()
 4[
 5    {
 6        'method': 'polkadot-staked',
 7        'aclass': 'currency',
 8        'asset': 'DOT.S',
 9        'refid': 'POLZN7T-RWBL2YD-3HAPL1',
10        'amount': '121.1',
11        'fee': '1.0000000000',
12        'time': 1622971496,
13        'status': 'Success'.
14        'type': 'bonding',
15        'bond_start': 1623234684,
16        'bond_end': 1632345316
17    }, ...
18]
property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

stake_asset(asset: str, amount: str | float, method: str, *, extra_params: dict | None = None) dict

Deprecated since version v2.2.0.

Stake the specified asset from the Spot wallet.

Requires the Withdraw funds permission in the API key settings.

Have a look at kraken.spot.Staking.list_stakeable_assets() to get information about the stakable assets and methods.

Parameters:
  • asset (str) – The asset to stake

  • amount (str | float) – The amount to stake

  • method (str) – The staking method

Returns:

The reference id of the staking transaction

Return type:

dict

Spot Staking: Stake an asset
1>>> from kraken.spot import Staking
2>>> staking = Staking(key="api-key", secret="secret-key")
3>>> staking.stake_asset(
4...     asset="DOT",
5...     amount=2000,
6...     method="polkadot-staked"
7... )
8{ 'refid': 'BOG5AE5-KSCNR4-VPNPEV' }
unstake_asset(asset: str, amount: str | float, method: str | None = None, *, extra_params: dict | None = None) dict

Deprecated since version v2.2.0.

Unstake an asset and transfer the amount to the Spot wallet.

Requires the Withdraw funds permission in the API key settings.

Have a look at kraken.spot.Staking.list_stakeable_assets() to get information about the stakeable assets and methods.

Parameters:
  • asset (str) – The asset to stake

  • amount (str | float) – The amount to stake

  • method (str, optional) – Filter by staking method (default: None)

Returns:

The reference id of the unstaking transaction

Return type:

dict

Spot Staking: Unstake a staked asset
1>>> from kraken.spot import Staking
2>>> staking = Staking(key="api-key", secret="secret-key")
3>>> staking.unstake_asset(
4...     asset="DOT",
5...     amount=2000,
6...     method="polkadot-staked"
7... )
8{ 'refid': 'BOG5AE5-KSCNR4-VPNPEV' }