passivbot Documentation

repository·master·Indexed 24 days ago

https://github.com/enarjord/passivbot

A cryptocurrency trading bot written in Python and Rust for perpetual futures markets. It operates as a contrarian market maker using grid-based and trailing orders, featuring a Martingale-inspired strategy, an unstucking mechanism, and a Forager for dynamic market selection. The project includes a Rust runtime (passivbot_rust v0.1.0) and provides tools for configuration migration from v7 to v8.

Tokens
133.2K
Snippets
181
Records
677
Agent score
84%

What's inside passivbot

  1. Getting started with Passivbot

    master

    Passivbot is a trading bot written in Python and Rust designed for perpetual futures markets. To begin using the bot, follow these primary steps:

    1. Installation: Set up the Python and Rust environments required to run the bot.
    2. Configuration: Use the Config Workflow and Configuration guides to create or update your trading settings.
    3. Execution: Choose a workflow based on your goal: running live trades, performing backtesting, or optimizing existing strategies.
  2. Supported Live-Exchange Connectors

    master

    Passivbot provides production-ready live connectors for the following exchanges:

    • Binance
    • Bybit
    • Bitget
    • Bitunix
    • OKX
    • Gate.io
    • KuCoin
    • Hyperliquid
    • WEEX

    Important Notes:

    • Defx: This is a legacy placeholder and is not a supported connector for live operation or authenticated probes. It lacks support for realized PnL, unstuck, and HSL replay.
    • Paradex: This is an experimental connector. It is outside the supported production boundary and lacks complete contracts for live fill/PnL, unstuck, and HSL replay.
    • CCXTBot (Generic Fallback): This is for arbitrary exchange names and is outside the supported production boundary. It is used for unaudited CCXT venues and does not guarantee authoritative normalization of order types, position sides, or quantities.
  3. What is Forager Mode

    master

    Forager mode is Passivbot's dynamic coin-selection system. It determines which symbols should occupy the limited entry slots available at any given time.

    The system follows a three-step sequence:

    1. Pruning: Removes weak candidates based on volume (forager_volume_drop_pct).
    2. Ranking: Ranks the remaining candidates using a weighted score.
    3. Filling: Fills available shortlist slots based on that ranking.

    This allows you to control the tradeoff between liquidity, volatility, and entry readiness directly via configuration.

  4. Overview of Passivbot configuration optimization

    master

    Passivbot configurations can be optimized using a multi-objective evolutionary algorithm. This process allows you to balance different performance metrics (scoring objectives) while ensuring the resulting configuration adheres to specific constraints.

    Key resources for configuration:

    • Canonical Defaults: Located in src/config/schema.py.
    • Example Configuration: configs/examples/default_trailing_martingale_long.json is an exact mirror of the canonical defaults.
  5. Interaction between TWEL auto-reduce and `max_realized_loss_pct`

    master

    TWEL auto-reduce orders are not an emergency bypass for risk management. They must pass through the existing max_realized_loss_pct gate.

    • Blocking: If a TWEL auto-reduce order would realize a loss exceeding max_realized_loss_pct, the order will be blocked.
    • Risk Warning: If max_realized_loss_pct blocks TWEL repair while the current TWE remains above twel_repair_target, the bot will emit a loud risk warning containing the side, current TWE, repair target, policy, number of candidates, and number of blocked orders.
    • Exception: The only exception is ClosePanicLong and ClosePanicShort orders. These panic close orders bypass max_realized_loss_pct regardless of whether they were triggered by HSL panic-close handling or another explicit panic-mode path.
  6. Understand the Live Execution Gatekeeper Architecture

    master

    The Live Execution Gatekeeper is a multi-layered system designed to ensure trading safety by separating strategy intent from exchange execution. The architecture consists of four primary components:

    1. Rust Orchestrator: The source of truth for 'ideal' order behavior. It determines what the strategy wants to do based on market data.
    2. ActionPlanner: Reconciles the ideal orders from Rust against the actual state of the exchange (open orders, positions, etc.) to produce a concrete ActionPlan.
    3. Gatekeeper: Evaluates the ActionPlan against a 'freshness contract' (e.g., checking if market data or account balances are sufficiently recent) to decide if an action is safe to execute.
    4. Executor: A narrow component responsible only for constructing and sending the approved exchange payloads and recording the results.

    This separation ensures that even if the strategy (Rust) suggests an order, the Gatekeeper can block it if the underlying data (like candles or balance) is stale or unreliable.

  7. Enable Opt-in Debug Profiles for Observability

    master

    Passivbot supports opt-in structured debug enrichment via the logging.live_event_debug_profiles configuration or the PASSIVBOT_LIVE_EVENT_DEBUG_PROFILES environment variable. Enabling these profiles provides deeper insights into specific events without changing trading behavior or console output.

    Available debug profiles include:

    • ema (or ema-readiness): Enriches ema.unavailable events with parsed EMA type, span, and inner reason summaries.
    • remote_calls: Enriches candle remote-fetch and authoritative state-fetch events with key shape, timing/correlation fields, and status/surface/kind.
    • candles: Enriches candle.tail_projected and candle.coverage_checked events with timeframe/window and missing-coverage counters.
  8. KuCoin Futures: Hedge Mode and Position Side Normalization

    master

    Even if the strategy setting live.hedge_mode=false is used (which disables simultaneous long/short strategy exposure), the KuCoin connector keeps the exchange account in hedge mode.

    Key behaviors for KuCoin Hedge Mode:

    • Position Side: You must rely on explicit info.positionSide or info.posSide from the exchange. Never infer a resting order's position side from the current position.
    • Order Side: In hedge mode, the entry/close-only effect is derived from the combination of the authoritative buy/sell action and the long/short tuple, especially when KuCoin omits the native reduceOnly field.
  9. TWEL Policy Interaction with Bot Modes

    master

    The TWEL auto-reduce mechanism interacts differently with various bot operational modes. While auto-reduce measures exposure from all open exchange positions (including manual and panic), the selection of which positions to reduce is restricted by the mode:

    • normal, graceful_stop, and tp_only: The bot chooses repair candidates only from managed open positions.
    • manual and panic: The bot will not emit TWEL auto-reduce orders for these positions, even if the total exposure exceeds the target. This prevents the enforcer from overriding manual or emergency exit logic.
  10. Understand data source priority for stock perps

    master

    The CandlestickManager automatically selects the best data source based on the following priority:

    1. Local cache: If available.
    2. Hyperliquid API: Provides the last ~3.5 days (5000 1m candles) of native perp data with oracle pricing. Best for live trading and recent backtesting.
    3. Yahoo Finance: Provides the last 7 days of 1m data for free. Limited to market hours only (no weekends).
    4. Configured TradFi provider: Used for older historical data (requires API key).
  11. Understand the Live Logging Event Contract

    master

    The LiveEvent is a structured data object used for real-time observability. It is designed to be serialized into NDJSON for structured sinks. A LiveEvent includes a stable set of fields for tracking bot state, order waves, and exchange interactions.

    Core Fields:

    • schema_version: Version of the event schema.
    • event_id: Unique identifier for the event.
    • event_type: The category of the event (e.g., bot.started, cycle.completed).
    • ts_ms / monotonic_ms: Timestamps.
    • level: Logging level.
    • source / component: Origin of the event.
    • tags: Metadata tags.
    • exchange / user / bot_id / symbol: Contextual identifiers.
    • pside / side: Order side information.
    • order_id / client_order_id: Order identifiers.
    • cycle_id / snapshot_id / plan_id / action_id / order_wave_id: IDs used to reconstruct the lifecycle of a single trading cycle or order wave.
    • status / reason_code / message: Outcome information.
    • data: The event payload.
    • raw_ref / raw_hash: References to raw payloads (subject to redaction and policy).
  12. Understand the trailing_grid_v7 compatibility strategy

    master

    In Passivbot v8, trailing_martingale is the canonical strategy. To support users transitioning from v7, a deprecated compatibility strategy called trailing_grid_v7 is provided.

    Key characteristics of trailing_grid_v7:

    • It preserves the original v7 trailing-grid behavior.
    • It is intended as a bridge to move v7 users onto the v8 infrastructure.
    • It is a deprecated strategy; new optimization work should target trailing_martingale or other native v8 strategies.
    • The migration helper converts v7 configs into v8-shaped configs using trailing_grid_v7, but it does not convert them into trailing_martingale.