Contents¶
Overview¶
docs |
|
---|---|
tests |
|
package |
A Kraken Exchange API adapter.
Free software: MIT license
Installation¶
pip install krakenexapi
You can also install the in-development version with:
pip install https://github.com/Querela/python-krakenexapi/archive/master.zip
Documentation¶
Development¶
To run all the tests run:
tox
Note, to combine the coverage data from all the tox environments run:
Windows |
set PYTEST_ADDOPTS=--cov-append
tox
|
---|---|
Other |
PYTEST_ADDOPTS=--cov-append tox
|
Usage¶
To use KrakenExApi in a project:
import krakenexapi.api as kea
import krakenexapi.wallet as kew
api = kea.BasicKrakenExAPI(tier="Intermediate")
api.load_key()
kew.CurrencyPair.build_from_api(api)
wallet = kew.Wallet(api)
wallet._update()
Reference¶
krakenexapi¶
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 (storesUser-Agent
)
-
api_domain
= 'https://api.kraken.com'¶
-
load_key
(path: Optional[os.PathLike] = None)[source]¶ Load private Kraken Exchange API key/secret.
Search order:
path if file, then load directly,
path is folder, append
kraken.key
and load,no path, try to load locally from
kraken.key
.
Raise
NoPrivateKey
, ifno 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.
-
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 ofNONCE_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, theRawKrakenExAPI.query_public()
can be used.Notes
See official API documentation (public)
-
_get_asset_pairs
(pair: Optional[Union[str, List[str]]] = None, info: Optional[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_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]¶
-
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_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]¶
-
class
krakenexapi.api.
BasicKrakenExAPIPrivateUserTradingMethods
[source]¶ Private Kraken Exchange API user trading endpoints.
Notes
-
class
krakenexapi.api.
BasicKrakenExAPIPrivateUserFundingMethods
[source]¶ Private Kraken Exchange API user funding endpoints.
Notes
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 incorrecttotal
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]¶
-
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
Exceptions¶
krakenexapi.exceptions¶
-
exception
krakenexapi.exceptions.
APIRateLimitExceeded
[source]¶ Bases:
krakenexapi.exceptions.KrakenExAPIError
API Error:
EAPI:Rate limit exceeded
.
-
exception
krakenexapi.exceptions.
APIArgumentUsageError
[source]¶ Bases:
krakenexapi.exceptions.KrakenExAPIError
,ValueError
Error from Kraken API if arguments incorrectly supplied or used or values not supported.
API Error:
EGeneral:Invalid arguments
-
exception
krakenexapi.exceptions.
NoPrivateKey
[source]¶ Bases:
krakenexapi.exceptions.KrakenExAPIError
Thrown if trying to use a private Kraken Exchange API without a private key.
-
exception
krakenexapi.exceptions.
NoSuchAPIMethod
[source]¶ Bases:
krakenexapi.exceptions.KrakenExAPIError
Error thrown if trying to use an invalid API method.
-
exception
krakenexapi.exceptions.
APIPermissionDenied
[source]¶ Bases:
krakenexapi.exceptions.KrakenExAPIError
Error when trying to call API methods without given permission.
API Error:
EGeneral:Permission denied
-
exception
krakenexapi.exceptions.
APIInvalidNonce
[source]¶ Bases:
krakenexapi.exceptions.KrakenExAPIError
Error when trying to call API methods concurrently or out of order. Nonce will no be monotonic, so API throws error.
API Error:
EAPI:Invalid nonce
krakenexapi.wallet¶
Currency¶
They are intended to work as singletons, and therefore track of registered/created instances.
-
class
krakenexapi.wallet.
Currency
(symbol: str, name: str, decimals: int, display_decimals: int, letter: Optional[str] = None, description: Optional[str] = None)[source]¶ Immutable singleton currency info dataclass.
- Raises
AssertionError – If trying to create a new Currency singleton instance with an already registered symbol identifier.
-
symbol
: str¶ Currency symbol used by Kraken Exchange.
-
name
: str¶ Alternative currency symbol. (can be same as symbol, often without X/Z prefix)
-
decimals
: int¶ Number of decimals used in computation (precision).
-
display_decimals
: int¶ Number of decimals displayed to user.
-
letter
: Optional[str] = None¶ Optional. Currency symbol/glyph.
-
description
: Optional[str] = None¶ Optional. Short currency description/name.
-
property
is_fiat
¶ Returns
True
if currency is fiat,False
if crypto.- Returns
bool –
True
if fiat currency.
-
property
is_staked_onchain
¶ On-chain staked currency.
- Returns
bool
-
property
is_staked_offchain
¶ Off-chain staked currency.
- Returns
bool
-
property
is_staked
¶ Is a currency, staked on Kraken Exchange.
- Returns
bool
-
format_value
(value: float) → str[source]¶ Formats a given value according to the display_decimals of the currency.
If a currency symbol/letter exists, append it.
- Parameters
value (float) – The value to be formatted.
- Returns
str – Formatted string.
-
round_value
(value: float) → float[source]¶ Round a given value to the maximum number of digits as specified in decimals of the currency.
- Parameters
value (float) – Number to be rounded.
- Returns
float – Number rounded to decimals digits.
-
classmethod
find
(symbol: str) → krakenexapi.wallet.Currency[source]¶ Finds the singleton instance of the currency described by the symbol (Kraken Exchange identifier) string.
- Returns
krakenexapi.wallet.Currency – Currency singleton instance.
- Raises
KeyError – If no Currency exists for the symbol.
-
classmethod
all_symbols
(unique: bool = True) → Set[str][source]¶ Return a list of all instanciated Currency symbols.
This allows the retrieval of all Currency instances via
find()
(with/without) duplicates.- Parameters
unique (bool, optional) – Whethere the list of symbols allows for duplicate when used for retrieval, or not, by default True (no duplicates)
- Returns
Set[str] – Currency symbol names (used on Kraken Exchange)
-
classmethod
build_from_api
(api: krakenexapi.api.BasicKrakenExAPIPublicMethods)[source]¶ Uses the api to query a list of all currencies on Kraken Exchange and builds singleton instances for each of it.
- Parameters
api (BasicKrakenExAPIPublicMethods) – An API that allows to query public Kraken Exchange endpoints.
-
class
krakenexapi.wallet.
CurrencyPair
(symbol: str, altname: str, name: str, pair_decimals: int, base: krakenexapi.wallet.Currency, quote: krakenexapi.wallet.Currency, ordermin: Optional[float] = None)[source]¶ Immutable singleton currency trading pair info dataclass.
- Raises
AssertionError – If trying to create a new CurrencyPair singleton instance with an already registered symbol identifier.
-
symbol
: str¶ Trading pair symbol (used on Kraken Exchange)
-
altname
: str¶ Alternative name for trading pair.
-
name
: str¶ Visual name (human readable).
-
base
: krakenexapi.wallet.Currency¶ Base currency
-
quote
: krakenexapi.wallet.Currency¶ Quote currency, determines value/price for base currency.
-
ordermin
: Optional[float] = None¶ Minimum amount of base currency for a new order.
-
property
is_fiat2crypto
¶ Trading pair between crypto and fiat currency.
- Returns
bool
-
property
is_crypto2crypto
¶ Trading pair between two crypto currencies.
- Returns
bool
-
property
is_fiat2fiat
¶ Trading pair between two fiat currencies.
- Returns
bool
-
classmethod
find
(symbol: str) → krakenexapi.wallet.CurrencyPair[source]¶ Find the singleton CurrencyPair instance for the given symbol names. (as used on Kraken Exchange)
- Returns
krakenexapi.wallet.CurrencyPair – The CurrencyPair singleton instance.
- Raises
KeyError – If no CurrencyPair exists for the symbol.
-
classmethod
all_symbols
(unique: bool = True) → Set[str][source]¶ Return a list of symbol for all registered CurrencyPair instances.
- Parameters
unique (bool, optional) – Whether the list should contain all registered symbol and name, or just enough to allow retrieval of all singleton instances, by default True
- Returns
Set[str] – List of currency pair symbols. (used on Kraken Exchange)
-
classmethod
build_from_api
(api: krakenexapi.api.BasicKrakenExAPIPublicMethods)[source]¶ Build a list of CurrencyPair and optionally Currency singleton instances.
Uses the public Kraken Exchange API to retrieve a list of all available currency trading pairs and build instances for each of it.
- Parameters
api (BasicKrakenExAPIPublicMethods) – An API object that allows querying the public Kraken Exchange endpoints.
Transactions¶
-
class
krakenexapi.wallet.
TradingTransaction
(currency_pair: krakenexapi.wallet.CurrencyPair, price: float, amount: float, cost: float, fees: float, timestamp: datetime.datetime, txid: str, otxid: Optional[Union[float, str]] = None)[source]¶ A trading transaction.
Subclasses should be used to mark buy / sell type.
-
currency_pair
: krakenexapi.wallet.CurrencyPair¶ Currency pair, of base and quote currency. quote currency determines the price. base is the currency being traded.
-
price
: float¶ Price of (crypto) currency.
-
amount
: float¶ Amount of currency.
-
cost
: float¶ Cost of base currency (
currency_pair
) in quote currency.
-
fees
: float¶ Fees for transactions, in quote currency.
-
timestamp
: datetime.datetime¶ Timestamp of transaction.
-
txid
: str¶ Transaction ID.
-
otxid
: Optional[Union[float, str]] = None¶ Optional. Order ID associated with transaction.
-
property
base_currency
¶ Base currency being traded.
- Returns
Currency
-
property
quote_currency
¶ Quote currency. Determines the price and value of the base_currency currency.
- Returns
Currency
-
-
class
krakenexapi.wallet.
CryptoBuyTransaction
(currency_pair: krakenexapi.wallet.CurrencyPair, price: float, amount: float, cost: float, fees: float, timestamp: datetime.datetime, txid: str, otxid: Optional[Union[float, str]] = None)[source]¶ Bases:
krakenexapi.wallet.TradingTransaction
Crypto currency buy transaction.
-
class
krakenexapi.wallet.
CryptoSellTransaction
(currency_pair: krakenexapi.wallet.CurrencyPair, price: float, amount: float, cost: float, fees: float, timestamp: datetime.datetime, txid: str, otxid: Optional[Union[float, str]] = None)[source]¶ Bases:
krakenexapi.wallet.TradingTransaction
Crypto currency sell transaction.
-
class
krakenexapi.wallet.
FundingTransaction
(currency: krakenexapi.wallet.Currency, amount: float, timestamp: datetime.datetime, fees: float = 0.0, lxid: Optional[Union[int, float, str]] = None)[source]¶ A funding transaction.
Subclasses show whether it is a
deposit
orwithdrawal
.-
currency
: krakenexapi.wallet.Currency¶ Currency.
-
amount
: float¶ Amount of currency in transaction.
-
timestamp
: datetime.datetime¶ Timestamp of transaction.
-
fees
: float = 0.0¶ Fees for transaction.
-
lxid
: Optional[Union[int, float, str]] = None¶ Ledger ID. (more exact than timestamp if used in API queries)
-
-
class
krakenexapi.wallet.
DepositTransaction
(currency: krakenexapi.wallet.Currency, amount: float, timestamp: datetime.datetime, fees: float = 0.0, lxid: Optional[Union[int, float, str]] = None)[source]¶ Bases:
krakenexapi.wallet.FundingTransaction
Deposit transaction of (fiat) currency to Kraken Exchange.
-
class
krakenexapi.wallet.
WithdrawalTransaction
(currency: krakenexapi.wallet.Currency, amount: float, timestamp: datetime.datetime, fees: float = 0.0, lxid: Optional[Union[int, float, str]] = None)[source]¶ Bases:
krakenexapi.wallet.FundingTransaction
Withdrawal transaction from the Kraken Exchange.
Assets and Wallet¶
-
class
krakenexapi.wallet.
Asset
(currency: krakenexapi.wallet.Currency, api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, quote_currency: Optional[krakenexapi.wallet.Currency] = None)[source]¶ Wrapper around a Currency and api for easy asset win/loss computation.
-
property
has_transactions
¶ Return
True
if thecurrency
has transactions.- Returns
bool –
True
if transactions exist.
-
property
currency
¶ The asset currency.
- Returns
Currency
-
property
amount
¶ Amount of
currency
the user has on Kraken Exchange since the last update.- Returns
float – Amount of currency.
-
property
amount_buy
¶ Total amount of
currency
being bought.Retrieved from API via transactions.
- Returns
float – total amount of currency bought.
-
property
amount_sell
¶ Total amount of
currency
being sold.Retrieved from API via transactions.
- Returns
float – total amount of currency sold.
-
property
amount_by_transactions
¶ Total of bought (
amount_buy
) and sold (amount_sell
) amount.- Returns
float – Amount of currency just by buy/sell transactions.
Notes
\[amount = amount_{buy} - amount_{sell}\]
-
property
price_buy_avg
¶ Average price of all buy transactions.
- Returns
float – average buy price
Notes
Price calculation
\[price_{buy} = \frac{\sum cost_{buy}}{\sum amount_{buy}}\]
-
property
price_sell_avg
¶ Average price of all sell transactions.
- Returns
float – average sell price
See also
-
property
price_avg
¶ Average price based on
cost
by transaction and currentamount
.- Returns
float – average price
-
price_for_noloss
(fees_sell: float = 0.26) → float[source]¶ Minimum price that should be used for sell if no loss should be incurred. Prices larger than the noloss price will be wins.
- Parameters
fees_sell (float, optional) – Kraken Exchange sell fees, by default 0.26 (maximum for market orders)
- Returns
float – noloss price (based on quote currency)
Note
Current computation may not be completely correct but should be rather close. Please verify manually! (e.g. adjust price ±5%)
\[price_{no loss} = price_{avg} * \frac{1 + fees_{total}}{1 - fees_{sell}}\]with \(fees_{total}\) being all fees incurred through transactions
See also
-
property
cost_buy
¶ Sum of costs of buy transactions, based on quote currency.
- Returns
float – total costs of buy transactions (without fees)
-
property
cost_sell
¶ Sum of costs of sell transactions, based on quote currency.
- Returns
float – total costs of sell transactions (without fees)
-
property
cost
¶ Total costs computed by
cost_buy
andcost_sell
.So, only costs computed by transactions. Negative costs means that costs of buy is higher than sell, positive costs means the opposite. (Positive costs would mean a win based on transactions alone.)
- Returns
float – Difference of costs for buy and sell
Notes
\[cost = - cost_{buy} + cost_{sell}\]
-
property
fees_buy
¶ Fees incurred by buy transactions.
- Returns
float – total sum of fees
-
property
fees_sell
¶ Fees incurred by sell transactions.
- Returns
float – total sum of fees
-
property
fees
¶ Total sum of fees for both buy and sell transactions.
- Returns
float – total sum of fees
See also
-
property
fees_percentage
¶ Percentage of fees compared to costs, of transactions.
- Returns
float – fee percentage, see Kraken Exchange fees
Notes
\[fees_{\%} = 100 * \frac{fees}{cost_{buy} + cost_{sell}}\]
-
property
is_loss
¶ Loss based on transactions. Loss if costs for buy higher than sell.
- Returns
bool –
True
if loss (i.e. higher costs for buy)
-
property
-
class
krakenexapi.wallet.
Fund
(currency: krakenexapi.wallet.Currency, api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods)[source]¶ Wrapper around fiat Currency info and computations.
-
property
has_transactions
¶ Return
True
if thecurrency
has ledger entries for deposit and withdrawal.- Returns
bool –
True
if transactions exist.
-
property
currency
¶ The fund fiat currency.
- Returns
Currency
-
property
amount
¶ Amount of
currency
the user has on Kraken Exchange since the last update.- Returns
float – Amount of currency.
-
property
amount_deposit
¶ Total amount of
currency
being deposited.Retrieved from API via ledger entries.
- Returns
float – total amount of currency deposited.
-
property
amount_withdrawal
¶ Total amount of
currency
being withdrawn.Retrieved from API via ledger entries.
- Returns
float – total amount of currency withdrawn.
-
property
amount_by_transactions
¶ Total of deposited (
amount_deposit
) and withdrawn (amount_withdrawal
) amount.- Returns
float – Amount of currency just by deposit/withdrawal transactions.
Notes
\[amount = amount_{deposit} - amount_{withdrawal}\]
-
property
fees_deposit
¶ Fees incurred by deposit transactions (ledgers).
- Returns
float – total sum of fees
-
property
fees_withdrawal
¶ Fees incurred by withdrawal transactions (ledgers).
- Returns
float – total sum of fees
-
property
fees
¶ Total sum of fees for both deposit and withdrawal transactions.
- Returns
float – total sum of fees
See also
-
property
fees_percentage
¶ Percentage of fees compared to amount of fiat currency.
- Returns
float – fee percentage
Notes
\[fees_{\%} = 100 * \frac{fees}{amount_{deposit} + amount_{withdrawal}}\]
-
property
-
class
krakenexapi.wallet.
Wallet
(api: krakenexapi.api.BasicKrakenExAPI)[source]¶ -
-
_update_assets
()[source]¶ Update internal dictionary of
Asset
.If no assets exist, create an initial dictionary of assets.
Check if new transactions found, then update all assets. If _last_txid is not
None
then query a subset of trading transactions to reduce traffic/calls.
-
_update_funds
()[source]¶ Update internal dictionary of
Fund
.If no assets exist, create an initial dictionary of funds.
Check if new funding transactions found, then update all funds. If _last_lxid is not
None
then query a subset of funding transactions to reduce traffic/calls.
-
static
get_all_account_currencies
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods) → List[krakenexapi.wallet.Currency][source]¶ Retrieve a full list of currencies used on Kraken Exchange by the user.
Current balance might not even show currency because sold, withdrawn or staked etc.
Will look for currencies by trading transactions,
then will look at deposit/withdrawals ledger entries,
WIP then staking/transfering ledger entries,
Currencies listed in current account balance.
- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API object that allows querying private endpoints
- Returns
List[Currency] – List of all Currencies used by trader.
-
static
get_account_crypto_currencies
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods) → List[krakenexapi.wallet.Currency][source]¶ Return a list of crypto currencies used by the trader.
- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private Kraken Exchange endpoints.
- Returns
List[Currency] – List of crypto currencies
-
static
get_account_fiat_currencies
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods) → List[krakenexapi.wallet.Currency][source]¶ Return a list of fiat currencies used by the trader.
- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private Kraken Exchange endpoints.
- Returns
List[Currency] – List of fiat currencies
-
static
build_assets_from_api
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, fiat_currency: Optional[krakenexapi.wallet.Currency] = None) → List[krakenexapi.wallet.Asset][source]¶ Build a list of
Asset
from the list of crypto currencies of the trader.Optionally set a quote currency for computations.
- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private Kraken Exchange endpoints.
fiat_currency (Optional[Currency], optional) – Fiat currency for asset value computations, by default None
- Returns
List[Asset] – List of crypto currency assets.
-
static
build_funds_from_api
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods)[source]¶ Build a list of
Fund
from the list of fiat currencies of the trader.- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance with access to private Kraken Exchange endpoints.
- Returns
List[Fund] – List of fiat currency funds.
-
static
build_funding_transactions
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, start: Optional[Union[int, float, str]] = None, sort: bool = True) → List[krakenexapi.wallet.FundingTransaction][source]¶ Build a list of funding transactions based on ledger entries.
- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance to query private Kraken Exchange endpoints
start (Optional[Union[int, float, str]], optional) – Start timestamp or ledger LXID, by default None
sort (bool, optional) – Whether to sort transactions by timestamp ascending, by default True
- Returns
List[FundingTransaction] – List of funding transactions
- Raises
RuntimeError – On unknown funding (deposit/withdrawal) transaction type.
-
static
build_trading_transactions
(api: krakenexapi.api.BasicKrakenExAPIPrivateUserDataMethods, start: Optional[Union[int, float, str]] = None, sort: bool = True) → List[krakenexapi.wallet.TradingTransaction][source]¶ Build a list of trading transactions.
- Parameters
api (BasicKrakenExAPIPrivateUserDataMethods) – An API instance to query private Kraken Exchange endpoints.
start (Optional[Union[int, float, str]], optional) – Start unix timestamp or transaction TXID, by default None
sort (bool, optional) – Whether to sort transactions by timestamp ascending, by default True
- Returns
List[TradingTransaction] – List of trading transactions
- Raises
RuntimeError – On unknown transaction type.
-
Contributing¶
Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
Bug reports¶
When reporting a bug please include:
Your operating system name and version.
Any details about your local setup that might be helpful in troubleshooting.
Detailed steps to reproduce the bug.
Documentation improvements¶
KrakenExApi could always use more documentation, whether as part of the official KrakenExApi docs, in docstrings, or even on the web in blog posts, articles, and such.
Feature requests and feedback¶
The best way to send feedback is to file an issue at https://github.com/Querela/python-krakenexapi/issues.
If you are proposing a feature:
Explain in detail how it would work.
Keep the scope as narrow as possible, to make it easier to implement.
Remember that this is a volunteer-driven project, and that code contributions are welcome :)
Development¶
To set up python-krakenexapi for local development:
Fork python-krakenexapi (look for the “Fork” button).
Clone your fork locally:
git clone git@github.com:YOURGITHUBNAME/python-krakenexapi.git
Create a branch for local development:
git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
When you’re done making changes run all the checks and docs builder with tox one command:
tox
Commit your changes and push your branch to GitHub:
git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature
Submit a pull request through the GitHub website.
License¶
Any contribution that you make to this repository will be under the MIT license.
Developer Certificate of Origin¶
Contributors must sign-off each commit by adding a Signed-off-by: … line to commit messages to certify that they have the right to submit the code they are contributing to the project according to the Developer Certificate of Origin (DCO).
Pull Request Guidelines¶
If you need some code review or feedback while you’re developing the code just make the pull request.
For merging, you should:
Include passing tests (run
tox
) 1.Update documentation when there’s new API, functionality etc.
Add a note to
CHANGELOG.rst
about the changes.Add yourself to
AUTHORS.rst
.
- 1
If you don’t have all the necessary python versions available locally you can rely on Travis - it will run the tests for each change you add in the pull request.
It will be slower though …
Tips¶
To run a subset of tests:
tox -e envname -- pytest -k test_myfeature
To run all the test environments in parallel:
tox -p auto
Authors¶
Erik Körner - ekdev@live.de
MIT License¶
Copyright (c) 2020, Erik Körner
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Changelog¶
WIP¶
Add tests (raw query, public + private API).
Add tooling for docs, checks.
Add meta info dataclasses…
Fix many minor issues, badges, docs, workflows/tests.
Add wrappers around transactions, handling, statistics etc.
Rename private user data ledgers endpoints!
Extract exceptions into own module.
Start with websocket API.
Add live-api tests (markers, github workflow).
Call rate limiting - retry with backoff.
Add Funds (same as Assets) to
wallet.py
.Rewrite
wallet.py
, group functions, addWallet
.
0.0.1 (2020-12-27)¶
Add raw kraken Exchange API.
Add basic Kraken Exchange API - public methods.
Add custom exceptions.
Add basic response classes for better accessing of entries, fix stringified floats.
Add call rate limiting (crl).
Add tests for crl, more in work.
Add private user data API endpoints.
Add basic documentation.
First official pre-release.
0.0.0 (2020-12-25)¶
First release on PyPI.