Configuration Guide

Complete reference for configuration settings


Overview

The bot uses a unified configuration system with support for TOML configuration files and environment variables. All variables have sensible defaults and are validated on startup.

Current Version: v0.33.0 uses simplified configuration structure with direct field access.

Configuration Files:

  • config.toml - Main configuration file (instruments, leverage, trading params) - Preferred
  • config.json - Legacy JSON format (still supported for backward compatibility)
  • .env - Local environment configuration for sensitive values

Hot-Reload Support: The bot supports runtime configuration updates for safe parameters without requiring a restart. See Configuration Hot-Reload for details on which parameters can be hot-reloaded.

Configuration Architecture:

  • AppConfig - Single unified configuration structure
  • Direct field access: config.trading.*, config.risk.*, config.leverage.*
  • Environment variables with WEALTH__ prefix override TOML/JSON settings

Loading Priority:

  1. Environment variables with WEALTH__ prefix (highest priority)
  2. TOML/JSON configuration file (config.toml or config.json)
  3. Default values (fallback)

Configuration Sections

The configuration is organized into clear sections:

SectionDescription
instrumentsTrading pairs to monitor
leveragePer-symbol leverage settings
tradingStrategy parameters (spread thresholds, position sizing)
riskRisk management (slippage, trailing stops, fees)
executionExecution mode (paper/live) and resilience
observabilityMetrics, logging, telemetry
licensingLicense configuration

Environment Variable Overrides:

  • All configuration can be overridden via environment variables
  • Prefix pattern: WEALTH__SECTION__FIELD (e.g., WEALTH__TRADING__MIN_FUNDING_SPREAD)

Trading Configuration

WEALTH__TRADING__MIN_FUNDING_SPREAD

Minimum funding rate spread required to open a position.

  • Type: Decimal (0.0-1.0)
  • Default: 0.0004 (0.04%)
  • TOML Path: trading.min_funding_spread
  • Example: WEALTH__TRADING__MIN_FUNDING_SPREAD=0.0005

WEALTH__TRADING__MAX_POSITION_USD

Maximum position size cap in USD (safety limit).

  • Type: Decimal
  • Default: 10000 ($10,000)
  • TOML Path: trading.max_position_usd
  • Example: WEALTH__TRADING__MAX_POSITION_USD=20000

WEALTH__TRADING__POSITION_SIZE_PERCENT

Percentage of available balance to use per position.

  • Type: Decimal (0.0 - 1.0)
  • Default: 0.3 (30%)
  • TOML Path: trading.position_size_percent
  • Example: WEALTH__TRADING__POSITION_SIZE_PERCENT=0.25

WEALTH__TRADING__TARGET_PROFIT_PERCENT

Target profit percentage per position.

  • Type: Decimal (0.0 - 1.0)
  • Default: 0.05 (5%)
  • TOML Path: trading.target_profit_percent
  • Example: WEALTH__TRADING__TARGET_PROFIT_PERCENT=0.08

WEALTH__TRADING__MAX_POSITION_DURATION_HOURS

Maximum position duration in hours before forced exit. Prevents capital from being tied up indefinitely.

  • Type: Integer
  • Default: 168 (7 days)
  • TOML Path: trading.max_position_duration_hours
  • Example: WEALTH__TRADING__MAX_POSITION_DURATION_HOURS=336
  • Note: Set to 0 to disable duration-based exits

WEALTH__TRADING__NARROW_SPREAD_EXIT_PERIODS

Number of consecutive narrow spread periods (8-hour intervals) before closing position.

  • Type: Integer
  • Default: 3 (24 hours of narrow spread)
  • TOML Path: trading.narrow_spread_exit_periods
  • Example: WEALTH__TRADING__NARROW_SPREAD_EXIT_PERIODS=2
  • Note: Set to 0 for immediate spread narrowing exit

WEALTH__TRADING__MAX_CONCURRENT_POSITIONS

Maximum number of concurrent arbitrage pairs.

  • Type: Integer
  • Default: 5
  • TOML Path: trading.max_concurrent_positions
  • Example: WEALTH__TRADING__MAX_CONCURRENT_POSITIONS=3

WEALTH__TRADING__UPDATE_INTERVAL_SECS

Funding rate update interval in seconds.

  • Type: Integer
  • Default: 60
  • TOML Path: trading.update_interval_secs
  • Example: WEALTH__TRADING__UPDATE_INTERVAL_SECS=30

