learning_ai_invt_trdg/backend
Saravana Achu Mac e2806b28c1 test(F6): cover market data proxy endpoints
Add static contract coverage for the dashboard market data and research proxy routes so auth, upstream URL construction, response normalization, and FMP cache usage stay guarded by the backend test gate.

Refs: docs/AUDIT_REDESIGN.md item F6.

Co-Authored-By: GPT-5 Codex <noreply@openai.com>
2026-05-04 16:25:44 -07:00
..
grafana/provisioning/datasources feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
runbooks feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
schema feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
src fix(C2): cache FMP upstream responses 2026-05-04 16:06:47 -07:00
.gitignore feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
ADMIN_TRADE_CONTROL_ARCHITECTURE.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
ADMIN_TRADE_CONTROL_IMPLEMENTATION.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
ADMIN_TRADE_CONTROL_QUICK_REF.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
ADMIN_TRADE_CONTROL_TEST_PLAN.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
admin-observability.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
apply_standard_risk_profiles.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
ARCHITECTURE_RISK_ANALYSIS.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
architecture.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
audit_profile_mapping.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
audit_profile_structure.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
AUTH_THREAT_MODEL.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
backtesting.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
CAPITAL_FLOW_VALIDATION.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_alerts.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_alpaca_pos.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_cols.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_counts.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_db_users.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_orders_cols.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_persistence.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
check_user_schema.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
checkAlpacaPositions.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
COVERAGE_BEFORE_AFTER_2026-02-16.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
create_aggressive_profile.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
create_low_risk_profile.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
CROSS_REPO_TEST_BUGREPORT_2026-02-15.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
debug_config.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
debug_db_logging.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
debug_mode.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
debug_supabase.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
debugProfiles.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
diagnose_profiles.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
docker-compose.yml feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
Dockerfile feat(backend): WebSocket namespaces, audit persistence, tab flags, telemetry 2026-04-29 19:35:00 -04:00
dump_db.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
dump_recent.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
e2e_full_scenario.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
ENTERPRISE_ARCHITECTURE_REFERENCE.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
example_profile_config.json feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
final_e2e_param_verification.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
fix_dashboard_rules.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
fix_imports.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
force_rules_reset.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
HISTORY_PURGE_RUNBOOK.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
INCIDENT_RUNBOOKS.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
inspect_btc.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
invariants.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
list_history.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
live_signal_check.js feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
manualOverrideCloseTrades.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
MOBILE_APP_BOOTSTRAP_ROADMAP.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
monitorFreshWindow.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
ORDER_STATUS_SYNC.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
package.json test(F6): cover market data proxy endpoints 2026-05-04 16:25:44 -07:00
phase8-validation.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
pre-deploy.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
print_btc_rules.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
print_symbols.js feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
PRODUCT_FLOW_TRADING_LOGIC.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
prometheus-metrics.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
prometheus.yml feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
proposed_risk_profiles.json feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
quick_eth.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
README.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
reconcileAlpacaVsSupabase.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
reconcileAttributionRepair.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
reconcileCapitalLedgerState.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
reconcileClosedOrderFillData.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
reconcileExitBackfillOnce.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
reconcileMissingOrderCoverage.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
reconcileNoGoQtyMismatchOnce.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
reconcileSubTagRepair.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
reconcileTradeHistoryLifecycle.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
rename_profile.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
REPO_AUDIT_ROADMAP.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
run_all_tests.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
runCoverageSuite.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
runCriticalCoverageSuite.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
SECRET_ROTATION_RUNBOOK.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
seed_profile_data.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
seedTwoBestProfiles.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
SESSION_RULE_FIX.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
simple_check.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
simulate_high_activity.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
simulate_hot_loading.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
strategy_config_schema.json feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
STRATEGY_MARKETPLACE.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_ai_cache.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_ai_fallback.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_ai_layer.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_alert.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_alpaca_execution.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_alpaca_exhaustive.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_alpaca_exit.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_alpaca_full_cycle.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_alpaca.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_broadcast_logic.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_feed_us.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_final.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_fuzzy_match.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_hot_loading.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_noslash_hardcoded.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_pro_strategy.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_query.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_risk_formula.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_risk_scenarios.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_safe.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_signal_sim.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_simulation_pro.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_simulation.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_slash.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_stock_baseline.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_strategy_logic.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_verbose_insert.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
test_wa.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testAlpacaSubTag.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testBacktestIsolation.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testConnectorAndAiCoverage.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testCoreModuleCoverage.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testFailureInjection.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testFmpCache.ts fix(C2): cache FMP upstream responses 2026-05-04 16:06:47 -07:00
testLifecycleRegressions.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testManualTraderCapitalGuard.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testOrderStatusSyncRegressions.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testReconciliationExitBackfillEvidenceGuard.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testReconciliationParityHeartbeat.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testReconciliationWatchdogAutoResume.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testSessionRuleNormalization.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testStateMergeCoverage.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testStrictCapitalGuard.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testSupabaseOrderPersistenceRegressions.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testSupabaseTradeHistorySourceFallback.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
testTradeExecutorLifecycle.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
TRADE_LIFECYCLE_INTEGRITY_PLAN.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
TRADING_CONTROL_PERSISTENCE.md feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
tsconfig.json feat(backend): WebSocket namespaces, audit persistence, tab flags, telemetry 2026-04-29 19:35:00 -04:00
verify_btc_logic.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_dynamic_config.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
verify_e2e_fix.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_fetch.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_final_e2e.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_full_lifecycle.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_order_logging.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_profiles_e2e.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_profiles.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
verify_realtime.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00
verify_signals_live.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_sl_tp_persistence.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_sync.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verify_traceability.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verifyApiContract.ts fix(audit): close agent follow-up gaps 2026-05-04 16:18:21 -07:00
verifyAuditRepository.ts feat(backend): WebSocket namespaces, audit persistence, tab flags, telemetry 2026-04-29 19:35:00 -04:00
verifyMarketDataEndpoints.ts test(F6): cover market data proxy endpoints 2026-05-04 16:25:44 -07:00
verifyRlsPolicies.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verifySchemaContract.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verifySecretHygiene.ts feat: scaffold trading monorepo foundation 2026-04-04 11:18:21 -07:00
verifySecurityGuards.ts fix: harden repo verification scripts 2026-04-04 14:35:01 -07:00
verifyTenantIsolation.ts refactor(backend): root scripts use legacySupabase client where possible 2026-04-04 20:44:24 -07:00

