283 lines
8.0 KiB
Plaintext
283 lines
8.0 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# OpenClaw Trading - Getting Started\n",
|
|
"\n",
|
|
"This notebook introduces the basics of OpenClaw Trading.\n",
|
|
"\n",
|
|
"## What You'll Learn\n",
|
|
"\n",
|
|
"- How to create and use an economic tracker\n",
|
|
"- How to simulate trades and track performance\n",
|
|
"- How to check survival status\n",
|
|
"- How to visualize balance history"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Setup\n",
|
|
"import sys\n",
|
|
"sys.path.insert(0, '../src')\n",
|
|
"\n",
|
|
"from openclaw.core.economy import TradingEconomicTracker\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"import pandas as pd\n",
|
|
"\n",
|
|
"print(\"✓ Imports successful\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 1. Creating an Economic Tracker\n",
|
|
"\n",
|
|
"The `TradingEconomicTracker` is the core component for tracking agent finances."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Create an economic tracker\n",
|
|
"tracker = TradingEconomicTracker(\n",
|
|
" agent_id=\"tutorial_agent\",\n",
|
|
" initial_capital=1000.0\n",
|
|
")\n",
|
|
"\n",
|
|
"print(f\"Agent ID: {tracker.agent_id}\")\n",
|
|
"print(f\"Initial Capital: ${tracker.initial_capital:,.2f}\")\n",
|
|
"print(f\"Current Balance: ${tracker.balance:,.2f}\")\n",
|
|
"print(f\"Status: {tracker.get_survival_status().value}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 2. Simulating Decisions and Trades\n",
|
|
"\n",
|
|
"Agents pay for decisions (API calls, analysis) and trades."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Simulate some decisions (analysis costs)\n",
|
|
"for i in range(5):\n",
|
|
" cost = tracker.calculate_decision_cost(\n",
|
|
" tokens_input=1000,\n",
|
|
" tokens_output=500,\n",
|
|
" market_data_calls=2\n",
|
|
" )\n",
|
|
" print(f\"Decision {i+1} cost: ${cost:.4f}\")\n",
|
|
"\n",
|
|
"print(f\"\\nBalance after decisions: ${tracker.balance:,.2f}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Simulate some trades\n",
|
|
"import random\n",
|
|
"\n",
|
|
"for i in range(10):\n",
|
|
" is_win = i % 2 == 0 # Alternate wins and losses\n",
|
|
" win_amount = 20.0 if is_win else -10.0\n",
|
|
" \n",
|
|
" result = tracker.calculate_trade_cost(\n",
|
|
" trade_value=100.0,\n",
|
|
" is_win=is_win,\n",
|
|
" win_amount=win_amount\n",
|
|
" )\n",
|
|
" \n",
|
|
" print(f\"Trade {i+1}: {\"Win\" if is_win else \"Loss\"} ${win_amount:+.2f} | Balance: ${result.balance:,.2f}\")\n",
|
|
"\n",
|
|
"print(f\"\\nFinal Balance: ${tracker.balance:,.2f}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 3. Checking Performance"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Get current status\n",
|
|
"status = tracker.get_survival_status()\n",
|
|
"\n",
|
|
"print(\"Performance Summary\")\n",
|
|
"print(\"=\" * 40)\n",
|
|
"print(f\"Status: {status.value}\")\n",
|
|
"print(f\"Initial Capital: ${tracker.initial_capital:,.2f}\")\n",
|
|
"print(f\"Current Balance: ${tracker.balance:,.2f}\")\n",
|
|
"print(f\"Total Return: {(tracker.balance/tracker.initial_capital - 1)*100:+.2f}%\")\n",
|
|
"print(f\"\\nCosts:\")\n",
|
|
"print(f\" Token Costs: ${tracker.token_costs:.4f}\")\n",
|
|
"print(f\" Trade Costs: ${tracker.trade_costs:.4f}\")\n",
|
|
"print(f\" Total Costs: ${tracker.total_costs:.4f}\")\n",
|
|
"print(f\"\\nProfit/Loss: ${tracker.net_profit:+.2f}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 4. Visualizing Balance History"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Get balance history\n",
|
|
"history = tracker.get_balance_history()\n",
|
|
"\n",
|
|
"# Convert to DataFrame for easy plotting\n",
|
|
"df = pd.DataFrame([\n",
|
|
" {\n",
|
|
" 'timestamp': entry.timestamp,\n",
|
|
" 'balance': entry.balance,\n",
|
|
" 'change': entry.change\n",
|
|
" }\n",
|
|
" for entry in history\n",
|
|
"])\n",
|
|
"\n",
|
|
"# Plot balance over time\n",
|
|
"plt.figure(figsize=(12, 6))\n",
|
|
"plt.plot(df['timestamp'], df['balance'], marker='o')\n",
|
|
"plt.axhline(y=tracker.initial_capital, color='r', linestyle='--', label='Initial Capital')\n",
|
|
"plt.xlabel('Time')\n",
|
|
"plt.ylabel('Balance ($)')\n",
|
|
"plt.title('Agent Balance History')\n",
|
|
"plt.legend()\n",
|
|
"plt.grid(True, alpha=0.3)\n",
|
|
"plt.xticks(rotation=45)\n",
|
|
"plt.tight_layout()\n",
|
|
"plt.show()\n",
|
|
"\n",
|
|
"print(f\"Total entries: {len(df)}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 5. Experimenting with Different Scenarios\n",
|
|
"\n",
|
|
"Let's create multiple agents with different strategies and compare them."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Create three different agents\n",
|
|
"agents = {\n",
|
|
" 'Conservative': TradingEconomicTracker('conservative', 1000.0),\n",
|
|
" 'Balanced': TradingEconomicTracker('balanced', 1000.0),\n",
|
|
" 'Aggressive': TradingEconomicTracker('aggressive', 1000.0)\n",
|
|
"}\n",
|
|
"\n",
|
|
"# Simulate different strategies\n",
|
|
"for name, agent in agents.items():\n",
|
|
" for i in range(20):\n",
|
|
" if name == 'Conservative':\n",
|
|
" # Conservative: small wins, small losses\n",
|
|
" is_win = i % 3 == 0 # 33% win rate\n",
|
|
" amount = 5.0 if is_win else -3.0\n",
|
|
" elif name == 'Balanced':\n",
|
|
" # Balanced: medium wins/losses\n",
|
|
" is_win = i % 2 == 0 # 50% win rate\n",
|
|
" amount = 10.0 if is_win else -8.0\n",
|
|
" else: # Aggressive\n",
|
|
" # Aggressive: large wins/losses\n",
|
|
" is_win = i % 2 == 0 # 50% win rate\n",
|
|
" amount = 25.0 if is_win else -20.0\n",
|
|
" \n",
|
|
" agent.calculate_trade_cost(100.0, is_win, amount)\n",
|
|
"\n",
|
|
"# Compare results\n",
|
|
"print(\"Strategy Comparison\")\n",
|
|
"print(\"=\" * 60)\n",
|
|
"for name, agent in agents.items():\n",
|
|
" return_pct = (agent.balance/agent.initial_capital - 1) * 100\n",
|
|
" print(f\"{name:15} | Balance: ${agent.balance:>8,.2f} | Return: {return_pct:+6.2f}% | Status: {agent.get_survival_status().value}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Plot comparison\n",
|
|
"plt.figure(figsize=(12, 6))\n",
|
|
"\n",
|
|
"for name, agent in agents.items():\n",
|
|
" history = agent.get_balance_history()\n",
|
|
" balances = [entry.balance for entry in history]\n",
|
|
" plt.plot(balances, label=name, marker='o', markersize=3)\n",
|
|
"\n",
|
|
"plt.axhline(y=1000, color='black', linestyle='--', alpha=0.5, label='Initial')\n",
|
|
"plt.xlabel('Trade Number')\n",
|
|
"plt.ylabel('Balance ($)')\n",
|
|
"plt.title('Strategy Comparison')\n",
|
|
"plt.legend()\n",
|
|
"plt.grid(True, alpha=0.3)\n",
|
|
"plt.tight_layout()\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Next Steps\n",
|
|
"\n",
|
|
"- Learn about the workflow system in `02_workflow_demo.ipynb`\n",
|
|
"- Explore backtesting in `03_backtesting.ipynb`\n",
|
|
"- Create custom strategies in `04_custom_strategies.ipynb`"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"name": "python",
|
|
"version": "3.10.0"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 4
|
|
}
|