robinhood-options-mobile

Agentic Trading Documentation

Overview

The Agentic Trading system provides autonomous, AI-powered trading capabilities for RealizeAlpha. It combines multi-indicator technical analysis with risk management controls to execute trades automatically based on qualified trading signals.

Auto-Execution: The system includes a built-in timer that automatically checks for trading opportunities every 5 minutes when auto-trading is enabled. No manual intervention is required - simply enable auto-trading in settings and the system will monitor and execute trades autonomously.

Architecture

Components

  1. AgenticTradingConfig (lib/model/agentic_trading_config.dart)
    • User configuration model
    • Stores all trading parameters and risk controls
    • Persisted in Firestore User documents
  2. AgenticTradingProvider (lib/model/agentic_trading_provider.dart)
    • Core state management and trading execution logic
    • Implements ChangeNotifier for reactive UI updates
    • Manages trade execution, TP/SL monitoring, and safety checks
    • Handles automated buy trades tracking and Firebase persistence
    • Loads auto-trade history from Firestore ensuring persistence across app restarts
  3. TradeSignalsProvider (lib/model/trade_signals_provider.dart) [NEW]
    • Centralized trade signal management
    • Fetches signals from Firestore with real-time listeners
    • Provides indicator documentation for all 19 indicators (Price Movement, RSI, Market Direction, Volume, MACD, Bollinger Bands, Stochastic, ATR, OBV, VWAP, ADX, Williams %R, Ichimoku Cloud, CCI, Parabolic SAR, ROC, Chaikin Money Flow, Fibonacci Retracements, Pivot Points)
    • Used across InstrumentWidget, SearchWidget for consistent signal display
    • Signal Date Metadata: Signals are enriched with a date field for enhanced sorting in Firestore and historical tracking.
    • Separates signal management from execution logic
  4. FuturesAutoTradingProvider (lib/model/futures_auto_trading_provider.dart) [NEW]
    • Futures-specific auto-trading state, timers, and activity logging
    • Handles emergency stop, countdown timers, and history tracking
    • Powers FuturesTradingSettingsWidget and FuturesTradingPerformanceWidget
  5. MarketHours Utility (lib/utils/market_hours.dart) [NEW]
    • Reusable DST-aware market hours checking
    • Handles Eastern Time conversion (EDT/EST)
    • Comprehensive debug logging for troubleshooting
    • Used by providers and widgets for consistent market status
  6. AgenticTradingSettingsWidget (lib/widgets/agentic_trading_settings_widget.dart)
    • User interface for configuration
    • Real-time status monitoring with countdown timer, market analysis status, and emergency stop indicators
    • Auto-save functionality (no manual save button)
    • Manual Execution: Use the “Run Now” button to immediately trigger a market analysis and trade execution cycle.
    • Emergency Stop: Use the “Emergency Stop” button to immediately stop all automated trading activities. You can also long-press the auto-trade status badge in the app bar to quickly toggle the emergency stop.
    • Integration with both AgenticTradingProvider and TradeSignalsProvider
    • Paper Trading: Expanded paper trading functionality allows validatation of strategies across various widgets without risking real capital. Supports TP/SL monitoring in paper mode.
  7. Backend Functions (functions/src/)
    • riskguardTask: Advanced risk assessment and validation engine (powers both Agentic and Manual Trading protection)
    • RiskGuardAgent: Implements sector limits, correlation checks, and volatility filters
    • MacroAssessment: Integrates broader market conditions into trading logic for enhanced decision making
    • Trade signal generation cron jobs (daily, hourly, 15-min)
    • seedAgenticTrading function: Initializes monitored stocks (supports batch processing)
    • stock-list.ts: Source of S&P 500 symbols
  8. TradeSignalsWidget (lib/widgets/trade_signals_widget.dart) [NEW]
    • Dedicated home screen widget for trade signals
    • Provides a streamlined view of active auto-trading signals
    • Supports filtering by signal source (Strategy vs. Indicator)
    • Direct navigation to instrument details
  9. Search & Discovery Widgets (lib/widgets/search_widget.dart, screener_widget.dart, presets_widget.dart) [NEW]
    • SearchWidget: Main entry point for trade signal discovery. Features advanced filtering for signal strength and individual indicators.
    • ScreenerWidget: Dedicated stock screener interface for fundamental analysis (Market Cap, P/E, Dividend, etc.).
    • PresetsWidget: Quick access to pre-defined Yahoo Finance screeners (e.g., “Undervalued Growth”, “Day Gainers”).

