krakenexapi.api

Raw API

class krakenexapi.api.RawKrakenExAPI(key: Optional[str] = None, secret: Optional[str] = None)[source]

Bases: object

Raw Kraken Exchange API adspter.

Variables

session (requests.Session) – requests session object (stores User-Agent)

api_domain = 'https://api.kraken.com'
load_key(path: Optional[os.PathLike] = None)[source]

Load private Kraken Exchange API key/secret.

Search order:

  1. path if file, then load directly,

  2. path is folder, append kraken.key and load,

  3. no path, try to load locally from kraken.key.

Raise NoPrivateKey, if

  • no key file could be found,

  • not both key/secret are found,

  • secret is no valid base64.

Key file format:

key=your-key
secret=your-secret

Whitespaces will be stripped from front/end and around the equal sign.

Parameters

path (Optional[PathLike], optional) – Path to kraken.key file, by default None

Raises

NoPrivateKey – If no key file could be found or key not valid (format).

nonce() → int[source]

Nonce for API request. Should be monotonic.

Returns timestamps seconds + milliseconds. Substracts seconds since 2021 (makes the nonce smaller).

Returns

int

_query_raw(path: str, data: Dict[str, Any], headers: Dict[str, Any], timeout: Optional[Tuple[int, float]] = None) → Dict[str, Any][source]
_sign(api_path: str, data: Dict[str, Any]) → str[source]

Create signature for private Kraken Exchange API request.

Parameters
  • api_path (str) – API path (prefix + method)

  • data (Dict[str, Any]) – API request data, must contain nonce

Returns

str – signature

Notes

See Kraken Exchange API Docs, Example algorithm, Example client.

query_public(method: str, **kwargs) → Dict[str, Any][source]
query_private(method: str, otp: Optional[str] = None, **kwargs) → Dict[str, Any][source]
krakenexapi.api.NONCE_OFFSET = -1609459200.0

Nonce value offset, nonce value will start from year 2021

krakenexapi.api.API_METHODS_PUBLIC = ['Time', 'SystemStatus', 'Assets', 'AssetPairs', 'Ticker', 'OHLC', 'Depth', 'Trades', 'Spread']

List of allowed public endpoints

krakenexapi.api.API_METHODS_PRIVATE = ['Balance', 'TradeBalance', 'TradeVolume', 'DepositMethods', 'DepositAddresses', 'DepositStatus', 'WithdrawInfo', 'Withdraw', 'WithdrawCancel', 'WithdrawStatus', 'WalletTransfer', 'OpenOrders', 'QueryOrders', 'OpenPositions', 'ClosedOrders', 'QueryOrders', 'QueryTrades', 'TradesHistory', 'AddOrder', 'CancelOrder', 'Ledgers', 'QueryLedgers', 'AddExport', 'RetrieveExport', 'ExportStatus', 'RemoveExport', 'GetWebSocketsToken']

List of allowed private endpoints

krakenexapi.api.API_METHODS_NO_RETRY = ['AddOrder', 'AddExport', 'Withdraw', 'WalletTransfer']

List of API methods where we do not want to retry. e. g. no repeated AddOrder because it might create duplicate orders.

Notes

The nonce() will use an offset of NONCE_OFFSET for its value - so, the nonce value is comparatively smaller compared to the standard unix timestamp. Try to avoid using the same API key for different applications!

Basic Kraken Exchange API methods

Wraps the endpoints in API_METHODS_PUBLIC and API_METHODS_PRIVATE with simplified parameters and corrected return values. It will try to call rate limit both public and, when provided a tier (verification level), private API endpoints to avoid possible blacklisting. The full description of methods, parameters and return values csn be found in the Official Kraken REST API.

class krakenexapi.api.BasicKrakenExAPI(key: Optional[str] = None, secret: Optional[str] = None, tier: Optional[str] = 'Starter')[source]

Bases: krakenexapi.api.BasicKrakenExAPIPublicMethods, krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, krakenexapi.api.BasicKrakenExAPIPrivateUserTradingMethods, krakenexapi.api.BasicKrakenExAPIPrivateUserFundingMethods, krakenexapi.api.BasicKrakenExAPIPrivateWebsocketMethods, krakenexapi.api.RawCallRateLimitedKrakenExAPI

