Getting Started

A complete interface to the Kraken API provided by Krakipy.

Usage example:

from krakipy import KrakenAPI

kr = KrakenAPI()
data = kr.get_trade_volume("ZEUR")

KrakenAPI

class krakipy.KrakenAPI(key='', secret_key='', use_2fa=None, use_tor=False, tor_refresh=5, retry=0.5, limit=20)[source]

The KrakenAPI object stores the authentification information

__init__(key='', secret_key='', use_2fa=None, use_tor=False, tor_refresh=5, retry=0.5, limit=20)[source]

Creates an object that can hold the authentification information. The keys are only needed to perform private queries

Parameters:
  • key (str) – The key to the Kraken API (optional)
  • secret_key (str) – The secret key to the Kraken API (optional)
  • use_2fa (None or dict) –

    Is used to pass the desired two factor authentification (optional)

    • None = no two factor authentification (default)
    • {“static password”: your_static_2fa_password} = two factor authentification using a static password method. Example: use_2fa={“static password”: “/&59s^wqUU=baQ~W”}
    • {“2FA App”: your_2fa_app_setup_key} = two factor authentification using the Google Authenticator App method. Example: use_2fa={“2FA App”: “E452ZYHEX22AXGKIFUGQVPXF”}
  • use_tor (bool) –

    Weither or not to use the tor network for requests (optional)

    • False = use normal requests using the clearnet (default)
    • True = use tor requests using the darknet
  • tor_refresh (int) – Amount of requests per session before the IP is changed (optional) default = 5
  • retry (float) – Amount of time between retries in sec (optional)
  • limit (int) – The maximum amount of retries (optional)

Error Details

These are some of the Exceptions that can occur:

KeyNotSetError

class krakipy.KeyNotSetError[source]

This Error indicates that you tried to do a private request but did not set the Kraken API Keys.

KrakenAPIError

class krakipy.KrakenAPIError[source]

This Error indicates that in the response to your query had an error message when it was recieved.

CallRateLimitError

class krakipy.CallRateLimitError[source]

This Error indicates that you sent to many requests in the last 20s.

Note

Mind the API rate limits of Kraken.com

Public Market Data

Get Server Time

KrakenAPI.get_server_time()[source]

Public Market Data

Returns The time of the Kraken API server.

Returns:Rfc1123 and unixtime
Return type:(str, int)

Example: KrakenAPI.get_server_time() -> (“Sun, 6 Dec 20 14:12:39 +0000”, 1607263959)

Get System Status

KrakenAPI.get_system_status()[source]

Public Market Data

Returns the current system status or trading mode and a timestamp.

Returns:The system status and timestamp
Return type:(str, str)

Example: KrakenAPI.get_system_status() -> (“online”, “2020-12-06T13:59:55Z”)

Note

Possible status values include:

  • “online” (operational, full trading available)
  • “cancel_only” (existing orders are cancelable, but new orders cannot be created)
  • “post_only” (existing orders are cancelable, and only new post limit orders can be submitted)
  • “maintenance” (system is offline for maintenance)

Get Asset Info

KrakenAPI.get_asset_info(asset=None, aclass=None)[source]

Public Market Data

Get information about the assets that are available for deposit, withdrawal, trading and staking.

Parameters:
  • asset (str) – Comma delimited list of assets to get info on (optional) - default = “all”
  • aclass (str) – Asset class (optional) - default = “currency”
Returns:

DataFrame of asset names and their info

Return type:

pandas.DataFrame

Get Tradable Asset Pairs

KrakenAPI.get_tradable_asset_pairs(pair=None, info=None)[source]

Public Market Data

Parameters:
  • info (str) –

    The info to retrieve (optional)

    • info = all info (default)
    • leverage = leverage info
    • fees = fees schedule
    • margin = margin info
  • pair (str) – Comma delimited list of asset pairs to get info on (optional) - default = “all”
Returns:

DataFrame of pair names and their info

Return type:

pandas.DataFrame

Get Ticker Information

KrakenAPI.get_ticker_information(pair)[source]

Public Market Data

Parameters:pair (str) – Comma delimited list of asset pairs to get info on
Returns:DataFrame of pair names and their ticker info
Return type:pandas.DataFrame

