# Agent Trigger Tools Agent tools for automating tasks via the trigger system. ## Overview These tools allow the agent to: - **Schedule recurring tasks** - Run agent prompts on intervals or cron schedules - **Execute one-time tasks** - Trigger sub-agent runs immediately - **Manage scheduled jobs** - List and cancel scheduled triggers - **React to events** - (Future) Connect data updates to agent actions ## Available Tools ### 1. `schedule_agent_prompt` Schedule an agent to run with a specific prompt on a recurring schedule. **Use Cases:** - Daily market analysis reports - Hourly portfolio rebalancing checks - Weekly performance summaries - Monitoring alerts **Arguments:** - `prompt` (str): The prompt to send to the agent when triggered - `schedule_type` (str): "interval" or "cron" - `schedule_config` (dict): Schedule configuration - `name` (str, optional): Descriptive name for this task **Schedule Config:** *Interval-based:* ```json {"minutes": 5} {"hours": 1, "minutes": 30} {"seconds": 30} ``` *Cron-based:* ```json {"hour": "9", "minute": "0"} // Daily at 9:00 AM {"hour": "9", "minute": "0", "day_of_week": "mon-fri"} // Weekdays at 9 AM {"minute": "0"} // Every hour on the hour {"hour": "*/6", "minute": "0"} // Every 6 hours ``` **Returns:** ```json { "job_id": "interval_123", "message": "Scheduled 'daily_report' with job_id=interval_123", "schedule_type": "cron", "config": {"hour": "9", "minute": "0"} } ``` **Examples:** ```python # Every 5 minutes: check BTC price schedule_agent_prompt( prompt="Check current BTC price on Binance. If > $50k, alert me.", schedule_type="interval", schedule_config={"minutes": 5}, name="btc_price_monitor" ) # Daily at 9 AM: market summary schedule_agent_prompt( prompt="Generate a comprehensive market summary for BTC, ETH, and SOL. Include price changes, volume, and notable events from the last 24 hours.", schedule_type="cron", schedule_config={"hour": "9", "minute": "0"}, name="daily_market_summary" ) # Every hour on weekdays: portfolio check schedule_agent_prompt( prompt="Review current portfolio positions. Check if any rebalancing is needed based on target allocations.", schedule_type="cron", schedule_config={"minute": "0", "day_of_week": "mon-fri"}, name="hourly_portfolio_check" ) ``` ### 2. `execute_agent_prompt_once` Execute an agent prompt once, immediately (enqueued with priority). **Use Cases:** - Background analysis tasks - One-time data processing - Responding to specific events - Sub-agent delegation **Arguments:** - `prompt` (str): The prompt to send to the agent - `priority` (str): "high", "normal", or "low" (default: "normal") **Returns:** ```json { "queue_seq": 42, "message": "Enqueued agent prompt with priority=normal", "prompt": "Analyze the last 100 BTC/USDT bars..." } ``` **Examples:** ```python # Immediate analysis with high priority execute_agent_prompt_once( prompt="Analyze the last 100 BTC/USDT 1m bars and identify key support/resistance levels", priority="high" ) # Background task with normal priority execute_agent_prompt_once( prompt="Research the latest news about Ethereum upgrades and summarize findings", priority="normal" ) # Low priority cleanup task execute_agent_prompt_once( prompt="Review and archive old chart drawings from last month", priority="low" ) ``` ### 3. `list_scheduled_triggers` List all currently scheduled triggers. **Returns:** ```json [ { "id": "cron_456", "name": "Cron: daily_market_summary", "next_run_time": "2024-03-05 09:00:00", "trigger": "cron[hour='9', minute='0']" }, { "id": "interval_123", "name": "Interval: btc_price_monitor", "next_run_time": "2024-03-04 14:35:00", "trigger": "interval[0:05:00]" } ] ``` **Example:** ```python jobs = list_scheduled_triggers() for job in jobs: print(f"{job['name']} - next run: {job['next_run_time']}") ``` ### 4. `cancel_scheduled_trigger` Cancel a scheduled trigger by its job ID. **Arguments:** - `job_id` (str): The job ID from `schedule_agent_prompt` or `list_scheduled_triggers` **Returns:** ```json { "status": "success", "message": "Cancelled job interval_123" } ``` **Example:** ```python # List jobs to find the ID jobs = list_scheduled_triggers() # Cancel specific job cancel_scheduled_trigger("interval_123") ``` ### 5. `on_data_update_run_agent` **(Future)** Set up an agent to run whenever new data arrives for a specific symbol. **Arguments:** - `source_name` (str): Data source name (e.g., "binance") - `symbol` (str): Trading pair (e.g., "BTC/USDT") - `resolution` (str): Time resolution (e.g., "1m", "5m") - `prompt_template` (str): Template with variables like {close}, {volume}, {symbol} **Example:** ```python on_data_update_run_agent( source_name="binance", symbol="BTC/USDT", resolution="1m", prompt_template="New bar on {symbol}: close={close}, volume={volume}. Check if price crossed any key levels." ) ``` ### 6. `get_trigger_system_stats` Get statistics about the trigger system. **Returns:** ```json { "queue_depth": 3, "queue_running": true, "coordinator_stats": { "current_seq": 1042, "next_commit_seq": 1043, "pending_commits": 1, "total_executions": 1042, "state_counts": { "COMMITTED": 1038, "EXECUTING": 2, "WAITING_COMMIT": 1, "FAILED": 1 } } } ``` **Example:** ```python stats = get_trigger_system_stats() print(f"Queue has {stats['queue_depth']} pending triggers") print(f"System has processed {stats['coordinator_stats']['total_executions']} total triggers") ``` ## Integration Example Here's how these tools enable autonomous agent behavior: ```python # Agent conversation: User: "Monitor BTC price and send me a summary every hour during market hours" Agent: I'll set that up for you using the trigger system. # Agent uses tool: schedule_agent_prompt( prompt=""" Check the current BTC/USDT price on Binance. Calculate the price change from 1 hour ago. If price moved > 2%, provide a detailed analysis. Otherwise, provide a brief status update. Send results to user as a notification. """, schedule_type="cron", schedule_config={ "minute": "0", "hour": "9-17", # 9 AM to 5 PM "day_of_week": "mon-fri" }, name="btc_hourly_monitor" ) Agent: Done! I've scheduled an hourly BTC price monitor that runs during market hours (9 AM - 5 PM on weekdays). You'll receive updates every hour. # Later... User: "Can you show me all my scheduled tasks?" Agent: Let me check what's scheduled. # Agent uses tool: jobs = list_scheduled_triggers() Agent: You have 3 scheduled tasks: 1. "btc_hourly_monitor" - runs every hour during market hours 2. "daily_market_summary" - runs daily at 9 AM 3. "portfolio_rebalance_check" - runs every 4 hours Would you like to modify or cancel any of these? ``` ## Use Case: Autonomous Trading Bot ```python # Step 1: Set up data monitoring execute_agent_prompt_once( prompt=""" Subscribe to BTC/USDT 1m bars from Binance. When subscribed, set up the following: 1. Calculate RSI(14) on each new bar 2. If RSI > 70, execute prompt: "RSI overbought on BTC, check if we should sell" 3. If RSI < 30, execute prompt: "RSI oversold on BTC, check if we should buy" """, priority="high" ) # Step 2: Schedule periodic portfolio review schedule_agent_prompt( prompt=""" Review current portfolio: 1. Calculate current allocation percentages 2. Compare to target allocation (60% BTC, 30% ETH, 10% stable) 3. If deviation > 5%, generate rebalancing trades 4. Submit trades for execution """, schedule_type="interval", schedule_config={"hours": 4}, name="portfolio_rebalance" ) # Step 3: Schedule daily risk check schedule_agent_prompt( prompt=""" Daily risk assessment: 1. Calculate portfolio VaR (Value at Risk) 2. Check current leverage across all positions 3. Review stop-loss placements 4. If risk exceeds threshold, alert and suggest adjustments """, schedule_type="cron", schedule_config={"hour": "8", "minute": "0"}, name="daily_risk_check" ) ``` ## Benefits ✅ **Autonomous operation** - Agent can schedule its own tasks ✅ **Event-driven** - React to market data, time, or custom events ✅ **Flexible scheduling** - Interval or cron-based ✅ **Self-managing** - Agent can list and cancel its own jobs ✅ **Priority control** - High-priority tasks jump the queue ✅ **Future-proof** - Easy to add Python lambdas, strategy execution, etc. ## Future Enhancements - **Python script execution** - Schedule arbitrary Python code - **Strategy triggers** - Connect to strategy execution system - **Event composition** - AND/OR logic for complex event patterns - **Conditional execution** - Only run if conditions met (e.g., volatility > threshold) - **Result chaining** - Use output of one trigger as input to another - **Backtesting mode** - Test trigger logic on historical data ## Setup in main.py ```python from agent.tools import set_trigger_queue, set_trigger_scheduler, set_coordinator from trigger import TriggerQueue, CommitCoordinator from trigger.scheduler import TriggerScheduler # Initialize trigger system coordinator = CommitCoordinator() queue = TriggerQueue(coordinator) scheduler = TriggerScheduler(queue) await queue.start() scheduler.start() # Make available to agent tools set_trigger_queue(queue) set_trigger_scheduler(scheduler) set_coordinator(coordinator) # Add TRIGGER_TOOLS to agent's tool list from agent.tools import TRIGGER_TOOLS agent_tools = [..., *TRIGGER_TOOLS] ``` Now the agent has full control over the trigger system! 🚀