Логотип Pine Script

Pine Script

ОрганізаціяПопулярне
HKUDS
pine-script

Export backtest strategies to indicator/strategy code for major trading platforms — TradingView, 通达信, 同花顺, 东方财富, MT5.

Огляд

ВидавецьHKUDS
РепозиторійVibe-Trading
Назва навичкиpine-script
Зірки
35.2K
Форки
5.7K
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем HKUDS. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Pine Script у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/pine-script
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

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/pine-script .claude/skills/pine-script
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Pine Script в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Pine Script, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Pine Script не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Overview

This skill exports a Vibe-Trading strategy to all major trading platforms in one go. Output file: artifacts/strategy.pine (inside the run directory).

Supported platforms (always generate ALL):

GroupPlatformsLanguage
International ChartsTradingViewPine Script v6
China Equities通达信 / 同花顺 / 东方财富TDX Formula
Forex / CFDMetaTrader 5MQL5

Workflow: Export from Backtest

  1. load_skill("pine-script") — read this guide
  2. read_file("config.json") — understand instruments, dates, parameters
  3. read_file("code/signal_engine.py") — understand the Python strategy logic
  4. Translate the strategy to ALL platforms using the references below
  5. write_file("artifacts/strategy.pine") — save the combined output
  6. Return the code in a code block with usage instructions per platform

Workflow: Generate from Description

  1. load_skill("pine-script") — read this guide
  2. Write indicator/strategy code for ALL platforms based on the user's description
  3. write_file("artifacts/strategy.pine") — save the combined output
  4. Return the code with usage instructions

Output Format

The output file uses this structure (all platforms in one file):

================================================================================
  TRADINGVIEW — Pine Script v6
  Paste into: Pine Editor → New blank indicator → Add to Chart
================================================================================

[Pine Script code here]

================================================================================
  通达信 / 同花顺 / 东方财富 (TDX Formula)
  Paste into: 功能 → 公式管理器 → 新建指标公式
================================================================================

[TDX formula code here]

================================================================================
  MT5 — MQL5
  Save as: .mq5 file → MetaEditor → Compile → Navigator → Attach to Chart
================================================================================

[MQL5 code here]

Platform Reference

1. TradingView — Pine Script v6

Template

pinescript
// This strategy was generated by Vibe-Trading
// Paste into TradingView Pine Editor → Add to Chart
//@version=6
strategy("Strategy Name", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, initial_capital=1000000)

// ============================================================================
// INPUTS
// ============================================================================
// [Group inputs logically with input.int(), input.float(), input.string()]

// ============================================================================
// CALCULATIONS
// ============================================================================
// [Core indicator calculations]

// ============================================================================
// CONDITIONS
// ============================================================================
longCondition = false
shortCondition = false
exitLongCondition = false
exitShortCondition = false

// ============================================================================
// STRATEGY EXECUTION
// ============================================================================
if longCondition
    strategy.entry("Long", strategy.long)
if shortCondition
    strategy.entry("Short", strategy.short)
if exitLongCondition
    strategy.close("Long")
if exitShortCondition
    strategy.close("Short")

// ============================================================================
// PLOTS
// ============================================================================
// [Visual overlays: moving averages, bands, signals]

// ============================================================================
// ALERTS
// ============================================================================
alertcondition(longCondition, title="Long Signal", message="Long entry signal triggered")
alertcondition(shortCondition, title="Short Signal", message="Short entry signal triggered")

Python → Pine Script Mapping

Python (pandas/numpy)Pine Script v6
df['close'].rolling(n).mean()ta.sma(close, n)
df['close'].ewm(span=n).mean()ta.ema(close, n)
ta.RSI(df['close'], n) or manual RSIta.rsi(close, n)
ta.MACD(df['close'])[macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9)
df['close'].rolling(n).std()ta.stdev(close, n)
df['high'].rolling(n).max()ta.highest(high, n)
df['low'].rolling(n).min()ta.lowest(low, n)
df['close'].pct_change(fill_method=None)(close - close[1]) / close[1]
df['volume'].rolling(n).mean()ta.sma(volume, n)
df['close'] > df['close'].shift(1)close > close[1]
Bollinger Bands[mid, upper, lower] = ta.bb(close, length, mult)
ATRta.atr(length)
ADXta.adx(high, low, close, length)
Stochasticta.stoch(close, high, low, length, smoothK, smoothD)
CCIta.cci(close, length)
Williams %Rta.wpr(length)
MFIta.mfi(close, length)
OBVta.obv
VWAPta.vwap

Data References

PythonPine Script v6
df['open']open
df['high']high
df['low']low
df['close']close
df['volume']volume
df.index (datetime)time
df['close'].shift(n)close[n]

Signal Logic