Note

Today”s prices start at midnight UTC

Get OHLC Data

KrakenAPI.get_ohlc_data(pair, interval=1, since=None)[source]

Public Market Data

Parameters:
  • pair (str) – Asset pair to get OHLC data for
  • interval (int) –

    The time frame interval in minutes (optional):

    • 1 (default) = 1 minute
    • 5 = 5 minutes
    • 15 = 15 minutes
    • 30 = 30 minutes
    • 60 = 1 hour
    • 240 = 4 hours
    • 1440 = 1 day
    • 10080 = 1 week
    • 21600 = 15 days
  • since (int) – Return committed OHLC data since given id (optional. exclusive)
Returns:

DataFrame of pair name and OHLC data

Return type:

pandas.DataFrame

Note

The last entry in the OHLC array is for the current, not-yet-committed frame and will always be present, regardless of the value of since.

Get Order Book

KrakenAPI.get_order_book(pair, count=100)[source]

Public Market Data

Parameters:
  • pair (str) – Asset pair to get market depth for
  • count (int) – Maximum number of asks/bids (optional) - default = 100, Range: [1..500]
Returns:

Ask and bid DataFrame of pair name and market depth

Return type:

(pandas.DataFrame, pandas.DataFrame)

Get Recent Trades

KrakenAPI.get_recent_trades(pair, since=None)[source]

Public Market Data

Returns the last 1000 trades by default

Parameters:
  • pair (str) – Asset pair to get trade data for
  • since (int) – Return trade data since given id (optional. exclusive)
Returns:

DataFrame of pair name and recent trade data and id to be used as since when polling for new trade data.

Return type:

(pandas.DataFrame, int)

Get Recent Spreads

KrakenAPI.get_recent_spreads(pair, since=None)[source]

Public Market Data

Parameters:
  • pair (str) – Asset pair to get spread data for
  • since (int) – Return trade data since given id (optional. exclusive)
Returns:

DataFrame of pair name and recent spread data and id to be used as since when polling for new spread data

Return type:

(pandas.DataFrame, int)

Private User Data

Get Account Balance

KrakenAPI.get_account_balance()[source]

Private User Data

Retrieve all cash balances, net of pending withdrawals.

Returns:DataFrame of asset names and balance amount
Return type:pandas.DataFrame

Get Trade Balance

KrakenAPI.get_trade_balance(asset='ZEUR')[source]

Private User Data

Retrieve a summary of collateral balances, margin position valuations, equity and margin level.

Parameters:asset (str) – Base asset used to determine balance - default = “ZEUR”
Returns:DataFrame of trade balance info
Return type:pandas.DataFrame

Get Open Orders

KrakenAPI.get_open_orders(trades=False, userref=None)[source]

Private User Data

Retrieve information about currently open orders.

Parameters:
  • trades (bool) – Whether or not to include trades in output (optional) - default = False
  • userref (str) – Restrict results to given user reference id (optional)
Returns:

DataFrame of open order info with txid as the index

Return type:

pandas.DataFrame

Get Closed Orders

KrakenAPI.get_closed_orders(trades=False, userref=None, start=None, end=None, ofs=None, closetime=None)[source]

Private User Data

Retrieve information about orders that have been closed (filled or cancelled). 50 results are returned at a time, the most recent by default.

Parameters:
  • trades (bool) – Whether or not to include trades in output (optional) - default = False
  • userref (str) – Restrict results to given user reference id (optional)
  • start (int or str) – Starting unix timestamp or order tx id of results (optional. exclusive)
  • end – Ending unix timestamp or order tx id of results (optional. inclusive)
  • ofs (int) – The result offset
  • closetime (str) –

    Which time to use (optional):

    • open
    • close
    • both (default)
Returns:

DataFrame of of order info and amount of available order info matching criteria

Return type:

(pandas.DataFrame, int)

Query Orders Info

KrakenAPI.query_orders_info(txid, trades=False, userref=None)[source]

Private User Data

Retrieve information about specific orders.

Parameters:
  • trades (bool) – Whether or not to include trades in output (optional) - default = False
  • userref (str) – Restrict results to given user reference id (optional)
  • txid (str) – Comma delimited list of transaction ids to query info about (50 maximum)