WEALTH__TRADING__MAX_HEDGE_ATTEMPTS

Maximum number of hedging attempts for partial fills.

  • Type: Integer
  • Default: 5
  • TOML Path: trading.max_hedge_attempts
  • Example: WEALTH__TRADING__MAX_HEDGE_ATTEMPTS=3
  • Purpose: Prevents infinite hedging loops when orders partially fill

WEALTH__TRADING__HEDGE_TOLERANCE_PERCENT

Hedging tolerance as percentage (when to stop hedging).

  • Type: Decimal (0.0-1.0)
  • Default: 0.001 (0.1%)
  • TOML Path: trading.hedge_tolerance_percent
  • Example: WEALTH__TRADING__HEDGE_TOLERANCE_PERCENT=0.0005
  • Purpose: Allows small quantity mismatches without additional hedging orders

Note: Leverage is configured per-symbol in the [leverage] section, not as a global trading parameter.

Expected Value (EV) Gating

The bot uses expected value analysis to filter opportunities before execution. Only opportunities with positive risk-adjusted EV after costs are considered.

WEALTH__TRADING__MIN_EXPECTED_VALUE

Minimum expected value threshold (net profit after costs).

  • Type: Decimal (0.0-1.0)
  • Default: 0.0005 (0.05%)
  • TOML Path: trading.min_expected_value
  • Example: WEALTH__TRADING__MIN_EXPECTED_VALUE=0.0008
  • Purpose: Filters out low-quality opportunities with insufficient edge
  • Formula: EV = (time_weighted_spread × 3 funding payments) - (entry_fees + exit_fees + slippage)
  • Note: Time weighting applies linear decay based on minutes until next funding payment

WEALTH__TRADING__STALENESS_PENALTY

Discount applied to EV calculation when data nears staleness threshold.

  • Type: Decimal (0.0-1.0)
  • Default: 0.0003 (0.03%)
  • TOML Path: trading.staleness_penalty
  • Example: WEALTH__TRADING__STALENESS_PENALTY=0.0005
  • Purpose: Conservative adjustment for potential data lag
  • When Applied: Automatically reduces gross EV when funding rate data is >4 minutes old

Example EV Calculation:

Funding spread: 90 bps (0.0090)
Time to funding: 240 minutes (50% of 8h period)
Time weight: 0.5
Gross EV: 90 bps × 0.5 = 45 bps

Entry fees (both sides): 4 bps
Exit fees (both sides): 4 bps
Estimated slippage: 10 bps
Total costs: 18 bps

Adjusted EV: 45 - 18 = 27 bps
Passes threshold: 27 bps > 5 bps ✅

Kelly Position Sizing

The bot supports two position sizing modes: Kelly Criterion (dynamic, risk-adjusted) or Fixed Percentage (simple, predictable).

WEALTH__TRADING__USE_KELLY_CRITERION

Enable or disable Kelly Criterion for position sizing.

  • Type: Boolean
  • Default: true
  • TOML Path: trading.use_kelly_criterion
  • Example: WEALTH__TRADING__USE_KELLY_CRITERION=false
  • When true: Uses Kelly Criterion formula for dynamic sizing based on EV and variance
  • When false: Uses fixed percentage sizing: size = min(balance) × max_exchange_utilization × leverage
  • Recommendation: true for optimal capital allocation, false for simpler, predictable sizing

WEALTH__TRADING__KELLY_FRACTION

Fraction of full Kelly size to use (0.0 - 1.0).

  • Type: Decimal
  • Default: 0.25 (quarter-Kelly for conservative sizing)
  • TOML Path: trading.kelly_fraction
  • Example: WEALTH__TRADING__KELLY_FRACTION=0.5
  • Purpose: Reduces risk by using only a fraction of the mathematically optimal Kelly size
  • Recommendation: Keep at 0.25 or lower for funding rate arbitrage

WEALTH__TRADING__MAX_NOTIONAL_PER_SYMBOL

Maximum notional value per symbol across all exchanges in USD.

  • Type: Decimal
  • Default: 10000 ($10,000)
  • TOML Path: trading.max_notional_per_symbol
  • Example: WEALTH__TRADING__MAX_NOTIONAL_PER_SYMBOL=20000
  • Purpose: Hard cap on position size regardless of Kelly calculation
  • Applied: Per symbol across all exchanges (e.g., total BTC exposure)

