This document provides a high-level introduction to DEXBot2, a sophisticated grid trading bot for the BitShares blockchain. It explains the bot's purpose, core architectural principles, and how major system components interact.
For detailed architecture patterns and data flows, see Architecture. For fund accounting mechanics and grid topology, see Fund Accounting Model and Grid Topology & Boundary-Crawl. For practical development guidance, see Development Guide.
DEXBot2 is a grid trading bot that automates market making on the BitShares decentralized exchange. It places orders at geometric price intervals (a "grid") and profits from market oscillations by repeatedly buying low and selling high within a configured price range.
| Attribute | Description |
|---|---|
| Language | Node.js (JavaScript) |
| Target Exchange | BitShares DEX only |
| Strategy | Single deeply-engineered grid strategy with boundary-crawl rebalancing |
| State Management | Copy-on-Write (COW) immutable master grid with transactional commits |
| Concurrency Model | AsyncLock semaphores with atomic fund accounting |
| Configuration | JSON-based profiles (profiles/bots.json, profiles/general.settings.json) |
| Deployment | PM2 process management for multi-bot operation |
Sources: README.md1-16 package.json1-40 docs/architecture.md9-19
The master grid (OrderManager.orders) is immutable—it can only be replaced atomically, never mutated in place. All rebalancing operations work on isolated WorkingGrid clones. The master is only updated after blockchain confirmation succeeds.
Key Components:
| Component | File | Purpose |
|---|---|---|
OrderManager.orders | modules/order/manager.js396 | Frozen master grid (immutable) |
WorkingGrid | modules/order/working_grid.js1-238 | COW wrapper for isolated mutations |
_applySafeRebalanceCOW() | modules/order/manager.js1142-1232 | Rebalance pipeline entry point |
_commitWorkingGrid() | modules/order/manager.js1234-1314 | Atomic commit after blockchain success |
_gridVersion | modules/order/manager.js828 | Version counter for staleness detection |
Guarantees:
Sources: docs/COPY_ON_WRITE_MASTER_PLAN.md1-50 docs/architecture.md197-295 modules/order/manager.js396-415 modules/order/working_grid.js1-40
DEXBot2 implements one deeply-engineered strategy instead of a plugin system. This allows for aggressive optimization and correctness guarantees specific to grid trading mechanics.
Configuration Parameters:
| Parameter | File Location | Purpose |
|---|---|---|
startPrice | profiles/bots.json | Initial grid center ("pool", "market", or numeric) |
minPrice / maxPrice | profiles/bots.json | Grid boundaries (numeric or multiplier like "3x") |
incrementPercent | profiles/bots.json | Geometric step between levels (e.g., 0.5%) |
targetSpreadPercent | profiles/bots.json | Fixed spread width between BUY/SELL zones |
activeOrders | profiles/bots.json | Count of orders per side (e.g., {buy: 5, sell: 5}) |
When an order fills, the boundary shifts to follow price movement:
boundaryIdx--)boundaryIdx++)This "crawl" naturally repositions the grid around the market without manual recalculation.
Sources: docs/architecture.md21-30 docs/FUND_MOVEMENT_AND_ACCOUNTING.md269-322 README.md7-9 modules/order/strategy.js1-50
The OrderManager class acts as a central hub that coordinates four specialized engines:
Engine Responsibilities:
| Engine | File | Lines | Responsibility |
|---|---|---|---|
| Accountant | modules/order/accounting.js | 937 | Fund tracking, invariant verification, fee management |
| StrategyEngine | modules/order/strategy.js | 435 | Boundary-crawl algorithm, rotation logic, partial consolidation |
| SyncEngine | modules/order/sync_engine.js | 1,055 | Two-pass blockchain reconciliation, fill detection |
| Grid | modules/order/grid.js | 1,750 | Geometric grid creation, divergence detection, spread checks |
Sources: docs/architecture.md181-193 modules/order/manager.js1-100 README.md6-16
The Accountant module owns all fund data. Other modules read from it but never write. This prevents race conditions and ensures consistency.
| Component | Code Location | Definition |
|---|---|---|
| chainFree | accountTotals.buyFree / sellFree | Unallocated blockchain balance (liquid capital) |
| virtual | funds.virtual.buy / sell | Reserved for VIRTUAL orders (prevents double-spend) |
| committed.chain | funds.committed.chain | Locked in ACTIVE/PARTIAL orders (on-chain) |
| available | funds.available.buy / sell | True spending power = max(0, chainFree - virtual - fees) |
| btsFeesOwed | funds.btsFeesOwed | Accumulated transaction fees (must be settled) |
Available Funds Formula:
Available = max(0, ChainFree - Virtual - FeesOwed - FeesReservation)
This formula is calculated atomically in modules/order/utils/math.js
Critical Invariants Enforced:
total.chain = chainFree + committed.chaincommitted.grid ≤ total.chainavailable ≤ chainFreeViolations trigger automatic recovery via modules/order/accounting.js
Sources: docs/FUND_MOVEMENT_AND_ACCOUNTING.md6-27 docs/architecture.md560-637 modules/order/accounting.js1-100
DEXBot2 implements six defensive layers to prevent and recover from errors:
Key Mechanisms:
| Layer | Mechanism | File Location |
|---|---|---|
| Input | validateOrder(), validateWorkingGridFunds() | modules/order/utils/validate.js1-200 |
| Concurrency | _gridLock, _fundLock, _fillProcessingLock | modules/order/manager.js431-450 |
| Transactional | Object.freeze(), WorkingGrid | modules/order/manager.js396 modules/order/working_grid.js |
| Verification | _verifyFundInvariants(), evaluateCommit() | modules/order/accounting.js450-550 |
| Recovery | _attemptFundRecovery() (max 5 attempts) | modules/order/accounting.js600-700 |
| Monitoring | logFundsStatus(), getPipelineHealth() | modules/order/logger.js |
Sources: docs/architecture.md1030-1115 README.md11-13 modules/constants.js449-520
Entry Point Characteristics:
| File | Purpose | Use Case |
|---|---|---|
| dexbot.js | CLI with commands (keys, bots, start, stop, reset) | Development, testing, management |
| bot.js | Direct bot launcher (reads BOT_NAME env var) | Single bot operation |
| pm2.js | Generates ecosystem.config.js and starts via PM2 | Production deployment |
Key Lifecycle Methods:
| Phase | Method | File Location |
|---|---|---|
| Initialize | constructor() | modules/dexbot_class.js50-150 |
| Authenticate | initialize() | modules/dexbot_class.js200-300 |
| Bootstrap | _initializeAccount() | modules/dexbot_class.js400-500 |
| Load Grid | loadBotGrid() | modules/account_orders.js100-200 |
| Reconcile | performStartupReconciliation() | modules/order/startup_reconcile.js1-100 |
| Trading Loop | run() | modules/dexbot_class.js600-700 |
Sources: docs/architecture.md506-577 modules/dexbot_class.js1-200 README.md17-33
The following diagram bridges system concepts to concrete code entities:
Component Size and Complexity:
| Component | Lines | Complexity | Critical Methods |
|---|---|---|---|
DexBotClass | 3,132 | Very High | processFilledOrders(), _performGridChecks() |
OrderManager | 1,513 | Very High | _applySafeRebalanceCOW(), _commitWorkingGrid() |
Grid | 1,750 | High | createOrderGrid(), checkAndUpdateGridIfNeeded() |
SyncEngine | 1,055 | High | synchronizeWithChain(), syncFromFillHistory() |
chain_orders.js | 1,021 | High | updateOrdersOnChainBatch(), buildCreateOrderOp() |
Accountant | 937 | High | recalculateFunds(), _verifyFundInvariants() |
Sources: README.md1-16 docs/architecture.md115-177 package.json1-40 modules/order/manager.js1-50 modules/dexbot_class.js1-50
DEXBot2 uses fixed-cap batching to process fills efficiently while maintaining safety:
Batch Sizing Rules:
| Queue Depth | Behavior | Configuration |
|---|---|---|
| ≤ 4 fills | Single unified batch (all at once) | modules/constants.js413 MAX_FILL_BATCH_SIZE: 4 |
| > 4 fills | Chunked at 4-fill boundaries (repeated batches) | Same constant |
Performance Impact:
Sources: docs/architecture.md297-387 docs/FUND_MOVEMENT_AND_ACCOUNTING.md92-140 modules/constants.js399-414 modules/dexbot_class.js800-1000
Key Configuration Files:
| File | Purpose | Example Parameters |
|---|---|---|
| profiles/bots.json | Bot definitions | startPrice, minPrice, maxPrice, incrementPercent, activeOrders |
| profiles/general.settings.json | Global settings | BLOCKCHAIN_FETCH_INTERVAL_MIN, RUN_LOOP_MS, MAX_FILL_BATCH_SIZE |
| profiles/keys.json | Encrypted keys | AES-256-GCM encrypted private keys |
| profiles/ecosystem.config.js | PM2 config | Auto-generated from bots.json |
Sources: README.md115-168 docs/architecture.md506-577 modules/constants.js1-110
DEXBot2 is a production-ready grid trading bot with:
For detailed architecture patterns, see Architecture. For fund mechanics, see Fund Accounting Model. For development guidance, see Development Guide.
Sources: README.md1-303 docs/architecture.md1-100 docs/developer_guide.md1-50 CHANGELOG.md1-100
Refresh this wiki