Python PatternPine Script v6
(fast > slow) & (fast.shift(1) <= slow.shift(1))ta.crossover(fast, slow)
(fast < slow) & (fast.shift(1) >= slow.shift(1))ta.crossunder(fast, slow)
signal.where(condition, 0)condition ? value : 0
np.where(cond, val_true, val_false)cond ? val_true : val_false
signal.clip(-1, 1)math.max(-1, math.min(1, signal))
signal.fillna(0)nz(signal, 0)
pd.isna(value)na(value)

Position Sizing

Python PatternPine Script v6
Equal weight 1/Nstrategy.percent_of_equity with default_qty_value = 100/N
Full position on signal=1.0default_qty_type=strategy.percent_of_equity, default_qty_value=100
Half position on signal=0.5Use strategy.entry(..., qty=strategy.equity * 0.5 / close)
Stop-lossstrategy.exit("Exit", stop=entryPrice * (1 - stopPct))
Take-profitstrategy.exit("Exit", limit=entryPrice * (1 + tpPct))

Syntax Rules (Critical)

  1. Version declaration must be first line: //@version=6
  2. Ternary operators MUST stay on one line: text = condition ? "a" : "b"
  3. Line continuation: continuation lines must be indented MORE than the starting line
  4. No plot() in local scope (if/for/function) — use plot(condition ? value : na)
  5. var: persistent state across bars; regular assignment recalculates each bar
  6. Avoid repainting: use barstate.isconfirmed, lookahead=barmerge.lookahead_off
  7. Limits: max 500 bars lookback, 500 plot calls, 64 entry/exit per bar, 40 request.security()

2. 通达信 / 同花顺 / 东方财富 — TDX Formula

These platforms share 95%+ identical formula syntax. Write ONE version that works on all three.

Template

{Vibe-Trading 策略导出}
{策略名称: XXX}

{——————— 参数 ———————}
N:=14;
M:=6;

{——————— 指标计算 ———————}
RSI_VAL:=RSI(CLOSE,N);
MA_FAST:=MA(CLOSE,5);
MA_SLOW:=MA(CLOSE,20);

{——————— 买卖信号 ———————}
BUY:CROSS(MA_FAST,MA_SLOW) AND RSI_VAL<40,COLORRED;
SELL:CROSS(MA_SLOW,MA_FAST) AND RSI_VAL>60,COLORGREEN;

DRAWTEXT(BUY,LOW,'B'),COLORYELLOW;
DRAWTEXT(SELL,HIGH,'S'),COLORWHITE;

Python → TDX Mapping

PythonTDX Formula
df['close'].rolling(n).mean()MA(CLOSE,N)
df['close'].ewm(span=n).mean()EMA(CLOSE,N)
RSIRSI(CLOSE,N) (returns 0-100)
MACDMACD.DIF, MACD.DEA, MACD.MACD or manual: DIF:=EMA(CLOSE,12)-EMA(CLOSE,26); DEA:=EMA(DIF,9); MACD:=(DIF-DEA)*2;
Bollinger BandsBOLL(N,M) → BOLL.UPPER, BOLL.MID, BOLL.LOWER or manual
ATRATR:=MA(MAX(MAX(HIGH-LOW,ABS(HIGH-REF(CLOSE,1))),ABS(LOW-REF(CLOSE,1))),N);
df['close'].shift(n)REF(CLOSE,N)
df['high'].rolling(n).max()HHV(HIGH,N)
df['low'].rolling(n).min()LLV(LOW,N)
crossover(fast, slow)CROSS(FAST,SLOW)
crossunder(fast, slow)CROSS(SLOW,FAST)
df['volume']VOL
abs(x)ABS(X)
max(a,b)MAX(A,B)
min(a,b)MIN(A,B)
conditionalIF(COND,A,B)
df['close'].pct_change(fill_method=None)(CLOSE-REF(CLOSE,1))/REF(CLOSE,1)
count true in N barsCOUNT(COND,N)
sum over N barsSUM(X,N)
std over N barsSTD(CLOSE,N)
slope / linear regressionSLOPE(CLOSE,N)

Syntax Rules

  1. Assignment: := for intermediate variables, : for output (plotted) lines
  2. Comments: {comment} — curly braces, NOT //
  3. No semicolons optional: each statement ends with ;
  4. Colors: COLORRED, COLORGREEN, COLORYELLOW, COLORWHITE, COLORBLUE, COLORCYAN, COLORMAGENTA
  5. Line styles: LINETHICK2, POINTDOT, STICK, VOLSTICK
  6. Draw text: DRAWTEXT(COND, PRICE, 'TEXT'), COLOR;
  7. Draw icon: DRAWICON(COND, PRICE, ICON_ID);
  8. All function/variable names UPPERCASE
  9. No loops / no arrays — everything is vectorized bar-by-bar
  10. Max formula length: ~10,000 characters per formula

Platform Differences

Feature通达信同花顺东方财富
MACD built-inMACD(12,26,9)MACD(12,26,9)same
StochasticKDJ(N,M1,M2)samesame
Custom colorCOLOR+RRGGBBCOLOR+RRGGBBlimited
Strategy backtest条件选股 only条件选股 only条件选股 only

