DGX ONLINE (3.8-Flash)
PAPER TRADING
Cockpit Backtesting Help
Comprehensive System Reference & Technical Manual

Autonomous Multi-Agent Trading System

Deep dive into the 100% in-cluster DGX hardware infrastructure, the 7-stage autonomous agent deliberation pipeline, sub-second market data ingestion, quantitative indicator computations, and strict institutional risk guardrails.

1

Technical Architecture (Zero Cloud Cost)

All inference, vector similarity search, event streaming, and storage operate exclusively within the k8pi MicroK8s Kubernetes cluster.

Component In-Cluster Service DNS Hardware / Node Model / Engine Role & Specification
Primary LLM dgx.llm.svc.cluster.local:8000 NVIDIA DGX (192.168.1.194) 3.8-flash-next-nvfp4 Ultra-fast vLLM server executing multi-agent reasoning, catalyst interpretation, and hypothesis synthesis.
Embeddings Service dgx-embeddings.llm.svc.cluster.local:8081 NVIDIA DGX (192.168.1.194) BAAI/bge-large-en-v1.5 Generates 1024-dimensional semantic dense vectors for trade reflections, past errors, and market setup memory.
Secondary / Fallback LLM ollama-large.llm.svc.cluster.local:11434 rig-1-k8 (192.168.1.254) gemma4:31b / 30B High-capacity offline fallback if primary DGX node enters maintenance or high load.
Vector Memory qdrant.llm.svc.cluster.local:6333 k8pi (Namespace: llm) Qdrant StatefulSet Stores episodic trade reflections collection (1024-dim, Cosine distance) with sub-10ms query latency.
Database & Audit mongodb.inteltrade.svc.cluster.local:27017 k8pi (Namespace: inteltrade) MongoDB 6.0 Stores historical 5m OHLCV bars, daily candidate universes, order audit logs, and runtime state.
Real-time Event Bus mosquitto.mqtt.svc.cluster.local:9001 k8pi (Namespace: mqtt) Eclipse Mosquitto Broadcasts tick feeds, signal generation events, and execution alerts over WebSocket/TCP.
Sub-Second Quotes api.public.com / api.nasdaq.com External HTTPS (~35ms NBBO) Public SDK + NASDAQ Bypasses Alpaca free-tier 15-minute delay by ingesting real-time consolidated quotes directly.
Paper Broker paper-api.alpaca.markets External REST & WebSocket Alpaca v2 API Executes atomic bracket orders (Limit entry + OCO Stop-Loss + OCO Take-Profit) with margin tracking.
2

7-Agent Deliberation Pipeline

Institutional division of labor: No single agent makes decisions in isolation. Each agent enforces a specialized domain.

Stage 1: Pre-Market

Market Scanner Agent

Continuously scans the 535+ stock universe (S&P 500 & NASDAQ 100) using multi-threaded batch queries (5 workers). Filters for active institutional participation:

  • Liquidity: Recent volume ≥ 5,000 shares in 5m bars.
  • Momentum: Absolute price displacement ≥ 0.20%.
  • Ranking Score: |% change| × 100 × √volume.
  • Macro Anchors: Always includes SPY and QQQ for regime detection.
Stage 2: Technicals

Quantitative Agent

Constructs 5-minute historical bar DataFrames and calculates core mathematical indicators:

  • Trend Ribbons: EMA 9, EMA 21, EMA 50, EMA 200.
  • Oscillators: Wilder's RSI-14 & MACD (12, 26, 9) histogram.
  • Volatility: 14-period Average True Range (ATR).
  • Liquidity & Levels: VWAP, Relative Volume (RVOL), and 30-period Support/Resistance.
Stage 3: Catalysts

Sentiment & News Agent

Pulls the latest financial news articles and regulatory announcements via Alpaca News API. Feeds data to DGX vLLM for high-speed semantic extraction:

  • Polarity & Score: BULLISH / BEARISH / NEUTRAL [-1.0 to +1.0].
  • Catalyst Category: EARNINGS, UPGRADE, PARTNERSHIP, MACRO.
  • Risk Extraction: Summarizes key downside catalysts and warnings.
