398 lines
9.7 KiB
ReStructuredText
398 lines
9.7 KiB
ReStructuredText
Usage Examples
|
|
==============
|
|
|
|
This section provides detailed examples of using OpenClaw Trading.
|
|
|
|
Basic Examples
|
|
--------------
|
|
|
|
Example 1: Quickstart (Economic Tracker)
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. literalinclude:: ../../examples/01_quickstart.py
|
|
:language: python
|
|
:linenos:
|
|
:caption: Basic economic tracking and cost calculation
|
|
|
|
**Key Concepts:**
|
|
|
|
* Creating a ``TradingEconomicTracker``
|
|
* Checking survival status
|
|
* Calculating decision costs
|
|
* Simulating trades
|
|
* Tracking balance history
|
|
|
|
**Run it:**
|
|
|
|
.. code-block:: bash
|
|
|
|
python examples/01_quickstart.py
|
|
|
|
Example 2: Workflow Demo
|
|
~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. literalinclude:: ../../examples/02_workflow_demo.py
|
|
:language: python
|
|
:linenos:
|
|
:caption: Running a complete trading workflow
|
|
|
|
**Key Concepts:**
|
|
|
|
* Creating a ``TradingWorkflow``
|
|
* Running parallel analysis
|
|
* Getting trading signals
|
|
* Handling workflow results
|
|
|
|
**Run it:**
|
|
|
|
.. code-block:: bash
|
|
|
|
python examples/02_workflow_demo.py
|
|
|
|
Example 3: Factor Market
|
|
~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. literalinclude:: ../../examples/03_factor_market.py
|
|
:language: python
|
|
:linenos:
|
|
:caption: Working with the factor market system
|
|
|
|
**Key Concepts:**
|
|
|
|
* Browsing available factors
|
|
* Purchasing factors
|
|
* Using factors in analysis
|
|
* Factor unlocking mechanism
|
|
|
|
**Run it:**
|
|
|
|
.. code-block:: bash
|
|
|
|
python examples/03_factor_market.py
|
|
|
|
Example 4: Learning System
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. literalinclude:: ../../examples/04_learning_system.py
|
|
:language: python
|
|
:linenos:
|
|
:caption: Using the learning system to improve agents
|
|
|
|
**Key Concepts:**
|
|
|
|
* Browsing available courses
|
|
* Enrolling agents in courses
|
|
* Completing courses
|
|
* Applying learned skills
|
|
|
|
**Run it:**
|
|
|
|
.. code-block:: bash
|
|
|
|
python examples/04_learning_system.py
|
|
|
|
Example 5: Work-Trade Balance
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. literalinclude:: ../../examples/05_work_trade_balance.py
|
|
:language: python
|
|
:linenos:
|
|
:caption: Managing work-trade balance for struggling agents
|
|
|
|
**Key Concepts:**
|
|
|
|
* Monitoring agent performance
|
|
* Switching to work mode
|
|
* Earning through work
|
|
* Returning to trading
|
|
|
|
**Run it:**
|
|
|
|
.. code-block:: bash
|
|
|
|
python examples/05_work_trade_balance.py
|
|
|
|
Example 6: Portfolio Risk Management
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. literalinclude:: ../../examples/06_portfolio_risk.py
|
|
:language: python
|
|
:linenos:
|
|
:caption: Portfolio-level risk management
|
|
|
|
**Key Concepts:**
|
|
|
|
* Managing multiple positions
|
|
* Calculating portfolio risk
|
|
* Risk-adjusted position sizing
|
|
* Stop-loss and take-profit
|
|
|
|
**Run it:**
|
|
|
|
.. code-block:: bash
|
|
|
|
python examples/06_portfolio_risk.py
|
|
|
|
Advanced Examples
|
|
-----------------
|
|
|
|
Custom Agent Example
|
|
~~~~~~~~~~~~~~~~~~~~
|
|
|
|
Create a custom agent by inheriting from ``BaseAgent``:
|
|
|
|
.. code-block:: python
|
|
|
|
from openclaw.agents.base import BaseAgent, AgentState, ActivityType
|
|
from openclaw.core.economy import TradingEconomicTracker
|
|
|
|
class CustomAnalyst(BaseAgent):
|
|
"""Custom analyst agent with specialized strategy."""
|
|
|
|
def analyze(self, symbol: str) -> dict:
|
|
"""Perform custom analysis."""
|
|
# Pay for the analysis
|
|
cost = self.economic_tracker.calculate_decision_cost(
|
|
tokens_input=500,
|
|
tokens_output=200,
|
|
market_data_calls=1
|
|
)
|
|
|
|
if not self.can_afford_decision():
|
|
return {"error": "Insufficient funds"}
|
|
|
|
# Perform analysis
|
|
signal = self._custom_analysis_logic(symbol)
|
|
|
|
return {
|
|
"symbol": symbol,
|
|
"signal": signal,
|
|
"cost": cost,
|
|
"balance": self.economic_tracker.balance
|
|
}
|
|
|
|
def _custom_analysis_logic(self, symbol: str) -> str:
|
|
"""Implement custom analysis logic."""
|
|
# Your custom logic here
|
|
return "buy" # or "sell", "hold"
|
|
|
|
def can_afford_decision(self) -> bool:
|
|
"""Check if agent can afford another decision."""
|
|
return self.economic_tracker.balance > 10.0
|
|
|
|
# Usage
|
|
agent = CustomAnalyst(
|
|
agent_id="custom_001",
|
|
initial_capital=1000.0,
|
|
skill_level=0.7
|
|
)
|
|
|
|
result = agent.analyze("AAPL")
|
|
print(f"Analysis result: {result}")
|
|
|
|
Multi-Agent Collaboration
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
Run multiple agents collaboratively:
|
|
|
|
.. code-block:: python
|
|
|
|
import asyncio
|
|
from openclaw.agents.market_analyst import MarketAnalyst
|
|
from openclaw.agents.sentiment_analyst import SentimentAnalyst
|
|
from openclaw.agents.fundamental_analyst import FundamentalAnalyst
|
|
from openclaw.fusion.engine import DecisionFusion
|
|
|
|
async def collaborative_analysis(symbol: str):
|
|
"""Run collaborative multi-agent analysis."""
|
|
|
|
# Create agents
|
|
market_analyst = MarketAnalyst(
|
|
agent_id="market_001",
|
|
initial_capital=1000.0
|
|
)
|
|
sentiment_analyst = SentimentAnalyst(
|
|
agent_id="sentiment_001",
|
|
initial_capital=1000.0
|
|
)
|
|
fundamental_analyst = FundamentalAnalyst(
|
|
agent_id="fundamental_001",
|
|
initial_capital=1000.0
|
|
)
|
|
|
|
# Run analyses in parallel
|
|
results = await asyncio.gather(
|
|
market_analyst.analyze(symbol),
|
|
sentiment_analyst.analyze(symbol),
|
|
fundamental_analyst.analyze(symbol),
|
|
return_exceptions=True
|
|
)
|
|
|
|
# Fuse decisions
|
|
fusion = DecisionFusion()
|
|
fused_signal = fusion.fuse_signals(
|
|
signals=[
|
|
{"signal": results[0].signal, "confidence": results[0].confidence},
|
|
{"signal": results[1].signal, "confidence": results[1].confidence},
|
|
{"signal": results[2].signal, "confidence": results[2].confidence},
|
|
],
|
|
weights=[0.4, 0.3, 0.3]
|
|
)
|
|
|
|
return fused_signal
|
|
|
|
# Run
|
|
result = asyncio.run(collaborative_analysis("AAPL"))
|
|
print(f"Fused signal: {result}")
|
|
|
|
Backtesting Example
|
|
~~~~~~~~~~~~~~~~~~~
|
|
|
|
Run a backtest with custom parameters:
|
|
|
|
.. code-block:: python
|
|
|
|
from openclaw.backtest.engine import BacktestEngine
|
|
from openclaw.backtest.analyzer import BacktestAnalyzer
|
|
from datetime import datetime, timedelta
|
|
|
|
def run_backtest_example():
|
|
"""Run a comprehensive backtest."""
|
|
|
|
# Create backtest engine
|
|
engine = BacktestEngine(
|
|
symbols=["AAPL", "MSFT", "GOOGL"],
|
|
start_date=datetime.now() - timedelta(days=365),
|
|
end_date=datetime.now(),
|
|
initial_capital=10000.0
|
|
)
|
|
|
|
# Configure strategy
|
|
engine.configure_strategy({
|
|
"enable_parallel": True,
|
|
"risk_limits": {
|
|
"max_position_size": 0.2,
|
|
"max_drawdown": 0.1
|
|
}
|
|
})
|
|
|
|
# Run backtest
|
|
results = engine.run()
|
|
|
|
# Analyze results
|
|
analyzer = BacktestAnalyzer(results)
|
|
metrics = analyzer.calculate_metrics()
|
|
|
|
print("Backtest Results:")
|
|
print(f"Total Return: {metrics.total_return:.2%}")
|
|
print(f"Sharpe Ratio: {metrics.sharpe_ratio:.2f}")
|
|
print(f"Max Drawdown: {metrics.max_drawdown:.2%}")
|
|
print(f"Win Rate: {metrics.win_rate:.2%}")
|
|
print(f"Profit Factor: {metrics.profit_factor:.2f}")
|
|
|
|
# Plot results
|
|
analyzer.plot_equity_curve("backtest_equity.png")
|
|
analyzer.plot_drawdown("backtest_drawdown.png")
|
|
|
|
return metrics
|
|
|
|
if __name__ == "__main__":
|
|
run_backtest_example()
|
|
|
|
Jupyter Notebook Tutorials
|
|
--------------------------
|
|
|
|
Tutorial 1: Getting Started
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. code-block:: python
|
|
|
|
# In a Jupyter notebook
|
|
from openclaw.core.economy import TradingEconomicTracker
|
|
import matplotlib.pyplot as plt
|
|
|
|
# Create tracker
|
|
tracker = TradingEconomicTracker("tutorial", 1000.0)
|
|
|
|
# Simulate some trades
|
|
for i in range(10):
|
|
tracker.calculate_trade_cost(
|
|
trade_value=100.0,
|
|
is_win=i % 2 == 0,
|
|
win_amount=10.0 if i % 2 == 0 else -5.0
|
|
)
|
|
|
|
# Plot balance history
|
|
history = tracker.get_balance_history()
|
|
balances = [entry.balance for entry in history]
|
|
plt.plot(balances)
|
|
plt.title("Agent Balance Over Time")
|
|
plt.xlabel("Trade")
|
|
plt.ylabel("Balance ($)")
|
|
plt.show()
|
|
|
|
Tutorial 2: Comparing Agents
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
.. code-block:: python
|
|
|
|
import pandas as pd
|
|
import seaborn as sns
|
|
|
|
# Create multiple agents with different strategies
|
|
agents = {
|
|
"conservative": TradingEconomicTracker("conservative", 1000.0),
|
|
"aggressive": TradingEconomicTracker("aggressive", 1000.0),
|
|
"balanced": TradingEconomicTracker("balanced", 1000.0),
|
|
}
|
|
|
|
# Simulate different performance
|
|
for name, tracker in agents.items():
|
|
for i in range(20):
|
|
if name == "conservative":
|
|
win = i % 3 == 0 # 33% win rate
|
|
amount = 5.0 if win else -2.0
|
|
elif name == "aggressive":
|
|
win = i % 2 == 0 # 50% win rate
|
|
amount = 20.0 if win else -15.0
|
|
else:
|
|
win = i % 2 == 0 # 50% win rate
|
|
amount = 10.0 if win else -5.0
|
|
|
|
tracker.calculate_trade_cost(100.0, win, amount)
|
|
|
|
# Compare results
|
|
data = {
|
|
name: [entry.balance for entry in tracker.get_balance_history()]
|
|
for name, tracker in agents.items()
|
|
}
|
|
|
|
df = pd.DataFrame(data)
|
|
sns.lineplot(data=df)
|
|
plt.title("Agent Performance Comparison")
|
|
plt.ylabel("Balance ($)")
|
|
plt.show()
|
|
|
|
Running All Examples
|
|
--------------------
|
|
|
|
Run all examples at once:
|
|
|
|
.. code-block:: bash
|
|
|
|
# Make the script executable
|
|
chmod +x examples/run_all.sh
|
|
|
|
# Run all examples
|
|
./examples/run_all.sh
|
|
|
|
Or run individually:
|
|
|
|
.. code-block:: bash
|
|
|
|
for script in examples/0*.py; do
|
|
echo "Running $script..."
|
|
python "$script"
|
|
echo ""
|
|
done
|