Stock Universe & Seeding

The system monitoring is driven by a seeded list of documents in the charts collection.

Seeding the Database

To initialize or expand the list of monitored stocks, use the seedAgenticTrading Firebase Cloud Function.

Usage: Call the function with a JSON body to seed the charts collection.

Options:

Features

Trade Signals Widget

The dedicated Trade Signals Widget offers a focused view of all active trading signals generated by the system.

Trade Signal Discovery

The Search tab provides powerful tools to discover and filter trade signals generated by the Agentic Trading system.

Filtering Capabilities:

Exclusive Filtering Logic: To prevent conflicting queries, the system enforces exclusivity between high-level strength filters and granular indicator filters:

Performance Optimization:

Signal Processing & Deduplication

To ensure reliability and prevent duplicate trades, the system implements robust signal processing logic:

Paper Trading Mode

The system includes a fully functional Paper Trading Mode for risk-free strategy testing and validation.

Key Features:

How to Enable:

  1. Go to Agentic Trading Settings.
  2. Toggle Paper Trading Mode to ON.
  3. Configure your trading parameters as usual.
  4. Enable Auto-Trade.

Note: When Paper Trading is enabled, NO real orders will be sent to your brokerage.

Trading Strategy Management

New in v0.28.1

The system now offers centralized management for trading strategies, allowing users to switch between different trading styles and risk profiles instantly.

Strategies Page:

Entry Strategies:

Default Strategies: The system comes with a library of professionally designed templates to get you started:

  1. Momentum Master (Trend): Captures strong price moves by combining RSI and CCI momentum with MACD confirmation and Volume validation.
  2. Mean Reversion (Reversal): Identifies overbought/oversold reversals using Bollinger Bands, CCI, and RSI extremes.
  3. Trend Follower (Swing): Rides established trends using Moving Averages, Ichimoku Cloud, ADX trend strength, and OBV flow.
  4. Volatility Breakout (1h) (Intraday): Exploits explosive moves from squeeze conditions using Bollinger Bands, CCI, ATR, and VWAP.
  5. Intraday Scalper (15m) (Scalping): Short-term scalping via CCI/Stochastic with strict risk management (partial exits, tight stops).
  6. Custom EMA Trend (Custom): Automatically engages when Price crosses above the 21-period EMA.
  7. Crypto Proxy Momentum (Crypto): High-volatility momentum strategy (CCI, RSI) designed for crypto-correlated stocks.
  8. Golden Cross & RSI Filter (Classic): Classic 50/200 SMA Cross combined with RSI < 70 to avoid buying tops.
  9. Range Bound Income (Income): Ideal for sideways markets. Profitable when Price Movement and CCI Impulse are low.
  10. Strict Confluence (Conservative): High conviction entries requiring ALL enabled indicators (Momentum, Moving Avg, MACD) to agree.
  11. Risk-Managed Growth (Position Sizing): Uses dynamic position sizing to risk exactly 1% of account equity per trade.
  12. MACD Histogram Reversal (Reversal): Trades when MACD histogram flips positive while RSI is oversold (< 40).
  13. Bollinger Band Squeeze (Breakout): Breakout strategy. Low volatility period (ATR) followed by price piercing Upper Band.
  14. VWAP Pullback Entry (Intraday): Intraday trend is UP (Price > SMA), but entry is a pullback to VWAP.
  15. 0DTE Scalper (5m) (High Frequency): SPY 5m chart, riding rapid momentum (CCI/RSI) bursts with tight risk.
  16. Tech Sector Swing (Sector): Trend following on XLK (Tech Sector). Captures multi-day moves.
  17. Defensive Value (Low Beta): Low-beta strategy on SCHD. Buys dips (RSI < 30) in uptrends with CCI oversold confirmation.
  18. Ichimoku Cloud Breakout (Trend): Trend-following strategy utilizing the Ichimoku Cloud for support/resistance.
  19. Triple Screen Simulation (System): Simulates Elder’s Triple Screen: Trend (MACD/SMA) + Oscillator (Stochastic/Williams) + Breakout.
  20. Opening Range Breakout (Morning): Exploits early market volatility (9:30-10:30 AM). Uses VWAP as anchor.
  21. Turtle Trend Follower (Long Term): Long-term breakout strategy inspired by Turtle Traders. Buys new highs.
  22. RSI Fade (Contrarian): Fades overextended moves. Sells when RSI > 75 and price hits upper Bollinger Band.

