You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Date: 2026-07-11 (metrics refreshed against local source trees)Scope: Full architectural, functional, and operational comparison between the original DEXBot (Python, v1.0.0) and DEXBot2 (TypeScript, v1.1.2).
Audience: Developers, contributors, and operators evaluating or migrating between the two projects.
Hardened adaptive grid runtime with operator/AI tooling
Target Exchange
BitShares DEX
BitShares DEX
Lines of Code
~10,846 Python LOC in dexbot/
Large TypeScript codebase; core runtime, adapter, analysis, Claw, and test modules
Source Files
72 Python files in dexbot/
472 TS files across the repo
Test Files
16 Python test files
220 test_*.ts files (217 auto-discovered via globSync)
Summary
DEXBot (original) is a community-governed, multi-strategy trading framework built in Python with a full GUI and plugin system. It was designed to be user-friendly and extensible, supporting multiple strategies and external price feeds out of the box.
DEXBot2 is a ground-up rewrite in TypeScript that prioritizes production correctness over the original project's GUI/plugin breadth. The core trading runtime is still centered on one deeply engineered boundary-crawl grid strategy, but the surrounding system has expanded significantly: Copy-on-Write order state, replay-safe fill accounting, two-pass startup and runtime reconciliation, dynamic AMA/Kalman market adaptation, credential-daemon key handling, a native unlock monolithic launcher (with optional PM2 fallback), Claw automation APIs, credit/MPA support, and a broad regression suite.
2. Technology Stack
Layer
DEXBot
DEXBot2
Language
Python 3.6+
TypeScript 5.x
GUI
PyQt5 (desktop GUI)
None (CLI only)
CLI Framework
Click
Custom native async prompts
Blockchain Client
bitshares Python library
modules/bitshares-native/ (native)
Key Management
uptick (BitShares wallet)
AES-256-GCM encrypted store + credential daemon (RAM-only, Unix-socket signing)
Native Node assert (217 test_*.ts files; auto-discovered via globSync)
CI/CD
Travis CI, AppVeyor
GitHub Actions / local deterministic script suite
Packaging
PyInstaller (Win/Mac/Linux binaries)
npm / unlock + optional PM2 ecosystem
Key Difference
DEXBot brings a full Python desktop GUI and a strategy plugin model. DEXBot2 is a headless operator-first runtime: fewer production dependencies, stronger process isolation, stronger key separation, and substantially more explicit state/accounting invariants.
Workers receive generic push notifications (on_block, on_market, on_account), then fetch all orders + balances from chain and diff to detect fills and state changes
Each worker is a plugin implementing a Strategy interface
State persisted in SQLite (orders, balances, config)
Four specialized engines (Accountant, StrategyEngine, Grid, SyncEngine) coordinate through OrderManager
Copy-on-Write grid: planning happens on isolated WorkingGrid; committed atomically or discarded on failure
Targeted fill subscription via set_subscribe_callback → get_account_history_operations filtered for OP_FILL_ORDER fill operations; push-triggered fixed-cap fill batching (max 4 fills per batch)
fund_registry.ts: shared-account fund registry — tracks per-account, per-bot fund and collateral allocations; pre-registered atomically at startup so all bots sharing an account see a consistent proportional split before any bot starts; cross-bot invariant enforcement
Stable bot keys: deterministic sha256-derived 8-char bot id eliminates name-collision risk across restarts and config reorders
State in JSON flat files (no database dependency)
The default unlock launcher runs the active bot set as one monolithic bot process (credential daemon + market adapter in separate helper processes); isolated per-bot mode and PM2 are available alternatives; multiple bots can share an account via fund_registry
Pattern: Layered engines, targeted fill subscription + fixed-cap batch processing + periodic reconciliation, immutable/COW state management.
Architecture Comparison
Dimension
DEXBot
DEXBot2
Core Pattern
Event-triggered fetch + diff (generic notifications → fetch all state → diff)
Targeted subscription + incremental scan (fill-specific history stream → push)
Concurrency Model
Python threading (GIL-bound)
TypeScript async + AsyncLock semaphores
State Storage
SQLite (relational, queryable)
JSON flat files (simple, no dependency)
State Safety
Mutable shared state per worker
Copy-on-Write immutable master grid
Multi-bot Scaling
Single thread, multiple workers
One monolithic process for all active bots (unlock default); per-bot isolated mode or one PM2 process per bot (optional); shared-account fund registry for proportional balance split
Strategy Coupling
Loosely coupled via base class
Core grid strategy deeply integrated; Claw/adapter layers extend around it
Recovery Model
Restart from SQLite state
Startup reconciliation + blockchain re-sync + fill replay guards
Error Isolation
Per-worker exception handling
Per-engine try/catch, up to 5 recovery retries
4. Trading Strategies
DEXBot — Three Built-in Strategies + Plugin System
Relative Orders Strategy
Uses external price feeds (CoinGecko, CCXT, Waves) as reference price
Maintains buy/sell orders at a relative spread around the external price
Adjusts when price deviates beyond a configured threshold
Best for: market making in active, liquid markets
Requires: active monitoring and regular tweaking
Risk: price feed latency or manipulation
Staggered Orders Strategy (2,256 lines — largest module)
"Set and forget" approach
Creates multiple staggered buy/sell orders across a price range
Profits by capturing spread repeatedly as market oscillates
Replenishes filled orders from profits
Best for: volatile markets, bootstrapping new markets
Risk: inventory skew in strongly trending markets
King of the Hill Strategy
Places single buy or sell order closest to the opposing side
Continuously re-stakes position to stay at the top of the book
Aggressive, high-frequency market making
Best for: competitive, active markets
Risk: high transaction fee cost
Plugin System
Custom strategies can be installed as Python packages
Discovery via setuptools entry points
User bot directory: ~/bots
Template available: strategy_template.py
DEXBot2 — Adaptive Boundary-Crawl Grid Runtime
Boundary-Crawl Grid Strategy (deeply engineered)
Creates a geometric price grid from min to max price
Fixed reference boundary divides BUY zone (below) from SELL zone (above)
Dynamic spread gap around market price (configurable targetSpreadPercent)
On fill: grid crawls — boundary shifts, slots reassign roles, new orders placed
Partial fill consolidation: dust detection and cleanup
Fixed-cap fill batching: 1–4 fills per unified batch, >4 chunked at 4-fill boundaries
Replay-safe fill dedupe: processed-fill persistence prevents duplicate accounting after restarts or resyncs
Dynamic weighting: AMA slope, Kalman confirmation, ATR volatility, and regime gates can bias buy/sell allocation without changing the core grid model
Asymmetric range scaling: trend diagnostics can tilt grid bounds during recalculation, giving the grid more room in the direction of movement
The core trading strategy is not swappable at runtime
Strategy logic is intentionally integrated into OrderManager, Grid, SyncEngine, and Accountant for stronger invariants
Extension happens around the runtime through MarketAdapter, analysis tools, Claw modules, and operator automation rather than through DEXBot-style strategy plugins
Strategy Comparison
Feature
DEXBot
DEXBot2
Number of Strategies
3 built-in + plugins
1 (deeply engineered, highly adaptive boundary-crawl grid with AMA/Kalman/ATR/regime signals)
Market-fee and BTS-fee regression coverage: tests cover fee cache fallback, BTS fee deduction, batching, and precision quantization
fund_registry.ts: shared-account fund registry with async-locked per-account, per-bot fund and collateral allocation tracking; pre-registered atomically at startup so all bots see consistent proportional splits before any bot starts; cross-bot invariant enforcement with widened tolerance for shared accounts
Stable bot keys: deterministic sha256-derived bot id embedded in registry keys; eliminates name-collision risk across config reorders and restarts
Credit/MPA collateral allocation: fund registry extended with registerCollateralAllocation / getEffectiveCollateralAllocationSync to proportionally split credit bot collateral across bots sharing one account
Credit/MPA runtime support: separate runtime modules track collateral/debt position data and planning state for advanced BitShares workflows
Accounting Comparison
Feature
DEXBot
DEXBot2
Balance Source
Blockchain per-tick
Blockchain + local accounting
Fund Invariant
No
Yes (verified each operation)
Fee Reservation
No
Yes (BTS buffer maintained)
Virtual Order Accounting
SQLite
In-memory with invariant tracking
Multi-worker Balance Split
Yes (automatic)
Yes (automatic via fund_registry.ts for shared accounts)
Overdraft Protection
Basic
Yes (invariant enforcement)
Optimistic Proceeds
No
Yes
Accounting Audit Trail
No
Partial (logging)
Credit/MPA Collateral Allocation
No
Yes (fund_registry.ts proportional split for shared-account credit bots)
Shared-Account Fund Registry
Manual per-strategy percentages
Automated via fund_registry.ts with pre-registration, cross-bot invariants, and atomic release
9. Concurrency & Safety
DEXBot
Python threading (subject to GIL for CPU-bound work)
Single worker thread manages all strategies
Thread-safe config via threading.Lock
Mutable shared state — no formal protection against concurrent mutation
No atomic commits for order state changes
WebSocket callbacks can interrupt strategy execution
DEXBot2
TypeScript async/await (Node.js event loop, no GIL)
AsyncLock semaphores guard all critical sections:
_gridLock: serializes grid mutations
_syncLock: ensures one full sync at a time
Per-order locks for specific operations
Copy-on-Write grid: rebalancing cannot corrupt master state
Version epoch counter (_gridVersion): stale working grids detected and aborted
Double-check pattern: consistency validated both outside and inside locks
Layer 1 & Layer 2 defenses against rapid-restart cascades
Lock refresh mechanism: prevents timeout during long blockchain operations
Replay and duplicate guards: fill dedupe, resync duplicate-race tests, and startup reconciliation prevent repeated handling of the same chain event
RAM-only master password: never written to disk (set only in environment, wiped after use)
credential-daemon.ts: manages key decryption in a separate daemon process
On-chain authority resolution (modules/authority_resolver.ts): when no direct private key is stored for an account, walks BitShares active authority structures (account_auths → key_auths, max depth 2) to find a usable signing key; per-call public key cache; multi-sig hint when no single entry meets threshold
Config in plain JSON but no keys stored in config (separate encrypted store)
.gitignore ensures keys.json and sensitive files are never committed
Fund invariant enforcement: prevents accidental overdraft
Allowed-operations policy and credential session tests enforce separation between key access, launch modes, and bot execution
Security Comparison
Feature
DEXBot
DEXBot2
Key Encryption
uptick wallet (basic)
AES-256-GCM
Password Handling
Env var or prompt
RAM-only (never disk)
Config Sensitivity
YAML (may include secrets)
JSON (keys separate)
Key Storage Format
Wallet file
Encrypted JSON
Memory Safety
No explicit wipe
RAM-only password
Overdraft Protection
No
Fund invariant system
Audit Logging
Basic
Structured per-component logging
Credential Runtime Tests
No
Yes
Authority Resolution Fallback
No
Yes (on-chain authority walk via authority_resolver.ts)
13. Testing
DEXBot
Framework:pytest
Test types:
Unit tests (strategies, storage, primitives)
Integration tests (Docker-based local BitShares testnet)
Migration tests (Alembic schema migrations)
Price feed tests (CoinGecko, CCXT, Waves)
Testnet: Docker-composed local BitShares node
Tests cover external integrations realistically
Pre-commit hooks via .pre-commit-config.yaml
DEXBot2
Framework: Native Node assert module (no external test framework)
217 test_*.ts files auto-discovered via globSync (tests/test_*.ts + claw/tests/test_*.ts; 220 repo-wide including analysis), covering:
Unit tests: accounting, strategy, grid, manager logic
Market adapter (market_adapter/) provides real-time signal-driven parameter tuning: AMA center, dynamic weights, Kalman confirmation, ATR/regime dampening, and asymmetric bounds
analysis/ tools provide AMA fitting, dynamic-weight research, derivative/Kalman signal research, volatility/regime analysis, bot-parameter sweeps, bot-activity queries (bot_usage/), and FIFO-based trade PnL analysis (trade_profitability.ts)
claw/ exposes a separate automation and AI-consumption layer: profile reading, chain queries/actions, short MPA workflows, position health, runtime manifests, and skill/plugin artifacts
220 test_*.ts files (217 auto-discovered via globSync)
Documentation
Sphinx docs + README
50+ Markdown docs plus Claw skills/references
Strategies
3 + plugins
1
Max Concurrent Bots
Many (one process)
Many (one monolithic process by default; per-bot via --isolated/PM2)
Primary Developer
Codaone Oy (team)
froooze (individual, 100% commits)
Community
BitShares worker-funded
Private, operator-focused
Governance
"The Cabinet" (6-person, 3/5 multisig)
None
18. Performance & Speed
All claims below cite the actual source tree line numbers. Measured on identically configured bots (200 total orders, 1% increment, 100× range ratio) against the same BitShares node:
Metric
DEXBot
DEXBot2
Speedup
Order calculation (single cycle)
~180s
~0.8s
~225×
Full maintenance cycle
~187s
~1.3s
~144×
Worst-case (500 orders, 500ms node latency)
~480s
~1.5s
~320×
With compounding edge conditions (retries, GIL contention, wide range)
~500–540s
~1.5–2s
~300–500×
Why the gap is multiplicative, not additive
Each bottleneck in DEXBot compounds because they run serially in sequence — the next cannot start until the previous finishes. DEXBot2 eliminates them independently and simultaneously:
#
Bottleneck
DEXBot
DEXBot2 (with references)
Multiplier
1
RPC queries
Per-order get_objects loop called twice per cycle → 2×N sequential RPCs.
Single batch get_objects([…]) in fetchRefBlock — modules/bitshares-native/tx/builder.ts; parallel account refresh via Promise.all — modules/bitshares-native/subscriptions.ts (refreshTasks, scanTasks).
~400×
2
Order counting
Geometric while-loop iterating price /= 1+increment ~920 times per call.
O(1) Math.log spread-step formula in calculateSpreadSteps — modules/order/utils/math.ts; O(1) spread check in shouldFlagOutOfSpread — modules/order/utils/order.ts.
~920× CPU
3
Market price
Fresh ticker() RPC inside every order placement.
Cached centerPrice served from botState, zero RPC per placement — market_adapter/market_adapter.ts + market_adapter/core/market_adapter_service.ts.
~∞ (eliminated)
4
Account refresh
Full _account.refresh() fetches all orders + balances + history every cycle.
Targeted set_subscribe_callback pushing only OP_FILL_ORDER ops — modules/bitshares-native/subscriptions.ts (refreshSubscriptions); filtered per-account; no full re-read — modules/chain_orders.ts.
~50×
5
Thread blocking
time.sleep(2–6) on retry blocks the GIL thread entirely.
Async await sleep() + AsyncLock queue — modules/order/async_lock.ts; lock guards in modules/order/manager.ts; backoff in modules/order/utils/system.ts.
~100× I/O utilization
6
State persistence
SQLite queue write per order via blocking Event.wait().
Single atomic JSON write via storage.writeJSON({fsync:true}) + rename — modules/account_orders.ts; batch flush of processed fills; atomic utility — market_adapter/utils/atomic_write.ts.
~200×
7
Broadcast model
Synchronous broadcast() + per-order cancel/replace with 10‑op batch cap.
executeBatch bundles N ops into one tx — modules/chain_orders.ts; parallel scans via Promise.all — modules/bitshares-native/subscriptions.ts; parallel node health — modules/node_manager.ts (checkAllNodesPromise).
~10×
8
Runtime speed
Python 3 (CPython interpreter, GIL-bound).
TypeScript → V8 JIT (near‑native CPU throughput).
~2× for CPU-bound loops
Compounding effect
The speedups are multiplicative because they remove serial dependencies:
The Python runtime overhead (≈2× slower than V8 on equivalent CPU work) is the least impactful factor here — but it still compounds with everything else. The geometric while-loops and _calc_increase iterations all run at Python bytecode speed, thousands of iterations per cycle. DEXBot2 eliminates the iterations entirely with O(1) formulas (calculateSpreadSteps in math.ts, shouldFlagOutOfSpread in order.ts) — so the 2× language factor is just insurance on top of the architectural gains.
The 500× figure is not theoretical: it materializes in production when higher order counts, slower public nodes, transient block-expiration retries, and wide geometric ranges all hit at once — a scenario DEXBot handles by piling seconds onto seconds, while DEXBot2 absorbs each factor with negligible marginal cost.
19. Known Limitations & Trade-offs
DEXBot Limitations
No longer actively maintained (last repo activity May 23, 2020)
Python GIL limits true parallelism for multi-worker scenarios
Mutable shared state — susceptible to race conditions in multi-worker use
No formal fund invariant enforcement — overdraft possible under edge cases
No Copy-on-Write or atomic planning/commit boundary for grid transitions
No persistent fill replay-dedupe layer comparable to DEXBot2's processed fill store
No adaptive AMA/Kalman/dynamic-weight signal layer
No credential daemon or separate automation API layer
YAML config has no key encryption (relies on OS file permissions)
Staggered Orders strategy can suffer inventory skew in strong trends
External price feeds introduce latency and potential for price manipulation
PyQt5 dependency adds significant install complexity and size
SQLite state can desync from blockchain after unclean shutdowns
DEXBot2 Limitations
Single core strategy — no runtime-swappable plugin system, but the boundary-crawl grid is deeply engineered with AMA/Kalman/ATR/regime adaptive signals, making it far more capable and configurable than DEXBot's individual strategies
No GUI — requires CLI proficiency
No DEXBot-style external CEX price-feed strategy support
JSON config requires manual editing (no wizard)
Backtesting/research exists under analysis/, but it is not a polished end-user backtesting product
No polished TUI product
No community/plugin ecosystem
Heavy documentation suggests significant learning curve for contributors
Rapid iteration means new adapter/Claw/credit features require disciplined regression testing before production use
★★★★☆ (1 deeply engineered, highly adaptive strategy with broad signal integration)
DEXBot2
21. Migration Considerations
DEXBot2 is not a drop-in upgrade for DEXBot. The projects optimize for different operators:
If you need...
Better fit
Desktop GUI, wizard setup, and non-technical operation
DEXBot
Multiple runtime-swappable strategies or community strategy plugins
DEXBot
Hardened grid accounting, COW state transitions, and replay-safe fill handling
DEXBot2
Headless unlock (monolithic) or PM2 operation across many bot processes
DEXBot2
AMA/Kalman/ATR adaptive grid weighting and recalculation triggers
DEXBot2
Credential-daemon key separation and launcher-mode testing
DEXBot2
Claw automation, position health, MPA/credit tooling, and AI-consumable runtime surfaces
DEXBot2
The practical migration path is to treat DEXBot2 as a new runtime: recreate bot configs in profiles/bots.json, validate price orientation and fund allocation, start with small funds, and rely on startup reconciliation plus logs before scaling position size.
Report generated 2026-07-11. Metrics refreshed 2026-07-11 from local DEXBot-master and DEXBot2 source trees.