WEALTH__TRADING__MAX_EXCHANGE_UTILIZATION

Maximum percentage of free balance to use for a single position (0.0 - 1.0).

  • Type: Decimal
  • Default: 0.5 (50%)
  • TOML Path: trading.max_exchange_utilization
  • Example: WEALTH__TRADING__MAX_EXCHANGE_UTILIZATION=0.3
  • Purpose: Prevents over-concentration on one exchange
  • Reference Capital: Uses min(long_exchange_balance, short_exchange_balance) for sizing

Example Kelly Sizing:

EV: 30 bps per 8h (0.003)
Variance: 0.0001 (estimated spread volatility)
Kelly fraction: EV / variance = 0.003 / 0.0001 = 30
Reference capital: min($50,000, $80,000) = $50,000
Leverage: 10x
Full Kelly size: $50,000 × 30 × 10 = $15,000,000 (unrealistic)

Apply kelly_cap (0.25): $15,000,000 × 0.25 = $3,750,000
Apply max_notional cap: min($3,750,000, $10,000) = $10,000
Apply utilization cap: min($10,000, $50,000 × 0.5) = $10,000

Final position size: $10,000 (binding constraint: notional cap)

Slippage Protection Configuration

WEALTH__RISK__MAX_SLIPPAGE_BPS

Maximum allowed slippage in basis points.

  • Type: Integer
  • Default: 50 (0.5%)
  • TOML Path: risk.max_slippage_bps
  • Example: WEALTH__RISK__MAX_SLIPPAGE_BPS=30

WEALTH__RISK__MIN_SLIPPAGE_BPS

Minimum slippage buffer in basis points (always applied).

  • Type: Integer
  • Default: 10 (0.1%)
  • TOML Path: risk.min_slippage_bps
  • Example: WEALTH__RISK__MIN_SLIPPAGE_BPS=5

WEALTH__RISK__MARKET_ORDER_FALLBACK_ENABLED

Whether to fall back to MARKET orders if LIMIT order doesn't fill.

  • Type: Boolean
  • Default: true
  • TOML Path: risk.market_order_fallback_enabled
  • Values: true | false
  • Example: WEALTH__RISK__MARKET_ORDER_FALLBACK_ENABLED=false

WEALTH__RISK__LIMIT_ORDER_TIMEOUT_SECS

Timeout before falling back to MARKET order (seconds).

  • Type: Integer
  • Default: 5
  • TOML Path: risk.limit_order_timeout_secs
  • Example: WEALTH__RISK__LIMIT_ORDER_TIMEOUT_SECS=10

WEALTH__RISK__SLIPPAGE_VOLATILITY_MULTIPLIER

Multiplier to increase slippage tolerance in volatile markets.

  • Type: Float
  • Default: 1.5 (50% wider)
  • TOML Path: risk.slippage_volatility_multiplier
  • Example: WEALTH__RISK__SLIPPAGE_VOLATILITY_MULTIPLIER=2.0

Trailing Stop Configuration

Note: Trailing stop configuration is defined in config.toml or via environment variables below. See Phase 1 Features for detailed usage.

WEALTH__RISK__TRAILING_STOPS_ENABLED

Enable trailing stop loss functionality.

  • Type: Boolean
  • Default: true
  • TOML Path: risk.trailing_stops_enabled
  • Values: true | false
  • Example: WEALTH__RISK__TRAILING_STOPS_ENABLED=true

WEALTH__RISK__TRAILING_STOP_ACTIVATION

Profit threshold to activate trailing stop (as decimal percentage).

  • Type: Decimal (0.0-1.0)
  • Default: 0.03 (3%)
  • TOML Path: risk.trailing_stop_activation
  • Example: WEALTH__RISK__TRAILING_STOP_ACTIVATION=0.05

WEALTH__RISK__TRAILING_STOP_DISTANCE

Maximum allowed profit retracement before exit (as decimal percentage).

  • Type: Decimal (0.0-1.0)
  • Default: 0.40 (40% from peak)
  • TOML Path: risk.trailing_stop_distance
  • Example: WEALTH__RISK__TRAILING_STOP_DISTANCE=0.3

WEALTH__RISK__TRAILING_STOP_MIN_LOCK