Returns:

DataFrame of associative orders info

Return type:

pandas.DataFrame

Get Trades History

KrakenAPI.get_trades_history(trade_type='all', trades=False, start=None, end=None, ofs=None)[source]

Private User Data

Retrieve information about trades/fills. 50 results are returned at a time, the most recent by default.

Parameters:
  • trade_type (str) –

    type of trade (optional):

    • all = all types (default)
    • any position = any position (open or closed)
    • closed position = positions that have been closed
    • closing position = any trade closing all or part of a position
    • no position = non-positional trades
  • trades (bool) – Whether or not to include trades related to position in output (optional) - default = False
  • start (int or str) – Starting unix timestamp or order tx id of results (optional. exclusive)
  • end – Ending unix timestamp or order tx id of results (optional. inclusive)
  • ofs (int) – Result offset for pagination
Returns:

DataFrame of trade info and the amount of available trades info matching criteria

Return type:

(pandas.DataFrame, int)

Query Trades Info

KrakenAPI.query_trades_info(txid, trades=False)[source]

Private User Data

Retrieve information about specific trades/fills.

Parameters:
  • txid (str) – Comma delimited list of transaction ids to query info about (20 maximum)
  • trades (bool) – Whether or not to include trades related to position in output (optional) - default = False
Returns:

DataFrame of associative trades info

Return type:

pandas.DataFrame

Get Open Positions

KrakenAPI.get_open_positions(txid=None, docalcs=False, consolidation=None)[source]

Private User Data

Parameters:
  • txid (str) – Comma delimited list of transaction ids to restrict output to
  • docalcs (bool) – Whether or not to include profit/loss calculations (optional) - default = False
  • consolidation (str) – What to consolidate the positions data around (optional) - “market” = will consolidate positions based on market pair
Returns:

A DataFrame of open position info

Return type:

pandas.DataFrame

Note

Using the consolidation optional field will result in consolidated view of the data being returned.

Get Ledgers Info

KrakenAPI.get_ledgers_info(asset=None, aclass=None, selection_type='all', start=None, end=None, ofs=None)[source]

Private User Data

Retrieve information about ledger entries. 50 results are returned at a time, the most recent by default.

Parameters:
  • asset (str) – Comma delimited list of assets to restrict output to (optional) - default = “all”
  • aclass (str) – Asset class (optional) - default = “currency”
  • selection_type (str) –

    Type of trade (optional):

    • all (default)
    • deposit
    • withdrawal
    • trade
    • margin
  • start (int or str) – Starting unix timestamp or order tx id of results (optional. exclusive)
  • end – Ending unix timestamp or order tx id of results (optional. inclusive)
  • ofs (int) – Result offset for pagination
Returns:

DataFrame of associative ledgers info

Return type:

pandas.DataFrame

Query Ledgers

KrakenAPI.query_ledgers(id, trades=False)[source]

Private User Data

Retrieve information about specific ledger entries.

Parameters:
  • id (str) – Comma delimited list of ledger ids to query info about (20 maximum)
  • trades (bool (optional.) - default = False) – Whether or not to include trades related to position in output
Returns:

DataFrame of associative ledgers info

Return type:

pandas.DataFrame

Get Trade Volume

KrakenAPI.get_trade_volume(pair)[source]

Private User Data

Parameters:pair (str) – Comma delimited list of asset pairs to get fee info on (optional)
Returns:The volume currency, current discount volume, DataFrame of fees and DataFrame of maker fees
Return type:(str, float, pandas.DataFrame, pandas.DataFrame)

..note:

If an asset pair is on a maker/taker fee schedule, the taker side is given in fees and maker side in fees_maker. For pairs not on maker/taker, they will only be given in fees.

Request Export Report

KrakenAPI.request_export_report(description, report, data_format='CSV', fields=None, asset=None, starttm=None, endtm=None)[source]

Private User Data

Request export of trades or ledgers.

