Skip to content

Repository files navigation

Kolabi Bot

Presentation

Kolabi is a typed, DB-grounded, async order-pair bot for exchange-routed spot, margin, and futures strategies. The active production path is the Org strategy table runtime in kolabi.bot, backed by public market-data feeders and private account/order feeders in kolabi.tree. Kraken, Binance, and BitMEX now share the same DB-grounded route model: every order row resolves to an exchange, market type, and native exchange symbol.

The core strategy unit is an order pair:

  • a head order enters or opens the position;
  • a tail order protects or closes the position;
  • the pair can repeat, wait, update its tail, or activate another pair through a hook.

Supported Platforms

  • kraken: futures, spot, and spot-margin via KRKF, KRKS, and KRKM route codes.
  • binance: futures, spot, cross-margin, and isolated-margin via BINF, BINS, BINM, and BINI route codes.
  • bitmex: futures and spot via BTX / BTXF and BTXS route codes, with BMXF / BMXS kept as aliases.

The bot can run a strategy file whose rows target different exchange routes. Org strategy rows may carry platform-specific symbols directly; no canonical symbol mapping table is used. Each active route needs matching public and private DB feeder evidence before live execution.

Strategy Conditions

Each pair can be gated by:

  • an entry window, tps_run, in minutes from launch;
  • a typed price interval, pGate;
  • a head timeout, tOut, for unfilled head orders;
  • a repeat count, essais / -n;
  • a pause between repetitions, pause / -p;
  • a hook dependency, where a pair starts only after another pair reaches the required terminal condition.

Important runtime semantics:

  • tps_run controls when a new pair attempt may start. Once an attempt starts, it is not stopped only because the entry window closes.
  • tOut is stricter: if the head is not filled before the timeout, the head is cancelled and the attempt may repeat according to its repeat policy.
  • Tail stops are grounded on private fill/order evidence, not on a guessed public price.
  • Tail updates are no-widen by design: the pure reducer should not emit a tail amend that worsens the protected stop.

Price, Quantity, And Tail Units

The active Org strategy grammar puts the type prefix on each non-empty value:

  • pGate uses D, %, or A before its two bounds, for example D- +, D- -5, or %0.20 0.30.
  • hPrice uses D, %, or A before one value; it is forced lazily only when pGate opens and is relative to the gate-open reference unless absolute A is used.
  • qty uses A or %, for example A3.
  • tPrice uses D, %, or A, for example D20 or %0.10.
  • hDelta uses D or % for SL and LT head trigger-to-limit offsets; signed D values are accepted but materialised as positive distances.
  • tDelta uses D when present.
  • tUblk uses D or % when present, for example D5 or %0.20. Empty keeps the default first-unblock distance: the initial tail distance plus the first-jump guard.
  • After tUblk unblocks the tail, the first managed update protects entry by jumping to the profit side of entry by max(max observed spread, 8 ticks) + two taker fees; with a taker fee of 0.05%, the fee part is 0.001 * head-fill price. Later updates use the normal trailing curve.

Only empty typed fields receive implicit defaults. A non-empty typed value without its prefix is rejected. Legacy tab-separated files and compact atype inputs are no longer accepted.

The pGate field is a two-bound interval, not a single price. Use semi-open operator style in Org strategy tables when appropriate, for example D- -5 or D5 +, so the parser can translate the condition into a bounded internal interval. The hPrice field is not resolved before the pair is active; for example a sell L with pGate=%- -2 and hPrice=D10 places the limit at the gate-open reference plus 10.

Org Strategy Tables

Strategy files live under orders/.

The active Org table grammar is:

| exchg | symbol | name | tps_run | essais | tOut | pause | side | oType | hDelta | qty | tType | tDelta | pGate | hPrice | tPrice | tUblk | wUblk | hook |

The exchg and symbol columns are optional. When exchg is omitted, the CLI --exchange and --market-type are used. When symbol is omitted, the effective CLI symbol is used. If CLI --symbol is also omitted, the route default is selected: PI_XBTUSD for Kraken futures, XBT/USD for Kraken spot/margin, BTCUSDT for Binance futures/spot/margin/isolated margin, XBTUSD for BitMEX futures, and XBT_USDT for BitMEX spot. When present, rows use platform-specific symbols directly, for example PI_XBTUSD, BTCUSDT, or XBTUSD. Blank Org cells keep their typed defaults where a default exists. A multi-route strategy run requires one shared market DB URL and public/private feeders for every active exchange, market type, account scope, and symbol.

