Version 1.3 Open source · MIT Python 3.11+ Long & Short Self-hosted

Algorithmic crypto futures trading, with the safety rails built in.

CROT — CryptoRoboTrading — is an open-source Python bot for USDT-M perpetual futures. Its common engine keeps execution safety, exchange transport, state, and telemetry separate from switchable strategy plugins. Free to use, inspectable end to end, and honest about the risks.

HTX v5 private API · CCXT public data · strategy plugin contract API v2

Futures trading involves substantial risk of loss. This is software, not financial advice.

What it is

A standalone trading application — not another exchange template

If you have only used the bot constructors built into exchanges, think of this as the next level of control. Instead of picking a grid template and a few sliders, you run a full trading program on your own machine, connected to your exchange account (HTX today) through official API keys. Everything it does is visible: the source code, the configuration, and a line-by-line log of every trade decision.

Your infrastructure

Runs on your PC or a small VPS. Your API keys stay in a local file on your machine — they are never uploaded anywhere, never logged, and never committed to version control. Funds remain in your own exchange account at all times.

Your rules

Choose a strategy plugin by name. Its typed settings, documented ranges, and optional TOML overrides are validated before the engine can contact the exchange; typos and unsafe values fail loudly instead of silently keeping an old default.

Your data

SQLite is the primary analytical store for trade events, cycles, signals, diagnostics, candidates, and market candles. Read-only reports, replay, and forward labeling let you evaluate a strategy on evidence rather than marketing claims.

How it compares to exchange bot constructors

Exchange constructors
(grid / DCA templates)
This bot
(standalone, open source)
Strategy logic Fixed templates, a few sliders Full multi-layer strategy: trend, pullback, trigger, quality gates, ranking
Tunable parameters Typically 5–15 Typed per-strategy manifest, validated TOML overrides, JSON Schema output
Source code Closed — you trust the exchange's black box Open source (MIT) — audit every line before you fund it
Stop-loss Varies; often software-side or absent Reduce-only hard stop placed on the exchange from entry — active even if your server dies
Exchange lock-in Total — the bot lives and dies with that exchange The strategy and risk engine are yours; HTX today, built on CCXT to add exchanges
Records & analytics Summary numbers in a dashboard SQLite WAL telemetry, JSONL fallback, read-only reports and replay tools
Cost Often subscription or profit share Free. You pay only normal exchange fees
What you provide Nothing — it runs on their servers A machine that stays on (any PC or a ~$5/mo VPS) and basic terminal comfort

The last row is the honest trade-off: you host it yourself. In exchange, you get full control, full transparency, and zero recurring fees.

Version 1.3 update

A strategy-neutral trading engine — rebuilt from storage to execution

Version 1.3 is an architecture release, not a bundle of new presets. Storage, private exchange transport, market data, configuration, runtime safety, research, tests, and deployment have all changed so strategies can evolve independently from the engine.

v1.3architecture release
Engine ↔ strategy Plugin contract API v2

Versioned hooks, state schema, capabilities, and a stable StrategyContext.

Bot ↔ exchange HTX private API v5

Signed account, position, and order calls for HTX's current private surface.

Lifecycle & safetyCombinedEnginelocks · state · exchange · protection
Selected by nameStrategy pluginsignal · sizing · entry · exit
Evidence layerSQLite + researchtelemetry · replay · reports
01

Engine and strategy are separate

  • The engine owns credentials, account routing, exchange transport, precision, locks, persisted state, private sync, lifecycle, and shutdown.
  • Plugins own signals, selection, sizing, entry, exit, and their own typed strategy_state.
  • Mandatory reduce-only and close-order checks stay in the engine, ahead of strategy hooks.
02

Switch strategies without rewriting the bot

  • STRATEGY=btc_countertrend_grid_v1 selects the current default.
  • ema_pullback_lermont keeps the earlier EMA approach in an isolated, attributed adapter.
  • xsec_reversion_v1 is an experimental measurement package, while example_minimal is the developer template. External packages can register through Python entry points.
03

SQLite becomes the analytical source of truth

  • WAL storage with six typed tables for trades, cycles, signals, diagnostics, candidates, and candles, plus lossless sanitized JSON payloads.
  • Writes are fail-open: trading state and locks remain independent files; CSV is a write fallback and rich JSONL remains an emergency trail.
  • Idempotent import, integrity verification, online backup, read-only reports, candle archives, replay, and forward-label studies are included.