Stage 4: Synthesis

Chief Strategist Agent

Acts as the Chief Investment Officer powered by DGX vLLM. Retrieves past trade reflections from Qdrant vector memory to avoid repeating errors:

  • Episodic Recall: Evaluates past mistakes in similar setups.
  • Strict Conviction: Discards setups with confidence < 0.65.
  • Thesis Specification: Defines Entry, Stop-Loss, Take-Profit.
  • Minimum R:R: Enforces expected Risk/Reward ≥ 2.0.
Stage 5: Veto Power

Risk Guardian Agent

Possesses independent absolute veto authority. Evaluates the thesis against non-negotiable risk limits before any capital is committed:

  • Position Cap: Max 3 concurrent open positions.
  • Circuit Breaker: Trips on -$2,000 daily loss or 3 consecutive losses.
  • Sizing Engine: 1% equity risk per trade, max 2% portfolio risk.
  • Redundancy Block: Blocks duplicate positions in the same asset.
Stage 6: Execution

Order Execution Agent

Translates approved theses into atomic Alpaca bracket orders to protect every trade upon entry:

  • Atomic Bracket: Primary Limit entry + OCO Stop-Loss + OCO Take-Profit.
  • EOD Time Stop: At 15:55 EST, liquidates all intraday holdings.
  • Audit Logging: Streams order events to MongoDB & Mosquitto.
Stage 7: Continuous Self-Improvement

Post-Trade Reflection Agent

Whenever a trade is filled or closed, the Reflection Agent initiates an objective post-mortem using the DGX reasoning model. It examines the execution against the original thesis, extracts actionable lessons (e.g., "Premature exit", "Chased entry on high spread", "Good patience on pullback"), embeds the insight via DGX BGE-Large (1024-dim), and commits it into Qdrant vector memory.

3

Trading Logic, Indicators & Regime Classification

Mathematical rules governing technical signals, market regimes, and trigger conditions.

Dynamic Market Regime Detection

Every candidate symbol is mapped into one of four distinct market states on a 5-minute bar timeframe:

BULL_TREND Price > EMA(9) > EMA(21)

Aggressive momentum long setups favored. Long dips toward EMA(9) with RSI > 50.

BEAR_TREND Price < EMA(9) < EMA(21)

Short setups or capital preservation favored. Long entries vetoed unless oversold reversal confirmed.

HIGH_VOLATILITY ATR(14) / Price > 0.03 (3%)

Wide intraday swings. Position sizes automatically scaled down to prevent outsized dollar volatility.

RANGE_BOUND Choppy moving average crossovers

Mean-reversion setups only between rolling 30-period support and resistance boundaries.

Indicator Computation Engine

Exponential Moving Averages (EMA 9, 21, 50, 200)

Computed via exponential weighting: EMA_t = α × P_t + (1 - α) × EMA_{t-1} with α = 2 / (N + 1). Used to measure directional velocity and trailing support.

Wilder's Relative Strength Index (RSI-14)

Measures momentum balance between average gains and average losses. RSI < 30 indicates oversold; RSI > 70 indicates overbought.

Moving Average Convergence Divergence (MACD 12, 26, 9)

MACD line = EMA(12) - EMA(26); Signal line = EMA(9) of MACD; Histogram = MACD - Signal. Positive histogram inflection signals momentum acceleration.

Average True Range (ATR-14) & RVOL

ATR captures true price range including gap opens. RVOL evaluates current 5m volume against the 20-period historical rolling average.

4

Risk Guardrails & Mathematical Formulas

Strict portfolio safety mechanisms designed to guarantee capital preservation under all market conditions.

Volatility Position Sizing
Shares = ⌊ (Equity × 1%) / |Entry - StopLoss| ⌋

