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. |
7-Agent Deliberation Pipeline
Institutional division of labor: No single agent makes decisions in isolation. Each agent enforces a specialized domain.
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.
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.
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.
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.
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.
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.
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.
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:
Aggressive momentum long setups favored. Long dips toward EMA(9) with RSI > 50.
Short setups or capital preservation favored. Long entries vetoed unless oversold reversal confirmed.
Wide intraday swings. Position sizes automatically scaled down to prevent outsized dollar volatility.
Mean-reversion setups only between rolling 30-period support and resistance boundaries.
Indicator Computation Engine
Computed via exponential weighting: EMA_t = α × P_t + (1 - α) × EMA_{t-1} with α = 2 / (N + 1). Used to measure directional velocity and trailing support.
Measures momentum balance between average gains and average losses. RSI < 30 indicates oversold; RSI > 70 indicates overbought.
MACD line = EMA(12) - EMA(26); Signal line = EMA(9) of MACD; Histogram = MACD - Signal. Positive histogram inflection signals momentum acceleration.
ATR captures true price range including gap opens. RVOL evaluates current 5m volume against the 20-period historical rolling average.
Risk Guardrails & Mathematical Formulas
Strict portfolio safety mechanisms designed to guarantee capital preservation under all market conditions.
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).
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.
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
If tripped by daily losses or manual intervention, all deliberation is halted immediately.
If cumulative daily realized PnL drops below -$2,000, trading is terminated for the remainder of the session.
Three consecutive losing trades today immediately trips the circuit breaker to prevent revenge trading.
Strictly no more than 3 simultaneous positions are active at any time, capping aggregate market exposure.
Cannot purchase additional shares or initiate new positions in a ticker that already has an active position.
Maximum dollar loss if stop is hit is capped at 1% of account equity; portfolio-wide risk capped at 2% total.
Total trade value cannot exceed 95% of available buying power, maintaining a 5% liquid safety cushion against margin calls.
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.
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:
API & CLI Quick Reference
Endpoints and command-line interfaces for manual inspection and automation.