Useful examples:

  • orders/demo_ada.org documents order-type examples in the Org table grammar.
  • orders/demo_cross_exchange_chain.org demonstrates the typed multi-exchange Org table grammar.
  • orders/demo_kraken_xbt.org covers Kraken XBT combinations.

DB And Feed Services

The runtime expects fresh DB-backed evidence before active execution:

  • public market snapshots from kolabi.tree.kraken, kolabi.tree.binance, or kolabi.tree.bitmex;
  • private order/fill/account state from kolabi.tree.account, kolabi.tree.binance_account, or kolabi.tree.bitmex_account;
  • a critical private lane for open orders and fills;
  • optional REST audit and tail telemetry lanes.

PostgreSQL is the supported local runtime backend. Use scripts/kolabidb postgres start and the lane URLs from .env.postgres for public, private, critical, audit, and telemetry storage.

Start the default Kraken Futures demo lanes:

scripts/kolabidb postgres start
scripts/kolabidb public start --exchange kraken --market-type futures --environment demo --pair PI_XBTUSD
scripts/kolabidb private start --exchange kraken --market-type futures --environment demo --account-scope default

Start other route lanes by selecting the same exchange and market type that appears in the Org strategy table:

scripts/kolabidb public start --exchange binance --market-type spot --environment demo --pair BTCUSDT
scripts/kolabidb private start --exchange binance --market-type spot --environment demo --account-scope default
scripts/kolabidb public start --exchange kraken --market-type margin --environment live --pair XBT/USD
scripts/kolabidb private start --exchange kraken --market-type margin --environment live --account-scope default
scripts/kolabidb public start --exchange bitmex --market-type futures --environment demo --pair XBTUSD
scripts/kolabidb private start --exchange bitmex --market-type futures --environment demo --account-scope default

Check service status and logs:

scripts/kolabidb public status --environment demo --pair PI_XBTUSD
scripts/kolabidb private status --environment demo --account-scope default
scripts/kolabidb public logs --environment demo --pair PI_XBTUSD
scripts/kolabidb private logs --environment demo --account-scope default

Reset a local runtime before a fresh live or demo test with scripts/kolabi-fresh-run. The helper stops Kolabi feeder PID files that still belong to kolabi.tree processes, starts PostgreSQL, purges configured Kolabi runtime DB lanes, restarts the route feeders needed by the strategy, and prints the bot command unless --start-bot is passed. It does not cancel platform orders or close positions.

scripts/kolabi-fresh-run --dry-run --strategy orders/bmm_ada.tsv --environment live
scripts/kolabi-fresh-run --strategy orders/bmm_ada.tsv --environment live
scripts/kolabi-fresh-run --strategy orders/demo_cross_exchange_chain.org --environment demo --symbol PI_XBTUSD

Operator logs must not print credential-bearing DB URLs. Runtime preflight and feeder startup logs redact database passwords as postgresql+psycopg://user:***@host/db. Historical log files created before this rule may still contain full URLs and should be treated as sensitive.

Operator Commands

When --symbol is omitted in kolabi.bargain.cli, kolabi.bargain.smoke, or kolabi.bot, the route default follows --exchange and --market-type: Kraken futures PI_XBTUSD, Kraken spot/margin XBT/USD, Binance lanes BTCUSDT, BitMEX futures XBTUSD, and BitMEX spot XBT_USDT.

The routes command also reports permission_probe, order_write_probe, and demo_requires_base_url_override. Binance spot/futures can prove order-write with a no-order test_order endpoint. BitMEX can read apiKey metadata but that does not prove order-write unless the returned permissions include it. Kraken spot/margin and Binance margin demo lanes require an explicit market-capable demo base URL before adapter construction.

The bot preflight command reports credentials_ready, base_urls_ready, and route_config_ready for the effective route set. It reports base URL source names such as override or an env var name, not the URL value.

# Show route codes, default symbols, expected credential env names, and key/secret presence without connecting:
python -m kolabi.bargain.cli --environment demo routes

# List instruments and find exact symbols:  
python -m kolabi.bargain.cli --exchange kraken --market-type futures --environment live instruments --contains ADA