04

Native HTX v5 plus live order-book data

  • A signed HTX v5 client handles the private account, position, and order endpoints required by current account modes; public data still uses CCXT.
  • A reconnecting HTX WebSocket consumes 20 levels of depth.step6 and shares the cache across long and short profiles.
  • Stale cached prices cannot trigger a target: the engine requires fresh executable BBO, with an uncached public REST fallback.
05

Safer combined runtime

  • One process can run long and short with a shared exchange wrapper, market cache, private snapshot, symbol reservations, and equity guard — but separate state, locks, and direction rules.
  • Strategy-state mismatches with open exposure fail closed; unknown closing orders are adopted or handled by the common safety layer.
  • Reusable client order IDs, atomic file writes, heartbeat, and an external watchdog make retries and recovery observable.
06

Validated configuration and portable delivery

  • Secrets and infrastructure stay in .env; each plugin declares typed defaults and optional, range-checked TOML overrides.
  • The same manifest produces grouped documentation and JSON Schema, and invalid keys or values are refused before any exchange call.
  • An idempotent build.sh, Docker image, deployment healthcheck, and strategy-agnostic conformance suite support repeatable installs.
Current default strategy

BTC Countertrend Grid is a new execution model, not a renamed EMA setup

Maker-first entry. A five-rung post-only grid can shed unfundable rungs or fall back to one passive order without inflating risk to meet exchange minimums.

Economic preflight. Reward versus fees, spread, stop distance, rounded contracts, minimum notional, margin, and portfolio caps are checked before an order is sent.

Exchange-truth exits. A maker target, exchange-side protection, fresh-BBO confirmation, uncovered-remainder IOC, and a bounded time exit replace cached-price assumptions.

Account-wide guardrails. Planned risk, directional and portfolio exposure, margin, notional, daily loss, and high-water drawdown are enforced as a cascade.

The architecture and automated tests can be validated offline. That does not prove live activation, exchange-side protection on a particular account, or profitability; those require separate operational evidence, and futures remain high risk.

Bundled strategy example

EMA Pullback remains available as an isolated plugin

Version 1.3 defaults to BTC Countertrend Grid, but the earlier EMA Pullback approach is still selectable as ema_pullback_lermont. It trades pullbacks in an established trend: the plugin identifies the slow trend, waits for a dip and recovery on faster charts, and then applies its entry-quality pipeline. The walkthrough below describes that plugin, not a hard-coded engine behavior.

Changing plugins swaps strategy logic and typed strategy state. It does not replace the engine-owned exchange transport, persistence, execution-safety checks, combined lifecycle, or telemetry. That boundary is the central change in version 1.3.

Three timeframe layers

Signals are computed on closed candles only — the bot never reacts to a candle that is still forming, which removes a whole class of false signals.

LayerTimeframeEMAsRole
Macro trend1hEMA 48 / 120 Is there a real trend to trade?
Pullback5mEMA 24 / 72 Did price pull back and start recovering?
Trigger5mEMA 24 / 72 Is short-term momentum aligned right now?

The same logic runs symmetrically in both directions: the long profile buys pullbacks in uptrends, the short profile sells rallies in downtrends. Both run in one process, share market data, and never open opposite positions on the same coin.

Seven quality gates before any entry

An aligned trend is necessary but not sufficient. Before placing a single order, a candidate must clear a pipeline of independent checks:

  1. Choppiness filter — skips coins moving sideways in noise, where trend logic loses money.
  2. Volume confirmation — recent volume must support the move; suspicious single-candle spikes against the position block the entry.
  3. Volume profile — an adverse breakout through the value area is treated as reversal risk, not opportunity.
  4. Relative strength vs BTC — the coin must actually move on its own, not just drift with the market.
  5. BTC 30-minute filter — no longs while Bitcoin is falling hard, no shorts while it is squeezing up.
  6. Cross-exchange price check — if HTX is priced too far above the reference exchange, a long is blocked (and mirrored for shorts).
  7. Composite score ranking — surviving candidates are scored and ranked; only the strongest get capital, and negative indicators multiply the score down rather than being averaged away.