Bytelyst Trading Bot Service

Autonomous multi-profile crypto/equity trading bot with a pluggable rule-based strategy engine, per-profile execution, real-time dashboard integration, and AI-powered sentiment analysis.

Architecture

┌─────────────────────────────────────────────────────────┐
│                    Trading Loop                          │
│  for each symbol → for each profile → ProStrategyEngine │
│                                                          │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐              │
│  │TrendBias │→ │ Session  │→ │  Zone    │→ ...          │
│  │  Rule    │  │  Rule    │  │  Rule    │               │
│  └──────────┘  └──────────┘  └──────────┘              │
│                                                          │
│  Signal → AutoTrader → RiskEngine → TradeExecutor       │
│                                       ↓                  │
│                              ┌────────────────┐         │
│                              │  Alpaca / CCXT  │         │
│                              └────────────────┘         │
└─────────────────────────────────────────────────────────┘
         ↕ Socket.IO + REST          ↕ Supabase
┌──────────────────┐        ┌──────────────────┐
│    Dashboard      │        │    PostgreSQL     │
│   (React App)     │        │  (Supabase DB)   │
└──────────────────┘        └──────────────────┘

Features

  • Multi-Profile Execution — Each trade profile runs its own strategy rules, risk limits, and capital allocation independently
  • 7-Rule Strategy Pipeline — TrendBias → Session → Zone → Momentum → EntryTrigger → RiskManagement → AIAnalysis
  • Per-Profile Rule Config — Enable/disable rules, set parameters, and control execution order per profile
  • Profile Hot-Reload — New profiles created from the dashboard are picked up automatically within 60 seconds
  • Pluggable Exchanges — Alpaca (stocks/crypto) and CCXT (130+ exchanges) via factory pattern
  • AI Sentiment Analysis — Perplexity, OpenAI, and Gemini with automatic fallback chain
  • Real-Time Dashboard — Socket.IO for live price updates, signals, and position tracking
  • Profile-Mapped Orders — Every order and trade history record is tagged with profile_id
  • Configurable Everything — All thresholds, intervals, and parameters are configurable via env vars or per-profile JSON

Quick Start

Prerequisites

  • Node.js 18+
  • Supabase project (for auth, users, profiles, orders, trade history)
  • Alpaca account (for trade execution) or CCXT-compatible exchange

Installation

git clone https://github.com/saravanakumardb/bytelyst-trading-bot-service.git
cd bytelyst-trading-bot-service
npm install

Configuration

Copy the example environment file:

cp .env.example .env

Edit .env with your credentials (see Environment Variables below).