Minimum profit to lock in (prevents exit below this level).

  • Type: Decimal (0.0-1.0)
  • Default: 0.02 (2%)
  • TOML Path: risk.trailing_stop_min_lock
  • Example: WEALTH__RISK__TRAILING_STOP_MIN_LOCK=0.015

WEALTH__RISK__SLIPPAGE_AWARE_EXITS

Consider estimated slippage cost in exit decisions. When enabled, positions with remaining potential profit less than expected closing costs may be held for one more funding period.

  • Type: Boolean
  • Default: true
  • TOML Path: risk.slippage_aware_exits
  • Example: WEALTH__RISK__SLIPPAGE_AWARE_EXITS=false

Fee Configuration

WEALTH__RISK__FEES__ESTIMATED_SLIPPAGE

Estimated slippage for market orders (as decimal).

  • Type: Decimal (0.0-1.0)
  • Default: 0.001 (0.1%)
  • TOML Path: risk.fees.estimated_slippage
  • Example: WEALTH__RISK__FEES__ESTIMATED_SLIPPAGE=0.002

Exchange Fee Overrides

Override default exchange fee rates in config.toml under [risk.fees.<exchange>]:

Binance

[risk.fees.binance]
maker = 0.0002  # 0.02% - Maker fee
taker = 0.0004  # 0.04% - Taker fee
funding_interval_hours = 8

Bybit

[risk.fees.bybit]
maker = 0.0001  # 0.01% - Maker fee
taker = 0.0006  # 0.06% - Taker fee
funding_interval_hours = 8

HyperLiquid

[risk.fees.hyperliquid]
maker = 0.0000   # 0.00% - Maker rebate
taker = 0.00035  # 0.035% - Taker fee
funding_interval_hours = 8

Metrics Server Configuration

WEALTH__OBSERVABILITY__METRICS_PORT

Port for metrics and health check server.

  • Type: Integer
  • Default: 9090
  • TOML Path: observability.metrics_port
  • Example: WEALTH__OBSERVABILITY__METRICS_PORT=8080

WEALTH__OBSERVABILITY__METRICS_BIND_ADDRESS

Bind address for metrics server.

  • Type: String (IP address)
  • Default: 0.0.0.0 (all interfaces)
  • TOML Path: observability.metrics_bind_address
  • Example: WEALTH__OBSERVABILITY__METRICS_BIND_ADDRESS=127.0.0.1

Execution Mode

WEALTH__EXECUTION__MODE

Execution mode for order placement.

  • Type: String ("paper" | "live" | "dryrun")
  • Default: paper
  • TOML Path: execution.mode
  • Example: WEALTH__EXECUTION__MODE=live

Modes:

  • paper - Simulated trading with mock order fills
  • live - Real trading with actual exchange orders
  • dryrun - Logs order intent but doesn't execute (useful for testing strategy logic)

Note: The old PAPER_TRADING and DRY_RUN boolean flags have been replaced with WEALTH__EXECUTION__MODE in v0.33.0 for clearer semantics.

Exchange Credentials

Credential Loading Strategy

The bot automatically tries to load credentials in the following order:

  1. Encrypted Credentials File (if CREDENTIALS_PASSPHRASE is set)

    • Uses credentials.encrypted.json and .credentials.salt
    • Most secure, recommended for production
    • Managed via wealth credentials CLI commands
  2. Environment Variables (fallback)

    • Exchange-specific variables documented below
    • Simpler for development and testing

No configuration needed - the bot seamlessly uses whichever method you set up.

Initial Setup:

# 1. Set passphrase in .env
echo "CREDENTIALS_PASSPHRASE=your-secure-passphrase" >> .env

# 2. Create encrypted credentials file
wealth credentials create

# 3. Add exchange credentials
wealth credentials add binance YOUR_API_KEY YOUR_SECRET_KEY
wealth credentials add bybit YOUR_API_KEY YOUR_SECRET_KEY
wealth credentials add hyperliquid 0xWALLET_ADDRESS 0xPRIVATE_KEY

# 4. Verify
wealth verify --encrypted

Advantages:

  • AES-256-GCM encryption
  • Credentials never stored in plaintext
  • Secure key derivation from passphrase (PBKDF2 with 100,000 iterations)
  • Isolated from source code and version control

Security:

  • Never commit credentials.encrypted.json or .credentials.salt to version control
  • Use a strong passphrase (12+ characters, mix of types)
  • Store passphrase securely (password manager, secrets vault)

