#!/usr/bin/env python3 """Re-run the public BTC candle-direction example with Python 3 and Docker. The download is a fixed Binance Vision BTCUSDT spot archive. The Docker container is disposable and binds its backtest API to loopback. It places no orders and does not need an exchange account, API key, or license. """ import argparse import csv import hashlib import io import json import math from pathlib import Path import statistics import subprocess import tempfile import time import urllib.error import urllib.request import zipfile ARCHIVE = "BTCUSDT-1h-2024-01" SOURCE = f"https://data.binance.vision/data/spot/monthly/klines/BTCUSDT/1h/{ARCHIVE}.zip" SHA256 = "cf873a185bd5b24b8e00034e49583fcb49928e0c3a45c6fc27a632a683655417" IMAGE = "ghcr.io/sergio12s/aipp-backtester-server@sha256:c846275a6d9a368bb7b14d3fbed5f21f5d6be6bfb2208f2d61214867ad6e5749" LOOKBACK, HORIZON, NEIGHBOURS, WARMUP = 12, 4, 9, 12 * 24 INITIAL_CAPITAL, POSITION_SIZE = 10_000, 1.0 COMMISSION, SLIPPAGE = 0.0005, 0.0002 def load_archive(): with urllib.request.urlopen(SOURCE, timeout=30) as response: body = response.read() if hashlib.sha256(body).hexdigest() != SHA256: raise ValueError("The archive does not match the published checksum") with zipfile.ZipFile(io.BytesIO(body)) as archive: rows = list(csv.reader(io.StringIO(archive.read(f"{ARCHIVE}.csv").decode()))) start = 1704067200000 # 1 January 2024, 00:00 UTC if len(rows) != 744 or any(int(row[0]) != start + 3600000 * i for i, row in enumerate(rows)): raise ValueError("Expected all 744 hourly bars in January 2024") return rows def study(rows, dataset): close = [float(row[4]) for row in rows] log_close = list(map(math.log, close)) shapes = {} for i in range(LOOKBACK - 1, len(close)): window = log_close[i - LOOKBACK + 1:i + 1] center, spread = statistics.mean(window), statistics.pstdev(window) shapes[i] = tuple((value - center) / spread for value in window) if spread else (0,) * LOOKBACK direction_correct = always_up_correct = queries = up_votes = 0 target = 0 with dataset.open("w", newline="") as handle: writer = csv.writer(handle) writer.writerow(["timestamp", "open", "high", "low", "close", "volume", "analogue_long"]) for i in range(WARMUP, len(rows)): if i % HORIZON == 0 and i + HORIZON < len(rows): end = i - LOOKBACK - HORIZON candidates = sorted( range(LOOKBACK - 1, end + 1), key=lambda j: sum((a - b) ** 2 for a, b in zip(shapes[i], shapes[j])), ) neighbours = [] for j in candidates: if all(abs(j - other) >= LOOKBACK + HORIZON for other in neighbours): neighbours.append(j) if len(neighbours) == NEIGHBOURS: break if len(neighbours) != NEIGHBOURS: raise ValueError(f"Insufficient separated historical neighbours at bar {i}") target = int(sum(close[j + HORIZON] > close[j] for j in neighbours) > NEIGHBOURS // 2) outcome = int(close[i + HORIZON] > close[i]) direction_correct += int(target == outcome) always_up_correct += outcome up_votes += target queries += 1 elif i == len(rows) - 2: # Issue a final flat signal to close at the last available hourly open. target = 0 row = rows[i] writer.writerow([int(row[0]) // 1000, *row[1:6], target]) return { "queries": queries, "analogue_correct": direction_correct, "always_up_correct": always_up_correct, "analogue_up_votes": up_votes, "first_oos_open": int(rows[WARMUP][0]) // 1000, "last_open": int(rows[-1][0]) // 1000, } def docker(*args): return subprocess.check_output(["docker", *args], text=True, timeout=180).strip() def request(base, path, data=None): req = urllib.request.Request( base + path, data=json.dumps(data).encode() if data is not None else None, headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=30) as response: return json.load(response) def engine_run(base, dataset, commission, slippage): loaded = request(base, "/api/load-data", { "path": "/study.csv", "initial_capital": INITIAL_CAPITAL, "commission": commission, "slippage": slippage, "signal_execution_timing": "next_open", }) if loaded["status"] != "success": raise RuntimeError(loaded["message"]) result = request(base, "/api/run-backtest", { "entry_long": "analogue_long > 0.5", "exit_long": "analogue_long < 0.5", "position_size": POSITION_SIZE, }) if result["status"] != "success": raise RuntimeError(result["message"]) data = result["data"] raw = data["backtest_result"] trades = data["extended_trades"] if raw["total_trades"] == 0 or len(trades) != raw["total_trades"]: raise RuntimeError("Expected the complete executed trade history") with dataset.open(newline="") as handle: signals = {int(row["timestamp"]): int(row["analogue_long"]) for row in csv.DictReader(handle)} for trade in trades: if ( signals.get(trade["open_time"] - 3600) != 1 or signals.get(trade["close_time"] - 3600) != 0 or trade["exit_reason"] != "Signal" ): raise RuntimeError("A fill did not match the preceding closed bar's decision") return { "closed_trades": raw["total_trades"], "final_equity_usd": round(raw["final_capital"], 2), "return_pct": round((raw["final_capital"] / INITIAL_CAPITAL - 1) * 100, 4), "commission_usd": round(raw["total_commission"], 2), } def backtest(dataset): container = docker( "run", "--platform", "linux/amd64", "--detach", "--rm", "--init", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--publish", "127.0.0.1::8142", "--env", "RLXBT_BIND_HOST=0.0.0.0", "--env", "RLXBT_GBRAIN=off", "--tmpfs", "/tmp", "--tmpfs", "/var/lib/rlxbt", "--tmpfs", "/var/cache/rlxbt", "--mount", f"type=bind,src={dataset},dst=/study.csv,readonly", IMAGE, ) try: port = docker("port", container, "8142/tcp").rsplit(":", 1)[-1] base = f"http://127.0.0.1:{port}" for _ in range(30): try: request(base, "/api/health") break except (TimeoutError, urllib.error.URLError): time.sleep(1) else: raise RuntimeError("The local backtester did not start") return { "zero_cost": engine_run(base, dataset, 0, 0), "with_costs": engine_run(base, dataset, COMMISSION, SLIPPAGE), } finally: subprocess.run(["docker", "stop", container], capture_output=True, check=False, timeout=20) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--direction-only", action="store_true", help="Skip the Docker backtests") args = parser.parse_args() with tempfile.TemporaryDirectory(prefix="btc-candle-study-") as directory: dataset = Path(directory) / "study.csv" output = { "source": SOURCE, "sha256": SHA256, "engine_image": IMAGE, "settings": { "lookback": LOOKBACK, "horizon": HORIZON, "neighbours": NEIGHBOURS, "warmup_bars": WARMUP, "initial_capital": INITIAL_CAPITAL, "position_size": POSITION_SIZE, "commission_bps_per_fill": COMMISSION * 10_000, "slippage_bps_per_fill": SLIPPAGE * 10_000, }, "direction": study(load_archive(), dataset), } if not args.direction_only: output["backtest"] = backtest(dataset) print(json.dumps(output, indent=2)) if __name__ == "__main__": main()