# Validate a selected symbol:
python -m kolabi.bargain.cli --exchange kraken --market-type futures --environment demo --symbol PI_ADAUSD check-symbol

# Read account state:
python -m kolabi.bargain.cli --exchange bitmex --market-type futures --environment demo permissions
python -m kolabi.bargain.cli --exchange kraken --market-type futures --environment demo --symbol PI_XBTUSD balance
python -m kolabi.bargain.cli --exchange binance --market-type spot --environment demo --symbol BTCUSDT open-orders
python -m kolabi.bargain.cli --exchange binance --market-type margin --environment live --symbol BTCUSDT trigger-orders

# Emergency cleanup:
python -m kolabi.bargain.cli --exchange kraken --market-type futures --environment demo --symbol PI_XBTUSD close-all

# Show and run the lane-aware smoke order plan:
python -m kolabi.bargain.smoke --exchange binance --market-type spot --symbol BTCUSDT --environment demo --list-orders
python -m kolabi.bargain.smoke --exchange kraken --market-type futures --symbol PI_XBTUSD --environment demo --only limit_below --sleep-seconds 2

Running The Bot

# Dry-run an Org strategy table:
python -m kolabi.bot run --strategy orders/demo_ada.org --exchange kraken --symbol PI_XBTUSD --environment demo --dry-run

# Run an Org strategy table through the async runtime:
python -m kolabi.bot run --strategy orders/rep_xbt.tsv --exchange kraken --symbol PI_XBTUSD --environment demo
python -m kolabi.bot run --strategy orders/demo_margin.tsv --exchange binance --market-type margin --environment demo --base-url https://margin-demo.example.test

# Run one typed order pair:
python -m kolabi.bot run-once --symbol PI_XBTUSD --environment demo -m XSellTail -t 0 1440 -O 60 -x 'D1 2' --hPrice D1 --qty A1 --tPrice %0.5 -o L -y S- -c sell --dry-run

# Preflight route credential and DB readiness:
python -m kolabi.bot preflight --exchange kraken --symbol PI_XBTUSD --environment demo
python -m kolabi.bot preflight --exchange binance --market-type spot --environment demo --api-key-env BINS_DEMO_API_KEY --api-secret-env BINS_DEMO_API_SECRET
python -m kolabi.bot preflight --exchange binance --market-type margin --environment demo --base-url https://margin-demo.example.test --api-key-env BINM_DEMO_API_KEY --api-secret-env BINM_DEMO_API_SECRET

Live/preprod should be launched only after a clean demo run, fresh public/private DB state, no unexpected open orders or positions, and an explicit dry-run of the exact strategy. Start live with small size, --max-active-pairs 1, --rest-max-inflight 1, and a non-zero --rest-min-interval.

Installation

Use the repository Python environment declared by .python-version, then install the package and dependencies in editable mode:

pyenv local kola
python -m pip install -r requirements.txt
python -m pip install -e .

Credential values should come from environment variables or a local env file that is not committed. Kraken defaults are:

KRKF_DEMO_API_KEY
KRKF_DEMO_API_SECRET
KRKF_API_KEY
KRKF_API_SECRET

Use --api-key-env and --api-secret-env when selecting a non-default account.

Tests

Start with focused active-path tests:

PYENV_VERSION=kola pytest tests/bot tests/tree/test_kraken_tree.py -q
python -m ruff check kolabi tests

Legacy tests and archived paths exist for behavioural reference, but the active regression surface is under tests/bot, tests/tree, tests/exchanges, and tests/core.

Disclaimer

This is an educational and experimental trading system. It can submit real orders when run against a live platform. Review the code, use small size, keep exchange-side risk limits in place, and do not run unattended until the live preprod path has proven itself under your operating conditions.