Parameters:
  • description (str) – Report description info
  • report (str) –

    Report type

    • trades
    • ledgers
  • data_format (str) –

    The data format

    • CSV (default)
    • TSV
  • fields (str) –

    Comma delimited list of fields to include in report (optional). default = “all”

    trades:

    • ordertxid
    • time
    • ordertype
    • price
    • cost
    • fee
    • vol
    • margin
    • misc
    • ledgers

    ledgers:

    • refid
    • time
    • type
    • aclass
    • asset
    • amount
    • fee
    • vbalance
  • asset (str) – Comma delimited list of assets to get info on (optional) - default = “all”
  • starttm (int) – Report start unixtime (optional). default = one year before now
  • endtm (int) – Report end unixtime (optional). default = now
Returns:

Report id

Return type:

str

Note

Field options are based on report type.

Get Export Report Status

KrakenAPI.get_export_report_status(report)[source]

Private User Data

Parameters:report (str) –

Report type:

  • trades
  • ledgers
Returns:DataFrame of reports and their info
Return type:pandas.DataFrame

Retrieve Export Report

KrakenAPI.retrieve_export_report(report_id, return_raw=False, dir=None)[source]

Private User Data

Parameters:
  • report_id (str) – Report id
  • return_raw (bool) – Weither or not the report is returned as raw binary (optional) - default = False
  • dir (str) – If given a directory the report will be saved there as a zipfile
Returns:

None or the binary of the compressed report.zip file

Return type:

None or raw binary

Delete Export Report

KrakenAPI.delete_export_report(report_id, remove_type)[source]

Private User Data

Parameters:
  • report_id (str) – Report id
  • remove_type (str) –

    Removal type

    • cancel
    • delete
Returns:

Returns remove type

Return type:

dict

Note

The delete remove type can only be used for a report that has already been processed. Use cancel for queued and processing statuses.

Private User Trading

Add Standard Order

KrakenAPI.add_standard_order(pair, type, ordertype, volume, price=None, price2=None, leverage=None, oflags=None, starttm=0, expiretm=0, userref=None, validate=True, close_ordertype=None, close_price=None, close_price2=None, trading_agreement='agree')[source]

Private User Trading

Parameters:
  • pair (str) – Asset pair
  • type (str) –

    Type of order

    • buy
    • sell
  • ordertype (str) –

    Order type:

    • market
    • limit (price = limit price)
    • stop-loss (price = stop loss price)
    • take-profit (price = take profit price)
    • stop-loss-profit (price = stop loss price, price2 = take profit price)
    • stop-loss-profit-limit (price = stop loss price, price2 = take profit price)
    • stop-loss-limit (price = stop loss trigger price, price2 = triggered limit price)
    • take-profit-limit (price = take profit trigger price, price2 = triggered limit price)
    • trailing-stop (price = trailing stop offset)
    • trailing-stop-limit (price = trailing stop offset, price2 = triggered limit offset)
    • stop-loss-and-limit (price = stop loss price, price2 = limit price)
    • settle-position
  • volume (float) – Order volume in lots
  • price (float or str) – Price (optional. dependent upon ordertype)
  • price2 (float or str) – Secondary price (optional. dependent upon ordertype)
  • leverage (int) – Amount of leverage desired (optional. default = none)
  • oflags (str) –

    Comma delimited list of order flags (optional):

    • viqc = volume in quote currency (not available for leveraged orders)
    • fcib = prefer fee in base currency
    • fciq = prefer fee in quote currency
    • nompp = no market price protection
    • post = post only order (available when ordertype = limit)
  • starttm (int) –

    Scheduled start time (optional):

    • 0 = now (default)
    • +<n> = schedule start time <n> seconds from now
    • <n> = unix timestamp of start time
  • expiretm (int) –

    Expiration time (optional):

    • 0 = no expiration (default)
    • +<n> = expire <n> seconds from now
    • <n> = unix timestamp of expiration time
  • userref (str) – User reference id. 32-bit signed number. (optional)
  • validate (bool) – Validate inputs only. do not submit order (optional)
  • close_ordertype (str) –

    Optional closing order to add to system when order gets filled: order type

    • limit
    • stop-loss
    • take-profit
    • stop-loss-limit
    • take-profit-limit
  • close_price (float or int) – Price
  • close_price2 (float or int) – Secondary price
Returns:

Dictionary of order description info

Return type:

dict