Automatic Execution

The system automatically executes trades when auto-trading is enabled:

Timer-Based Execution:

Execution Cycle:

  1. Timer triggers every 5 minutes
  2. Checks if auto-trading is enabled in config
  3. Validates market hours using MarketHours.isMarketOpen()
  4. Validates required data (user, account, portfolio)
  5. Builds current portfolio state
  6. Calls autoTrade() with all parameters
  7. Calls monitorTakeProfitStopLoss() for automated trades
  8. Updates countdown timer for next cycle
  9. Logs execution results

Location: AgenticTradingProvider (lib/model/agentic_trading_provider.dart) - Centralized provider managing trading state and execution logic.

UI Integration:

Auto-Trade Logic

The autoTrade() method orchestrates automatic trade execution:

Future<Map<String, dynamic>> autoTrade({
  required Map<String, dynamic> portfolioState,
}) async

Process Flow:

  1. Pre-flight Checks (_canAutoTrade())
    • Verify auto-trade is enabled
    • Check emergency stop status
    • Validate market hours
    • Enforce daily trade limit
    • Verify cooldown period has elapsed
    • Check daily loss limit
  2. Signal Processing
    • Fetch current trade signals from Firestore
    • Filter for BUY signals
    • Validate signal quality
  3. Trade Execution
    • Call initiateTradeProposal() for each qualified signal
    • Assess risk with riskguardTask
    • Track execution history
    • Update counters and timestamps
  4. Post-Trade Actions
    • Log analytics events
    • Update UI state
    • Enforce rate limiting between trades
    • Record enabledIndicators snapshot for performance analysis
    • Mark trade as real or paper mode

Advanced Risk Controls

The system now includes a sophisticated RiskGuardAgent that enforces portfolio-level risk management rules before any trade is executed. These controls are configurable in the Agentic Trading Settings.

Partial Position Exits:

Stop Loss & Take Profit:

Advanced Risk Controls:

Safety Checks:

Key Risk Features:

Custom Indicators

Users can now define their own technical indicators to be used alongside the standard 15-indicator system.

ML Optimization

Machine Learning models are integrated to continuously optimize trade signals, leveraging Google’s Vertex AI Gemini 1.5 Flash model for high-speed, cost-effective analysis.

Advanced Exit Strategies

In addition to standard Stop Loss and Take Profit, the system supports sophisticated exit strategies:

Order Approval Workflow

For users who want the benefits of AI signal generation but prefer manual control over execution, the system offers an Order Approval Workflow.

How it works:

  1. Enable Approval: Toggle requireApproval in Agentic Trading Settings.
  2. Signal Generation: The system generates trade proposals as usual based on signals and risk checks.
  3. Pending State: Instead of executing immediately, orders are placed in a “Pending Approval” queue.
  4. Notification: The user receives a notification about the pending order.
  5. Review & Action:
    • Users can review pending orders in the Agentic Trading Settings.
    • Approve: The order is sent to the brokerage for execution.
    • Reject: The order is discarded.
    • Timeout: Pending orders may expire if not acted upon within a certain timeframe (configurable).

Advanced Performance Analytics

The AgenticTradingPerformanceWidget provides comprehensive trading insights across 9 analytics cards:

1. Performance Overview

2. Profit & Loss

3. Trade Breakdown

4. Best & Worst Trades

5. Advanced Analytics (4-Metric Grid)

6. Risk Metrics

7. Performance by Time of Day

8. Performance by Indicator Combo (v1.3)

9. Performance by Symbol

Paper vs Real Performance Tracking (v1.3)

Key Metrics Explained:

Sharpe Ratio

Profit Factor

Expectancy

Max Drawdown

The monitorTakeProfitStopLoss() method automatically exits positions when targets are met:

Future<Map<String, dynamic>> monitorTakeProfitStopLoss({
  required List<dynamic> positions,
  required brokerageUser,
  required account,
  required brokerageService,
  required instrumentStore,
}) async