CREDENTIALS_PASSPHRASE

Passphrase for encrypting/decrypting the credentials file.

  • Type: String
  • Default: None (not set)
  • Example: CREDENTIALS_PASSPHRASE=my-super-secure-passphrase-2024
  • Required for: Encrypted credentials (Option 1)
  • Not needed for: Direct environment variables (Option 2)

When set: Bot loads credentials from credentials.encrypted.json
When not set: Bot loads credentials from environment variables (see below)

Setup Option 2: Environment Variables (Development)

⚠️ Deprecated: Direct exchange credential environment variables are deprecated in v0.21.0+. Use encrypted credentials instead.

For backwards compatibility, you can still set exchange-specific variables:

Binance Futures

BINANCE_API_KEY="your-api-key"
BINANCE_SECRET_KEY="your-secret-key"
BINANCE_TESTNET="false"  # or "true" for testnet

URLs:

  • Production: https://fapi.binance.com
  • Testnet: https://testnet.binancefuture.com

Bybit Perpetuals

BYBIT_API_KEY="your-api-key"
BYBIT_SECRET_KEY="your-secret-key"
BYBIT_TESTNET="false"

URLs:

  • Production: https://api.bybit.com
  • Testnet: https://api-testnet.bybit.com

HyperLiquid (official SDK)

HYPERLIQUID_SECRET_KEY="0x1234567890abcdef..."  # API wallet private key (64 hex chars)
HYPERLIQUID_API_KEY="0x..."                     # Optional: master wallet address for subkey mode
HYPERLIQUID_TESTNET="false"                     # false=mainnet, true=testnet
HYPERLIQUID_VAULT_MODE="false"                  # false=subkey mode, true=vault mode