Basic Kraken Exchange API, public + private endpoints.

Public Endpoints

class krakenexapi.api.BasicKrakenExAPIPublicMethods[source]

Public Kraken Exchange API endpoints.

Most methods have additional post-processing, like conversion of strings to float (easier computation), or wrapping into NamedTuples to allow better access.

Raw responses can be retrieved via _ + method name. Alternatively, the RawKrakenExAPI.query_public() can be used.

Notes

See official API documentation (public)

_get_server_time() → Dict[str, Any][source]
get_server_time() → datetime.datetime[source]
get_system_status()[source]
get_asset_info(asset: Optional[Union[str, List[str]]] = None) → Dict[str, Dict[str, Any]][source]
_get_asset_pairs(pair: Optional[Union[str, List[str]]] = None, info: Optional[str] = None) → Dict[str, Dict[str, Any]][source]
_get_asset_pairs_static_values() → Dict[str, Union[int, float, str]][source]
get_asset_pairs(pair: Optional[Union[str, List[str]]] = None, info: Optional[str] = None) → Dict[str, Dict[str, Any]][source]
_get_ticker_information(pair: Union[str, List[str]]) → Dict[str, Dict[str, Any]][source]
get_ticker_information(pair: Union[str, List[str]]) → Dict[str, Dict[str, Any]][source]
_get_ohlc_data(pair: str, interval: Optional[int] = None, since: Optional[int] = None) → Tuple[List[List[Any]], int][source]
get_ohlc_data(pair: str, interval: Optional[int] = None, since: Optional[int] = None) → Tuple[List[List[Any]], int][source]
_get_order_book(pair: str, count: Optional[int] = None) → Tuple[List, List][source]
get_order_book(pair: str, count: Optional[int] = None) → Tuple[List, List][source]
_get_recent_trades(pair: str, since: Optional[str] = None) → Tuple[List[List[Any]], int][source]
get_recent_trades(pair: str, since: Optional[str] = None) → Tuple[List[List[Any]], int][source]
_get_recent_spread_data(pair: str, since: Optional[int] = None) → Tuple[List[List[Any]], int][source]
get_recent_spread_data(pair: str, since: Optional[int] = None) → Tuple[List[List[Any]], int][source]

Private Endpoints

class krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods[source]

Private Kraken Exchange API user data endpoints.

Endpoints to retrieve:

  • orders (open/closed),

  • transactions,

  • ledger entries,

  • account/trade balance, volume (fee information)

Methods with _info suffix allow retrieval of information by IDs, others will return sliced subsets with a total/offset.

Notes

See official API documentation (user data)

get_account_balance() → Dict[str, float][source]
get_trade_balance(asset: Optional[str] = None) → Dict[str, float][source]
get_open_orders(trades: Optional[bool] = None, userref: Optional[str] = None) → Dict[str, Dict[str, Any]][source]
get_closed_orders(trades: Optional[bool] = None, userref: Optional[str] = None, start: Optional[Union[int, float, str]] = None, end: Optional[Union[int, float, str]] = None, offset: Optional[int] = None, closetime: Optional[str] = None) → Tuple[Dict[str, Dict[str, Any]], int][source]
get_orders_info(txid: Union[str, List[str]], trades: Optional[bool] = None, userref: Optional[str] = None) → Dict[str, Dict[str, Any]][source]
get_trades_history(type: Optional[str] = None, trades: Optional[bool] = None, start: Optional[Union[int, float, str]] = None, end: Optional[Union[int, float, str]] = None, offset: Optional[int] = None) → Tuple[Dict[str, Dict[str, Any]], int][source]
get_trades_info(txid: Union[str, List[str]], trades: Optional[bool] = None) → Dict[str, Dict[str, Any]][source]
get_open_positions(txid: Union[str, List[str]], docalcs: Optional[bool] = None, trades: Optional[bool] = None, consolidation: Optional[str] = None) → Dict[str, Dict[str, Any]][source]
get_ledgers(asset: Optional[Union[str, List[str]]] = None, type: Optional[str] = None, start: Optional[Union[int, float, str]] = None, end: Optional[Union[int, float, str]] = None, offset: Optional[int] = None) → Tuple[Dict[str, Dict[str, Any]], int][source]
get_ledgers_info(lid: Union[str, List[str]]) → Dict[str, Dict[str, Any]][source]
get_trade_volume(pair: Optional[Union[str, List[str]]] = None, fee_info: Optional[bool] = None) → Dict[str, Any][source]
class krakenexapi.api.BasicKrakenExAPIPrivateUserTradingMethods[source]