Monitoring Flow:

  1. Position Filtering
    • Check only positions created by automated trading
    • Positions tracked in _automatedBuyTrades list
    • Manual trades and pre-existing positions are NOT monitored
  2. Position Analysis
    • Iterate through automated trade records
    • Extract entry price and current price
    • Calculate profit/loss percentage using trade record’s entry price
    • Update highestPrice for trailing stop tracking
  3. Threshold Checks
    • If P/L >= takeProfitPercent: Trigger Take Profit exit
    • If P/L <= -stopLossPercent: Trigger Stop Loss exit
    • If Trailing Stop enabled: Check if price dropped below (highestPrice - trailingStopPercent)
  4. Order Execution
    • Check paperTradingMode: Simulate or execute real order
    • Fetch instrument data for the symbol
    • Place SELL order through brokerage service (or simulate in paper mode)
    • Validate order response (200/201 status)
    • Remove trade record from _automatedBuyTrades
    • Track exit in history with reason and P/L%
  5. Analytics & Logging
    • Log exit execution events
    • Track failures separately
    • Update trade history with paper/real indicator
    • Record exit reason (Take Profit/Stop Loss/Trailing Stop)
  6. Persistence
    • Save updated trades list to Firebase after exits
    • Ensures accuracy across sessions

Integration:

Trade-Level Tracking:

Trailing Stop Loss:

Paper Trading Simulation:

Example - Automated Position:

Auto-trade buys: 10 AAPL at $150 → Trade record created
Record: {symbol: 'AAPL', quantity: 10, entryPrice: 150.00, timestamp: '...', enabledIndicators: ['momentum', 'macd'], paperMode: false, highestPrice: 150.00}
Current price: $165 → highestPrice updated to 165.00
P/L = ((165 - 150) / 150) * 100 = 10%

Scenario 1 - Take Profit:
If takeProfitPercent = 10%: Trigger SELL 10 shares
After exit: Trade record removed, analytics updated

Scenario 2 - Trailing Stop:
If trailingStopEnabled = true, trailingStopPercent = 3%
Price rises to $170 (highestPrice = 170.00)
Price drops to $165 (drop = 2.9%, below 3% threshold)
No exit yet

Price drops to $164.80 (drop = 3.05%, exceeds 3% threshold)
Trigger SELL 10 shares at $164.80
Locked in profit from $150 to $164.80

**Example - Manual + Automated Same Symbol:**

User owns: 100 AAPL at $140 (manual, not tracked) Auto-trade buys: 10 AAPL at $150 (tracked separately) Current price: $165

For automated trade: P/L = ((165 - 150) / 150) * 100 = 10% Action: SELL 10 shares (from automated trade) Result: Manual 100 shares @ $140 remain untouched


**Example - Multiple Automated Trades:**

Auto-trade 1: Buy 10 AAPL @ $150 (tracked) Auto-trade 2: Buy 5 AAPL @ $160 (tracked separately) Current price: $165

Trade 1 P/L: ((165-150)/150)100 = 10% → Triggers TP, SELL 10 shares Trade 2 P/L: ((165-160)/160)100 = 3.1% → No trigger Result: Two separate entries, tracked and managed independently


### Firebase Persistence

**Automated Buy Trades Storage:**
- **Collection Path**: `users/{userId}/automated_buy_trades`
- **Document Structure**: Each trade as a separate document
- **Fields**: 
  - `symbol`: Stock symbol (string)
  - `quantity`: Number of shares (int)
  - `entryPrice`: Entry price per share (double)
  - `timestamp`: Execution time (ISO string)
  - `enabledIndicators`: Active indicators at trade time (List<String>) *(v1.3)*
  - `paperMode`: Whether trade was simulated (bool) *(v1.3)*
  - `highestPrice`: Peak price for trailing stop tracking (double) *(v1.3)*
- **Security Rules**: Updated firestore.rules to allow read/write for authenticated users

**Automatic Saving:**
- Trades saved immediately after BUY order execution
- Trades removed immediately after TP/SL/Trailing Stop exit
- Ensures data integrity across app restarts
- Field validation on load for data integrity
- **Paper trades**: Persisted identically to real trades (marked with `paperMode: true`)

**Loading:**
- Trades loaded on user login (via `loadAutomatedBuyTradesFromFirestore`)
- Automatic sync across devices
- Enables continuous TP/SL monitoring across sessions
- Try-catch error handling for robustness
- Validates all required fields when loading