Patient entries

Entries use a ladder of post-only limit orders placed below the market (above, for shorts) — the bot waits for the price to come to it instead of chasing, and earns maker fees rather than paying taker fees.

Throttled by design

Hard limits cap how many new positions can open per signal and per hour. When too many coins signal at once — a classic sign of a market-wide move rather than genuine setups — crowded-market rules tighten every threshold automatically.

Strictly limited averaging

Adding to a losing position is the way most bots die. Here averaging is capped at two stages, requires a minimum drawdown scaled by volatility, a minimum time interval, a fresh recovery signal, and respect for all margin caps — or it simply doesn't happen.

Risk controls

Risk management is the core of the design, not an afterthought

Strategy-specific risk rules can vary, but version 1.3 keeps the non-negotiable execution, state, and account safeguards in the common engine.

Exchange-side protection

The common execution layer validates reduce-only closes, reconciles the real position, and treats incomplete visibility of closing orders as a safety problem. Strategies can request protection; they cannot bypass the engine's close-order invariants.

Economic preflight before entry

The default grid strategy checks rounded contracts, exchange minimums, reward after estimated costs, stop distance, required margin, and portfolio headroom before it sends an order. A target is never raised merely to make a weak trade pass.

Cascading exposure caps

Per-trade planned risk, directional risk, total portfolio risk, margin allocation, planned gross notional, open-position count, loss streaks, and cooldowns are checked as separate limits. Passing one never implies passing the rest.

Persistent equity guard

An atomic account-wide sidecar tracks high-water equity, the UTC day boundary, daily loss, and the entry block. If that guard cannot be read or written reliably, new entries fail closed while position protection and exits continue.

Fresh-data discipline

A stale WebSocket tick cannot trigger a target. The engine falls back to a fresh, uncached public BBO and otherwise keeps reconciling the position and protection without pretending that an executable exit price was observed.

Restart and state safety

State is written atomically and reconciled against the exchange after restart. A plugin cannot reinterpret an open position as another strategy's state; incompatible switches fail closed instead of guessing.

Configuration

Infrastructure in .env. Strategy settings in a validated schema.

Version 1.3 stops mixing secrets, runtime wiring, and trading decisions in one giant file. The selected plugin owns its typed defaults; an optional TOML override is validated before startup and recorded in diagnostics.

  • A clear boundary. API keys, paths, profiles, and infrastructure flags stay in .env; trading parameters live with the selected strategy package.
  • One strategy per combined process. STRATEGY selects a package globally, so long and short cannot silently run incompatible logic or state.
  • Strict validation. Unknown keys, wrong types, out-of-range values, bad choices, and attempts to change identity fields are refused before exchange setup.
  • Machine-readable by design. The same dataclass and annotations produce a manifest, grouped documentation, and JSON Schema for future tools or interfaces.
.env + optional strategy TOML
# .env — runtime wiring
STRATEGY=btc_countertrend_grid_v1
BOT_PROFILES=long,short
STRATEGY_CONFIG=config/conservative.toml
SQLITE_ENABLED=true

# config/conservative.toml — strategy overrides
leverage = 20
risk_per_trade_pct = 0.02
max_simultaneous_positions = 6
Transparency

The bot measures itself — and shows you the data

Most trading tools show you a PnL number and ask you to trust it. This bot records the full context of every decision and ships the tools to analyze that record with real statistical methods.

Complete audit trail

SQLite stores typed trade events, cycle statistics, signal analytics, diagnostics, candidate decisions, and market candles. Full sanitized JSON payloads preserve new strategy fields; rich JSONL remains an emergency human-readable trail.

Built-in research tooling

Read-only reports can point at the active database or a verified snapshot. Replay, forward labels, horizon reports, hold-time studies, factor diagnostics, and candle archives make hypotheses reproducible without writing to the trading database.

Tested, versioned, open

Separate engine, strategy, analysis, and conformance tests run on mocks and stubs without a live API. Generated engine-surface docs and schema checks fail when the plugin contract drifts — repository validation remains deliberately separate from live verification.

Getting started

From zero to a running bot