Database Setup

Run the schema migration in your Supabase SQL Editor:

# Full schema setup (creates all tables + adds missing columns)
# Copy and paste the contents of:
schema/004_full_schema_sync.sql

Run

# Development (with hot-reload via tsx)
npm run dev

# Production
npm start

Project Structure

src/
├── config/
│   └── index.ts              # All configuration (env vars + defaults)
├── connectors/
│   ├── alpaca.ts              # Alpaca exchange connector
│   ├── ccxt.ts                # CCXT multi-exchange connector
│   ├── factory.ts             # Connector factory (pluggable)
│   └── types.ts               # IExchangeConnector interface
├── services/
│   ├── AutoTrader.ts          # Signal → trade decision logic
│   ├── TradeExecutor.ts       # Order execution + position tracking
│   ├── riskEngine.ts          # Position sizing + SL/TP calculation
│   ├── tradeMonitor.ts        # Background SL/trailing stop monitor
│   ├── SupabaseService.ts     # DB operations (orders, history, profiles)
│   ├── apiServer.ts           # REST + Socket.IO API for dashboard
│   ├── notifier.ts            # WhatsApp/webhook notifications
│   ├── aiClient.ts            # Multi-provider AI sentiment analysis
│   ├── ManualTrader.ts        # Manual trade execution via dashboard
│   └── MetricsService.ts      # Trading metrics calculation
├── strategies/
│   ├── ProStrategyEngine.ts   # Main strategy orchestrator
│   ├── directionTracker.ts    # Legacy signal tracker
│   └── rules/
│       ├── types.ts           # IRule interface, MarketContext, RuleResult
│       ├── TrendBiasRule.ts   # EMA50/200 trend direction (4H)
│       ├── SessionRule.ts     # Market session filter (London/NY)
│       ├── ZoneRule.ts        # Price-to-EMA proximity check
│       ├── MomentumRule.ts    # RSI momentum confirmation
│       ├── EntryTriggerRule.ts# EMA reclaim / wick patterns
│       ├── RiskManagementRule.ts # ATR-based SL/TP/position sizing
│       └── AIAnalysisRule.ts  # LLM sentiment validation
├── utils/
│   ├── indicators.ts          # EMA, RSI, ATR calculations
│   ├── logger.ts              # Winston logger
│   └── symbolMapper.ts        # Symbol format conversion
└── index.ts                   # Main entry point + trading loop

Environment Variables

Required

Variable Description Example
SUPABASE_URL Supabase project URL https://xxx.supabase.co
SUPABASE_KEY Supabase service role key eyJ...
PROVIDER Default exchange provider alpaca or ccxt
ALPACA_API_KEY Alpaca API key PK...
ALPACA_API_SECRET Alpaca secret key ...

Exchange Configuration

Variable Default Description
DATA_PROVIDER $PROVIDER Provider for market data
EXECUTION_PROVIDER $PROVIDER Provider for order execution
EXCHANGE binance CCXT exchange (if using ccxt)
CCXT_API_KEY CCXT exchange API key
CCXT_API_SECRET CCXT exchange secret
PAPER_TRADING false Use paper trading keys
ASSET_CLASS crypto crypto or us_equity

Trading Symbols & Intervals

Variable Default Description
SYMBOLS BTC/USD Comma-separated trading pairs
POLLING_INTERVAL 60000 Main loop interval (ms)
SYMBOL_DELAY_MS 2000 Delay between symbol processing
TIMEFRAME 1Min Legacy candle timeframe

Execution & Risk

Variable Default Description
ENABLE_TRADING false Enable live trade execution
TOTAL_CAPITAL 1000 Default total capital ($)
MAX_OPEN_TRADES 3 Max concurrent positions
COOLDOWN_MS 3600000 Post-trade cooldown (ms)
PROFIT_EXIT_PERCENT 1.0 Auto-exit profit threshold (%)
TRAILING_STOP_PERCENT 0.001 Trailing stop pullback (0.1%)

Strategy Parameters

Variable Default Description
ENABLED_RULES all 7 rules Comma-separated rule list
R_TREND_TIMEFRAME 4h Trend bias timeframe
R_TREND_EMA_FAST 50 Fast EMA period
R_TREND_EMA_SLOW 200 Slow EMA period
R_RSI_PERIOD 14 RSI calculation period
R_RSI_OVERBOUGHT 70 RSI overbought threshold
R_RSI_OVERSOLD 30 RSI oversold threshold
R_ZONE_EMA_PERIOD 20 Zone EMA period
R_ATR_PERIOD 14 ATR calculation period
R_RISK_PER_TRADE 0.01 Risk per trade (1%)
R_RISK_REWARD_RATIO 1.5 Risk/reward ratio
R_SL_MULTIPLIER 1.5 Stop loss ATR multiplier
R_SESSION_WINDOWS JSON array Session time windows