**Benefits:**
- **Persistence**: Survives app crashes and restarts
- **Cross-Device**: User logs in on different device, trades sync
- **Reliability**: Firebase ensures data availability
- **History**: Complete audit trail of automated trades
- **Security**: Firestore rules protect user data
- **Analytics**: enabledIndicators enable performance analysis by indicator combination
- **Paper Tracking**: Separates paper and real trades for comparison

**Example Workflow:**

Session 1:

App restart:

Switch to Real Mode:

Device switch:

Trade Record Example:

{
  "symbol": "AAPL",
  "quantity": 10,
  "entryPrice": 150.25,
  "timestamp": "2025-12-13T14:30:45.123Z",
  "enabledIndicators": ["momentum", "macd", "volume"],
  "paperMode": false,
  "highestPrice": 155.50
}

Provider Architecture

Separation of Concerns:

The recent refactoring (commit 861f2bc) introduced a cleaner architecture with separated responsibilities:

  1. TradeSignalsProvider:
    • Purpose: Centralized signal management
    • Responsibilities:
      • Fetch trade signals from Firestore
      • Real-time signal listeners
      • Provide indicator documentation
      • Market status checking
    • Usage: InstrumentWidget, SearchWidget, etc.
  2. AgenticTradingProvider:
    • Purpose: Trade execution and automation
    • Responsibilities:
      • Auto-trade execution logic
      • TP/SL monitoring
      • Trade tracking (automated buy trades)
      • Firebase persistence
      • Risk management
    • Usage: NavigationWidget (timer), SettingsWidget
  3. MarketHours Utility:
    • Purpose: Consistent market hours checking
    • Functionality:
      • DST-aware Eastern Time conversion
      • Weekend detection
      • Market hours validation (9:30 AM - 4:00 PM ET)
    • Usage: Both providers and widgets

Benefits of Refactoring:

Risk Management Controls

Daily Trade Limit

Cooldown Period

Emergency Stop

Position Size Limits

Portfolio Concentration

Take Profit

Stop Loss

Configuration Parameters

Technical Analysis

smaPeriodFast: 10           // Fast moving average period
smaPeriodSlow: 30           // Slow moving average period
rsiPeriod: 14               // RSI calculation period
marketIndexSymbol: 'SPY'    // Reference market index

Trade Execution

autoTradeEnabled: false     // Master auto-trade switch
autoTradeCooldownMinutes: 60 // Minutes between trades

strategyConfig: {
  tradeQuantity: 1,           // Shares per trade
  dailyTradeLimit: 5,         // Max trades per day
  maxPositionSize: 100,       // Max shares per position
  maxPortfolioConcentration: 0.5, // Max 50% in single position
  takeProfitPercent: 10.0,    // Auto-exit at 10% profit
  stopLossPercent: 5.0,       // Auto-exit at 5% loss
  skipRiskGuard: false        // Optional: Skip risk checks for this agent
}

Indicators

enabledIndicators: {
  'priceMovement': true,      // Chart patterns & trends
  'momentum': true,           // RSI (overbought/oversold)
  'marketDirection': true,    // Market index trend
  'volume': true,             // Volume confirmation
  'macd': true,              // MACD crossovers
  'bollingerBands': true,    // Volatility bands
  'stochastic': true,        // Stochastic oscillator
  'atr': true,               // Average True Range
  'obv': true,               // On-Balance Volume
}

Macro Assessment

The system integrates a high-level macroeconomic analysis engine to contextually adjust trading behavior. This ensures that the agent is not just reacting to individual stock charts but is aware of the broader economic environment.

Core Metrics

Integration with Trading

User Interface

Settings Screen

Access via:

Recent UI Improvements (commit 861f2bc):

Sections:

  1. Master Toggle
    • Enable/disable agentic trading system
    • Shows current status with descriptive subtitle
    • Auto-saves on toggle
  2. Automated Trading
    • Auto-trade toggle
    • Real-time countdown timer (shows seconds until next check)
    • Status indicators (active, daily count, last trade time, next trade time)
    • Emergency stop button with confirmation dialog
    • Auto-saves on toggle
  3. Auto-Trade Configuration
    • Daily trade limit (auto-saves on change)
    • Cooldown period (auto-saves on change)
    • Max daily loss percentage (auto-saves on change)
    • Take profit percentage (auto-saves on change)
    • Stop loss percentage (auto-saves on change)
  4. Risk Management Rules
    • Trade quantity
    • Max position size
    • Portfolio concentration limit
  5. Technical Indicators
    • Individual indicator toggles
    • Inline documentation
    • Configuration parameters (RSI period, SMA periods, etc.)

