Skip to content

Trading Agents Overview

Multi-agent architecture for automated trading with event-driven communication


December 2025 Status

6-AGENT TRADING SYSTEM ACTIVE - Event-driven via Redis Pub/Sub

Component Status Details
Market Data Agent ✅ Active Real-time quotes from Alpaca API
Strategy Agent ✅ Active Trend following + sentiment integration
Sentiment Analyst ✅ Active BrightData + FinBERT scoring
Risk Management ✅ Active Position sizing, portfolio limits
Order Execution ✅ Active MARKET/LIMIT/STOP orders
Position Management ✅ Active ATR stops, trailing stops, profit-taking

Portfolio: Alpaca Paper ~$101k (19 positions) | Alpaca Live ~$1.6k | Schwab ~$2.7k


Architecture

The trading system uses a 6-agent architecture with event-driven communication via Redis Pub/Sub:

graph TB
    subgraph "Trading Agents System"
        MD[Market Data Agent]
        ST[Strategy Agent]
        SA[Sentiment Analyst Agent]
        RM[Risk Management Agent]
        OE[Order Execution Agent]
        PM[Position Management Agent]
    end

    subgraph "Message Bus"
        REDIS[(Redis Pub/Sub)]
    end

    subgraph "External Systems"
        ALPACA[Alpaca API]
        LLM[LM Studio / FinBERT]
        NEWS[News Sources]
    end

    MD -->|market_data.quote.updated| REDIS
    MD -->|market_data.bars.received| REDIS
    ST -->|strategy.entry_signal| REDIS
    SA -->|sentiment.score| REDIS
    SA -->|sentiment.alert| REDIS
    RM -->|risk.trade_approved| REDIS
    OE -->|order.filled| REDIS
    PM -->|position.opened| REDIS

    REDIS -->|Events| ST
    REDIS -->|Events| RM
    REDIS -->|Events| OE
    REDIS -->|Events| PM

    MD <-->|API Calls| ALPACA
    OE <-->|Order Submit| ALPACA
    PM <-->|Stop Orders| ALPACA
    SA <-->|Sentiment| LLM
    SA <-->|Scrape| NEWS

    style MD fill:#e1f5ff
    style ST fill:#fff4e6
    style SA fill:#f3e5f5
    style RM fill:#ffebee
    style OE fill:#e8f5e9
    style PM fill:#fff3e0

Agent Responsibilities

1. Market Data Agent

Role: Real-time market data fetching and distribution

Responsibilities: - Fetch real-time quotes from Alpaca API - Fetch historical bars for technical analysis - Check market open/closed status - Circuit breaker protection for API calls

Events Published: - market_data.quote.updated - Latest quote for symbol - market_data.bars.received - Historical bars data - market_data.status.updated - Market open/closed status

Events Subscribed: - market_data.get_quote - Request for latest quote - market_data.get_bars - Request for historical bars - market_data.check_status - Request for market status


2. Strategy Agent

Role: Trend following strategy with sentiment integration

Responsibilities: - Scan for entry candidates (MA20, RSI, volume) - Evaluate technical indicators - Generate entry/exit signals with sentiment weighting - Manage trade state machines - Monitor positions for exit conditions

Strategy: Trend Following 3:1 R/R + Sentiment - Entry: Price > MA20, RSI 50-70, Volume > 1.5x average - Sentiment: Score from SentimentAnalystAgent (-1 to +1) - Stop: ATR-based dynamic (15-24% micro-cap, 8-15% large-cap) - Target: 3:1 risk/reward ratio

Sentiment Integration (NEW 2025-11-26): - Strongly negative sentiment (-0.6 or below) can VETO entries - Strongly positive sentiment (+0.5 or above) enables 25% larger positions - Combined score = technical_score + (sentiment_score * 20 * confidence)

Events Published: - strategy.candidate_found - Potential entry detected - strategy.entry_signal - Entry criteria met (with sentiment data) - strategy.exit_signal - Exit condition met (target/stop/time)

Events Subscribed: - strategy.scan - Request to scan for candidates - strategy.evaluate - Request to evaluate specific symbol - position.opened - Track new position - sentiment.score - Receive sentiment analysis results


3. Sentiment Analyst Agent

Role: Real-time news sentiment analysis for trading signals

Responsibilities: - Scrape news/social media using BrightData MCP - Score sentiment (-1.0 to +1.0) using FinBERT or LM Studio - Provide confidence levels based on source count - Alert on significant sentiment shifts - Cache results to avoid redundant API calls

Sentiment Scoring: - +0.75 to +1.00: Strongly bullish (major positive catalyst) - +0.25 to +0.74: Moderately bullish (positive news flow) - -0.24 to +0.24: Neutral (mixed or no significant news) - -0.74 to -0.25: Moderately bearish (negative news flow) - -1.00 to -0.75: Strongly bearish (major negative catalyst)