For maximum compatibility, avoid platform-specific extensions. Stick to core functions.


3. MetaTrader 5 — MQL5

Template (Custom Indicator)

mql5
//+------------------------------------------------------------------+
//| Generated by Vibe-Trading                                         |
//+------------------------------------------------------------------+
#property copyright "Vibe-Trading"
#property indicator_chart_window       // or indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_color1  clrDodgerBlue
#property indicator_color2  clrRed

input int InpPeriod = 14;  // Period

double BuyBuffer[];
double SellBuffer[];

int OnInit()
{
   SetIndexBuffer(0, BuyBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, SellBuffer, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_ARROW, 233);  // up arrow
   PlotIndexSetInteger(1, PLOT_ARROW, 234);  // down arrow
   PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_ARROW);
   PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_ARROW);
   return(INIT_SUCCEEDED);
}

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   int start = MathMax(prev_calculated - 1, InpPeriod);
   for(int i = start; i < rates_total; i++)
   {
      BuyBuffer[i]  = EMPTY_VALUE;
      SellBuffer[i] = EMPTY_VALUE;

      // === YOUR LOGIC HERE ===
      // Example: if(buyCondition) BuyBuffer[i] = low[i];
      //          if(sellCondition) SellBuffer[i] = high[i];
   }
   return(rates_total);
}

Python → MQL5 Mapping

PythonMQL5
df['close'].rolling(n).mean()iMA(_Symbol, PERIOD_CURRENT, n, 0, MODE_SMA, PRICE_CLOSE) or manual loop
EMAiMA(..., MODE_EMA, ...)
RSIiRSI(_Symbol, PERIOD_CURRENT, n, PRICE_CLOSE)
MACDiMACD(_Symbol, PERIOD_CURRENT, 12, 26, 9, PRICE_CLOSE)
BollingeriBands(_Symbol, PERIOD_CURRENT, n, 0, mult, PRICE_CLOSE)
ATRiATR(_Symbol, PERIOD_CURRENT, n)
StochasticiStochastic(_Symbol, PERIOD_CURRENT, K, D, slowing, MODE_SMA, STO_LOWHIGH)
df['close'].shift(n)close[i-n] (in OnCalculate loop)
crossoverbuf[i] > ref[i] && buf[i-1] <= ref[i-1]

Syntax Rules

  1. Indicator handles: call iMA() etc. in OnInit(), use CopyBuffer() to get values
  2. Buffer direction: MQL5 buffers are indexed 0=oldest by default; use ArraySetAsSeries() to reverse
  3. EMPTY_VALUE: use for "no signal" on arrow plots
  4. Indicator vs EA: generate indicator (.mq5), not Expert Advisor, to match "indicator export" purpose
  5. Handle-based API: MQL5 uses handles — create in OnInit, read in OnCalculate

Symbol Format Mapping

When generating code, map Vibe-Trading instrument codes appropriately:

Vibe-TradingTradingView通达信/同花顺MT5
000001.SZSZSE:000001000001N/A
600519.SHSSE:600519600519N/A
AAPL.USNASDAQ:AAPLN/AAAPL
BTC-USDTBINANCE:BTCUSDTN/ABTCUSD

Note: Most indicator code is instrument-agnostic — the user applies it to whatever chart they're viewing. Include a comment noting the original instrument for reference only.

Limitations & Transparency

When a Python strategy uses features that can't be directly translated, clearly note it:

Python FeaturePlatform Limitation
ML models (sklearn, etc.)None — flag as "manual implementation required"
Custom pandas operationsTDX — limited to built-in functions
Multi-timeframe logicTDX — no native MTF; Pine/MQL5 — supported
Dynamic position sizingTDX — indicator only, no position control
External data (API calls)All — indicators run offline on chart data only

Always add a comment block at the top listing any features that could not be translated.

Quality Checklist

Before outputting:

  • ALL 3 platform sections are included (Pine Script, TDX, MQL5)
  • Each platform section has proper header with usage instructions
  • Pine Script: //@version=6 is first line, no plot() in local scope, ternary on single lines
  • TDX: all uppercase functions, := for intermediate, : for output, {comments}
  • MQL5: proper handle-based API, EMPTY_VALUE for no-signal
  • Entry/exit conditions match the Python signal logic semantically across ALL platforms
  • Untranslatable features are clearly documented at the top of each section
  • Comment header notes the original Vibe-Trading run_id and instrument

Поширені запитання

Що робить навичка ШІ Pine Script?

Export backtest strategies to indicator/strategy code for major trading platforms — TradingView, 通达信, 同花顺, 东方财富, MT5.

Навіщо використовувати Pine Script у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Pine Script — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Pine Script у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/pine-script. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Pine Script?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Pine Script?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Pine Script — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Pine Script?

Так. Навичку опубліковано на GitHub: HKUDS, за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