"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: multi-platform indicator export (TradingView + TDX + MT5)
warren61866cd96a3039b
diff --git a/README.md b/README.mdindex 3cd8eb31c..6a52efe50 100644--- a/README.md+++ b/README.md@@ -51,6 +51,7 @@## 📰 News+- **2026-04-12** 🌍 **Multi-Platform Indicator Export**: `/pine` now exports strategies to **TradingView (Pine Script v6)**, **通达信/同花顺/东方财富 (TDX formula)**, and **MetaTrader 5 (MQL5)** in a single file — covering international equities, China A-shares, and global forex/CFD markets. One command, three platforms.- **2026-04-11** 🛡️ **Reliability & DX**: `vibe-trading init` interactive .env bootstrap ([#19](https://github.com/HKUDS/Vibe-Trading/pull/19)), startup preflight checks for LLM & data sources, runtime data-source fallback when primary returns empty, hardened backtest engine with data validation & error isolation, date/time context injection into agent & swarm prompts. Multi-language README (zh/ja/ko) via community PR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21).- **2026-04-10** 📦 **v0.1.4**: Fix Docker build ([#8](https://github.com/HKUDS/Vibe-Trading/issues/8)), add `web_search` MCP tool (17 total), `akshare`/`ccxt` in deps & MCP. 11 LLM providers (DeepSeek, Groq, Gemini, Ollama, etc.), all tuning params via `.env`. Hardened `ml-strategy` skill. Published to PyPI and ClawHub.- **2026-04-09** 📊 **Backtest Wave 2 — multi-asset engines**: added ChinaFutures (CFFEX/SHFE/DCE/ZCE, 50+ contracts), GlobalFutures (CME/ICE/Eurex, 30+ contracts), Forex (24 pairs, spread + swap), Options v2 (American exercise, IV smile). Statistical validation: Monte Carlo permutation test, Bootstrap Sharpe CI, Walk-Forward analysis.@@ -67,7 +68,7 @@ Vibe-Trading is an AI-powered multi-agent finance workspace that turns natural l• **Strategy Generation** — Automatically writes trading code from your ideas<br>• **Smart Data Access** — 5 data sources with automatic fallback; zero-config for all markets<br>• **Performance Testing** — Tests your strategies against historical market data<br>-• **TradingView Export** — One-click convert strategies to Pine Script v6 for TradingView<br>+• **Multi-Platform Export** — One-click convert strategies to TradingView, 通达信/同花顺/东方财富, and MT5<br>• **Expert Teams** — Deploys specialized AI agents for complex research tasks<br>• **Live Updates** — Watch the entire analysis process in real-time@@ -334,7 +335,7 @@ vibe-trading serve # API server| `/list` | Recent runs || `/show <run_id>` | Run details + metrics || `/code <run_id>` | Generated strategy code |-| `/pine <run_id>` | Pine Script for TradingView |+| `/pine <run_id>` | Export indicators (TradingView + TDX + MT5) || `/trace <run_id>` | Full execution replay || `/continue <run_id> <prompt>` | Continue a run with new instructions || `/sessions` | List chat sessions |@@ -362,7 +363,7 @@ vibe-trading --swarm-run investment_committee '{"topic":"BTC outlook"}'vibe-trading --listvibe-trading --show <run_id>vibe-trading --code <run_id>-vibe-trading --pine <run_id> # Pine Script for TradingView+vibe-trading --pine <run_id> # Export indicators (TradingView + TDX + MT5)vibe-trading --trace <run_id>vibe-trading --continue <run_id> "refine the strategy"vibe-trading --upload report.pdf@@ -382,7 +383,7 @@ vibe-trading serve --port 8899|--------|----------|-------------|| `GET` | `/runs` | List runs || `GET` | `/runs/{run_id}` | Run details |-| `GET` | `/runs/{run_id}/pine` | Pine Script export |+| `GET` | `/runs/{run_id}/pine` | Multi-platform indicator export || `POST` | `/sessions` | Create session || `POST` | `/sessions/{id}/messages` | Send message || `GET` | `/sessions/{id}/events` | SSE event stream |diff --git a/README_ja.md b/README_ja.mdindex cb15d8b7d..e56dbc8a2 100644--- a/README_ja.md+++ b/README_ja.md@@ -51,6 +51,7 @@## 📰 ニュース+- **2026-04-12** 🌍 **マルチプラットフォームインジケーター出力**: `/pine`コマンドで**TradingView (Pine Script v6)**、**通達信/同花順/東方財富 (TDX数式)**、**MetaTrader 5 (MQL5)** の3プラットフォームに一括エクスポート — 国際株式、中国A株、グローバルFX/CFD市場をカバー。- **2026-04-11** 🛡️ **信頼性とDX向上**:`vibe-trading init` 対話式 .env ブートストラップ([#19](https://github.com/HKUDS/Vibe-Trading/pull/19))、起動時にLLM・データソースのプリフライトチェック、プライマリソースが空の場合のランタイムフォールバック、バックテストエンジンのデータ検証とエラー分離を強化、エージェントとSwarmプロンプトに現在日時を注入。コミュニティPR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21) で多言語README(zh/ja/ko)を追加。- **2026-04-10** 📦 **v0.1.4**: Dockerビルドを修正([#8](https://github.com/HKUDS/Vibe-Trading/issues/8))、`web_search` MCPツールを追加(合計17)、依存関係とMCPに`akshare`/`ccxt`を追加。11のLLMプロバイダー(DeepSeek, Groq, Gemini, Ollama など)、すべての調整パラメータを`.env`で設定可能。`ml-strategy`スキルを強化。PyPIとClawHubに公開。- **2026-04-09** 📊 **Backtest Wave 2 — マルチアセットエンジン**: ChinaFutures(CFFEX/SHFE/DCE/ZCE、50+銘柄)、GlobalFutures(CME/ICE/Eurex、30+銘柄)、Forex(24通貨ペア、スプレッド+スワップ)、Options v2(アメリカン行使、IVスマイル)を追加。統計的検証: モンテカルロ置換検定、ブートストラップSharpe信頼区間、ウォークフォワード分析。@@ -67,7 +68,7 @@ Vibe-Tradingは、自然言語リクエストをグローバル市場向けの• **Strategy Generation** — アイデアから自動でトレーディングコードを生成<br>• **Smart Data Access** — 自動フォールバック付き5つのデータソース、全市場ゼロ設定<br>• **Performance Testing** — 歴史的市場データで戦略を検証<br>-• **TradingView Export** — ワンクリックでTradingView用Pine Script v6に変換<br>+• **Multi-Platform Export** — ワンクリックでTradingView、通達信/同花順/東方財富、MT5にエクスポート<br>• **Expert Teams** — 複雑なリサーチタスクに特化したAIエージェントチームを展開<br>• **Live Updates** — 分析プロセス全体をリアルタイムで観察@@ -332,7 +333,7 @@ vibe-trading serve # APIサーバー| `/list` | 直近の実行 || `/show <run_id>` | 実行詳細と指標 || `/code <run_id>` | 生成された戦略コード |-| `/pine <run_id>` | TradingView用Pine Script |+| `/pine <run_id>` | インジケーターエクスポート(TradingView + TDX + MT5)|| `/trace <run_id>` | 実行リプレイ || `/continue <run_id> <prompt>` | 実行を新指示で継続 || `/sessions` | チャットセッション一覧 |@@ -359,7 +360,7 @@ vibe-trading --swarm-run investment_committee '{"topic":"BTC outlook"}'vibe-trading --listvibe-trading --show <run_id>vibe-trading --code <run_id>-vibe-trading --pine <run_id> # TradingView用Pine Script+vibe-trading --pine <run_id> # インジケーターエクスポート(TradingView + TDX + MT5)vibe-trading --trace <run_id>vibe-trading --continue <run_id> "refine the strategy"vibe-trading --upload report.pdf@@ -379,7 +380,7 @@ vibe-trading serve --port 8899|--------|----------|-------------|| `GET` | `/runs` | 実行一覧 || `GET` | `/runs/{run_id}` | 実行詳細 |-| `GET` | `/runs/{run_id}/pine` | Pine Scriptエクスポート |+| `GET` | `/runs/{run_id}/pine` | マルチプラットフォームインジケーターエクスポート || `POST` | `/sessions` | セッション作成 || `POST` | `/sessions/{id}/messages` | メッセージ送信 || `GET` | `/sessions/{id}/events` | SSEイベントストリーム |diff --git a/README_ko.md b/README_ko.mdindex cdcfe81bc..2ef8be898 100644--- a/README_ko.md+++ b/README_ko.md@@ -51,6 +51,7 @@## 📰 뉴스+- **2026-04-12** 🌍 **멀티 플랫폼 인디케이터 내보내기**: `/pine` 명령어로 **TradingView (Pine Script v6)**, **통달신/동화순/동방재부 (TDX 수식)**, **MetaTrader 5 (MQL5)** 3개 플랫폼에 한 번에 내보내기 — 국제 주식, 중국 A주, 글로벌 FX/CFD 시장을 커버. 하나의 명령어, 세 개 플랫폼.- **2026-04-11** 🛡️ **안정성 및 DX 개선**: `vibe-trading init` 대화형 .env 부트스트랩([#19](https://github.com/HKUDS/Vibe-Trading/pull/19)), 시작 시 LLM·데이터소스 프리플라이트 체크, 기본 데이터소스 빈 응답 시 런타임 폴백, 백테스트 엔진 데이터 검증 및 에러 격리 강화, 에이전트·Swarm 프롬프트에 현재 날짜/시간 주입. 커뮤니티 PR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21)로 다국어 README(zh/ja/ko) 추가.- **2026-04-10** 📦 **v0.1.4**: Docker 빌드 수정([#8](https://github.com/HKUDS/Vibe-Trading/issues/8)), `web_search` MCP 도구 추가(총 17개), 의존성 및 MCP에 `akshare`/`ccxt` 추가. 11개 LLM 제공자(DeepSeek, Groq, Gemini, Ollama 등), 모든 튜닝 파라미터를 `.env`로 설정. `ml-strategy` 스킬 하드닝. PyPI와 ClawHub에 게시.- **2026-04-09** 📊 **Backtest Wave 2 — 멀티자산 엔진**: ChinaFutures(CFFEX/SHFE/DCE/ZCE, 50+ 종목), GlobalFutures(CME/ICE/Eurex, 30+ 종목), Forex(24 페어, 스프레드 + 스왑), Options v2(미국형 행사, IV 스마일) 추가. 통계 검증: 몬테카를로 순열 테스트, Bootstrap 샤프 CI, 워크포워드 분석.@@ -67,7 +68,7 @@ Vibe-Trading은 AI 기반 멀티 에이전트 금융 워크스페이스로, 자• **전략 생성** — 아이디어를 자동으로 트레이딩 코드로 작성<br>• **스마트 데이터 접근** — 자동 폴백이 있는 5개 데이터 소스; 모든 시장 무설정<br>• **성능 테스트** — 전략을 과거 시장 데이터로 검증<br>-• **TradingView 내보내기** — 클릭 한 번으로 전략을 Pine Script v6로 변환<br>+• **멀티 플랫폼 내보내기** — 클릭 한 번으로 TradingView, 통달신/동화순/동방재부, MT5로 내보내기<br>• **전문 팀** — 복잡한 리서치 작업에 특화 에이전트 팀 배치<br>• **실시간 업데이트** — 전체 분석 과정을 실시간 스트리밍@@ -332,7 +333,7 @@ vibe-trading serve # API 서버| `/list` | 최근 실행 || `/show <run_id>` | 실행 상세 + 지표 || `/code <run_id>` | 생성된 전략 코드 |-| `/pine <run_id>` | TradingView용 Pine Script |+| `/pine <run_id>` | 인디케이터 내보내기 (TradingView + TDX + MT5) || `/trace <run_id>` | 전체 실행 리플레이 || `/continue <run_id> <prompt>` | 새 지시로 실행 계속 || `/sessions` | 채팅 세션 목록 |@@ -360,7 +361,7 @@ vibe-trading --swarm-run investment_committee '{"topic":"BTC outlook"}'vibe-trading --listvibe-trading --show <run_id>vibe-trading --code <run_id>-vibe-trading --pine <run_id> # Pine Script for TradingView+vibe-trading --pine <run_id> # 인디케이터 내보내기 (TradingView + TDX + MT5)vibe-trading --trace <run_id>vibe-trading --continue <run_id> "refine the strategy"vibe-trading --upload report.pdf@@ -380,7 +381,7 @@ vibe-trading serve --port 8899|--------|----------|-------------|| `GET` | `/runs` | 실행 목록 || `GET` | `/runs/{run_id}` | 실행 상세 |-| `GET` | `/runs/{run_id}/pine` | Pine Script 내보내기 |+| `GET` | `/runs/{run_id}/pine` | 멀티 플랫폼 인디케이터 내보내기 || `POST` | `/sessions` | 세션 생성 || `POST` | `/sessions/{id}/messages` | 메시지 전송 || `GET` | `/sessions/{id}/events` | SSE 이벤트 스트림 |diff --git a/README_zh.md b/README_zh.mdindex c70c55966..f79f32cf5 100644--- a/README_zh.md+++ b/README_zh.md@@ -51,6 +51,7 @@## 📰 新闻+- **2026-04-12** 🌍 **多平台指标导出**:`/pine` 命令现在一次性导出 **TradingView (Pine Script v6)**、**通达信/同花顺/东方财富 (TDX 公式)** 和 **MetaTrader 5 (MQL5)** 三个平台的指标代码 — 覆盖国际股票、中国 A 股和全球外汇/CFD 市场。一条命令,三大平台。- **2026-04-11** 🛡️ **可靠性与开发体验**:`vibe-trading init` 交互式 .env 引导([#19](https://github.com/HKUDS/Vibe-Trading/pull/19)),启动预检 LLM 与数据源连通性,主数据源返空时自动回退,回测引擎数据校验与错误隔离加固,Agent 与 Swarm 提示词注入当前日期时间。社区 PR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21) 贡献多语言 README(zh/ja/ko)。- **2026-04-10** 📦 **v0.1.4**:修复 Docker 构建([#8](https://github.com/HKUDS/Vibe-Trading/issues/8)),新增 `web_search` MCP 工具(共 17 个),在依赖与 MCP 中加入 `akshare`/`ccxt`。支持 11 家 LLM 提供商(DeepSeek、Groq、Gemini、Ollama 等),全部调优参数可通过 `.env` 配置。加固 `ml-strategy` 技能。已发布至 PyPI 和 ClawHub。- **2026-04-09** 📊 **回测 Wave 2 —— 多资产引擎**:新增 ChinaFutures(CFFEX/SHFE/DCE/ZCE,50+ 合约)、GlobalFutures(CME/ICE/Eurex,30+ 合约)、Forex(24 货币对,点差 + 掉期)、Options v2(美式行权、IV 微笑)。统计验证:蒙特卡洛置换检验、Bootstrap 夏普区间、Walk-Forward 分析。@@ -67,7 +68,7 @@ Vibe-Trading 是一个由 AI 驱动的多代理金融工作台,将自然语言• **Strategy Generation** —— 从你的想法自动生成交易代码<br>• **Smart Data Access** —— 5 大数据源自动回退;所有市场零配置<br>• **Performance Testing** —— 使用历史行情测试你的策略<br>-• **TradingView Export** —— 一键转换为 TradingView 的 Pine Script v6<br>+• **Multi-Platform Export** —— 一键导出到 TradingView、通达信/同花顺/东方财富 和 MT5<br>• **Expert Teams** —— 部署专职 AI 代理处理复杂研究任务<br>• **Live Updates** —— 全程实时查看分析过程@@ -332,7 +333,7 @@ vibe-trading serve # API 服务器| `/list` | 最近的运行 || `/show <run_id>` | 运行详情与指标 || `/code <run_id>` | 生成的策略代码 |-| `/pine <run_id>` | TradingView 的 Pine Script |+| `/pine <run_id>` | 导出指标代码(TradingView + TDX + MT5)|| `/trace <run_id>` | 完整执行回放 || `/continue <run_id> <prompt>` | 带新指令继续运行 || `/sessions` | 列出聊天会话 |@@ -359,7 +360,7 @@ vibe-trading --swarm-run investment_committee '{"topic":"BTC outlook"}'vibe-trading --listvibe-trading --show <run_id>vibe-trading --code <run_id>-vibe-trading --pine <run_id> # TradingView 的 Pine Script+vibe-trading --pine <run_id> # 导出指标代码(TradingView + TDX + MT5)vibe-trading --trace <run_id>vibe-trading --continue <run_id> "refine the strategy"vibe-trading --upload report.pdf@@ -379,7 +380,7 @@ vibe-trading serve --port 8899|--------|----------|-------------|| `GET` | `/runs` | 列出运行 || `GET` | `/runs/{run_id}` | 运行详情 |-| `GET` | `/runs/{run_id}/pine` | Pine Script 导出 |+| `GET` | `/runs/{run_id}/pine` | 多平台指标导出 || `POST` | `/sessions` | 创建会话 || `POST` | `/sessions/{id}/messages` | 发送消息 || `GET` | `/sessions/{id}/events` | SSE 事件流 |diff --git a/agent/src/skills/pine-script/SKILL.md b/agent/src/skills/pine-script/SKILL.mdindex 004ad8e6c..f5050771e 100644--- a/agent/src/skills/pine-script/SKILL.md+++ b/agent/src/skills/pine-script/SKILL.md@@ -1,34 +1,73 @@---name: pine-script-description: Convert Python backtest strategies to TradingView Pine Script v6, or generate Pine Script from natural language descriptions.+description: Export backtest strategies to indicator/strategy code for major trading platforms — TradingView, 通达信, 同花顺, 东方财富, MT5.category: tool---## Overview-This skill enables two workflows:-1. **Export**: convert an existing `signal_engine.py` (from a completed backtest run) into a TradingView Pine Script v6 strategy-2. **Generate**: write Pine Script v6 directly from a natural-language strategy description+This skill exports a Vibe-Trading strategy to **all major trading platforms** in one go.+Output file: `artifacts/strategy.pine` (inside the run directory).-Output file: `artifacts/strategy.pine` (inside the run directory, or a new run directory).+Supported platforms (always generate ALL):++| Group | Platforms | Language |+|-------|-----------|----------|+| International Charts | TradingView | Pine Script v6 |+| China Equities | 通达信 / 同花顺 / 东方财富 | TDX Formula |+| Forex / CFD | MetaTrader 5 | MQL5 |## Workflow: Export from Backtest-1. `load_skill("pine-script")` — read this conversion guide+1. `load_skill("pine-script")` — read this guide2. `read_file("config.json")` — understand instruments, dates, parameters3. `read_file("code/signal_engine.py")` — understand the Python strategy logic-4. **Translate** the strategy to Pine Script v6 using the mapping table below-5. `write_file("artifacts/strategy.pine")` — save the output-6. Return the Pine Script in a code block with usage instructions+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 Description1. `load_skill("pine-script")` — read this guide-2. Write Pine Script v6 directly based on the user's description-3. `write_file("artifacts/strategy.pine")` — save the output+2. Write indicator/strategy code for ALL platforms based on the user's description+3. `write_file("artifacts/strategy.pine")` — save the combined output4. Return the code with usage instructions-## Pine Script v6 Strategy Template+## 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@@ -78,9 +117,7 @@ alertcondition(longCondition, title="Long Signal", message="Long entry signal tralertcondition(shortCondition, title="Short Signal", message="Short entry signal triggered")```-## Python → Pine Script Mapping Table--### Technical Indicators+### Python → Pine Script Mapping| Python (pandas/numpy) | Pine Script v6 ||------------------------|----------------|@@ -94,13 +131,13 @@ alertcondition(shortCondition, title="Short Signal", message="Short entry signal| `df['close'].pct_change()` | `(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 (manual) | `[mid, upper, lower] = ta.bb(close, length, mult)` |-| ATR (manual or ta-lib) | `ta.atr(length)` |-| ADX | `ta.adx(high, low, close, length)` (returns adx value) |+| Bollinger Bands | `[mid, upper, lower] = ta.bb(close, length, mult)` |+| ATR | `ta.atr(length)` |+| ADX | `ta.adx(high, low, close, length)` || Stochastic | `ta.stoch(close, high, low, length, smoothK, smoothD)` |-| CCI | `ta.cci(close, length)` (Pine v6: `ta.cci(close, length)`) |+| CCI | `ta.cci(close, length)` || Williams %R | `ta.wpr(length)` |-| MFI | `ta.mfi(hlc3, volume, length)` — Pine v6: `ta.mfi(close, length)` |+| MFI | `ta.mfi(close, length)` || OBV | `ta.obv` || VWAP | `ta.vwap` |@@ -138,94 +175,212 @@ alertcondition(shortCondition, title="Short Signal", message="Short entry signal| Stop-loss | `strategy.exit("Exit", stop=entryPrice * (1 - stopPct))` || Take-profit | `strategy.exit("Exit", limit=entryPrice * (1 + tpPct))` |-## Pine Script v6 Syntax Rules--### Critical Rules (common errors)+### Syntax Rules (Critical)1. **Version declaration must be first line**: `//@version=6`-2. **Ternary operators MUST stay on one line** or use intermediate variables:- ```pinescript- // WRONG — causes "end of line without line continuation"- text = condition ? "value1" :- "value2"-- // CORRECT- text = condition ? "value1" : "value2"- ```+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):- ```pinescript- // WRONG- if condition- plot(value)+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()- // CORRECT- plot(condition ? value : na)- ```-5. **var vs regular variables**: use `var` for persistent state across bars, regular assignment recalculates each bar-6. **varip**: persistent even on real-time bar updates (intrabar persistence)+----### Script Types+## 2. 通达信 / 同花顺 / 东方财富 — TDX Formula-| Type | Declaration | Use Case |-|------|-------------|----------|-| `strategy` | `strategy("Name", ...)` | Backtestable with entry/exit orders |-| `indicator` | `indicator("Name", ...)` | Visual indicators, no backtesting |-| `library` | `library("Name")` | Reusable functions |+These platforms share 95%+ identical formula syntax. Write ONE version that works on all three.-**Default output: `strategy`** (matches Vibe-Trading's backtest-first philosophy).+### Template-### Avoid Repainting+```+{Vibe-Trading 策略导出}+{策略名称: XXX}-- Use `barstate.isconfirmed` for signals on confirmed bars only-- Use `request.security()` with `lookahead=barmerge.lookahead_off` (default in v6)-- Do NOT use `security()` on lower timeframes without understanding implications+{——————— 参数 ———————}+N:=14;+M:=6;-### Platform Limits+{——————— 指标计算 ———————}+RSI_VAL:=RSI(CLOSE,N);+MA_FAST:=MA(CLOSE,5);+MA_SLOW:=MA(CLOSE,20);-- Max 500 bars lookback for `[]` operator-- Max 500 plot calls-- Max 64 `strategy.entry/exit` calls per bar-- Max 40 `request.security()` calls+{——————— 买卖信号 ———————}+BUY:CROSS(MA_FAST,MA_SLOW) AND RSI_VAL<40,COLORRED;+SELL:CROSS(MA_SLOW,MA_FAST) AND RSI_VAL>60,COLORGREEN;-## TradingView Symbol Format+DRAWTEXT(BUY,LOW,'B'),COLORYELLOW;+DRAWTEXT(SELL,HIGH,'S'),COLORWHITE;+```-When generating Pine Script, map Vibe-Trading codes to TradingView symbols:+### Python → TDX Mapping++| Python | TDX Formula |+|--------|-------------|+| `df['close'].rolling(n).mean()` | `MA(CLOSE,N)` |+| `df['close'].ewm(span=n).mean()` | `EMA(CLOSE,N)` |+| RSI | `RSI(CLOSE,N)` (returns 0-100) |+| MACD | `MACD.DIF`, `MACD.DEA`, `MACD.MACD` or manual: `DIF:=EMA(CLOSE,12)-EMA(CLOSE,26); DEA:=EMA(DIF,9); MACD:=(DIF-DEA)*2;` |+| Bollinger Bands | `BOLL(N,M)` → `BOLL.UPPER`, `BOLL.MID`, `BOLL.LOWER` or manual |+| ATR | `ATR:=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)` |+| conditional | `IF(COND,A,B)` |+| `df['close'].pct_change()` | `(CLOSE-REF(CLOSE,1))/REF(CLOSE,1)` |+| count true in N bars | `COUNT(COND,N)` |+| sum over N bars | `SUM(X,N)` |+| std over N bars | `STD(CLOSE,N)` |+| slope / linear regression | `SLOPE(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-in | `MACD(12,26,9)` | `MACD(12,26,9)` | same |+| Stochastic | `KDJ(N,M1,M2)` | same | same |+| Custom color | `COLOR+RRGGBB` | `COLOR+RRGGBB` | limited |+| Strategy backtest | 条件选股 only | 条件选股 only | 条件选股 only |++For maximum compatibility, avoid platform-specific extensions. Stick to core functions.-| Vibe-Trading Format | TradingView Format | Exchange |-|---------------------|-------------------|----------|-| `000001.SZ` | `SZSE:000001` | Shenzhen |-| `600519.SH` | `SSE:600519` | Shanghai |-| `AAPL.US` | `NASDAQ:AAPL` | US (auto-detect) |-| `700.HK` | `HKEX:0700` | Hong Kong |-| `BTC-USDT` | `OKX:BTCUSDT.P` or `BINANCE:BTCUSDT` | Crypto |+----**Note**: Pine Script strategies are chart-independent — the user applies them to whichever symbol they want on TradingView. Include a comment noting the original instrument.+## 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);+}+```-## Usage Instructions (include in response)+### Python → MQL5 Mapping-After generating the Pine Script, always include:+| Python | MQL5 |+|--------|------|+| `df['close'].rolling(n).mean()` | `iMA(_Symbol, PERIOD_CURRENT, n, 0, MODE_SMA, PRICE_CLOSE)` or manual loop |+| EMA | `iMA(..., MODE_EMA, ...)` |+| RSI | `iRSI(_Symbol, PERIOD_CURRENT, n, PRICE_CLOSE)` |+| MACD | `iMACD(_Symbol, PERIOD_CURRENT, 12, 26, 9, PRICE_CLOSE)` |+| Bollinger | `iBands(_Symbol, PERIOD_CURRENT, n, 0, mult, PRICE_CLOSE)` |+| ATR | `iATR(_Symbol, PERIOD_CURRENT, n)` |+| Stochastic | `iStochastic(_Symbol, PERIOD_CURRENT, K, D, slowing, MODE_SMA, STO_LOWHIGH)` |+| `df['close'].shift(n)` | `close[i-n]` (in OnCalculate loop) |+| crossover | `buf[i] > ref[i] && buf[i-1] <= ref[i-1]` |-```-How to use in TradingView:-1. Open TradingView → Pine Editor (bottom panel)-2. Click "Open" → "New blank indicator"-3. Delete all existing code-4. Paste the Pine Script above-5. Click "Add to Chart"-6. The strategy will appear on your chart with entry/exit markers-7. Open "Strategy Tester" tab to see backtest results-```+### 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-Trading | TradingView | 通达信/同花顺 | MT5 |+|-------------|-------------|---------------|-----|+| `000001.SZ` | `SZSE:000001` | `000001` | N/A |+| `600519.SH` | `SSE:600519` | `600519` | N/A |+| `AAPL.US` | `NASDAQ:AAPL` | N/A | `AAPL` |+| `BTC-USDT` | `BINANCE:BTCUSDT` | N/A | `BTCUSD` |++**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 Feature | Platform Limitation |+|---------------|-------------------|+| ML models (sklearn, etc.) | None — flag as "manual implementation required" |+| Custom pandas operations | TDX — limited to built-in functions |+| Multi-timeframe logic | TDX — no native MTF; Pine/MQL5 — supported |+| Dynamic position sizing | TDX — 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 the Pine Script:-- [ ] `//@version=6` is the first line-- [ ] `strategy()` declaration includes commission and initial_capital matching config.json-- [ ] All indicator calculations use Pine built-in `ta.*` functions (not manual reimplementation)-- [ ] Entry/exit conditions match the Python signal logic semantically-- [ ] No `plot()` inside local scopes (if/for/function)-- [ ] Ternary operators are on single lines-- [ ] Inputs use `input.int()` / `input.float()` so users can tune parameters in TradingView UI-- [ ] Alert conditions are included for key signals+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