algo-trading
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesealgo-trading
algo-trading
Purpose
功能目标
This skill automates algorithmic trading by integrating quantitative models with financial APIs to execute buy/sell orders based on predefined strategies. It processes market data, runs backtests, and handles live trading to minimize human intervention in financial markets.
本技能通过整合量化模型与金融API,基于预设策略自动执行买卖订单,实现算法交易自动化。它可处理市场数据、运行回测并实盘交易,以减少金融市场中的人工干预。
When to Use
适用场景
Use this skill for high-frequency trading, portfolio optimization, or strategy backtesting in volatile markets. Apply it when you need to automate trades based on indicators like moving averages or RSI, especially for stocks, forex, or crypto, to reduce emotional decisions and improve efficiency.
在高频交易、投资组合优化或波动市场中的策略回测场景下使用本技能。当你需要基于moving averages、RSI等指标自动化执行交易时(尤其是股票、外汇或加密货币领域),应用本技能可减少情绪化决策,提升交易效率。
Key Capabilities
核心能力
- Fetch real-time or historical data from APIs like Alpha Vantage or Yahoo Finance using endpoints such as .
/query?function=TIME_SERIES_DAILY - Implement strategies like moving average crossover or mean reversion with built-in functions, e.g., .
strategy.run('MA_Crossover', params) - Backtest models on historical data with metrics like Sharpe ratio, using commands like .
backtest --data CSV_FILE --strategy STRATEGY_NAME - Execute trades via broker APIs, supporting integration with Alpaca (e.g., POST /v2/orders) or Robinhood, with risk controls like stop-loss.
- Handle data analysis with libraries like NumPy for calculations, e.g., computing RSI in 2 lines: .
rsi = talib.RSI(close, timeperiod=14); signals = np.where(rsi > 70, 'sell', 'buy')
- 通过Alpha Vantage或Yahoo Finance等API获取实时或历史数据,使用如这类接口。
/query?function=TIME_SERIES_DAILY - 利用内置函数实现移动均线交叉(moving average crossover)或均值回归(mean reversion)等策略,例如。
strategy.run('MA_Crossover', params) - 基于历史数据对模型进行回测,使用Sharpe ratio等指标,执行命令如。
backtest --data CSV_FILE --strategy STRATEGY_NAME - 通过经纪商API执行交易,支持与Alpaca(如POST /v2/orders)或Robinhood集成,并具备止损等风险控制功能。
- 使用NumPy等库进行数据分析计算,例如仅用两行代码计算RSI:。
rsi = talib.RSI(close, timeperiod=14); signals = np.where(rsi > 70, 'sell', 'buy')
Usage Patterns
使用模式
To use this skill, first set environment variables for authentication, e.g., export ALPHA_VANTAGE_API_KEY=$SERVICE_API_KEY. Initialize the skill in your code with . For CLI, run to load a strategy file. In scripts, call strategies like . Always wrap calls in try-except blocks for error resilience. For live trading, enable with a flag: .
import openclaw; oc = openclaw.Skill('algo-trading')openclaw algo-trading init --config config.jsonoc.execute_strategy('MA_Crossover', symbols=['AAPL'], timeframe='1d')oc.run_live('--broker alpaca --key $ALPACA_KEY')使用本技能前,需先设置身份验证环境变量,例如。在代码中初始化技能:。若使用CLI,运行加载策略文件。在脚本中调用策略,例如。为保证错误韧性,需始终将调用包裹在try-except块中。若要开启实盘交易,需添加标志:。
export ALPHA_VANTAGE_API_KEY=$SERVICE_API_KEYimport openclaw; oc = openclaw.Skill('algo-trading')openclaw algo-trading init --config config.jsonoc.execute_strategy('MA_Crossover', symbols=['AAPL'], timeframe='1d')oc.run_live('--broker alpaca --key $ALPACA_KEY')Common Commands/API
常用命令/API
- CLI Command: to execute a strategy on specified stocks.
openclaw algo-trading run --strategy MA_Crossover --symbols AAPL,GOOG --timeframe 1h - API Endpoint: GET https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&apikey=$SERVICE_API_KEY for fetching intraday data.
- Code Snippet:
python
import openclaw oc = openclaw.Skill('algo-trading') data = oc.fetch_data('AAPL', '1d') # Fetches daily data signals = oc.analyze_strategy('MA_Crossover', data) - Config Format: Use JSON for strategies, e.g., {"strategy": "MA_Crossover", "params": {"short_window": 50, "long_window": 200}, "symbols": ["AAPL"]}. Load via .
openclaw algo-trading load-config path/to/config.json - Another Command: to run simulations.
openclaw algo-trading backtest --file historical.csv --strategy RSI_Overbought --iterations 100 - API Call Example: POST https://api.alpaca.markets/v2/orders with body {"symbol": "AAPL", "qty": 10, "side": "buy", "type": "market"} for placing orders, authenticated via $ALPACA_KEY header.
- CLI命令:,用于在指定股票上执行策略。
openclaw algo-trading run --strategy MA_Crossover --symbols AAPL,GOOG --timeframe 1h - API接口:GET ,用于获取日内数据。
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&apikey=$SERVICE_API_KEY - 代码片段:
python
import openclaw oc = openclaw.Skill('algo-trading') data = oc.fetch_data('AAPL', '1d') # 获取日线数据 signals = oc.analyze_strategy('MA_Crossover', data) - 配置格式:使用JSON定义策略,例如。通过
{"strategy": "MA_Crossover", "params": {"short_window": 50, "long_window": 200}, "symbols": ["AAPL"]}加载配置。openclaw algo-trading load-config path/to/config.json - 其他命令:,用于运行模拟回测。
openclaw algo-trading backtest --file historical.csv --strategy RSI_Overbought --iterations 100 - API调用示例:POST ,请求体为
https://api.alpaca.markets/v2/orders,通过{"symbol": "AAPL", "qty": 10, "side": "buy", "type": "market"}请求头进行身份验证,用于下单。$ALPACA_KEY
Integration Notes
集成说明
Integrate by adding the skill to your OpenClaw agent via . For external APIs, set auth in env vars like export BROKER_API_KEY=$SERVICE_API_KEY and use in code: . Ensure data pipelines match, e.g., parse API responses into Pandas DataFrames for analysis. For webhooks, configure callbacks like . Test integrations in a sandbox environment first, using flags like to simulate trades without real execution.
openclaw add-skill algo-tradingoc.set_auth('alpaca', os.environ['BROKER_API_KEY'])oc.register_webhook('/triggers', lambda event: oc.execute_strategy('event_strategy'))--sandbox true通过将本技能添加至你的OpenClaw Agent中。对于外部API,需在环境变量中设置身份验证信息,例如,并在代码中使用:。确保数据管道匹配,例如将API响应解析为Pandas DataFrames用于分析。对于Webhook,配置回调函数如。需先在沙箱环境中测试集成,使用等标志模拟交易,避免实际执行。
openclaw add-skill algo-tradingexport BROKER_API_KEY=$SERVICE_API_KEYoc.set_auth('alpaca', os.environ['BROKER_API_KEY'])oc.register_webhook('/triggers', lambda event: oc.execute_strategy('event_strategy'))--sandbox trueError Handling
错误处理
Always check for API errors by wrapping calls in try-except, e.g.:
python
try:
response = oc.fetch_data('AAPL', '1d')
except APIError as e:
print(f"API Error: {e.code} - {e.message}") # Handles 429 for rate limitsHandle common issues like rate limits by implementing retries: use . For invalid configs, validate with , which returns errors like "Missing param: short_window". Log all errors with timestamps for auditing, e.g., via . If authentication fails, prompt for env var checks, e.g., ensure $SERVICE_API_KEY is set.
oc.retry_on_error(call_func, max_retries=3)openclaw algo-trading validate-config config.jsonoc.log_error('Trade failed: insufficient funds')需始终将API调用包裹在try-except块中以检查API错误,例如:
python
try:
response = oc.fetch_data('AAPL', '1d')
except APIError as e:
print(f"API Error: {e.code} - {e.message}") # 处理429请求超限错误通过实现重试机制处理请求超限等常见问题:使用。对于无效配置,使用验证,该命令会返回如“Missing param: short_window”这类错误。记录所有带时间戳的错误用于审计,例如通过。若身份验证失败,提示检查环境变量,例如确保已设置。
oc.retry_on_error(call_func, max_retries=3)openclaw algo-trading validate-config config.jsonoc.log_error('Trade failed: insufficient funds')$SERVICE_API_KEYConcrete Usage Examples
实际使用示例
-
Backtesting a Moving Average Strategy: Load historical data and run a backtest. Command:. In code:
openclaw algo-trading backtest --file aapl_historical.csv --strategy MA_Crossoverpythonoc = openclaw.Skill('algo-trading') data = oc.load_data('aapl_historical.csv') results = oc.backtest_strategy('MA_Crossover', data) print(results['sharpe_ratio']) # Outputs e.g., 1.2This analyzes past performance to refine the strategy before live use. -
Executing a Live Trade on RSI Signal: Fetch real-time data, generate signals, and place an order. Command:. In code:
openclaw algo-trading run --strategy RSI_Overbought --symbols TSLA --broker alpacapythonoc = openclaw.Skill('algo-trading') rsi_data = oc.fetch_data('TSLA', '1m') signal = oc.analyze_strategy('RSI_Overbought', rsi_data) if signal == 'sell': oc.execute_trade('TSLA', 'sell', 5) # Sells 5 sharesThis automates selling when RSI exceeds 70, using live API calls.
-
回测移动均线策略:加载历史数据并运行回测。命令:。代码实现:
openclaw algo-trading backtest --file aapl_historical.csv --strategy MA_Crossoverpythonoc = openclaw.Skill('algo-trading') data = oc.load_data('aapl_historical.csv') results = oc.backtest_strategy('MA_Crossover', data) print(results['sharpe_ratio']) # 输出示例:1.2该示例可分析策略过往表现,以便在实盘使用前优化策略。 -
基于RSI信号执行实盘交易:获取实时数据、生成信号并下单。命令:。代码实现:
openclaw algo-trading run --strategy RSI_Overbought --symbols TSLA --broker alpacapythonoc = openclaw.Skill('algo-trading') rsi_data = oc.fetch_data('TSLA', '1m') signal = oc.analyze_strategy('RSI_Overbought', rsi_data) if signal == 'sell': oc.execute_trade('TSLA', 'sell', 5) # 卖出5股该示例可在RSI超过70时自动执行卖出操作,使用实时API调用。
Graph Relationships
关联关系
- Depends on: financial-data-fetcher (for market data retrieval)
- Related to: risk-analysis (for evaluating trade risks)
- Conflicts with: manual-trading (due to automation focus)
- Enhances: portfolio-management (by adding automated strategies)
- 依赖:financial-data-fetcher(用于获取市场数据)
- 相关:risk-analysis(用于评估交易风险)
- 冲突:manual-trading(因聚焦自动化)
- 增强:portfolio-management(通过添加自动化策略)