Four steps. Budget an evening for it: most of the time goes into reading the configuration comments and the launch checklist — which is exactly how it should be.

  1. 1

    Open an HTX futures account

    HTX is the exchange the bot supports today, so you need an HTX account with USDT-M futures enabled. If you don't have one yet, you can register with invite code 6hc25223 — a referral that supports this project at no cost to you. Set the account to cross margin, one-way position mode.

  2. 2

    Create API keys — trading only

    In HTX account settings, create an API key with futures trading permission and withdrawals disabled. The key goes into a local file on your machine and nowhere else.

  3. 3

    Install and configure

    Clone the repository, install dependencies into a virtual environment, and copy the example config:

    terminal
    git clone https://github.com/Lermont/HTX-crypto-bot.git
    cd HTX-crypto-bot
    python -m venv .venv && source .venv/bin/activate
    pip install -r requirements.txt
    cp .env.example .env   # then add your API keys and coin list
  4. 4

    Verify, then launch small

    Run the test suite, keep the default conservative caps, and start with budgets you are comfortable watching closely for the first days:

    terminal
    python -m pytest -q     # all tests should pass
    python bot.py           # runs both long and short profiles

    The repository includes a full pre-launch checklist covering leverage verification, margin mode, and safe first-run budgets. Read it.

FAQ

Straight answers

Will this bot make me money?

No one can promise that, and we won't. The strategy is built to control downside first — hard stop-losses, margin caps, throttled entries — and to document every decision it makes so you can judge it on real data. Markets change, and any strategy can have losing periods. Start with small budgets, review the logs, and scale only when the numbers earn your trust.

Do I need to know how to program?

Not to run a bundled strategy. Secrets and infrastructure settings live in .env; strategy selection is one named value, and optional tuning uses a validated TOML file. You should be comfortable with basic terminal commands, running the test suite, and editing text files. Writing a new strategy plugin does require Python.

Where does the bot run?

On any machine you control with Python 3.11 or newer — your home PC, a mini-PC, or a small cloud VPS (a $5/month instance is plenty). Because it trades continuously, most users run it on an always-on server. A watchdog script is included to restart the bot if it ever stops. Critically, the hard stop-loss is placed on the exchange itself, so your downside protection stays active even if your server goes offline.

Are my funds and API keys safe?

Your funds never leave your own HTX account — the bot only sends signed trading orders through the official API. API keys are stored in a local .env file on your machine and are excluded from logs, config snapshots, and version control. Create API keys with trading permission only and withdrawals disabled: even in the worst case, a leaked key cannot move funds out of your account.

What does it cost?

Nothing. The bot is free and open-source under the MIT License — no subscription, no profit share, no license tier. Your only costs are the exchange's normal trading fees and whatever you pay for a server, if you use one.

Which exchanges does it support?

HTX is the supported exchange today, trading USDT-M perpetual futures. The bot is built on a hybrid transport: CCXT handles public market data while a native HTX v5 client handles the private account and order surface used by current HTX accounts. Exchange transport is engine-owned, so adding another venue does not require rewriting each strategy.

Is the strategy set in stone?

No. Version 1.3 selects a strategy package by name, without changing the engine. The default is BTC Countertrend Grid; an isolated EMA Pullback adapter is included, and third-party packages can register through a standard entry point. Engine-owned execution safety, state, exchange transport, and telemetry remain in place when the strategy changes.

How is this different from the bots built into exchanges?

Exchange bot constructors offer a handful of templates (grid, DCA) with a few sliders. CROT separates a reusable execution engine from versioned strategy plugins, keeps analytical telemetry in SQLite, exposes validated strategy schemas, and ships offline conformance tests and research tools. Because the code is open, every order path and safety rule can be inspected.

Can I test it before risking real money?

Yes. The project ships engine, strategy, analysis, and strategy-agnostic conformance tests that run against mocks and stubs without placing live orders. Passing them proves repository integrity, not profitability or live readiness; permissions, account mode, risk tiers, open positions, and exchange-side protection still require a separate check.

Why are the exchange links referral links?

Full disclosure: the HTX and MEXC links on this page carry a referral code. If you register through them, the project receives a commission from the exchange at no extra cost to you — it is the only monetization this free project has. You are, of course, free to register directly instead.

Read the code first. That's the point.

Everything described on this page is verifiable in the repository — the strategy document, the configuration reference, the test suite, and the full commit history. Start there.