Vnpy Export logo

Vnpy Export

OrganizationPopular
HKUDS
vnpy-export

Export a Vibe-Trading backtest strategy to a runnable vnpy CtaTemplate Python class — supports A-share equities, futures, and crypto via BarGenerator + ArrayManager.

Overview

PublisherHKUDS
RepositoryVibe-Trading
Skill namevnpy-export
Stars
35.2K
Forks
5.7K
Bundled files
1
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 1 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by HKUDS on GitHub. Read the source before you install it.

Installation

Install the Vnpy Export AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/vnpy-export
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading.git /tmp/Vibe-Trading
mkdir -p .claude/skills
cp -r /tmp/Vibe-Trading/agent/src/skills/vnpy-export .claude/skills/vnpy-export
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Vnpy Export in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Vnpy Export on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Vnpy Export is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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 ClassInstrument Examplevt_symbol FormatPosition Unit
A-share stockPing An Bank000001.SZSEshares (整手, min 100)
FuturesIF2406IF2406.CFFEXlots
CryptoBTC/USDTBTC/USDT.BINANCEcoin 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:

MethodPurpose
__init__Declare parameters, variables, BarGenerator, ArrayManager
on_initCalled once at startup; call load_bar(n) to warm up indicators
on_startCalled when strategy is started by user
on_stopCalled when strategy is stopped
on_tickReceives live tick data; forward to BarGenerator
on_barMain logic — called once per bar by BarGenerator
on_orderOrder status updates
on_tradeFill notifications
on_stop_orderStop-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_ctastrategy 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 and avoids look-ahead bias.

Python (Vibe-Trading / pandas / ta-lib)vnpy ArrayManager
df['close'].rolling(n).mean()am.sma(n)
df['close'].ewm(span=n).mean()am.ema(n)
ta.RSI(close, n)am.rsi(n)
ta.MACD(close, 12, 26, 9)am.macd(12, 26, 9) → (macd, signal, hist)
Bollinger Bandsam.boll(n, dev) → (mid, upper, lower)
ATRam.atr(n)
ADXam.adx(n)
df['close'].rolling(n).std()am.std(n)
Stochastic K, Dam.kd(n, m) → (k, d)
df['high'].rolling(n).max()am.high_array[-n:].max()
df['low'].rolling(n).min()am.low_array[-n:].min()
Donchian channelam.donchian(n) → (upper, lower)
df['close'].shift(1) (previous bar)am.close_array[-2]
Last N bars as arrayam.sma(n, array=True) (returns full array)

Using arrays: pass array=True to get the full history array (e.g. for crossover detection):

python
fast_ma = am.sma(self.fast_window, array=True)
cross_over = fast_ma[-1] > slow_ma[-1] and fast_ma[-2] <= slow_ma[-2]

Signal → Order Mapping

Vibe-Trading signalPosition checkvnpy call
Long entryself.pos == 0self.buy(price, volume)
Long entry (reverse from short)self.pos < 0self.cover(price, vol); self.buy(price, vol)
Long exitself.pos > 0self.sell(price, volume)
Short entryself.pos == 0self.short(price, volume)
Short entry (reverse from long)self.pos > 0self.sell(price, vol); self.short(price, vol)
Short exitself.pos < 0self.cover(price, volume)
Close all (stop signal)anyself.cancel_all() then sell / cover as needed

Price conventions:

  • For backtesting: use bar.close_price (market order equivalent)
  • For live trading with limit orders: use bar.close_price ± a small offset (e.g. * 1.001)
  • For stop orders: use self.buy_stop(trigger, volume) / self.short_stop(trigger, volume)

Volume conventions:

  • Stocks: volume in shares; must be a multiple of 100 (round lots)
  • Futures: volume in lots (usually 1 for CtaTemplate strategies)
  • Crypto: volume in base-currency units (e.g., BTC)

Multi-Timeframe Strategies

When the Vibe-Trading strategy uses multiple timeframes (e.g., daily signal, hourly entry):

python
def __init__(self, ...):
    super().__init__(...)
    self.bg = BarGenerator(self.on_bar, 5, self.on_5min_bar)   # 5-min bars
    self.bg_d = BarGenerator(self.on_bar, window=1, on_window_bar=self.on_daily_bar,
                              interval=Interval.DAILY)          # daily bars
    self.am = ArrayManager()
    self.am_d = ArrayManager(size=100)                          # daily ArrayManager

def on_bar(self, bar: BarData):
    self.bg.update_bar(bar)    # feeds 5-min generator

def on_5min_bar(self, bar: BarData):
    self.bg_d.update_bar(bar)  # feeds daily generator
    # put intraday entry logic here

def on_daily_bar(self, bar: BarData):
    self.am_d.update_bar(bar)
    # put daily trend-filter logic here

Output File Instructions

Save the generated file to: artifacts/vnpy_strategy/<StrategyName>Strategy.py

To load in vnpy:

  1. Copy the file to your vnpy project's strategies/ folder (or any folder on sys.path)
  2. Open the vnpy Trader → CTA Strategy App
  3. Click Add Strategy → select <StrategyName>Strategy from the dropdown
  4. Set vt_symbol (e.g. IF2406.CFFEX) and adjust parameters
  5. Click Init → Start to begin

To run the vnpy backtester:

python
from vnpy_ctastrategy.backtesting import BacktestingEngine
from vnpy.trader.constant import Interval

engine = BacktestingEngine()
engine.set_parameters(
    vt_symbol="000001.SZSE",
    interval=Interval.DAILY,
    start=datetime(2020, 1, 1),
    end=datetime(2024, 1, 1),
    rate=0.0003,
    slippage=0.02,
    size=1,
    pricetick=0.01,
    capital=1_000_000,
)
engine.add_strategy({{StrategyName}}Strategy, {})
engine.load_data()
engine.run_backtesting()
df = engine.calculate_result()
engine.calculate_statistics()
engine.show_chart()

Quality Checklist

Before saving the output file:

  • Class name ends with Strategy and matches the filename
  • All parameters entries have matching class-level defaults and __init__ instance attributes
  • All variables entries have matching instance attributes initialised in __init__
  • on_bar calls self.cancel_all() at the start
  • on_bar calls self.put_event() at the end
  • on_bar returns early if not am.inited
  • Position direction checked with self.pos before every order call
  • Stocks: no short / cover calls unless margin trading is explicitly requested
  • load_bar(n) warmup in on_init is at least max(all indicator windows) + 2
  • Comment block at top of file notes the original Vibe-Trading run_id and instrument

References

  • vnpy CtaTemplate source: vnpy/app/cta_strategy/template.py
  • ArrayManager source: vnpy/app/cta_strategy/base.py
  • Official docs: https://www.vnpy.com/docs/cn/cta_strategy.html
  • Example strategies (official): vnpy/app/cta_strategy/strategies/

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Vnpy Export AI skill do?

Export a Vibe-Trading backtest strategy to a runnable vnpy CtaTemplate Python class — supports A-share equities, futures, and crypto via BarGenerator + ArrayManager.

Why use Vnpy Export on TypingMind?

Because you install it once and use it with any model. Vnpy Export is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Vnpy Export in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/vnpy-export. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Vnpy Export?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Vnpy Export?

As many as you like. As long as a model supports skills, you can use Vnpy Export with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Vnpy Export AI skill free?

Yes. It is published on GitHub by HKUDS under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