stock/docs/source/agents.rst
2026-02-27 03:17:12 +08:00

358 lines
8.0 KiB
ReStructuredText

Agents
======
Agents are the core decision-making components of OpenClaw Trading. Each agent is a specialized entity that performs specific analysis or trading functions while managing its own economic survival.
Agent Architecture
------------------
Base Agent
~~~~~~~~~~
All agents inherit from :class:`openclaw.agents.base.BaseAgent`:
.. code-block:: python
from openclaw.agents.base import BaseAgent, AgentState
class MyCustomAgent(BaseAgent):
def __init__(self, agent_id: str, initial_capital: float):
super().__init__(agent_id, initial_capital)
# Custom initialization
def analyze(self, symbol: str):
"""Required: implement analysis logic."""
raise NotImplementedError
Agent State
~~~~~~~~~~~
Each agent maintains internal state:
* **agent_id**: Unique identifier
* **skill_level**: Current skill (0.0 to 1.0)
* **win_rate**: Historical win rate
* **total_trades**: Number of trades executed
* **winning_trades**: Number of profitable trades
* **unlocked_factors**: List of unlocked trading factors
* **current_activity**: Current activity type
* **is_bankrupt**: Bankruptcy status
Analysis Agents
---------------
Market Analyst
~~~~~~~~~~~~~~
Performs technical analysis using price and volume data:
.. code-block:: python
from openclaw.agents.market_analyst import MarketAnalyst
analyst = MarketAnalyst(
agent_id="market_001",
initial_capital=1000.0
)
result = analyst.analyze("AAPL")
print(f"Signal: {result.signal}")
print(f"Confidence: {result.confidence}")
**Capabilities:**
* Technical indicator calculation
* Trend analysis
* Support/resistance detection
* Pattern recognition
Sentiment Analyst
~~~~~~~~~~~~~~~~~
Analyzes market sentiment from various sources:
.. code-block:: python
from openclaw.agents.sentiment_analyst import SentimentAnalyst
analyst = SentimentAnalyst(
agent_id="sentiment_001",
initial_capital=1000.0
)
result = analyst.analyze("AAPL")
print(f"Sentiment: {result.sentiment}")
**Capabilities:**
* News sentiment analysis
* Social media sentiment
* Market mood detection
* Sentiment trend tracking
Fundamental Analyst
~~~~~~~~~~~~~~~~~~~
Analyzes company fundamentals and financial data:
.. code-block:: python
from openclaw.agents.fundamental_analyst import FundamentalAnalyst
analyst = FundamentalAnalyst(
agent_id="fundamental_001",
initial_capital=1000.0
)
result = analyst.analyze("AAPL")
print(f"Fair value: {result.fair_value}")
**Capabilities:**
* Financial statement analysis
* Valuation metrics
* Growth assessment
* Competitive analysis
Debate Agents
-------------
Bull Researcher
~~~~~~~~~~~~~~~
Advocates for bullish positions:
.. code-block:: python
from openclaw.agents.bull_researcher import BullResearcher
bull = BullResearcher(
agent_id="bull_001",
initial_capital=1000.0
)
argument = bull.generate_argument("AAPL", target_price=180.0)
**Capabilities:**
* Bullish case construction
* Positive catalyst identification
* Upside potential calculation
Bear Researcher
~~~~~~~~~~~~~~~
Advocates for bearish positions:
.. code-block:: python
from openclaw.agents.bear_researcher import BearResearcher
bear = BearResearcher(
agent_id="bear_001",
initial_capital=1000.0
)
argument = bear.generate_argument("AAPL", target_price=120.0)
**Capabilities:**
* Bearish case construction
* Risk identification
* Downside protection strategies
Execution Agents
----------------
Risk Manager
~~~~~~~~~~~~
Validates trades against risk limits:
.. code-block:: python
from openclaw.agents.risk_manager import RiskManager
risk_mgr = RiskManager(
agent_id="risk_001",
initial_capital=1000.0
)
assessment = risk_mgr.assess_trade(
symbol="AAPL",
position_size=100,
entry_price=150.0
)
if assessment.approved:
print(f"Trade approved with size: {assessment.recommended_size}")
else:
print(f"Trade rejected: {assessment.reason}")
**Capabilities:**
* Position sizing
* Risk limit enforcement
* Portfolio heat monitoring
* Drawdown prevention
Trader
~~~~~~
Executes trades and manages positions:
.. code-block:: python
from openclaw.agents.trader import Trader
trader = Trader(
agent_id="trader_001",
initial_capital=1000.0
)
order = trader.execute_trade(
symbol="AAPL",
side="buy",
quantity=10,
order_type="market"
)
**Capabilities:**
* Order execution
* Position management
* PnL tracking
* Trade logging
Agent Lifecycle
---------------
Creating an Agent
~~~~~~~~~~~~~~~~~
.. code-block:: python
from openclaw.agents.market_analyst import MarketAnalyst
# Create agent with initial capital
agent = MarketAnalyst(
agent_id="my_agent_001",
initial_capital=1000.0,
skill_level=0.5 # Optional: initial skill level
)
Running Analysis
~~~~~~~~~~~~~~~~
.. code-block:: python
# Run analysis (costs money)
result = agent.analyze("AAPL")
# Check if agent can afford analysis
if agent.can_afford_analysis():
result = agent.analyze("AAPL")
else:
print("Agent cannot afford analysis")
Tracking Performance
~~~~~~~~~~~~~~~~~~~~
.. code-block:: python
# Get current balance
balance = agent.economic_tracker.balance
# Get survival status
status = agent.economic_tracker.get_survival_status()
# Update win rate after trade
agent.update_performance(is_win=True)
Agent Events
------------
Event Hooks
~~~~~~~~~~~
Register callbacks for agent events:
.. code-block:: python
def on_trade_completed(agent, trade_result):
print(f"Trade completed: {trade_result}")
def on_bankruptcy(agent):
print(f"Agent {agent.agent_id} is bankrupt!")
agent.register_hook("trade_completed", on_trade_completed)
agent.register_hook("bankruptcy", on_bankruptcy)
Available Events
~~~~~~~~~~~~~~~~
* **trade_completed**: When a trade finishes
* **analysis_completed**: When analysis finishes
* **bankruptcy**: When agent goes bankrupt
* **level_up**: When agent skill increases
* **factor_unlocked**: When a factor is unlocked
Best Practices
--------------
1. **Always check affordability**: Verify agents can afford operations
2. **Monitor survival status**: Watch for struggling agents
3. **Use appropriate skill levels**: Start with 0.5 for new agents
4. **Handle bankruptcy gracefully**: Have recovery mechanisms
5. **Track performance**: Monitor win rates and adjust strategies
Custom Agents
-------------
Creating Custom Agents
~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: python
from openclaw.agents.base import BaseAgent, AgentState
from typing import Dict, Any
class CustomAnalyst(BaseAgent):
"""Custom analyst with specialized logic."""
def __init__(self, agent_id: str, initial_capital: float):
super().__init__(agent_id, initial_capital)
self.custom_data = {}
def analyze(self, symbol: str) -> Dict[str, Any]:
"""Implement custom analysis."""
# Check affordability
if not self.can_afford_analysis():
return {"error": "Insufficient funds"}
# Calculate analysis cost
cost = self.economic_tracker.calculate_decision_cost(
tokens_input=500,
tokens_output=200,
market_data_calls=2
)
# Perform custom analysis
signal = self._custom_logic(symbol)
return {
"symbol": symbol,
"signal": signal,
"cost": cost,
"balance": self.economic_tracker.balance
}
def _custom_logic(self, symbol: str) -> str:
"""Your custom analysis logic."""
# Implement your strategy here
return "buy" # or "sell", "hold"
def can_afford_analysis(self) -> bool:
"""Check if agent can afford analysis."""
return self.economic_tracker.balance > 5.0