AI Configuration

Variable Default Description
AI_PROVIDER openai Primary AI provider
PERPLEXITY_API_KEY Perplexity API key
OPENAI_API_KEY OpenAI API key
GEMINI_API_KEY Google Gemini API key
AI_FALLBACK_LIST openai,perplexity,gemini Fallback chain
AI_MODEL gpt-4o AI model to use
AI_CONFIDENCE_THRESHOLD 70 Min confidence score
AI_CACHE_HOURS 4 Cache duration (hours)

Server & Notifications

Variable Default Description
API_PORT 5000 API server port
NOTIFICATION_PHONE_NUMBERS Comma-separated phone numbers
NOTIFICATION_API_HOST www.zenhustles.com Notification API host
NOTIFICATION_API_PATH /api/whatsapp/send Notification API path
WEBHOOK_URL Legacy webhook URL

System Intervals

Variable Default Description
PROFILE_SYNC_INTERVAL_MS 60000 Profile hot-reload interval
MONITOR_INTERVAL_MS 60000 Position monitor polling

Database Schema

7 tables are used (see schema/004_full_schema_sync.sql for full DDL):

Table Purpose
users User accounts + exchange API keys
entries Watchlist & manual positions
trade_profiles Strategy profiles with per-profile rule config
orders Active/pending orders (with profile_id)
trade_history Completed trade ledger (with profile_id)
bot_config Global config key-value store
dynamic_config Runtime config overrides

strategy_config JSON Structure

Each profile stores its strategy configuration as a jsonb column:

{
  "rules": [
    { "ruleId": "TrendBiasRule", "enabled": true, "params": { "emaFast": 50, "emaSlow": 200 } },
    { "ruleId": "SessionRule", "enabled": true, "params": { "allowedSessions": ["NY", "LDN"] } },
    { "ruleId": "ZoneRule", "enabled": true, "params": { "emaPeriod": 20 } },
    { "ruleId": "MomentumRule", "enabled": true, "params": { "rsiPeriod": 14 } },
    { "ruleId": "EntryTriggerRule", "enabled": true, "params": {} },
    { "ruleId": "RiskManagementRule", "enabled": true, "params": { "atrPeriod": 14 } },
    { "ruleId": "AIAnalysisRule", "enabled": false, "params": { "minConfidence": 80 } }
  ],
  "riskLimits": {
    "maxDailyLossUsd": 50,
    "dailyProfitTargetUsd": 100,
    "maxConsecutiveLosses": 2,
    "maxOpenTrades": 3
  },
  "execution": {
    "orderType": "market",
    "cooldownMinutes": 30,
    "minRulePassRatio": 0.70
  }
}

API Endpoints

REST

Method Endpoint Description
GET /health Health check with uptime
GET /api/status Bot status, settings, symbols, positions
GET /api/config Current bot configuration (non-secret)
GET /api/alerts Recent alerts (supports ?limit=N)
GET /api/symbol/:symbol Single symbol data
POST /api/trade Execute manual trade
POST /api/chat AI-powered profile generation (see below)

POST /api/chat — AI Strategy Assistant

Translates plain English into structured trading profile configurations using the bot's AI fallback chain (Perplexity → OpenAI → Gemini).

Request:

{
  "message": "Create a conservative BTC swing trader with $2000 capital",
  "context": [{ "id": "...", "name": "Existing Profile", "allocated_capital": 1000, ... }]
}

Response:

{
  "action": "create_profile",
  "profile": {
    "name": "Conservative BTC Swing Trader",
    "allocated_capital": 2000,
    "risk_per_trade_percent": 1,
    "symbols": "BTC/USDT",
    "is_active": true,
    "strategy_config": { "rules": [...], "riskLimits": {...}, "execution": {...} }
  },
  "summary": "Created a conservative BTC swing trading profile with $2000 capital and 1% risk per trade.",
  "reasoning": "Conservative profiles use lower risk and fewer aggressive rules."
}

Supported actions: create_profile, update_profile, explain

Socket.IO Events

Event Direction Description
state Server → Client Full bot state update
symbol_update Server → Client Single symbol price/signal update
new_alert Server → Client New trading alert
orders_update Server → Client Order status change
positions_update Server → Client Aggregated positions from all profiles

License

ISC