Confidence Levels: - 0.80+: High confidence (10+ sources, consistent sentiment) - 0.50-0.79: Medium confidence (5-9 sources, mostly consistent) - <0.50: Low confidence (few sources, mixed signals)

Events Published: - sentiment.score - Sentiment analysis complete - sentiment.alert - Significant sentiment shift detected

Events Subscribed: - sentiment.analyze - Request to analyze symbol - strategy.candidate_found - Auto-analyze new candidates


4. Risk Management Agent

Role: Trade validation and position sizing

Responsibilities: - Calculate position size based on risk parameters - Validate trades against portfolio limits - Enforce cash reserve requirements - Approve or reject trade requests - Handle sentiment alerts (block entries on bearish alerts)

Risk Rules: - Max position size: $1000 (configurable) - Max portfolio exposure: 20% per position - Min cash reserve: 50% of portfolio - Min risk/reward ratio: 2.5:1 - Stop loss required: Always

Sentiment Integration (NEW 2025-11-26): - Respects position_size_multiplier from StrategyAgent - Subscribes to sentiment.alert for symbol blocking - Blocks new entries for symbols with HIGH severity bearish alerts

Events Published: - risk.trade_approved - Trade meets all risk criteria - risk.trade_rejected - Trade violates risk rules - risk.size_calculated - Position size determined - risk.review_position - Review existing position (sentiment trigger)

Events Subscribed: - strategy.entry_signal - Validate entry requests - risk.calculate_size - Calculate position size - risk.check_limits - Validate against limits - sentiment.alert - Handle sentiment alerts


5. Order Execution Agent

Role: Order submission and lifecycle tracking

Responsibilities: - Submit orders to broker (Alpaca API) - Track order status (submitted, filled, rejected, cancelled) - Handle fills and partial fills - Manage order state machines - Circuit breaker protection

Order Types Supported: - MARKET orders - LIMIT orders - STOP orders

Events Published: - order.submitted - Order sent to broker - order.accepted - Broker accepted order - order.filled - Order fully executed - order.partially_filled - Partial execution - order.rejected - Broker rejected order - order.cancelled - Order cancelled

Events Subscribed: - order.submit - Request to place new order - order.cancel - Request to cancel pending order - order.status - Request for order status


6. Position Management Agent

Role: Position tracking and protection

Responsibilities: - Track all open positions - Set and update stop loss orders - Calculate unrealized P&L - Monitor for stop/target hits - Handle short positions correctly - Trailing stops for profitable positions - Automatic profit-taking (20%/50% targets)

Position Protection: - ATR-based Dynamic Stops (Phase 5): - Micro-caps: 15-24% ATR-based (vs. old fixed 9%) - Large-caps: 8-15% ATR-based (vs. old fixed 5%) - Trailing Stops: Lock in profits as price rises - Profit-Taking: - Sell 50% at +20% gain - Sell remaining at +50% gain - Pre-Earnings Reduction: Reduce positions by 50% if earnings within 7 days

Events Published: - position.opened - New position tracked - position.stop_set - Stop loss order placed - position.stop_hit - Stop loss triggered - position.target_hit - Profit target reached - position.pnl_updated - P&L recalculated - position.trailing_stop_updated - Stop price trailed up

Events Subscribed: - risk.trade_approved - Place entry order and track - order.filled - Update position with fill data - market_data.quote.updated - Monitor for exits


Current Portfolio Status

As of December 23, 2025:

Account Type Balance Positions
Alpaca Paper Practice ~$101,000 19 positions
Alpaca Live Live ~$1,600 1 position
Schwab ...6800 Live ~$2,700 Manual only

Event Flow Example

Here's how a typical trade flows through the system:

sequenceDiagram
    participant ST as Strategy Agent
    participant SA as Sentiment Agent
    participant RM as Risk Management
    participant OE as Order Execution
    participant PM as Position Management
    participant MD as Market Data
    participant REDIS as Message Bus

    ST->>REDIS: market_data.get_quote (AAPL)
    REDIS->>MD: Request quote
    MD->>REDIS: market_data.quote.updated
    REDIS->>ST: Quote received

    ST->>REDIS: sentiment.analyze (AAPL)
    REDIS->>SA: Analyze request
    SA->>REDIS: sentiment.score (+0.65, 80% conf)
    REDIS->>ST: Sentiment received

    ST->>REDIS: strategy.entry_signal (AAPL, sentiment boost)
    REDIS->>RM: Entry validation

    RM->>REDIS: risk.trade_approved (qty, prices)
    REDIS->>PM: Approved trade

    PM->>REDIS: order.submit (BUY 10 AAPL @ $175.50)
    REDIS->>OE: Submit order

    OE->>REDIS: order.filled (10 shares @ $175.48)
    REDIS->>PM: Fill notification

    PM->>REDIS: position.opened (AAPL, stop @ $166.70)
    PM->>REDIS: position.stop_set (stop order placed)