Status Indicators

Auto-Trading Active:

🔄 Auto-trading in progress...

Normal Status:

Daily Trades: 3/5
Last Trade: 2h ago

Emergency Stop:

⚠️ Emergency Stop Activated [Resume]

Integration Points

Trade Signal Generation

Risk Assessment

Brokerage Integration

Safety Features

Market Hours Detection

Rate Limiting

Error Handling

Audit Trail

Testing

Unit Tests

Location: test/agentic_trading_*_test.dart

Test Files:

  1. agentic_trading_config_test.dart - Configuration model tests
  2. agentic_trading_provider_test.dart - Provider logic tests
  3. agentic_trading_settings_widget_test.dart - UI widget tests [NEW]

Coverage:

Run Tests:

# All agentic trading tests
flutter test test/agentic_trading_config_test.dart
flutter test test/agentic_trading_provider_test.dart
flutter test test/agentic_trading_settings_widget_test.dart

# Or run all at once
flutter test test/ --name="agentic"

New Widget Tests (commit 861f2bc):

Integration Testing

Recommended approach:

  1. Use paper trading mode
  2. Test with small position sizes
  3. Monitor execution closely
  4. Validate risk controls
  5. Test emergency stop

Security Considerations

Configuration Storage

Trade Execution

Firebase Security Rules

// New rules for automated buy trades (commit 861f2bc)
match /users/{userId}/automated_buy_trades/{tradeId} {
  allow read, write: if request.auth != null && request.auth.uid == userId;
}

Rate Limiting

Best Practices

Initial Setup

  1. Start with conservative limits (1-2 trades/day)
  2. Use longer cooldown periods (60+ minutes)
  3. Set tight loss limits (1-2%)
  4. Monitor closely for first week

Risk Management

  1. Never risk more than 2% of portfolio per day
  2. Keep position sizes small relative to portfolio
  3. Maintain portfolio diversification
  4. Use emergency stop if uncertain

Monitoring

  1. Check trade history daily
  2. Review rejected proposals
  3. Adjust indicators based on performance
  4. Monitor analytics events

Emergency Procedures

  1. Market Volatility: Activate emergency stop
  2. System Issues: Disable auto-trade, investigate
  3. Unexpected Behavior: Stop immediately, review logs

Analytics Events

The system logs the following events:

Future Enhancements

Planned Features

  1. Push Notifications: Alert on auto-trade executions
  2. Performance Tracking: Win/loss ratio, P&L analytics
  3. Backtesting: Historical strategy simulation
  4. Machine Learning: Adaptive indicator weighting
  5. Advanced Orders: Stop-loss, take-profit automation
  6. Portfolio Rebalancing: Automatic position adjustment

Under Consideration

Troubleshooting

Auto-Trade Not Executing

Check:

  1. Is autoTradeEnabled true in settings?
  2. Is emergency stop activated?
  3. Is market currently open?
  4. Have you reached daily trade limit?
  5. Is cooldown period active?
  6. Are there any BUY signals available?

Debug Steps:

  1. Check provider state: provider.isAutoTrading
  2. Review _canAutoTrade() conditions
  3. Verify trade signals: provider.tradeSignals
  4. Check analytics logs for error events

Trades Being Rejected

Common Causes:

  1. Risk assessment failure (position too large)
  2. Portfolio concentration limit exceeded
  3. Insufficient funds
  4. Invalid price data
  5. Brokerage API errors

Resolution:

  1. Review lastAssessment for rejection reason
  2. Adjust position sizes or limits
  3. Check brokerage account status
  4. Verify market data availability

Emergency Stop Not Working

Verification:

  1. Check provider.emergencyStopActivated state
  2. Verify UI shows emergency status
  3. Test with manual toggle in settings

If Issue Persists:

  1. Restart app
  2. Check Firestore config sync
  3. Review error logs

API Reference

AgenticTradingProvider Methods

autoTrade({required Map<String, dynamic> portfolioState, required brokerageUser, required account, required brokerageService, required instrumentStore})

Executes automatic trading based on current signals and places orders through the brokerage.

Parameters:

Returns: Map<String, dynamic>