Private Kraken Exchange API user trading endpoints.

Notes

See official API documentation (user trading)

class krakenexapi.api.BasicKrakenExAPIPrivateUserFundingMethods[source]

Private Kraken Exchange API user funding endpoints.

Notes

See official API documentation (user funding)

class krakenexapi.api.BasicKrakenExAPIPrivateWebsocketMethods[source]

Private Kraken Exchange API websocket endpoint.

Notes

See official API documentation (websocket)

get_websocket_token() → str[source]

Utility functions

To ease the gathering of complete lists of orders/trades/ledger entries. The Kraken API will for some endpoints with possibly a large amount of entries split the response into chunks of 50 (or similar) and subsequent calls can use the ofs (offset parameter) and the returned total to gather all entries as needed. Note, that for some endpoints and argument choices the total will not be correct and the endpoint will return an empty dictionary instead. (which the functions below handle for you)

krakenexapi.api.gather_closed_orders(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, *args, **kwargs) → Dict[str, Any][source]

Gather a complete list of closed orders.

Wraps get_closed_orders() and iteratively queries next subsets until everything retrieved.

Parameters

api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private user data endpoints

Returns

Dict[str, Any] – same as get_closed_orders()

krakenexapi.api.gather_ledgers(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, *args, **kwargs) → Dict[str, Any][source]

Gather a complete list of ledger entries.

Wraps get_ledgers() and iteratively queries next subsets until everything retrieved.

Note, that get_ledgers() returns incorrect total if only parameterized with type, which will be handled here.

Parameters

api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private user data endpoints

Returns

Dict[str, Any] – same as get_ledgers()

krakenexapi.api.gather_trades(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, *args, **kwargs) → Dict[str, Any][source]

Gather a complete list of transactions (trades).

Wraps get_trades_history() and iteratively queries next subsets until everything retrieved.

Parameters

api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private user data endpoints

Returns

Dict[str, Any] – same as get_trades_history()

Call Rate Limiting

The Kraken Exchange used different quotas for its API methods, see the article What are the API rate limits?.

class krakenexapi.api._CallRateLimitInfo(limit: float = 1, cost: float = 1, decay: float = 1.0)[source]
decay()[source]
time_to_call(cost: float) → float[source]
can_call(cost: Optional[Union[int, float]] = None) → bool[source]
set_exceeded()[source]
check(cost: Optional[Union[int, float]] = None) → bool[source]
check_and_wait(cost: Optional[Union[int, float]] = None)[source]
class krakenexapi.api.KrakenExAPICallRateLimiter(tier: Optional[str] = None)[source]
_reset_account_crl()[source]
static _is_private(method: str)[source]
static _get_cost(method: str) → int[source]
check_call(method: str, wait: bool = True) → bool[source]
set_exceeded(method)[source]
class krakenexapi.api.RawCallRateLimitedKrakenExAPI(key: Optional[str] = None, secret: Optional[str] = None, tier: Optional[str] = 'Starter')[source]

Extend RawKrakenExAPI with call rate limiting and request retry mechanisms.

Parameters

tier (str, optional) – Kraken verification level, can be “Starter”, “Intermediate”, “Pro”, by default “Starter”

Variables

_num_retries (int) – Maximum number of retries, by default 3

_query_raw(path: str, data: Dict[str, Any], headers: Dict[str, Any], timeout: Optional[Tuple[int, float]] = None) → Dict[str, Any][source]
query_public(method: str, **kwargs) → Dict[str, Any][source]
query_private(method: str, otp: Optional[str] = None, **kwargs) → Dict[str, Any][source]

Exceptions

See krakenexapi.exceptions.