Every position size is dynamically calibrated so that if the stop loss is struck, the total portfolio loss does not exceed exactly 1.0% of total portfolio equity ($1,000 on a $100k portfolio).

Minimum Risk-to-Reward
R:R = |TakeProfit - Entry| / |Entry - StopLoss| ≥ 2.0

The Strategist must identify at least $2.00 of expected upside for every $1.00 of downside risk. The Risk Guardian automatically vetoes any thesis where R:R is under 1.5.

Mandatory Intraday Time Stop
Liquidate Intraday at 15:55:00 EST

Exactly 5 minutes before the NYSE cash close (15:55 EST), the Execution Agent cancels open limit orders and liquidates all intraday positions to eliminate overnight gap-down risk.

The 7 Non-Negotiable Risk Guardrails

1. Circuit Breaker Active Check

If tripped by daily losses or manual intervention, all deliberation is halted immediately.

2. Maximum Daily Loss Limit ($2,000)

If cumulative daily realized PnL drops below -$2,000, trading is terminated for the remainder of the session.

3. Consecutive Loss Cap (3 Trades)

Three consecutive losing trades today immediately trips the circuit breaker to prevent revenge trading.

4. Maximum Concurrent Positions (3)

Strictly no more than 3 simultaneous positions are active at any time, capping aggregate market exposure.

5. Redundant Ticker Prevention

Cannot purchase additional shares or initiate new positions in a ticker that already has an active position.

6. 1% Risk Allocation Limit

Maximum dollar loss if stop is hit is capped at 1% of account equity; portfolio-wide risk capped at 2% total.

7. Buying Power Buffer (95% Cap)

Total trade value cannot exceed 95% of available buying power, maintaining a 5% liquid safety cushion against margin calls.

5

Sub-Second Market Data Ingestion

Eliminating the standard 15-minute retail delay to capture high-velocity institutional market opportunities.

Primary Feed: Public.com API (~35ms NBBO)

Uses Public's official trading SDK with pre-authenticated API keys to ingest consolidated National Best Bid and Offer (NBBO) pricing with sub-50ms latency. Provides sub-second execution fidelity for limit order placement.

Secondary Feed: NASDAQ Direct Web API (~70ms)

Provides direct session-based quotes from NASDAQ for all US equities. Acts as an automated fallback if the primary broker quote connector encounters rate limiting or network latency.

6

In-Cluster Backtester (Bar Replay)

Simulate multi-agent decisions across historical MongoDB 5-minute bars without cloud costs.

The BacktestEngine executes walk-forward historical simulation over historical periods. It replays 5-minute bars sequentially, calculates indicators on rolling windows, applies entry/exit triggers, and tracks portfolio equity step-by-step:

Metrics Tracked
Win Rate % & Profit Factor
Risk Profile
Maximum Drawdown %
Performance
Total PnL & Return %
Granularity
Individual Trade Audit Log
7

API & CLI Quick Reference

Endpoints and command-line interfaces for manual inspection and automation.

REST API Endpoints

GET /api/status
Account, positions, open orders & breaker state
GET /api/quote/{symbol}
Real-time quotes (Public.com & NASDAQ Direct)
GET /api/deliberate/{symbol}
Triggers full 4-agent cognitive reasoning cycle
POST /api/backtest
Executes historical bar replay simulation
POST /api/collect-bars
Pulls and stores historical 5m bars in MongoDB
GET /help
This interactive documentation & help page

CLI Management Commands

python -m trader.cli quote NVDA
Fetches sub-second real-time quotes from Public.com & NASDAQ
python -m trader.cli scan --limit 20
Executes pre-market screening over S&P 500 / NASDAQ 100 universe
python -m trader.cli deliberate AAPL
Runs multi-agent technical + sentiment + strategist deliberation
python -m trader.cli backtest NVDA --days 30
Replays historical bar data from MongoDB or broker
python -m trader.cli web --port 8000
Launches the web cockpit and documentation server