Note

  • See Get tradable asset pairs for specifications on asset pair prices, lots, and leverage.
  • Prices can be preceded by +, -, or # to signify the price as a relative amount (with the exception of trailing stops, which are always relative). + adds the amount to the current offered price. - subtracts the amount from the current offered price. # will either add or subtract the amount to the current offered price, depending on the type and order type used. Relative prices can be suffixed with a % to signify the relative amount as a percentage of the offered price.
  • For orders using leverage, 0 can be used for the volume to auto-fill the volume needed to close out your position.
  • If you receive the error “EOrder:Trading agreement required”, refer to your API key management page for further details.
  • Volume can be specified as 0 for closing margin orders to automatically fill the requisite quantity.

Cancel Order

KrakenAPI.cancel_order(txid)[source]

Private User Trading

Cancel a particular open order (or set of open orders) by txid

Parameters:txid (str) – Transaction id
Returns:Number of orders canceled and weither order(s) is/are pending cancellation
Return type:(int, bool)

Cancel All Orders

KrakenAPI.cancel_all_orders()[source]

Private User Trading

Cancel all open orders

Returns:Number of orders canceled
Return type:int

Cancel All Orders After X

KrakenAPI.cancel_all_orders_after(timeout)[source]

Private User Trading

This method provides a “Dead Man”s Switch” mechanism to protect the client from network malfunction, extreme latency or unexpected matching engine downtime. The client can send a request with a timeout (in seconds), that will start a countdown timer which will cancel all client orders when the timer expires. The client has to keep sending new requests to push back the trigger time, or deactivate the mechanism by specifying a timeout of 0. If the timer expires, all orders are cancelled and then the timer remains disabled until the client provides a new (non-zero) timeout. The recommended use is to make a call every 15 to 30 seconds, providing a timeout of 60 seconds. This allows the client to keep the orders in place in case of a brief disconnection or transient delay, while keeping them safe in case of a network breakdown. It is also recommended to disable the timer ahead of regularly scheduled trading engine maintenance (if the timer is enabled, all orders will be cancelled when the trading engine comes back from downtime - planned or otherwise).

Parameters:timeout (int) – Duration (in seconds) to set/extend the timer by
Returns:The timestamp when the request was recieved, The timestamp after which all orders will be cancelled, unless the timer is extended or disabled
Return type:str, str

Example Return: KrakenAPI.cancel_all_orders_after(60) -> (“2021-03-24T17:41:56Z”, “2021-03-24T17:42:56Z”)

Private User Funding

Get Deposit Methods

KrakenAPI.get_deposit_methods(asset)[source]

Private User Funding

Retrieve methods available for depositing a particular asset.

Parameters:asset (str) – Asset being deposited
Returns:DataFrame of deposit methods
Return type:pandas.DataFrame

Get Deposit Addresses

KrakenAPI.get_deposit_addresses(asset, method, new=False)[source]

Private User Funding

Retrieve (or generate a new) deposit addresses for a particular asset and method.

Parameters:
  • asset (str) – Asset being deposited
  • method (str) – Name of the deopsit method
  • new (bool) – Whether or not to generate a new address (optional.) - default = False
Returns:

DataFrame of associative deposit addresses

Return type:

pandas.DataFrame

Get Status Of Recent Deposits

KrakenAPI.get_deposit_status(asset, method=None)[source]

Private User Funding

Retrieve information about recent deposits made.

Parameters:
  • asset (str) – Asset being deposited
  • method (str) – Name of the deopsit method (optional)
Returns:

DataFrame of deposit status information

Return type:

pandas.DataFrame

Get Withdrawal Information

KrakenAPI.get_withdrawal_info(asset, key, amount)[source]

Private User Funding

Retrieve fee information about potential withdrawals for a particular asset, key and amount.

Parameters:
  • asset (str) – Asset being withdrawn
  • key (str) – Withdrawal key name, as set up on your account
  • amount (float) – Amount to withdraw
Returns:

DataFrame of associative withdrawal info

Return type:

pandas.DataFrame

Withdraw Funds

KrakenAPI.withdraw_funds(asset, key, amount)[source]

Private User Funding