Authentication Modes:

  1. Direct Wallet Mode (simplest):

    • Only set HYPERLIQUID_SECRET_KEY
    • Trades directly with the wallet derived from the private key
    • Use for single-wallet trading
  2. API Wallet (Subkey) Mode (recommended):

    • Set HYPERLIQUID_SECRET_KEY (API wallet private key)
    • Set HYPERLIQUID_API_KEY (master wallet address starting with 0x)
    • Set HYPERLIQUID_VAULT_MODE=false (or omit, this is default)
    • API wallet must be authorized via HyperLiquid UI under Settings → API
    • Queries use master wallet, signing uses API wallet
    • Provides better security isolation
  3. Vault Mode:

    • Set HYPERLIQUID_SECRET_KEY (vault's API wallet private key)
    • Set HYPERLIQUID_API_KEY (vault address starting with 0x)
    • Set HYPERLIQUID_VAULT_MODE=true
    • For trading on behalf of HyperLiquid vaults only

Note: Signing is handled by the official hyperliquid_rust_sdk (git). It uses Alloy v1.0 PrivateKeySigner under the hood. No custom signing code is implemented in this repository.

Networks:

  • Mainnet: Arbitrum One (Chain ID 42161)
  • Testnet: Arbitrum Sepolia (Chain ID 421614)

Security: Private key is stored in secrecy::Secret to prevent accidental logging.

Resilience Configuration

WEALTH__EXECUTION__RESILIENCE__CIRCUIT_BREAKER_FAILURES

Number of failures before circuit breaker opens.

  • Type: Integer
  • Default: 5
  • TOML Path: execution.resilience.circuit_breaker_failures
  • Example: WEALTH__EXECUTION__RESILIENCE__CIRCUIT_BREAKER_FAILURES=10

WEALTH__EXECUTION__RESILIENCE__CIRCUIT_BREAKER_TIMEOUT_SECS

Time to wait before testing recovery.

  • Type: Integer
  • Default: 60
  • TOML Path: execution.resilience.circuit_breaker_timeout_secs
  • Example: WEALTH__EXECUTION__RESILIENCE__CIRCUIT_BREAKER_TIMEOUT_SECS=120

WEALTH__EXECUTION__RESILIENCE__CIRCUIT_BREAKER_SUCCESS_THRESHOLD

Number of successful calls needed to close circuit breaker.

  • Type: Integer
  • Default: 2
  • TOML Path: execution.resilience.circuit_breaker_success_threshold
  • Example: WEALTH__EXECUTION__RESILIENCE__CIRCUIT_BREAKER_SUCCESS_THRESHOLD=3

WEALTH__EXECUTION__RESILIENCE__MAX_RETRIES

Maximum retry attempts for API calls.

  • Type: Integer
  • Default: 3
  • TOML Path: execution.resilience.max_retries
  • Example: WEALTH__EXECUTION__RESILIENCE__MAX_RETRIES=5

WEALTH__EXECUTION__RESILIENCE__RETRY_INITIAL_BACKOFF_MS

Initial retry backoff in milliseconds.

  • Type: Integer
  • Default: 100
  • TOML Path: execution.resilience.retry_initial_backoff_ms
  • Example: WEALTH__EXECUTION__RESILIENCE__RETRY_INITIAL_BACKOFF_MS=200

WEALTH__EXECUTION__RESILIENCE__RETRY_MAX_BACKOFF_SECS

Maximum retry backoff in seconds.

  • Type: Integer
  • Default: 10
  • TOML Path: execution.resilience.retry_max_backoff_secs
  • Example: WEALTH__EXECUTION__RESILIENCE__RETRY_MAX_BACKOFF_SECS=30

WEALTH__EXECUTION__RESILIENCE__WEBSOCKET_MAX_RECONNECTS

Maximum WebSocket reconnection attempts.

  • Type: Integer
  • Default: 100
  • TOML Path: execution.resilience.websocket_max_reconnects
  • Example: WEALTH__EXECUTION__RESILIENCE__WEBSOCKET_MAX_RECONNECTS=50

Observability Configuration

WEALTH__OBSERVABILITY__METRICS_PORT

Port number for the metrics/API server.

  • Type: u16
  • Default: 9090
  • TOML Path: observability.metrics_port
  • Example: WEALTH__OBSERVABILITY__METRICS_PORT=9090

The metrics server exposes:

  • /metrics - OpenTelemetry metrics info (JSON)
  • /health, /ready, /live - Health check endpoints
  • /api/positions, /api/funding_rates, /api/balances - HTTP API for querying bot state
  • /api/arbitrage_positions - Cached arbitrage positions with funding collected (fast, no API quota)

WEALTH__OBSERVABILITY__METRICS_BIND_ADDRESS

IP address for the metrics/API server to bind to.

  • Type: IP Address
  • Default: 0.0.0.0 (all network interfaces)
  • TOML Path: observability.metrics_bind_address
  • Example: WEALTH__OBSERVABILITY__METRICS_BIND_ADDRESS=127.0.0.1

Set to 127.0.0.1 for localhost-only access (recommended for production with external proxy).

WEALTH__OBSERVABILITY__OTLP_ENDPOINT

OpenTelemetry Protocol (OTLP) endpoint URL for exporting traces, metrics, and logs.

  • Type: String (URL)
  • Default: None (OTLP export disabled, local logging only)
  • TOML Path: observability.otlp_endpoint
  • Example: WEALTH__OBSERVABILITY__OTLP_ENDPOINT=http://localhost:4317

When set, the bot will export all telemetry (traces, metrics, logs) to an OpenTelemetry Collector or compatible backend (Tempo, Jaeger, etc.) via gRPC. This replaces the previous Loki push logging with a unified observability pipeline.

URL Validation:

  • Must start with http:// or https://
  • Default port for OTLP gRPC is 4317
  • Supports authentication via standard OTLP headers (configure in collector)
  • Can be configured via CLI: --loki-url <URL> (flag name preserved for compatibility)

Resource Attributes: You can add custom resource attributes via the OTEL_RESOURCE_ATTRIBUTES environment variable:

export OTEL_RESOURCE_ATTRIBUTES="service.name=wealth-bot,deployment.environment=production,service.version=0.16.0"

WEALTH__OBSERVABILITY__SERVICE_NAME

Service name for telemetry resource attributes.

  • Type: String
  • Default: wealth
  • TOML Path: observability.service_name
  • Example: WEALTH__OBSERVABILITY__SERVICE_NAME=wealth-prod

Used as the service.name resource attribute in OpenTelemetry spans, metrics, and logs. Useful when running multiple bot instances.

WEALTH__OBSERVABILITY__ENVIRONMENT

Environment name for telemetry resource attributes (e.g., production, development, staging).

  • Type: String
  • Default: development
  • TOML Path: observability.environment
  • Example: WEALTH__OBSERVABILITY__ENVIRONMENT=production

Used as a custom resource attribute for environment-based filtering in observability backends.

WEALTH__OBSERVABILITY__ENABLE_TRACES

Enable distributed tracing via OTLP.

  • Type: Boolean
  • Default: true
  • TOML Path: observability.enable_traces
  • Example: WEALTH__OBSERVABILITY__ENABLE_TRACES=false

When enabled alongside otlp_endpoint, exports trace spans to the OTLP endpoint for distributed tracing visualization in Tempo, Jaeger, or similar backends.

WEALTH__OBSERVABILITY__TRACE_SAMPLE_RATE

Trace sampling rate (0.0 = never sample, 1.0 = always sample).

  • Type: Decimal (0.0 - 1.0)
  • Default: 1.0 (100% of traces)
  • TOML Path: observability.trace_sample_rate
  • Example: WEALTH__OBSERVABILITY__TRACE_SAMPLE_RATE=0.1

Lower values reduce observability costs in high-throughput scenarios. Recommended: 1.0 for development, 0.1-0.01 for high-volume production.

WEALTH__OBSERVABILITY__LOG_FILE

Path to log file for file-based logging.

  • Type: String (file path)
  • Default: None (logs to stdout only)
  • TOML Path: observability.log_file
  • Example: WEALTH__OBSERVABILITY__LOG_FILE=/var/log/wealth.log

When set, logs are written to both stdout and the specified file. Useful for debugging without disrupting OTLP telemetry.

Configuration Methods:

  1. Environment Variables:

    export WEALTH__OBSERVABILITY__OTLP_ENDPOINT=http://localhost:4317
    export WEALTH__OBSERVABILITY__SERVICE_NAME=wealth-prod
    export WEALTH__OBSERVABILITY__ENVIRONMENT=production
    
  2. TOML Config:

    [observability]
    otlp_endpoint = "http://localhost:4317"
    service_name = "wealth-prod"
    environment = "production"
    
  3. JSON Config (Legacy):

    {
      "observability": {
        "otlp_endpoint": "http://localhost:4317",
        "service_name": "wealth-prod",
        "environment": "production"
      }
    }
    

Configuration Precedence: Environment variables > TOML config > JSON config (legacy) > Defaults

See Logging Guide for complete OpenTelemetry setup instructions.

Configuration Examples

Development (Paper Trading)

# Trading
WEALTH__TRADING__MIN_FUNDING_SPREAD=0.0004
WEALTH__TRADING__MAX_POSITION_USD=10000
WEALTH__TRADING__POSITION_SIZE_PERCENT=0.3
WEALTH__TRADING__TARGET_PROFIT_PERCENT=0.05

# Execution
WEALTH__EXECUTION__MODE=paper

# Observability
RUST_LOG=info
# Optional: Enable OTLP export for development
WEALTH__OBSERVABILITY__OTLP_ENDPOINT=http://localhost:4317
WEALTH__OBSERVABILITY__SERVICE_NAME=wealth-dev
WEALTH__OBSERVABILITY__ENVIRONMENT=development

Production (Live Trading)

# Trading
WEALTH__TRADING__MIN_FUNDING_SPREAD=0.0004
WEALTH__TRADING__MAX_POSITION_USD=50000
WEALTH__TRADING__POSITION_SIZE_PERCENT=0.25
WEALTH__TRADING__TARGET_PROFIT_PERCENT=0.05

# Execution
WEALTH__EXECUTION__MODE=live

# Exchange Credentials (use encrypted credentials file instead)
CREDENTIALS_PASSPHRASE="your-secure-passphrase"

# Observability
RUST_LOG=info
WEALTH__OBSERVABILITY__OTLP_ENDPOINT=https://otlp.example.com:4317
WEALTH__OBSERVABILITY__SERVICE_NAME=wealth-prod
WEALTH__OBSERVABILITY__ENVIRONMENT=production

Testing Configuration

# Execution
WEALTH__EXECUTION__MODE=paper

# Conservative settings
WEALTH__TRADING__MAX_POSITION_USD=100
WEALTH__TRADING__POSITION_SIZE_PERCENT=0.1

# Verbose logging
RUST_LOG=debug

Configuration Validation

All configuration is validated on startup with fail-fast behavior.

Validation Process:

  • Type validation during JSON parsing (serde)
  • Cross-field validation after loading
  • Clear error messages indicating which rule failed

Validated Constraints:

  • All numeric thresholds must be positive
  • Percentages must be between 0 and 1
  • Port numbers must be non-zero
  • At least one instrument must be configured
  • Retry counts and timeouts must be valid

Example Error:

ERROR Configuration validation failed: Metrics port must be non-zero
ERROR Configuration validation failed: At least one instrument must be configured

Debugging Configuration

Use the config show --show-sources command to see where each configuration value comes from:

$ wealth config show --show-sources

📋 Configuration Sources

Shows: default → file (config.toml) → env vars → ✓ final value

🎯 Trading Configuration:
  min_funding_spread:
    default:  0.0004
    file:     0.0005
    env:      0.0006
    ✓ final:  0.0006 ← using environment override

  max_position_usd:
    default:  10000
    ✓ final:  10000 ← using default

This helps identify configuration issues and understand which values are active.

Environment Variable Precedence

Configuration loading happens in this order:

  1. Environment variables with WEALTH__ prefix (highest priority) - Override all other settings
  2. TOML/JSON configuration file (config.toml or config.json) - Provides structured config
  3. Default values (lowest priority) - Built-in sensible defaults

Example: If you set WEALTH__TRADING__MIN_FUNDING_SPREAD=0.001 in .env and min_funding_spread = 0.0004 in config.toml, the environment variable takes precedence.

Best Practices:

  • Use config.toml for static configuration (instruments, leverage, strategy parameters)
  • Use environment variables with WEALTH__ prefix for deployment-specific settings
  • Use encrypted credentials file for API keys (safer than environment variables)
  • Use .env file for local development overrides

Using with Different Tools

Systemd

[Service]
Environment="WEALTH__EXECUTION__MODE=live"
Environment="CREDENTIALS_PASSPHRASE=your-passphrase"

Docker

docker run -e WEALTH__EXECUTION__MODE=live \
  -e CREDENTIALS_PASSPHRASE=xxx \
  -v $(pwd)/config.toml:/app/config.toml \
  wealth

Docker Compose

environment:
  - WEALTH__EXECUTION__MODE=live
  - CREDENTIALS_PASSPHRASE=${CREDENTIALS_PASSPHRASE}
volumes:
  - ./config.toml:/app/config.toml:ro
  - ./credentials.encrypted.json:/app/credentials.encrypted.json:ro

Kubernetes

env:
- name: WEALTH__EXECUTION__MODE
  value: "live"
- name: CREDENTIALS_PASSPHRASE
  valueFrom:
    secretKeyRef:
      name: wealth-secrets
      key: credentials-passphrase
volumeMounts:
- name: config
  mountPath: /app/config.toml
  subPath: config.toml

Configuration Debugging

Config Show Sources Command

Display where each configuration value comes from (default → file → env):

wealth config --show-sources

Example Output:

📋 Configuration Sources

Shows: default → file (config.toml) → env vars → ✓ final value

🎯 Trading Configuration:
  min_funding_spread:
    default:  0.0004
    env:      0.0008
    ✓ final:  0.0008 ← using environment override
    
  max_position_usd:
    default:  10000
    file:     15000
    ✓ final:  15000 ← from config file

Use cases:

  • Debug which source is being used for each config value
  • Verify environment variable overrides are working
  • Identify misconfigured values before running the bot

Validation Error Messages

Configuration errors now include source tracking (v0.33.0+):

File-based error:

Error: Invalid value for leverage.default: Must be greater than 0 
(from config file: config.toml)

Environment variable error:

Error: Invalid value for trading.min_funding_spread: Cannot be negative
(from environment variable: WEALTH__TRADING__MIN_FUNDING_SPREAD)

Default value error:

Error: Invalid value for risk.max_slippage_bps: must be positive
(using default value)

Benefits:

  • Quickly identify where the problematic value is configured
  • Avoid checking multiple configuration sources manually
  • Clear distinction between file errors and env var errors

Config Validation

Validate configuration without starting the bot:

wealth config --validate

Output:

🔍 Validating configuration...

  ✓ Loading config.toml
  ✓ TOML parsing successful
  ✓ Environment variable parsing successful
  ✓ Validating configuration... OK

✅ Configuration is valid!
   Instruments: 6
   Metrics Port: 9090
   Execution Mode: Paper

Common validation errors:

  • Negative values (spreads, slippage, leverage)
  • Out-of-range percentages (must be 0.0-1.0)
  • Invalid exchange names (must be: binance, bybit, hyperliquid)
  • Missing required instruments

See Also