vnpy-export
This Claude Code skill exports a Vibe-Trading backtest strategy into a vnpy CtaTemplate Python class file that runs directly in vnpy's CTA Strategy App for live trading or backtesting. Use it when exporting strategies to vnpy, running `/vnpy` commands, or integrating Vibe-Trading strategies with vnpy's framework, which supports A-share equities, futures, and cryptocurrency via BarGenerator and ArrayManager abstractions.
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading /tmp/vnpy-export && cp -r /tmp/vnpy-export/agent/src/skills/vnpy-export ~/.claude/skills/vnpy-exportSKILL.md
## Overview
This skill translates a Vibe-Trading strategy into a **vnpy `CtaTemplate` subclass** `.py` file
that can be loaded directly into the vnpy CTA Strategy App for live trading or vnpy backtesting.
Output file: `artifacts/vnpy_strategy/<StrategyName>Strategy.py` (inside the run directory).
vnpy is the most widely-used open-source quant framework in mainland China (39k+ GitHub stars).
Use this skill when the user asks to export to vnpy, requests a `/vnpy` command, or wants to
run a Vibe-Trading strategy inside vnpy's CTA backtester or live trading engine.
---
## Workflow: Export from Backtest Run
1. `load_skill("vnpy-export")` — read this guide
2. `read_file("config.json")` — extract instrument, dates, parameters, interval
3. `read_file("code/signal_engine.py")` — understand the Python signal logic
4. Determine asset class from `config.json` → choose correct CtaTemplate convention (see below)
5. Translate signal logic to CtaTemplate using the reference tables
6. `write_file("artifacts/vnpy_strategy/<StrategyName>Strategy.py")` — save the output
7. Return the class in a code block with setup instructions
## Workflow: Generate from Description
1. `load_skill("vnpy-export")` — read this guide
2. Write a CtaTemplate class from the user's strategy description
3. `write_file("artifacts/vnpy_strategy/<StrategyName>Strategy.py")` — save the output
4. Return the class with setup and usage instructions
---
## Asset Class Conventions
vnpy uses the same `CtaTemplate` base class for all asset types, but parameter conventions differ:
| Asset Class | Instrument Example | `vt_symbol` Format | Position Unit |
|-------------|-------------------|---------------------|---------------|
| A-share stock | Ping An Bank | `000001.SZSE` | shares (整手, min 100) |
| Futures | IF2406 | `IF2406.CFFEX` | lots |
| Crypto | BTC/USDT | `BTC/USDT.BINANCE` | coin units |
For **stocks**: use `buy` / `sell` only (no short selling unless margin account).
For **futures / crypto**: use all four directions — `buy`, `sell`, `short`, `cover`.
---
## CtaTemplate Structure
Every strategy must subclass `CtaTemplate` and implement these methods:
| Method | Purpose |
|--------|---------|
| `__init__` | Declare parameters, variables, BarGenerator, ArrayManager |
| `on_init` | Called once at startup; call `load_bar(n)` to warm up indicators |
| `on_start` | Called when strategy is started by user |
| `on_stop` | Called when strategy is stopped |
| `on_tick` | Receives live tick data; forward to BarGenerator |
| `on_bar` | Main logic — called once per bar by BarGenerator |
| `on_order` | Order status updates |
| `on_trade` | Fill notifications |
| `on_stop_order` | Stop-order status (if using stop orders) |
**Always call** `self.cancel_all()` at the start of `on_bar` to avoid stale orders.
**Always call** `self.put_event()` at the end of `on_bar` to refresh the UI.
---
## Full Template
See `scripts/cta_template.py` for a complete, runnable example (MA crossover).
The template below is the canonical skeleton — replace the `# SIGNAL LOGIC` section:
```python
from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
class {{StrategyName}}Strategy(CtaTemplate):
"""
Vibe-Trading export — {{StrategyName}}
Generated from run: {{run_id}}
Instrument: {{vt_symbol}}
"""
author = "Vibe-Trading"
# ── Parameters (editable in vnpy UI) ──────────────────────────────────
{{param_name}} = {{param_default}} # add one line per parameter
parameters = [{{param_list_as_strings}}]
# ── Variables (displayed in vnpy UI, reset on strategy restart) ────────
{{var_name}} = 0.0 # add one line per runtime variable
variables = [{{var_list_as_strings}}]
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
self.am = ArrayManager()
# initialise variable attributes to match class-level defaults
# (vnpy requires instance attributes for variables declared above)
def on_init(self):
self.write_log("Strategy initialised")
self.load_bar({{warmup_bars}}) # load enough bars to warm up all indicators
def on_start(self):
self.write_log("Strategy started")
self.put_event()
def on_stop(self):
self.write_log("Strategy stopped")
def on_tick(self, tick: TickData):
self.bg.update_tick(tick)
def on_bar(self, bar: BarData):
self.cancel_all()
am = self.am
am.update_bar(bar)
if not am.inited:
return
# ── INDICATOR CALCULATIONS ──────────────────────────────────────────
# translate indicators from signal_engine.py using the mapping table
# ── SIGNAL LOGIC ───────────────────────────────────────────────────
# set cross_over / cross_under (or long_signal / short_signal) here
# ── ORDER EXECUTION ────────────────────────────────────────────────
if cross_over:
if self.pos == 0:
self.buy(bar.close_price, 1)
elif self.pos < 0:
self.cover(bar.close_price, 1)
self.buy(bar.close_price, 1)
elif cross_under:
if self.pos == 0:
self.short(bar.close_price, 1)
elif self.pos > 0:
self.sell(bar.close_price, 1)
self.short(bar.close_price, 1)
self.put_event()
def on_order(self, order: OrderData):
pass
def on_trade(self, trade: TradeData):
self.put_event()
def on_stop_order(self, stop_order: StopOrder):
pass
```
---
## Python → ArrayManager Indicator Mapping
`ArrayManager` is vnpy's built-in vectorised indicator library. Always prefer it over pandas
when the equivalent method exists — it is faster andProfessional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).
ADR/H-share/A-share cross-listing premium analysis — track pricing gaps between US-listed ADRs, HK-listed H-shares, and A-shares for arbitrage signals, dual-listing valuation, and delisting risk assessment.
AKShare financial data aggregator (18k+ stars). Free, no API key. Covers A-shares, US, HK, futures, macro, forex. Primary fallback for tushare and yfinance.
Browse and bench the bundled alpha zoos — prebuilt cross-sectional factor libraries (Kakushadze 101, GTJA 191, Qlib 158, Fama-French / Carhart). Use when the user asks "which alphas exist", wants metadata on a named alpha, or wants to run IC/IR on a whole zoo over a universe.
A 股 ST/*ST 风险预测框架 — 基于最新中报/三季报或业绩预告/快报,预测下一财年是否会因营收、利润、净资产、分红不达标而被风险警示,并将新浪监管处罚记录作为独立证据面纳入风险等级。仅适用于 A 股,不预测财务造假。
Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 4 optimizers and rebalancing rules.
Diagnose failed or underperforming backtests, locate the root cause, and fix the issue
Behavioral finance applications: theories of overreaction and underreaction, behavioral explanations for momentum and reversal, investor sentiment cycles, cognitive-bias checklists, and debiasing quantitative strategies.