Parameters:
  • asset (str) – Asset being withdrawn
  • key (str) – Withdrawal key name, as set up on your account
  • amount (float) – Amount to withdraw
Returns:

Reference id

Return type:

str

Get Status Of Recent Withdrawals

KrakenAPI.get_withdrawal_status(asset, method=None)[source]

Private User Funding

Retrieve information about recently requests withdrawals.

Parameters:
  • asset (str) – Asset being withdrawn
  • method (str) – Name of the withdrawal method (optional)
Returns:

DataFrame of withdrawal status information

Return type:

pandas.DataFrame

Request Withdrawal Cancelation

KrakenAPI.request_withdrawal_cancel(asset, refid)[source]

Private User Funding

Cancel a recently requested withdrawal, if it has not already been successfully processed.

Parameters:
  • asset (str) – Asset being withdrawn
  • refid (str) – Withdrawal reference id
Returns:

True on success

Return type:

bool

Note

Cancelation cannot be guaranteed. This will put in a cancelation request. Depending upon how far along the withdrawal process is, it may not be possible to cancel the withdrawal.

Wallet Transfer

KrakenAPI.wallet_transfer_to_futures(asset, amount)[source]

Private User Funding

Transfer from Kraken spot wallet to Kraken Futures holding wallet. Note that a transfer in the other direction must be requested via the Kraken Futures API endpoint.

Parameters:
  • asset (str) – Asset being withdrawn
  • amount (float) – Amount to withdraw
Returns:

Reference id

Return type:

str

Private User Staking

Stake Asset

KrakenAPI.stake_asset(asset, amount, method)[source]

Private User Staking

Stake an asset from your spot wallet. This operation requires an API key with Withdraw funds permission.

Parameters:
  • asset (str) – Asset to stake
  • amount (float) – Amount of the asset to stake
  • method (str) – Name of the staking option to use (refer to KrakenAPI.get_stakeable_assets for the correct method names for each asset)
Returns:

Reference ID of the Staking Transaction

Return type:

str

Unstake Asset

KrakenAPI.unstake_asset(asset, amount)[source]

Private User Staking

Unstake an asset from your spot wallet. This operation requires an API key with Withdraw funds permission.

Parameters:
  • asset (str) – Asset to unstake (asset ID or altname). Must be a valid staking asset (e.g. XBT.M, XTZ.S, ADA.S)
  • amount (float) – Amount of the asset to unstake
Returns:

Reference ID of the Unstaking Transaction

Return type:

str

Get Stakeable Assets

KrakenAPI.get_stakeable_assets()[source]

Private User Staking

Returns the list of assets that the user is able to stake. This operation requires an API key with both Withdraw funds and Query funds permission.

Returns:DataFrame of stakeable assets
Return type:pandas.DataFrame

Get Pending Staking Transactions

KrakenAPI.get_pending_staking_transactions()[source]

Private User Staking

Returns the list of pending staking transactions. Once resolved, these transactions will appear on the List of Staking Transactions endpoint. This operation requires an API key with both Query funds and Withdraw funds permissions.

Returns:DataFrame of pending staking transactions
Return type:pandas.DataFrame

Get Staking Transactions

KrakenAPI.get_staking_transactions()[source]

Private User Staking

Returns the list of all staking transactions. This endpoint can only return up to 1000 of the most recent transactions. This operation requires an API key with Query funds permissions.

Returns:DataFrame of all staking transactions
Return type:pandas.DataFrame

Extras

Add datetime

krakipy.add_dtime(df)[source]

Extra

Adds a new column “dtime” (datetime) from the column “time” (unixtime)

Parameters:df (pandas.DataFrame) – A DataFrame with a column “time” in unixtime-format
Returns:df with a “dtime” column added
Return type:pandas.DataFrame

Datetime to unixtime

krakipy.datetime_to_unixtime(dt)[source]

Extra

Converts from datetime to unixtime

Parameters:dt (datetime.datetime) – datetime object
Returns:the unixtime of dt
Return type:int

Unixtime to datetime

krakipy.unixtime_to_datetime(ux)[source]

Extra

Converts from unixtime to datetime

Parameters:ux (int) – unixtime timestamp
Returns:the datetime of ux
Return type:datetime.datetime