State Machines

Trade State Machine (StrategyAgent)

IDLE
  └→ SETUP_DETECTED (MA20, RSI, volume met)
      └→ ENTRY_APPROVED (risk checks passed)
          └→ ORDER_PLACED (order submitted)
              └→ FILLED (execution confirmed)
                  └→ HOLDING (monitoring position)
                      ├→ EXIT_TRIGGERED (target/stop hit)
                      │   └→ CLOSED (position exited)
                      └→ STOPPED_OUT (stop loss hit)
                          └→ CLOSED

Order State Machine (OrderExecutionAgent)

PENDING_SUBMISSION
  └→ SUBMITTED (sent to broker)
      └→ ACCEPTED (broker acknowledged)
          ├→ FILLED (fully executed)
          ├→ PARTIALLY_FILLED (partial execution)
          │   └→ FILLED (completed)
          ├→ REJECTED (broker rejected)
          └→ CANCELLED (user cancelled)

Circuit Breakers

All agents using external APIs (Market Data, Order Execution, Position Management) implement circuit breaker protection:

Thresholds: - Failure rate: >50% failures in window - Minimum requests: 5 requests before opening - Recovery timeout: 60 seconds - Half-open max calls: 1 call to test recovery

States: 1. CLOSED: Normal operation 2. OPEN: API calls blocked (too many failures) 3. HALF_OPEN: Testing recovery (1 call allowed)


Distributed Tracing

All agents use OpenTelemetry for observability:

Trace Attributes: - agent.name - Which agent generated the span - event.name - Event type being processed - trace.id - Correlation ID across agents - error - Whether the operation failed - error.message - Error details

Example Trace:

strategy.entry_signal [trace_id: abc123]
├─ risk_management.approve_trade
│  ├─ alpaca.get_account (circuit breaker)
│  └─ position_size_calculation
├─ order_execution.submit_order
│  └─ alpaca.submit_order (circuit breaker)
└─ position_management.track_position
   └─ alpaca.submit_stop_order (circuit breaker)


Running the System

Start All Agents

from trading_agents import (
    MarketDataAgent,
    StrategyAgent,
    SentimentAnalystAgent,
    RiskManagementAgent,
    OrderExecutionAgent,
    PositionManagementAgent
)

# Initialize agents
market_data = MarketDataAgent(paper=True)
strategy = StrategyAgent()
sentiment = SentimentAnalystAgent(use_finbert=True)
risk = RiskManagementAgent(max_position_size=1000)
orders = OrderExecutionAgent(paper=True)
positions = PositionManagementAgent(paper=True)

# Start agents
market_data.start()
strategy.start()
sentiment.start()
risk.start()
orders.start()
positions.start()

# Agents now communicate via Redis Pub/Sub
# System is event-driven and asynchronous

Trigger a Strategy Scan

# Publish scan request event
strategy.publish_event(
    event="strategy.scan",
    data={
        "symbols": ["AAPL", "NVDA", "TSLA", "AMD", "PLTR"]
    }
)

# System will:
# 1. MarketDataAgent fetches quotes/bars
# 2. SentimentAnalystAgent analyzes news
# 3. StrategyAgent evaluates setups
# 4. RiskManagementAgent validates trades
# 5. OrderExecutionAgent submits orders
# 6. PositionManagementAgent tracks positions

Key Features

1. Event-Driven Architecture

  • Agents communicate via Redis Pub/Sub
  • Asynchronous, non-blocking operations
  • Loose coupling between components
  • Easy to add/remove agents

2. Sentiment Integration

  • Real-time news analysis via BrightData + FinBERT
  • Sentiment can VETO entries (-0.6 threshold)
  • Sentiment can BOOST positions (+0.5 threshold, 25% larger)
  • Combined technical + sentiment scoring

3. Dynamic Risk Management

  • ATR-based stops (adapts to volatility)
  • Trailing stops lock in profits
  • Automatic profit-taking (20%/50%)
  • Pre-earnings risk reduction

4. Circuit Breaker Protection

  • Prevents cascading failures
  • Auto-recovery after timeout
  • Protects against API rate limits
  • Maintains system stability

5. Distributed Tracing

  • OpenTelemetry integration
  • Trace events across agents
  • Debug complex workflows
  • Performance monitoring

References


Last Updated: January 10, 2026 Platform: 6 Trading Agents | Redis Pub/Sub | Alpaca Paper ~$101k | Circuit Breaker Protection