Skip to main content

A basic rebalance trading bot for the Kraken Cryptocurrency Exchange.

Project description

Welcome to the Spot Rebalance Bot for the Kraken Cryptocurrency Exchange 🐙

GitHub License: GPL v3 Generic badge

ql-workflow python-package

This is an unofficial trading bot that performs buys and sells on the Kraken cryptocurrency exchange using Python.


📌 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.

It is not certain that this software will ever lead to profits.

Package Update

  • January 25, 2023

📝 The Strategy

This algorithm can buy and sell one or more Spot assets without leverage.

The goal is to hold a certain amount of each base currency so that, for example, there is always about $1000 worth of BTC in the portfolio. If the price of Bitocoin increases so that there is now $1050 worth of Bitcoin in the portfolio, the excess $50 is sold. If the price of Bitcoin falls, so that the Bitcoin in the portfolio are only worth $950, the algorithm buys Bitcoin, to hold a value of about $1000 in Bitcoin in the portfolio again.

The algorithm checks the price range every 6 hours by default. The margin, from how many percent price difference the algorithm becomes active, can also be adjusted.

Actions can be logged on the command-line using the logging module with active INFO-level and can also be sent to a telegram bot.


⚙️ Quick start and configuration

0. Check the source code of this algorithm on GitHub and read the README.md carefully

1. Install the Python module:

python3 -m pip install kraken-rebalance-bot

2. Register at Kraken and generate API keys with trading access:

3. (optional) Create a Telegram Bot to get notified when the algorithm takes action

  1. Create a bot using @BotFather
  2. Write down/remember the token
  3. Start @RawDataBot and write down your personal chat id

4. Setup the configuration and start the algorithm

a.) Using docker

Build an image and pass a config when starting the container:

docker build -t krb:latest examples/docker
docker run --env-file examples/docker/.docker.env krb

(examples/docker/.docker.env contains the configuration for this bot)

Output:

2023/01/25 18:54:29 main,line: 42  WARNING | Not using telegram.
2023/01/25 18:54:29 bot,line: 59     INFO | Starting the `kraken-rebalance-bot`
2023/01/25 18:54:29 bot,line: 62     INFO | Using scheduled times @['00:00', '06:00', '12:00', '18:00']
...

b.) Using a Python script

In the following a minimal working example is shown that uses this strategy to hold a target_quantity of $500 of ETH and $500 worth of XBT. Both are traded agains USD. The demo key must be set to False to enable the trading functionality. Of course, this also works with only one asset, too.

from krakenRebalanceBot.bot import RebalanceBot

def main() -> None:
    bot = RebalanceBot(
        key='kraken-api-key',
        secret='kraken-secret-key',
        config={
            'base_currency': ['ETH', 'XBT'],    # base assets to maintain
            'quote_currency': ['USD', 'USD'],   # quote assets to trade with
            'target_quantity': [500, 500],      # how many of the base to hold (value in quote)
            'quote_to_maintain': [200, 200],    # freezed quote/dont trade with this
            'margin': [0.035, 0.035],           # buy/sell threshold
            'lowest_buy_price': [1000, 15000],  # dont buy below this price
            'times': ['06:00', '18:00'],        # optional of use_build_in_sheduler is True
            'use_build_in_sheduler': False,     # if set to False, the script will only run once
            'demo': True,                       # set to false to enable trading
            'telegram': {                       # optional to get notified via telegram
                'token': 'telegram-bot-token',
                'chat_id': 'your-telegram-chat-id'
            }
    })
    bot.run()  # start the bot

if __name__ == '__main__': main()

The file /examples/main.py serves as an example on how to initialize and run this trading algorithm using the .env and config.json files (see GitHub). There is also a Jupyter notebook in which one can test the algorithm without risking any assets.

  • To see the output on the command line you need to enable logging with level INFO as shown in the example script.
  • If use_build_in_sheduler is enabled, there will be no output until the time is one of times.

📖 Documentation of configuration arguments:

Key Type Description
base_currency List[str] Array of base currrncies to trade and hold.
quote_currency List[str] Array of quote currencies to trade the base currency with.
target_quantity List[float] | List[int] Defines how much of a base currency should be held. This value is the worth of the base currency in quote currency.
quote_to_maintain List[float] | List[int] How much of quote currency should not be touched in the portfolio.
margin List[float] Rebalance levels e.g. 0.035 = 3.5%: at a change of 3.5% the algorithm will buy or sell the missing/surplus quantity
lowest_buy_price List[float] (optional) The bot will not buy if the price falls below this price to avoid catching a falling knife. Acts Kind of stop loss, but without selling.
times List[str] (optional, default: ['00:00', '06:00', '12:00', '18:00']) At which time the bot should check the balances.
use_build_in_sheduler bool (optional, default: False) Checks the balances once and exits if set to False. Otherwise the program will run forever and check the balances at the specified times
demo bool Trade or not sample trade output. Set to True if you know what this algorithm does.
telegram {'chat_id': str, 'token': str} (optional) Specify token and chat id to get notified when the bot does something.

If use_build_in_sheduler is set to False, the program is executed once and ends after the iteration over all assets. This offers the possibility to create own scripts, which execute this algorithm at individual times (e.g. using cron).


📍 Notes

  • Make sure to always have enough quote currency in your Kraken portfolio. Too low target_quantity values can cause the bot not to trade or even crash. Therefore, pay attention to the minimum order sizes.

    • Example:
      • situation:
        • minimal order size of ETH is 0.01
        • price of ETH: $1300
        • margin is set to 0.04
        • target_quantity is 200
      • what will happen:
        • If your actual holdings of ETH is $192 the bot tries to buy Ethereum with a volume of $8 because $200 - $200 * 0.04 will trigger the buy order. But the minimum ordersize of Ethereum is 0.01 ETH (see here), and with a price of $1300 0.01 ETH equals $13 so: $13 < $8 will raise an error.
    • So make sure that the minimum order sizes of the respective assets are consistent with the margin value and the target_quantity. The example would work if the targe_quantity is set to 500, because $500 _ 0.04 = $20 which is larger than $1300 _ 0.01 = $13.
    • Also make sure that there is enough quote currency, otherwise the bot cannot buy anything.
  • This strategy is one of the simplest and most basic approaches for trading cryptocurrencies. For this reason, it should be noted here that this does not necessarily lead to profits. Before running such an algorithm, everyone should be clear about what products are being traded, what these products are for in the first place, and what makes them valuable. Even the best companies, stocks, materials, and also cryptocurrencies can become worthless from one day to the next, so everyone should do their own research and make their decisions based on these results.

  • It has been decided here not to present any material regarding the profitability of this algorithm, as this could lead you to make your decisions based on my successes and failures. What works once or over a long period of time does not necessarily work in the future. But please let me know what you think about this basic algorithm and what could be improved.

  • For any problems, issues, and errors, please open an issue.


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kraken-rebalance-bot-0.5.7.3.tar.gz (25.4 kB view details)

Uploaded Source

Built Distribution

kraken_rebalance_bot-0.5.7.3-py2.py3-none-any.whl (21.3 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file kraken-rebalance-bot-0.5.7.3.tar.gz.

File metadata

  • Download URL: kraken-rebalance-bot-0.5.7.3.tar.gz
  • Upload date:
  • Size: 25.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.7 tqdm/4.62.3 importlib-metadata/4.8.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.7

File hashes

Hashes for kraken-rebalance-bot-0.5.7.3.tar.gz
Algorithm Hash digest
SHA256 bfdbbe693346298974b44d310e6265552d99c012352489676c0916352eebc61e
MD5 1d58a8ac88bcd3296f15c10633dd9b36
BLAKE2b-256 4f99064a11e416617c5542dc6e5f58ab978fd4c29ae5d45c42f737f5bd973e78

See more details on using hashes here.

File details

Details for the file kraken_rebalance_bot-0.5.7.3-py2.py3-none-any.whl.

File metadata

  • Download URL: kraken_rebalance_bot-0.5.7.3-py2.py3-none-any.whl
  • Upload date:
  • Size: 21.3 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.7 tqdm/4.62.3 importlib-metadata/4.8.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.7

File hashes

Hashes for kraken_rebalance_bot-0.5.7.3-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 aa483fed98532d9fa5316770d05045a682f2eaa398f00a6d5973af95eeca648d
MD5 c48018f159b4a795192706d4847562b9
BLAKE2b-256 e0ce52cb46272a78dbc78cc21cc37fba2780bb562244fbb0d13a66d6405af445

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page