Workflow System =============== OpenClaw uses LangGraph for workflow orchestration, enabling state-driven, parallel execution of trading analysis. Overview -------- The trading workflow coordinates multiple agents in a structured pipeline: .. code-block:: text START │ ├─→ Market Analysis (parallel) ├─→ Sentiment Analysis (parallel) ├─→ Fundamental Analysis (parallel) │ └─→ Bull-Bear Debate │ └─→ Decision Fusion │ └─→ Risk Assessment │ END Workflow Components ------------------- TradingWorkflow Class ~~~~~~~~~~~~~~~~~~~~~ The main workflow orchestrator: .. code-block:: python from openclaw.workflow.trading_workflow import TradingWorkflow workflow = TradingWorkflow( symbol="AAPL", initial_capital=1000.0, enable_parallel=True # Run analyses in parallel ) # Run the workflow result = await workflow.run() Workflow State ~~~~~~~~~~~~~~ The workflow maintains state throughout execution: .. code-block:: python from openclaw.workflow.state import TradingWorkflowState state = TradingWorkflowState( symbol="AAPL", market_analysis={}, sentiment_analysis={}, fundamental_analysis={}, debate_result={}, fused_decision={}, risk_assessment={}, final_signal=None ) Workflow Nodes ~~~~~~~~~~~~~~ Individual processing nodes: * **market_analysis_node**: Technical analysis * **sentiment_analysis_node**: Sentiment analysis * **fundamental_analysis_node**: Fundamental analysis * **bull_bear_debate_node**: Debate between bull and bear researchers * **decision_fusion_node**: Combine all signals * **risk_assessment_node**: Final risk validation Using the Workflow ------------------ Basic Usage ~~~~~~~~~~~ .. code-block:: python import asyncio from openclaw.workflow.trading_workflow import TradingWorkflow async def analyze_stock(): # Create workflow workflow = TradingWorkflow( symbol="AAPL", initial_capital=1000.0, enable_parallel=True ) # Run workflow result = await workflow.run() # Process results print(f"Symbol: {result['symbol']}") print(f"Signal: {result['signal']}") print(f"Confidence: {result['confidence']:.2%}") print(f"Position Size: {result['position_size']:.2f}") return result # Run result = asyncio.run(analyze_stock()) Custom Configuration ~~~~~~~~~~~~~~~~~~~~ .. code-block:: python # Configure individual agents workflow = TradingWorkflow( symbol="AAPL", initial_capital=1000.0, enable_parallel=True, agent_config={ "market_analyst": { "skill_level": 0.8, "indicators": ["sma", "rsi", "macd"] }, "risk_manager": { "max_position_size": 0.2, "max_drawdown": 0.1 } } ) Workflow Execution ------------------ Sequential vs Parallel ~~~~~~~~~~~~~~~~~~~~~~ Sequential execution: .. code-block:: python workflow = TradingWorkflow( symbol="AAPL", enable_parallel=False # Run one at a time ) Parallel execution (default): .. code-block:: python workflow = TradingWorkflow( symbol="AAPL", enable_parallel=True # Run analyses concurrently ) Conditional Flow ~~~~~~~~~~~~~~~~ The workflow includes conditional branching: .. code-block:: python # Debate node decides whether to continue def should_continue_after_analysis(state) -> str: if state["debate_result"]["confidence"] > 0.7: return "continue" return "end" Error Handling ~~~~~~~~~~~~~~ .. code-block:: python async def safe_workflow_execution(): workflow = TradingWorkflow(symbol="AAPL") try: result = await workflow.run() return result except TimeoutError: print("Workflow timed out") return None except Exception as e: print(f"Workflow error: {e}") return None Extending the Workflow ---------------------- Custom Nodes ~~~~~~~~~~~~ Add custom processing nodes: .. code-block:: python from openclaw.workflow.state import TradingWorkflowState async def custom_analysis_node(state: TradingWorkflowState): """Custom analysis node.""" # Access current state symbol = state.symbol # Perform custom analysis analysis_result = await my_custom_analysis(symbol) # Update state state.custom_analysis = analysis_result return state # Add to workflow workflow.add_node("custom_analysis", custom_analysis_node) workflow.add_edge("fundamental_analysis", "custom_analysis") workflow.add_edge("custom_analysis", "bull_bear_debate") Custom State ~~~~~~~~~~~~ Extend the workflow state: .. code-block:: python from openclaw.workflow.state import TradingWorkflowState from typing import Optional class ExtendedWorkflowState(TradingWorkflowState): """Extended state with custom fields.""" custom_field: Optional[str] = None custom_data: dict = {} Monitoring Workflows -------------------- Progress Tracking ~~~~~~~~~~~~~~~~~ .. code-block:: python from openclaw.workflow.trading_workflow import TradingWorkflow workflow = TradingWorkflow(symbol="AAPL") # Register progress callback def on_progress(stage: str, data: dict): print(f"Completed: {stage}") workflow.on_progress = on_progress result = await workflow.run() State Inspection ~~~~~~~~~~~~~~~~ .. code-block:: python # Get intermediate results state = workflow.get_state() print(f"Market analysis: {state.market_analysis}") print(f"Debate result: {state.debate_result}") print(f"Risk assessment: {state.risk_assessment}") Performance Optimization ------------------------ Caching ~~~~~~~ .. code-block:: python # Enable result caching workflow = TradingWorkflow( symbol="AAPL", cache_enabled=True, cache_ttl=300 # 5 minutes ) Timeouts ~~~~~~~~ .. code-block:: python # Set execution timeout workflow = TradingWorkflow( symbol="AAPL", timeout_seconds=60 ) Resource Limits ~~~~~~~~~~~~~~~ .. code-block:: python # Limit concurrent executions workflow = TradingWorkflow( symbol="AAPL", max_workers=4 ) Best Practices -------------- 1. **Use parallel execution**: Faster analysis for independent tasks 2. **Set appropriate timeouts**: Prevent hanging workflows 3. **Handle errors gracefully**: Always wrap in try-except 4. **Monitor state**: Log intermediate results for debugging 5. **Cache when possible**: Avoid redundant calculations 6. **Validate inputs**: Check symbol validity before running