python-kraken-sdk


Namepython-kraken-sdk JSON
Version 2.2.0 PyPI version JSON
download
home_page
SummaryCollection of REST and websocket clients to interact with the Kraken cryptocurrency exchange.
upload_time2024-03-10 14:41:02
maintainer
docs_urlNone
author
requires_python>=3.11
licenseCopyright 2023 Benjamin Thomas Schwertfeger Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
keywords crypto trading kraken exchange api
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <h1 align="center">Futures, Spot and NFT - REST and Websocket API Python SDK for the Kraken Cryptocurrency Exchange 🐙</h1>

<div align="center">

[![GitHub](https://badgen.net/badge/icon/github?icon=github&label)](https://github.com/btschwertfeger/python-kraken-sdk)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Generic badge](https://img.shields.io/badge/python-3.11+-blue.svg)](https://shields.io/)
[![Downloads](https://static.pepy.tech/personalized-badge/python-kraken-sdk?period=total&units=abbreviation&left_color=grey&right_color=orange&left_text=downloads)](https://pepy.tech/project/python-kraken-sdk)

[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Typing](https://img.shields.io/badge/typing-mypy-informational)](https://mypy-lang.org/)
[![CI/CD](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml/badge.svg?branch=master)](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml)
[![codecov](https://codecov.io/gh/btschwertfeger/python-kraken-sdk/branch/master/badge.svg)](https://app.codecov.io/gh/btschwertfeger/python-kraken-sdk)

![release](https://shields.io/github/release-date/btschwertfeger/python-kraken-sdk)
[![release](https://img.shields.io/pypi/v/python-kraken-sdk)](https://pypi.org/project/python-kraken-sdk/)
[![DOI](https://zenodo.org/badge/510751854.svg)](https://zenodo.org/badge/latestdoi/510751854)
[![Documentation Status stable](https://readthedocs.org/projects/python-kraken-sdk/badge/?version=stable)](https://python-kraken-sdk.readthedocs.io/en/stable)

</div>

> ⚠️ This is an unofficial collection of REST and websocket clients for Spot and
> Futures trading on the Kraken cryptocurrency exchange using Python. Payward
> Ltd. and Kraken are in no way associated with the authors of this package and
> documentation.
>
> Please note that this project is independent and not endorsed by Kraken or
> Payward Ltd. Users should be aware that they are using third-party software,
> and the authors of this project are not responsible for any issues, losses, or
> risks associated with its usage.

## 📌 Disclaimer

There is no guarantee that this software will work flawlessly at this or later
times. Of course, no responsibility is taken for possible profits or losses.
This software probably has some errors in it, so use it at your own risk. Also
no one should be motivated or tempted to invest assets in speculative forms of
investment. By using this software you release the author(s) from any liability
regarding the use of this software.

---

## Features

Available Clients:

- NFT REST Clients
- Spot REST Clients
- Spot Websocket Clients (Websocket API v1 and v2)
- Spot Orderbook Clients (Websocket API v1 and v2)
- Futures REST Clients
- Futures Websocket Client

General:

- access both public and private, REST and websocket endpoints
- responsive error handling and custom exceptions
- extensive example scripts (see `/examples` and `/tests`)
- tested using the [pytest](https://docs.pytest.org/en/7.3.x/) framework
- releases are permanently archived at [Zenodo](https://zenodo.org/badge/latestdoi/510751854)
- releases before v2.0.0 also support Python 3.7+

Documentation:

- [https://python-kraken-sdk.readthedocs.io/en/stable](https://python-kraken-sdk.readthedocs.io/en/stable)
- [https://python-kraken-sdk.readthedocs.io/en/latest](https://python-kraken-sdk.readthedocs.io/en/latest)

---

## ❗️ Attention

**ONLY** tagged releases are available at PyPI. So the content of the master may
not match with the content of the latest release. - Please have a look at the
release specific READMEs and changelogs.

It is also recommended to _pin the used version_ to avoid unexpected behavior on
new releases.

---

## Table of Contents

- [ Installation and setup ](#installation)
- [ Spot Clients ](#spotusage)
  - [REST API](#spotrest)
  - [Websocket API V2](#spotws)
- [ Futures Clients ](#futuresusage)
  - [REST API](#futuresrest)
  - [Websocket API](#futuresws)
- [ NFT Clients ](#nftusage)
- [ Troubleshooting ](#trouble)
- [ Contributions ](#contribution)
- [ Notes ](#notes)
- [ References ](#references)

---

<a name="installation"></a>

# 🛠 Installation and setup

### 1. Install the package into the desired environment

```bash
python3 -m pip install python-kraken-sdk
```

### 2. Register at [Kraken](https://www.kraken.com) and generate API keys

- Spot Trading: https://www.kraken.com/u/security/api
- Futures Trading: https://futures.kraken.com/trade/settings/api (see _[help](https://docs.futures.kraken.com/#introduction-generate-api-keys)_)
- Futures Sandbox: https://demo-futures.kraken.com/settings/api

### 3. Start using the provided example scripts

### 4. Error handling

If any unexpected behavior occurs, please check <b style="color: yellow">your
API permissions</b>, <b style="color: yellow">rate limits</b>, update the
python-kraken-sdk, see the [Troubleshooting](#trouble) section, and if the error
persists please open an issue.

---

<a name="spotusage"></a>

# 📍 Spot Clients

A template for Spot trading using both websocket and REST clients can be found
in `examples/spot_trading_bot_template_v2.py`.

For those who need a realtime order book - a script that demonstrates how to
maintain a valid order book using the Orderbook client can be found in
`examples/spot_orderbook_v2.py`.

<a name="spotrest"></a>

## Spot REST API

The Kraken Spot REST API offers many endpoints for almost every use-case. The
python-kraken-sdk aims to provide all of them - split in User, Market, Trade,
Funding and Staking (Earn) related clients.

The following code block demonstrates how to use some of them. More examples
can be found in `examples/spot_examples.py`.

```python
from kraken.spot import Earn, User, Market, Trade, Funding

def main():
    key = "kraken-public-key"
    secret = "kraken-secret-key"

    # ____USER________________________
    user = User(key=key, secret=secret)
    print(user.get_account_balance())
    print(user.get_open_orders())
    # …

    # ____MARKET____
    market = Market()
    print(market.get_ticker(pair="BTCUSD"))
    # …

    # ____TRADE_________________________
    trade = Trade(key=key, secret=secret)
    print(trade.create_order(
         ordertype="limit",
         side="buy",
         volume=1,
         pair="BTC/EUR",
         price=20000
    ))
    # …

    # ____FUNDING___________________________
    funding = Funding(key=key, secret=secret)
    print(
        funding.withdraw_funds(
            asset="DOT", key="MyPolkadotWallet", amount=200
        )
    )
    print(funding.cancel_withdraw(asset="DOT", refid="<some id>"))
    # …

    # ____EARN________________________
    earn = Earn(key=key, secret=secret)
    print(earn.list_earn_strategies(asset="DOT"))
    # …

if __name__ == "__main__":
    main()
```

<a name="spotws"></a>

## Spot Websocket API V2

Kraken offers two versions of their websocket API (V1 and V2). Since V2 is
offers more possibilities, is way faster and easier to use, only those examples
are shown below. For using the websocket API V1 please have a look into the
`examples/spot_ws_examples_v1.py`.

The documentation for both API versions can be found here:

- https://docs.kraken.com/websockets
- https://docs.kraken.com/websockets-v2

Note that authenticated Spot websocket clients can also un-/subscribe from/to
public feeds.

The example below can be found in an extended way in
`examples/spot_ws_examples_v2.py`.

```python
import asyncio
from kraken.spot import KrakenSpotWSClientV2

async def main():
    key = "spot-api-key"
    secret = "spot-secret-key"

    class Client(KrakenSpotWSClientV2):
        """Can be used to create a custom trading strategy"""

        async def on_message(self, message):
            """Receives the websocket messages"""
            if message.get("method") == "pong" \
                or message.get("channel") == "heartbeat":
                return

            print(message)
            # here we can access lots of methods, for example to create an order:
            # if self.is_auth:  # only if the client is authenticated …
            #     await self.send_message(
            #         message={
            #             "method": "add_order",
            #             "params": {
            #                 "limit_price": 1234.56,
            #                 "order_type": "limit",
            #                 "order_userref": 123456789,
            #                 "order_qty": 1.0,
            #                 "side": "buy",
            #                 "symbol": "BTC/USD",
            #                 "validate": True,
            #             },
            #         }
            #     )
            # … it is also possible to call regular REST endpoints
            # but using the websocket messages is more efficient.
            # You can also un-/subscribe here using self.subscribe/self.unsubscribe.

    # Public/unauthenticated websocket client
    client = Client()  # only use this one if you don't need private feeds

    await client.subscribe(
        params={"channel": "ticker", "symbol": ["BTC/USD", "DOT/USD"]}
    )
    await client.subscribe(
        params={"channel": "book", "depth": 25, "symbol": ["BTC/USD"]}
    )
    # wait because unsubscribing is faster than unsubscribing … (just for that example)
    await asyncio.sleep(3)
    # print(client.active_public_subscriptions) # to list active subscriptions
    await client.unsubscribe(
        params={"channel": "ticker", "symbol": ["BTC/USD", "DOT/USD"]}
    )
    # …

    # Per default, the authenticated client starts two websocket connections,
    # one for authenticated and one for public messages. If there is no need
    # for a public connection, it can be disabled using the ``no_public``
    # parameter.
    client_auth = Client(key=key, secret=secret, no_public=True)
    await client_auth.subscribe(params={"channel": "executions"})

    while not client.exception_occur and not client_auth.exception_occur:
        await asyncio.sleep(6)
    return


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
        # The websocket client will send {'event': 'asyncio.CancelledError'}
        # via on_message so you can handle the behavior/next actions
        # individually within your strategy.
```

---

<a name="futuresusage"></a>

# 📍 Futures Clients

Kraken provides a sandbox environment at https://demo-futures.kraken.com for
Futures paper trading. When using these API keys you have to set the `sandbox`
parameter to `True` when instantiating the respective client.

A template for Futures trading using both websocket and REST clients can be
found in `examples/futures_trading_bot_template.py`.

The Kraken Futures API documentation can be found here:

- https://docs.futures.kraken.com
- https://support.kraken.com/hc/en-us/sections/360012894412-Futures-API

<a name="futuresrest"></a>

## Futures REST API

As the Spot API, Kraken also offers a REST API for Futures. Examples on how to
use the python-kraken-sdk for Futures are shown in
`examples/futures_examples.py` and listed in a shorter ways below.

```python
from kraken.futures import Market, User, Trade, Funding

def main():

    key = "futures-api-key"
    secret = "futures-secret-key"

    # ____USER________________________
    user = User(key=key, secret=secret) # optional: sandbox=True
    print(user.get_wallets())
    print(user.get_open_orders())
    print(user.get_open_positions())
    print(user.get_subaccounts())
    # …

    # ____MARKET____
    market = Market()
    print(market.get_ohlc(tick_type="trade", symbol="PI_XBTUSD", resolution="5m"))

    priv_market = Market(key=key, secret=secret)
    print(priv_market.get_fee_schedules_vol())
    print(priv_market.get_execution_events())
    # …

    # ____TRADE_________________________
    trade = Trade(key=key, secret=secret)
    print(trade.get_fills())
    print(trade.create_batch_order(
        batchorder_list = [{
            "order": "send",
            "order_tag": "1",
            "orderType": "lmt",
            "symbol": "PI_XBTUSD",
            "side": "buy",
            "size": 1,
            "limitPrice": 12000,
            "cliOrdId": "some-client-id"
        }, {
            "order": "send",
            "order_tag": "2",
            "orderType": "stp",
            "symbol": "PI_XBTUSD",
            "side": "buy",
            "size": 1,
            "limitPrice": 10000,
            "stopPrice": 11000,
        }, {
            "order": "cancel",
            "order_id": "e35dsdfsdfsddd-8a30-4d5f-a574-b5593esdf0",
        }, {
            "order": "cancel",
            "cliOrdId": "another-client-id",
        }],
    ))
    print(trade.cancel_all_orders())
    print(
        trade.create_order(
            orderType="lmt",
            side="buy",
            size=1,
            limitPrice=4,
            symbol="pf_bchusd"
        )
    )
    # …

    # ____FUNDING___________________________
    funding = Funding(key=key, secret=secret)
    # …

if __name__ == "__main__":
    main()
```

<a name="futuresws"></a>

## Futures Websocket API

Not only REST, also the websocket API for Kraken Futures is available. Examples
are shown below and demonstrated in `examples/futures_ws_examples.py`.

- https://docs.futures.kraken.com/#websocket-api

Note: Authenticated Futures websocket clients can also un-/subscribe from/to
public feeds.

```python
import asyncio
from kraken.futures import KrakenFuturesWSClient

async def main():

    key = "futures-api-key"
    secret = "futures-secret-key"

    class Client(KrakenFuturesWSClient):

        async def on_message(self, event):
            print(event)

    # Public/unauthenticated websocket connection
    client = Client()

    products = ["PI_XBTUSD", "PF_ETHUSD"]

    # subscribe to a public websocket feed
    await client.subscribe(feed="ticker", products=products)
    # await client.subscribe(feed="book", products=products)
    # …

    # unsubscribe from a public websocket feed
    # await client.unsubscribe(feed="ticker", products=products)

    # Private/authenticated websocket connection (+public)
    client_auth = Client(key=key, secret=secret)
    # print(client_auth.get_available_private_subscription_feeds())

    # subscribe to a private/authenticated websocket feed
    await client_auth.subscribe(feed="fills")
    await client_auth.subscribe(feed="open_positions")
    await client_auth.subscribe(feed="open_orders")
    # …

    # unsubscribe from a private/authenticated websocket feed
    await client_auth.unsubscribe(feed="fills")

    while True:
        await asyncio.sleep(6)

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        # do some exception handling …
        pass
```

---

<a name="nftusage"></a>

# 📍 NFT REST Clients

The Kraken NFT REST API offers endpoints for accessing the market and trade API
provided by Kraken. To access the private (trade) endpoints, you have to provide
API keys - same as for the Spot REST API.

The following code excerpt demonstrates the usage. Please have a look into
`tests/nft/*.py` for more examples.

```python
from kraken.nft import  Market, Trade

def main():
    key = "kraken-public-key"
    secret = "kraken-secret-key"

    market = Market()
    print(market.get_nft(nft_id="NT4GUCU-SIJE2-YSQQG2", currency="USD"))

    trade = Trade(key=key, secret=secret)
    print(trade.create_auction(
        auction_currency="ETH",
        nft_id=["NT4EFBO-OWGI5-QLO7AG"],
        auction_type="fixed",
        auction_params={
            "allow_offers": True,
            "ask_price": 100000,
        },
    ))

if __name__ == "__main__":
    main()
```

---

<a name="contribution"></a>

# 🆕 Contributions

… are welcome - but:

- First check if there is an existing issue or PR that addresses your
  problem/solution. If not - create one first - before creating a PR.
- Typo fixes, project configuration, CI, documentation or style/formatting PRs
  will be rejected. Please create an issue for that.
- PRs must provide a reasonable, easy to understand and maintain solution for an
  existing problem. You may want to propose a solution when creating the issue
  to discuss the approach before creating a PR.
- Please have a look at [CONTRIBUTION.md](./CONTRIBUTING.md).

---

<a name="trouble"></a>

# 🚨 Troubleshooting

- Check if you downloaded and installed the **latest version** of the
  python-kraken-sdk.
- Check the **permissions of your API keys** and the required permissions on the
  respective endpoints.
- If you get some Cloudflare or **rate limit errors**, please check your Kraken
  Tier level and maybe apply for a higher rank if required.
- **Use different API keys for different algorithms**, because the nonce
  calculation is based on timestamps and a sent nonce must always be the highest
  nonce ever sent of that API key. Having multiple algorithms using the same
  keys will result in invalid nonce errors.

---

<a name="notes"></a>

# 📝 Notes

The versioning scheme follows the pattern `v<Major>.<Minor>.<Patch>`. Here's what each part signifies:

- **Major**: This denotes significant changes that may introduce new features or
  modify existing ones. It's possible for these changes to be breaking, meaning
  backward compatibility is not guaranteed. To avoid unexpected behavior, it's
  advisable to specify at least the major version when pinning dependencies.
- **Minor**: This level indicates additions of new features or extensions to
  existing ones. Typically, these changes do not break existing implementations.
- **Patch**: Here, you'll find bug fixes, documentation updates, and changes
  related to continuous integration (CI). These updates are intended to enhance
  stability and reliability without altering existing functionality.

Coding standards are not always followed to make arguments and function names as
similar as possible to those of the Kraken API documentations.

<a name="references"></a>

# 🔭 References

- https://python-kraken-sdk.readthedocs.io/en/stable
- https://docs.kraken.com/rest
- https://docs.kraken.com/websockets
- https://docs.kraken.com/websockets-v2
- https://docs.futures.kraken.com
- https://support.kraken.com/hc/en-us/sections/360012894412-Futures-API

---

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "python-kraken-sdk",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": "Benjamin Thomas Schwertfeger <contact@b-schwertfeger.de>",
    "keywords": "crypto,trading,kraken,exchange,api",
    "author": "",
    "author_email": "Benjamin Thomas Schwertfeger <contact@b-schwertfeger.de>",
    "download_url": "https://files.pythonhosted.org/packages/bc/25/478fbcb772a1fb546e924003bfa9bf924880553a4e183c16ebba9923b886/python-kraken-sdk-2.2.0.tar.gz",
    "platform": null,
    "description": "<h1 align=\"center\">Futures, Spot and NFT - REST and Websocket API Python SDK for the Kraken Cryptocurrency Exchange \ud83d\udc19</h1>\n\n<div align=\"center\">\n\n[![GitHub](https://badgen.net/badge/icon/github?icon=github&label)](https://github.com/btschwertfeger/python-kraken-sdk)\n[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n[![Generic badge](https://img.shields.io/badge/python-3.11+-blue.svg)](https://shields.io/)\n[![Downloads](https://static.pepy.tech/personalized-badge/python-kraken-sdk?period=total&units=abbreviation&left_color=grey&right_color=orange&left_text=downloads)](https://pepy.tech/project/python-kraken-sdk)\n\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![Typing](https://img.shields.io/badge/typing-mypy-informational)](https://mypy-lang.org/)\n[![CI/CD](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml/badge.svg?branch=master)](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml)\n[![codecov](https://codecov.io/gh/btschwertfeger/python-kraken-sdk/branch/master/badge.svg)](https://app.codecov.io/gh/btschwertfeger/python-kraken-sdk)\n\n![release](https://shields.io/github/release-date/btschwertfeger/python-kraken-sdk)\n[![release](https://img.shields.io/pypi/v/python-kraken-sdk)](https://pypi.org/project/python-kraken-sdk/)\n[![DOI](https://zenodo.org/badge/510751854.svg)](https://zenodo.org/badge/latestdoi/510751854)\n[![Documentation Status stable](https://readthedocs.org/projects/python-kraken-sdk/badge/?version=stable)](https://python-kraken-sdk.readthedocs.io/en/stable)\n\n</div>\n\n> \u26a0\ufe0f This is an unofficial collection of REST and websocket clients for Spot and\n> Futures trading on the Kraken cryptocurrency exchange using Python. Payward\n> Ltd. and Kraken are in no way associated with the authors of this package and\n> documentation.\n>\n> Please note that this project is independent and not endorsed by Kraken or\n> Payward Ltd. Users should be aware that they are using third-party software,\n> and the authors of this project are not responsible for any issues, losses, or\n> risks associated with its usage.\n\n## \ud83d\udccc Disclaimer\n\nThere is no guarantee that this software will work flawlessly at this or later\ntimes. Of course, no responsibility is taken for possible profits or losses.\nThis software probably has some errors in it, so use it at your own risk. Also\nno one should be motivated or tempted to invest assets in speculative forms of\ninvestment. By using this software you release the author(s) from any liability\nregarding the use of this software.\n\n---\n\n## Features\n\nAvailable Clients:\n\n- NFT REST Clients\n- Spot REST Clients\n- Spot Websocket Clients (Websocket API v1 and v2)\n- Spot Orderbook Clients (Websocket API v1 and v2)\n- Futures REST Clients\n- Futures Websocket Client\n\nGeneral:\n\n- access both public and private, REST and websocket endpoints\n- responsive error handling and custom exceptions\n- extensive example scripts (see `/examples` and `/tests`)\n- tested using the [pytest](https://docs.pytest.org/en/7.3.x/) framework\n- releases are permanently archived at [Zenodo](https://zenodo.org/badge/latestdoi/510751854)\n- releases before v2.0.0 also support Python 3.7+\n\nDocumentation:\n\n- [https://python-kraken-sdk.readthedocs.io/en/stable](https://python-kraken-sdk.readthedocs.io/en/stable)\n- [https://python-kraken-sdk.readthedocs.io/en/latest](https://python-kraken-sdk.readthedocs.io/en/latest)\n\n---\n\n## \u2757\ufe0f Attention\n\n**ONLY** tagged releases are available at PyPI. So the content of the master may\nnot match with the content of the latest release. - Please have a look at the\nrelease specific READMEs and changelogs.\n\nIt is also recommended to _pin the used version_ to avoid unexpected behavior on\nnew releases.\n\n---\n\n## Table of Contents\n\n- [ Installation and setup ](#installation)\n- [ Spot Clients ](#spotusage)\n  - [REST API](#spotrest)\n  - [Websocket API V2](#spotws)\n- [ Futures Clients ](#futuresusage)\n  - [REST API](#futuresrest)\n  - [Websocket API](#futuresws)\n- [ NFT Clients ](#nftusage)\n- [ Troubleshooting ](#trouble)\n- [ Contributions ](#contribution)\n- [ Notes ](#notes)\n- [ References ](#references)\n\n---\n\n<a name=\"installation\"></a>\n\n# \ud83d\udee0 Installation and setup\n\n### 1. Install the package into the desired environment\n\n```bash\npython3 -m pip install python-kraken-sdk\n```\n\n### 2. Register at [Kraken](https://www.kraken.com) and generate API keys\n\n- Spot Trading: https://www.kraken.com/u/security/api\n- Futures Trading: https://futures.kraken.com/trade/settings/api (see _[help](https://docs.futures.kraken.com/#introduction-generate-api-keys)_)\n- Futures Sandbox: https://demo-futures.kraken.com/settings/api\n\n### 3. Start using the provided example scripts\n\n### 4. Error handling\n\nIf any unexpected behavior occurs, please check <b style=\"color: yellow\">your\nAPI permissions</b>, <b style=\"color: yellow\">rate limits</b>, update the\npython-kraken-sdk, see the [Troubleshooting](#trouble) section, and if the error\npersists please open an issue.\n\n---\n\n<a name=\"spotusage\"></a>\n\n# \ud83d\udccd Spot Clients\n\nA template for Spot trading using both websocket and REST clients can be found\nin `examples/spot_trading_bot_template_v2.py`.\n\nFor those who need a realtime order book - a script that demonstrates how to\nmaintain a valid order book using the Orderbook client can be found in\n`examples/spot_orderbook_v2.py`.\n\n<a name=\"spotrest\"></a>\n\n## Spot REST API\n\nThe Kraken Spot REST API offers many endpoints for almost every use-case. The\npython-kraken-sdk aims to provide all of them - split in User, Market, Trade,\nFunding and Staking (Earn) related clients.\n\nThe following code block demonstrates how to use some of them. More examples\ncan be found in `examples/spot_examples.py`.\n\n```python\nfrom kraken.spot import Earn, User, Market, Trade, Funding\n\ndef main():\n    key = \"kraken-public-key\"\n    secret = \"kraken-secret-key\"\n\n    # ____USER________________________\n    user = User(key=key, secret=secret)\n    print(user.get_account_balance())\n    print(user.get_open_orders())\n    # \u2026\n\n    # ____MARKET____\n    market = Market()\n    print(market.get_ticker(pair=\"BTCUSD\"))\n    # \u2026\n\n    # ____TRADE_________________________\n    trade = Trade(key=key, secret=secret)\n    print(trade.create_order(\n         ordertype=\"limit\",\n         side=\"buy\",\n         volume=1,\n         pair=\"BTC/EUR\",\n         price=20000\n    ))\n    # \u2026\n\n    # ____FUNDING___________________________\n    funding = Funding(key=key, secret=secret)\n    print(\n        funding.withdraw_funds(\n            asset=\"DOT\", key=\"MyPolkadotWallet\", amount=200\n        )\n    )\n    print(funding.cancel_withdraw(asset=\"DOT\", refid=\"<some id>\"))\n    # \u2026\n\n    # ____EARN________________________\n    earn = Earn(key=key, secret=secret)\n    print(earn.list_earn_strategies(asset=\"DOT\"))\n    # \u2026\n\nif __name__ == \"__main__\":\n    main()\n```\n\n<a name=\"spotws\"></a>\n\n## Spot Websocket API V2\n\nKraken offers two versions of their websocket API (V1 and V2). Since V2 is\noffers more possibilities, is way faster and easier to use, only those examples\nare shown below. For using the websocket API V1 please have a look into the\n`examples/spot_ws_examples_v1.py`.\n\nThe documentation for both API versions can be found here:\n\n- https://docs.kraken.com/websockets\n- https://docs.kraken.com/websockets-v2\n\nNote that authenticated Spot websocket clients can also un-/subscribe from/to\npublic feeds.\n\nThe example below can be found in an extended way in\n`examples/spot_ws_examples_v2.py`.\n\n```python\nimport asyncio\nfrom kraken.spot import KrakenSpotWSClientV2\n\nasync def main():\n    key = \"spot-api-key\"\n    secret = \"spot-secret-key\"\n\n    class Client(KrakenSpotWSClientV2):\n        \"\"\"Can be used to create a custom trading strategy\"\"\"\n\n        async def on_message(self, message):\n            \"\"\"Receives the websocket messages\"\"\"\n            if message.get(\"method\") == \"pong\" \\\n                or message.get(\"channel\") == \"heartbeat\":\n                return\n\n            print(message)\n            # here we can access lots of methods, for example to create an order:\n            # if self.is_auth:  # only if the client is authenticated \u2026\n            #     await self.send_message(\n            #         message={\n            #             \"method\": \"add_order\",\n            #             \"params\": {\n            #                 \"limit_price\": 1234.56,\n            #                 \"order_type\": \"limit\",\n            #                 \"order_userref\": 123456789,\n            #                 \"order_qty\": 1.0,\n            #                 \"side\": \"buy\",\n            #                 \"symbol\": \"BTC/USD\",\n            #                 \"validate\": True,\n            #             },\n            #         }\n            #     )\n            # \u2026 it is also possible to call regular REST endpoints\n            # but using the websocket messages is more efficient.\n            # You can also un-/subscribe here using self.subscribe/self.unsubscribe.\n\n    # Public/unauthenticated websocket client\n    client = Client()  # only use this one if you don't need private feeds\n\n    await client.subscribe(\n        params={\"channel\": \"ticker\", \"symbol\": [\"BTC/USD\", \"DOT/USD\"]}\n    )\n    await client.subscribe(\n        params={\"channel\": \"book\", \"depth\": 25, \"symbol\": [\"BTC/USD\"]}\n    )\n    # wait because unsubscribing is faster than unsubscribing \u2026 (just for that example)\n    await asyncio.sleep(3)\n    # print(client.active_public_subscriptions) # to list active subscriptions\n    await client.unsubscribe(\n        params={\"channel\": \"ticker\", \"symbol\": [\"BTC/USD\", \"DOT/USD\"]}\n    )\n    # \u2026\n\n    # Per default, the authenticated client starts two websocket connections,\n    # one for authenticated and one for public messages. If there is no need\n    # for a public connection, it can be disabled using the ``no_public``\n    # parameter.\n    client_auth = Client(key=key, secret=secret, no_public=True)\n    await client_auth.subscribe(params={\"channel\": \"executions\"})\n\n    while not client.exception_occur and not client_auth.exception_occur:\n        await asyncio.sleep(6)\n    return\n\n\nif __name__ == \"__main__\":\n    try:\n        asyncio.run(main())\n    except KeyboardInterrupt:\n        pass\n        # The websocket client will send {'event': 'asyncio.CancelledError'}\n        # via on_message so you can handle the behavior/next actions\n        # individually within your strategy.\n```\n\n---\n\n<a name=\"futuresusage\"></a>\n\n# \ud83d\udccd Futures Clients\n\nKraken provides a sandbox environment at https://demo-futures.kraken.com for\nFutures paper trading. When using these API keys you have to set the `sandbox`\nparameter to `True` when instantiating the respective client.\n\nA template for Futures trading using both websocket and REST clients can be\nfound in `examples/futures_trading_bot_template.py`.\n\nThe Kraken Futures API documentation can be found here:\n\n- https://docs.futures.kraken.com\n- https://support.kraken.com/hc/en-us/sections/360012894412-Futures-API\n\n<a name=\"futuresrest\"></a>\n\n## Futures REST API\n\nAs the Spot API, Kraken also offers a REST API for Futures. Examples on how to\nuse the python-kraken-sdk for Futures are shown in\n`examples/futures_examples.py` and listed in a shorter ways below.\n\n```python\nfrom kraken.futures import Market, User, Trade, Funding\n\ndef main():\n\n    key = \"futures-api-key\"\n    secret = \"futures-secret-key\"\n\n    # ____USER________________________\n    user = User(key=key, secret=secret) # optional: sandbox=True\n    print(user.get_wallets())\n    print(user.get_open_orders())\n    print(user.get_open_positions())\n    print(user.get_subaccounts())\n    # \u2026\n\n    # ____MARKET____\n    market = Market()\n    print(market.get_ohlc(tick_type=\"trade\", symbol=\"PI_XBTUSD\", resolution=\"5m\"))\n\n    priv_market = Market(key=key, secret=secret)\n    print(priv_market.get_fee_schedules_vol())\n    print(priv_market.get_execution_events())\n    # \u2026\n\n    # ____TRADE_________________________\n    trade = Trade(key=key, secret=secret)\n    print(trade.get_fills())\n    print(trade.create_batch_order(\n        batchorder_list = [{\n            \"order\": \"send\",\n            \"order_tag\": \"1\",\n            \"orderType\": \"lmt\",\n            \"symbol\": \"PI_XBTUSD\",\n            \"side\": \"buy\",\n            \"size\": 1,\n            \"limitPrice\": 12000,\n            \"cliOrdId\": \"some-client-id\"\n        }, {\n            \"order\": \"send\",\n            \"order_tag\": \"2\",\n            \"orderType\": \"stp\",\n            \"symbol\": \"PI_XBTUSD\",\n            \"side\": \"buy\",\n            \"size\": 1,\n            \"limitPrice\": 10000,\n            \"stopPrice\": 11000,\n        }, {\n            \"order\": \"cancel\",\n            \"order_id\": \"e35dsdfsdfsddd-8a30-4d5f-a574-b5593esdf0\",\n        }, {\n            \"order\": \"cancel\",\n            \"cliOrdId\": \"another-client-id\",\n        }],\n    ))\n    print(trade.cancel_all_orders())\n    print(\n        trade.create_order(\n            orderType=\"lmt\",\n            side=\"buy\",\n            size=1,\n            limitPrice=4,\n            symbol=\"pf_bchusd\"\n        )\n    )\n    # \u2026\n\n    # ____FUNDING___________________________\n    funding = Funding(key=key, secret=secret)\n    # \u2026\n\nif __name__ == \"__main__\":\n    main()\n```\n\n<a name=\"futuresws\"></a>\n\n## Futures Websocket API\n\nNot only REST, also the websocket API for Kraken Futures is available. Examples\nare shown below and demonstrated in `examples/futures_ws_examples.py`.\n\n- https://docs.futures.kraken.com/#websocket-api\n\nNote: Authenticated Futures websocket clients can also un-/subscribe from/to\npublic feeds.\n\n```python\nimport asyncio\nfrom kraken.futures import KrakenFuturesWSClient\n\nasync def main():\n\n    key = \"futures-api-key\"\n    secret = \"futures-secret-key\"\n\n    class Client(KrakenFuturesWSClient):\n\n        async def on_message(self, event):\n            print(event)\n\n    # Public/unauthenticated websocket connection\n    client = Client()\n\n    products = [\"PI_XBTUSD\", \"PF_ETHUSD\"]\n\n    # subscribe to a public websocket feed\n    await client.subscribe(feed=\"ticker\", products=products)\n    # await client.subscribe(feed=\"book\", products=products)\n    # \u2026\n\n    # unsubscribe from a public websocket feed\n    # await client.unsubscribe(feed=\"ticker\", products=products)\n\n    # Private/authenticated websocket connection (+public)\n    client_auth = Client(key=key, secret=secret)\n    # print(client_auth.get_available_private_subscription_feeds())\n\n    # subscribe to a private/authenticated websocket feed\n    await client_auth.subscribe(feed=\"fills\")\n    await client_auth.subscribe(feed=\"open_positions\")\n    await client_auth.subscribe(feed=\"open_orders\")\n    # \u2026\n\n    # unsubscribe from a private/authenticated websocket feed\n    await client_auth.unsubscribe(feed=\"fills\")\n\n    while True:\n        await asyncio.sleep(6)\n\nif __name__ == \"__main__\":\n    try:\n        asyncio.run(main())\n    except KeyboardInterrupt:\n        # do some exception handling \u2026\n        pass\n```\n\n---\n\n<a name=\"nftusage\"></a>\n\n# \ud83d\udccd NFT REST Clients\n\nThe Kraken NFT REST API offers endpoints for accessing the market and trade API\nprovided by Kraken. To access the private (trade) endpoints, you have to provide\nAPI keys - same as for the Spot REST API.\n\nThe following code excerpt demonstrates the usage. Please have a look into\n`tests/nft/*.py` for more examples.\n\n```python\nfrom kraken.nft import  Market, Trade\n\ndef main():\n    key = \"kraken-public-key\"\n    secret = \"kraken-secret-key\"\n\n    market = Market()\n    print(market.get_nft(nft_id=\"NT4GUCU-SIJE2-YSQQG2\", currency=\"USD\"))\n\n    trade = Trade(key=key, secret=secret)\n    print(trade.create_auction(\n        auction_currency=\"ETH\",\n        nft_id=[\"NT4EFBO-OWGI5-QLO7AG\"],\n        auction_type=\"fixed\",\n        auction_params={\n            \"allow_offers\": True,\n            \"ask_price\": 100000,\n        },\n    ))\n\nif __name__ == \"__main__\":\n    main()\n```\n\n---\n\n<a name=\"contribution\"></a>\n\n# \ud83c\udd95 Contributions\n\n\u2026 are welcome - but:\n\n- First check if there is an existing issue or PR that addresses your\n  problem/solution. If not - create one first - before creating a PR.\n- Typo fixes, project configuration, CI, documentation or style/formatting PRs\n  will be rejected. Please create an issue for that.\n- PRs must provide a reasonable, easy to understand and maintain solution for an\n  existing problem. You may want to propose a solution when creating the issue\n  to discuss the approach before creating a PR.\n- Please have a look at [CONTRIBUTION.md](./CONTRIBUTING.md).\n\n---\n\n<a name=\"trouble\"></a>\n\n# \ud83d\udea8 Troubleshooting\n\n- Check if you downloaded and installed the **latest version** of the\n  python-kraken-sdk.\n- Check the **permissions of your API keys** and the required permissions on the\n  respective endpoints.\n- If you get some Cloudflare or **rate limit errors**, please check your Kraken\n  Tier level and maybe apply for a higher rank if required.\n- **Use different API keys for different algorithms**, because the nonce\n  calculation is based on timestamps and a sent nonce must always be the highest\n  nonce ever sent of that API key. Having multiple algorithms using the same\n  keys will result in invalid nonce errors.\n\n---\n\n<a name=\"notes\"></a>\n\n# \ud83d\udcdd Notes\n\nThe versioning scheme follows the pattern `v<Major>.<Minor>.<Patch>`. Here's what each part signifies:\n\n- **Major**: This denotes significant changes that may introduce new features or\n  modify existing ones. It's possible for these changes to be breaking, meaning\n  backward compatibility is not guaranteed. To avoid unexpected behavior, it's\n  advisable to specify at least the major version when pinning dependencies.\n- **Minor**: This level indicates additions of new features or extensions to\n  existing ones. Typically, these changes do not break existing implementations.\n- **Patch**: Here, you'll find bug fixes, documentation updates, and changes\n  related to continuous integration (CI). These updates are intended to enhance\n  stability and reliability without altering existing functionality.\n\nCoding standards are not always followed to make arguments and function names as\nsimilar as possible to those of the Kraken API documentations.\n\n<a name=\"references\"></a>\n\n# \ud83d\udd2d References\n\n- https://python-kraken-sdk.readthedocs.io/en/stable\n- https://docs.kraken.com/rest\n- https://docs.kraken.com/websockets\n- https://docs.kraken.com/websockets-v2\n- https://docs.futures.kraken.com\n- https://support.kraken.com/hc/en-us/sections/360012894412-Futures-API\n\n---\n",
    "bugtrack_url": null,
    "license": "Copyright 2023 Benjamin Thomas Schwertfeger  Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ",
    "summary": "Collection of REST and websocket clients to interact with the Kraken cryptocurrency exchange.",
    "version": "2.2.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/btschwertfeger/python-kraken-sdk/issues",
        "Documentation": "https://python-kraken-sdk.readthedocs.io/en/stable/",
        "Homepage": "https://github.com/btschwertfeger/python-kraken-sdk"
    },
    "split_keywords": [
        "crypto",
        "trading",
        "kraken",
        "exchange",
        "api"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5b05c7c39a66662c374c1dc6e20c9092164c71953c391237b248e8519a0120c8",
                "md5": "43c92cf1354a621d29ad7f187c0fad3c",
                "sha256": "1614ff38fa4a1f86d2824ff80bf7acc7ab3adbf3941ac4ef28b8d4c029a8177d"
            },
            "downloads": -1,
            "filename": "python_kraken_sdk-2.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "43c92cf1354a621d29ad7f187c0fad3c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 106380,
            "upload_time": "2024-03-10T14:41:00",
            "upload_time_iso_8601": "2024-03-10T14:41:00.112935Z",
            "url": "https://files.pythonhosted.org/packages/5b/05/c7c39a66662c374c1dc6e20c9092164c71953c391237b248e8519a0120c8/python_kraken_sdk-2.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bc25478fbcb772a1fb546e924003bfa9bf924880553a4e183c16ebba9923b886",
                "md5": "fa4da6c06ed831cbb82e05d6c97fcb6e",
                "sha256": "fee9b3d3c7093eba6121bf8872b4f1855c9755969181576ee77b6423e0f0c119"
            },
            "downloads": -1,
            "filename": "python-kraken-sdk-2.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "fa4da6c06ed831cbb82e05d6c97fcb6e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 110325,
            "upload_time": "2024-03-10T14:41:02",
            "upload_time_iso_8601": "2024-03-10T14:41:02.678784Z",
            "url": "https://files.pythonhosted.org/packages/bc/25/478fbcb772a1fb546e924003bfa9bf924880553a4e183c16ebba9923b886/python-kraken-sdk-2.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-10 14:41:02",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "btschwertfeger",
    "github_project": "python-kraken-sdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "python-kraken-sdk"
}
        
Elapsed time: 0.26695s