kolabi/
|- bargain/                     # direct exchange-facing operator tools
|  |- cli.py                      # direct Kraken Futures CLI: balance, position, limit, market, amend, cancel
|  `- smoke.py                    # paced smoke-test runner with exchange/market aware order plans
|- bot/                         # active strategy entrypoint layer
|  |- __main__.py                 # bot CLI: run, preflight, run-once
|  |- chronos.py                  # async repetition/dependency supervisor helpers
|  |- domain.py                   # typed strategy, pair, command, and lifecycle dataclasses
|  |- dragon.py                   # event constructors and platform-fact translation
|  |- horus.py                    # pure intent-to-runtime-command translation
|  |- isis.py                     # narrow reducer entrypoint over targeted strategy events
|  |- ogun_executor.py            # paced async command execution boundary
|  |- pair_cycle.py               # pure head/tail lifecycle transition functions
|  |- service.py                  # runtime orchestration, readiness checks, exchange-port routing
|  |- strategy_runtime.py         # active async foreground runtime path
|  |- indicators.py               # reads indicator snapshots from the public DB
|  |- persistence.py              # optional bot-run persistence
|  `- tsv/
|     `- parser.py                # Org strategy table parser and OrderSpec normalisation
|- kraken_contract/
|  `- futures.py                  # Kraken Futures wire contract and order serialisation
|- openapi/
|  `- kraken/
|     `- README.org                 # scaffold for future OpenAPI or Swagger import
|- runtime/
|  |- kola/                       # active runtime shell and transitional order logic
|  `- RUNTIME_LAYOUT.org          # active-vs-archive notes for runtime cleanup
|- archives/
|  `- runtime/                    # archived runners kept only for behavioural reference
|- shared/                      # common exchange and persistence layer
|  |- config.py                   # exchange config resolution and credentials
|  |- kraken_futures.py           # demo/live Kraken Futures endpoint mapping
|  |- binance_futures.py          # demo/live Binance Futures endpoint and DB mapping
|  |- bitmex_futures.py           # demo/live BitMEX endpoint and DB mapping
|  |- logging.py                  # common logger setup
|  |- pruning.py                  # central retention defaults for DB lanes
|  |- runtime_state.py            # combined public/private DB readiness view
|  |- core/
|  |  |- models.py                  # shared dataclasses for positions and order acknowledgements
|  |  |- runtime_commands.py        # typed exchange command request objects
|  |  |- runtime_types.py           # shared enum-like runtime constants
|  |  `- types.py                   # abstract exchange interfaces
|  |- exchanges/
|  |  |- kraken_adapter.py          # Kraken futures, spot, and margin adapter
|  |  |- binance_adapter.py         # Binance futures, spot, cross-margin, and isolated-margin adapter
|  |  `- bitmex_adapter.py          # BitMEX futures and spot adapter
|  `- persistence/
|     |- db.py                      # SQLAlchemy session helpers
|     |- models.py                  # shared persistence models
|     `- retention.py               # lane-scoped pruning helpers
`- tree/                        # market and account state services
   |- kraken.py                   # public Kraken futures/spot/margin book service
   |- account.py                  # private Kraken futures/spot/margin account and order service
   |- binance.py                  # public Binance futures/spot/margin book service
   |- binance_account.py          # private Binance futures/spot/margin account/order service
   |- bitmex.py                   # public BitMEX futures/spot book service
   |- bitmex_account.py           # private BitMEX REST account/order reconciler
   `- service.py                  # shared service helpers for tree modules

orders/                       # example strategy definitions
|- demo_ada.org                 # Org table contract and order-type examples
|- demo_kraken_xbt.org          # Kraken XBT grammar matrix
`- demo_cross_exchange_chain.org # multi-exchange chain scenario

tests/                        # active regression suite
|- bot/                         # bot CLI, parser, and runtime regression tests
|- core/                        # runtime command and shared contract tests
|- exchanges/                   # adapter tests
`- tree/                        # public and private Kraken service tests

Read order for the core code:

  • Start with kolabi/tree/kraken.py and kolabi/tree/account.py to see how the public and private Kraken DBs are fed.
  • Read kolabi/shared/exchanges/kraken_adapter.py next to inspect real order placement, amend, cancel, and REST mapping.
  • Read kolabi/bot/__main__.py and kolabi/bot/service.py to see how run, preflight, and run-once enter the runtime.
  • Read kolabi/bot/tsv/parser.py if you want to map one Org strategy row to one normalized bot strategy.
  • Read kolabi/bot/ for the active strategy runtime and archives/runtime/ only for historical reference.

Misc

Architecture diagrams

Generate UML diagrams of the kolabi package via the helper script:

./scripts/draw_models.sh -e scripts/models_to_exclude.txt -o Diagrams/kolabi.png

Requires “pyreverse“ (provided by “pylint“) and Graphviz’s “dot“ binary.

About

A multi-order hook trading bot for bitMEX and soon other plateforms

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages