Kraken Trader
A long-running service that manages a Kraken portfolio. It runs any number of trading strategies side by side and shows how each one is doing, plus your whole account, on a web dashboard.
- Pluggable strategies. To add a strategy, drop one Python file into
kraken_trader/strategies/. - Several strategies at once. Each strategy has its own virtual slice of capital, its own trades and its own equity history, so you can compare them.
- Paper or live. In
papermode a strategy trades against live Kraken prices with simulated fills, fees and slippage. Inlivemode it places real market orders. - Dashboard. Shows account value and holdings, every strategy's return, max drawdown, Sharpe ratio, win rate and fees, plus charts and a trade log. You can pick any Catppuccin theme (Mocha is the default).
- Kubernetes-ready. Runs as a single non-root container. SQLite is stored on a PersistentVolume, and a health probe catches a stalled trading loop.
No strategy is guaranteed to make money. Start every new strategy in
papermode, compare it against thebuy_and_holdbenchmark over a meaningful period, and only then give it a small amount of real capital.
How it works
flowchart LR
K[Kraken API] -->|prices, candles| E[Engine loop]
E -->|Context| S1[Strategy A]
E -->|Context| S2[Strategy B]
S1 -->|target weights| E
S2 -->|target weights| E
E -->|orders| PB[Paper broker]
E -->|orders| LB[Live broker] --> K
E --> DB[(SQLite)]
DB --> W[Web dashboard / JSON API]
The engine runs every poll_interval_seconds:
- It fetches the latest prices.
- When a new candle closes for a strategy's pairs and interval, it calls that
strategy's
decide(). - The strategy returns target weights, meaning the fraction of its equity it wants in each pair. The engine works out the buy and sell orders, applies fees, rounds to Kraken's lot size and minimum order size, and sells before it buys.
- It records equity snapshots for each strategy and the real account balance.
Writing a strategy
Create kraken_trader/strategies/my_strategy.py:
from .base import Context, Strategy, register
@register("breakout")
class Breakout(Strategy):
"""Go long when price closes above the N-candle high; exit below the N-candle low."""
default_params = {"lookback": 20}
def decide(self, ctx: Context) -> dict[str, float]:
n = self.params["lookback"]
targets = {}
for pair in self.pairs:
df = ctx.candles[pair] # pandas DataFrame: open/high/low/close/vwap/volume
if len(df) <= n:
continue
prior = df.iloc[-n - 1:-1]
close = df["close"].iloc[-1]
if close > prior["high"].max():
targets[pair] = 1 / len(self.pairs)
elif close < prior["low"].min():
targets[pair] = 0.0
return targets # omitted pairs keep their current allocation
Then reference the strategy in config/strategies.yaml:
- id: breakout-btc
type: breakout
mode: paper
starting_capital: 1000
pairs: [XBTUSD]
interval: 60
params: {lookback: 20}
To compare variants, run the same type several times with different params,
pairs or intervals. Each one needs its own id.
Context gives you:
candles: closed candles, up to 720, for each pair.prices: latest prices.weights: current allocation per pair.cashandequity.
You can keep extra state on self, but it does not survive a restart. Only
portfolios, trades and history are persisted.
Included strategies (shared indicator helpers are in kraken_trader/strategies/indicators.py):
| type | Basis | Idea |
|---|---|---|
buy_and_hold |
Benchmark | Split capital equally and hold. |
time_series_momentum |
Moskowitz, Ooi & Pedersen (2012); Liu & Tsyvinski (2021); Moreira & Muir (2017) | Exposure = share of 20/60/120-candle lookbacks with positive returns, scaled to a volatility target. |
donchian_breakout |
Turtle rules; Hurst, Ooi & Pedersen (2017) | Buy a close above the N-candle high, sell below the M-candle low. Position is volatility-sized. |
cross_sectional_momentum |
Liu, Tsyvinski & Wu (2022); Antonacci (2014) | Each week, hold the top-K coins by 3-week return, but only those with a positive return. Inverse-volatility weighted. |
trend_risk_parity |
Faber (2007); risk parity | Inverse-volatility slots, each held only while the coin is above its long SMA. |
adaptive_regime |
Novel | The efficiency ratio picks the regime: trend-follow in trending markets, buy z-score dips in choppy ones. Never long below the long SMA. |
squeeze_breakout |
Novel | After a Bollinger-bandwidth squeeze (lowest 20% of recent bandwidth), buy an upside band break in an uptrend. Exit at the middle band. |
btc_regime_rotation |
Novel | Go to cash whenever BTC is below its SMA. Otherwise rotate weekly into the coins outperforming BTC. |
sma_crossover |
Simple example | Hold while the fast SMA is above the slow SMA. |
rsi_mean_reversion |
Simple example | Buy when RSI is below oversold, sell when above overbought. |
The academic results describe how these strategies did in the past. They do not guarantee future results. Crypto trend and momentum effects have been strong but have weakened as markets matured. Treat every strategy as a hypothesis, backtest it and paper-trade it before going live.
Backtesting
python -m kraken_trader.backtest # every strategy in the config, including disabled ones
python -m kraken_trader.backtest --only tsmom-basket,hodl-basket --warmup 200
The backtest replays Kraken candles through the same runner and paper broker that paper trading uses, so fees, slippage and minimum order sizes are included. It prints return, CAGR, max drawdown, Sharpe, time invested, trade count and fees. Results are sorted by Sharpe ratio.
Limitations:
- Kraken returns at most 720 candles, so daily strategies get about two years of history. That is roughly one market cycle and is easy to overfit.
- The coin list is chosen with hindsight (survivorship bias).
- Fills happen at the candle close. Real fills land a few seconds later.
Prefer parameters that work over a broad range of values over the single best result.
Running locally
python -m venv .venv; .venv\Scripts\Activate.ps1
pip install -r requirements-dev.txt
copy .env_example .env # set DASHBOARD_PASSWORD; optionally add API keys
python -m kraken_trader # http://localhost:8080 (user: admin)
pytest
API keys are optional. Without them, paper strategies still work because they only use public market data. Account tracking needs a key with Query Funds permission. Live trading also needs Create & Modify Orders. Never grant Withdraw Funds.
Going live
- Set
mode: liveon a strategy. Itsstarting_capitalis the share of your real USD balance that it may use. - Make sure the combined
starting_capitalof all live strategies is no more than the USD you actually hold on Kraken. - Set
LIVE_TRADING_ENABLED=true. If a live strategy is configured without this setting, the service refuses to start.
After a strategy has started, its portfolio state is stored in the database.
Changing its starting_capital later has no effect. To reset a strategy, give it
a new id.
Docker
docker build -t kraken-trader .
docker run --rm -p 8080:8080 --env-file .env -v ${PWD}/data:/data kraken-trader
Kubernetes
Kubernetes deployment is managed by the sibling ansible-role-kraken-bot
repository, the single source of truth for Kubernetes resources. Build and push
the image, then set its full reference as kraken_bot_image in your Ansible
playbook. Follow the role README for playbook, secret, configuration, and deploy
instructions.
The role deploys one non-root replica with a persistent SQLite volume, probes, resource limits, a read-only root filesystem, and an internal ClusterIP Service. It requires a dashboard password and stores that password and Kraken credentials in a Kubernetes Secret. Keep the Service private; use TLS if adding an ingress.
Configuration reference
Environment variables:
| Variable | Default | Purpose |
|---|---|---|
KRAKEN_API_KEY, KRAKEN_API_SECRET |
— | Kraken credentials |
DASHBOARD_PASSWORD |
— (required) | Password for the web dashboard and API |
DASHBOARD_USERNAME |
admin |
Username for the web dashboard and API |
LIVE_TRADING_ENABLED |
false |
Must be true for any mode: live strategy |
CONFIG_PATH |
config/strategies.yaml |
Strategy config file |
DATA_DIR |
data |
SQLite location |
PORT |
8080 |
Web port |
LOG_LEVEL |
INFO |
Logging level |
Global options such as fees, slippage and polling intervals are documented at the top of config/strategies.yaml.
Project layout
kraken_trader/
__main__.py entry point (engine + web server)
kraken.py async Kraken REST client (signing, rate limiting, metadata)
engine.py trading loop and per-strategy runners / rebalancing
broker.py paper and live order execution
portfolio.py virtual portfolios, cost basis, realized P&L
storage.py SQLite persistence
stats.py performance metrics
web.py, templates/ dashboard and JSON API (/api/overview, /api/docs)
strategies/ strategy base class, registry, and strategies
config/strategies.yaml
tests/