activateEmergencyStop()

Immediately halts all auto-trading.

deactivateEmergencyStop()

Resumes auto-trading functionality.

loadConfigFromUser(dynamic agenticTradingConfig)

Loads configuration from User model.

updateConfig(Map<String, dynamic> newConfig, DocumentReference userDocRef)

Updates configuration and saves to Firestore.

monitorTakeProfitStopLoss({required List positions, required brokerageUser, required account, required brokerageService, required instrumentStore})

Monitors positions and executes take profit or stop loss orders.

Parameters:

Returns: Map<String, dynamic>

Process:

  1. Calculates P/L percentage for each position
  2. Triggers SELL when P/L >= takeProfitPercent
  3. Triggers SELL when P/L <= -stopLossPercent
  4. Places orders and tracks exits

Static Methods

TradeSignalsProvider.indicatorDocumentation(String key) [MOVED]

Returns documentation for a given indicator.

Note: This method was moved from AgenticTradingProvider to TradeSignalsProvider in commit 861f2bc as part of the architecture refactoring.

Parameters:

Returns: Map<String, String>

Usage:

final docInfo = TradeSignalsProvider.indicatorDocumentation('priceMovement');
print(docInfo['title']);         // "Price Movement"
print(docInfo['documentation']); // Full description

Support

For issues or questions:

  1. Review this documentation
  2. Check unit tests for examples
  3. Consult multi-indicator-trading.md for signal details
  4. Review Firebase Analytics for system events
  5. File a GitHub issue with detailed logs

Integration Examples

Basic Setup (New Architecture)

In main.dart:

MultiProvider(
  providers: [
    // New: TradeSignalsProvider for signal management
    ChangeNotifierProvider(
      create: (context) => TradeSignalsProvider(),
    ),
    // Existing: AgenticTradingProvider for execution
    ChangeNotifierProvider(
      create: (context) => AgenticTradingProvider(),
    ),
    // ... other providers
  ],
  child: MaterialApp(/* ... */),
)

Fetching Trade Signals (TradeSignalsProvider)

In any widget:

// Access the provider
final tradeSignalsProvider = Provider.of<TradeSignalsProvider>(context);

// Fetch signals for a symbol
await tradeSignalsProvider.fetchTradeSignals(
  symbol: 'AAPL',
  interval: '1d',
  userDocRef: userDocRef,
);

// Access the signals
final signals = tradeSignalsProvider.signals;

Executing Auto-Trade (AgenticTradingProvider)

From navigation widget (timer integration):

final agenticProvider = Provider.of<AgenticTradingProvider>(context, listen: false);
final accountStore = Provider.of<AccountStore>(context, listen: false);
final instrumentStore = Provider.of<InstrumentStore>(context, listen: false);

final result = await agenticProvider.autoTrade(
  portfolioState: {
    'equity': portfolioStore.equity,
    'cash': accountStore.items.first.portfolioCash,
    // ... other portfolio data
  },
  brokerageUser: currentUser,
  account: accountStore.items.first,
  brokerageService: brokerageService,
  instrumentStore: instrumentStore,
  userDocRef: userDocRef,  // For Firebase persistence
);

Monitoring TP/SL

From navigation widget (timer integration):

final positions = portfolioStore.positions;

final result = await agenticProvider.monitorTakeProfitStopLoss(
  positions: positions,
  brokerageUser: currentUser,
  account: accountStore.items.first,
  brokerageService: brokerageService,
  instrumentStore: instrumentStore,
  userDocRef: userDocRef,  // For Firebase persistence
);

Checking Market Hours

Using MarketHours utility:

import 'package:robinhood_options_mobile/utils/market_hours.dart';

if (MarketHours.isMarketOpen()) {
  // Market is open, proceed with trading
  print('✅ Market is open');
} else {
  // Market is closed
  print('❌ Market is closed');
}

Settings Widget Integration

Navigate to settings:

Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => AgenticTradingSettingsWidget(
      user: currentUser,
      userDocRef: userDocRef,
    ),
  ),
);

Settings now auto-save - no manual save button needed. Every change is persisted immediately to Firestore.

SliverAppBar Status Badge

The refactored SliverAppBar now shows auto-trade status:

// Automatically displays when auto-trading is active
// Shows countdown timer
// Tapping navigates to settings
// No manual integration needed - built into SliverAppBar

Version History