返回《給 CFD 交易者的 TradingView PineScript》
第三部分

從 study 到 strategy:宣告一個策略

一個策略就只是一個也能下單的指標。宣告方式,以及你需要知道的限制。

中級閱讀時間約 8 分鐘初學 → 進階第 10 / 17 堂
在 TradingView 實際跑一次
換一個字,指標就變策略

跟之前一樣的圖,但現在打開 Strategy Tester 分頁——你有交易了。改 default_qty_value,看權益曲線變化。

//@version=5
strategy("Lesson 10 - My first strategy", overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=10)

fast = ta.ema(close, 9)
slow = ta.ema(close, 21)

plot(fast, "Fast EMA", color=color.blue, linewidth=2)
plot(slow, "Slow EMA", color=color.orange, linewidth=2)

// Entry on the cross. strategy.entry reverses if already in the other direction.
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.entry("Short", strategy.short)
如何執行
  1. 1. 在 TradingView 打開任一圖表,點選下方的 Pine Editor
  2. 2. 把編輯器裡的內容全選,用這段程式覆蓋過去,然後按 Save
  3. 3. 點選 Add to chart。如果是策略, 再打開 Strategy Tester 分頁。

為什麼策略不同於指標

一個指標是一個被動的計算——它在圖上畫線與形狀。一個策略是一個額外能模擬訂單的指標。TradingView 裡的策略測試器分頁就是結果:它拿你的邏輯去跑歷史 K 線,並回報獲利、回撤,以及逐筆交易明細。

宣告一個策略

//@version=5
strategy("My first strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

default_qty_typedefault_qty_value 控制的是:如果你在下單時沒有指定數量,每一次進場會怎麼決定自己的大小。

指標 → 策略的遷移

拿第一部分那個 SMA 交叉指標。唯一的改變是第一行——indicator 變成 strategy

//@version=5
strategy("SMA cross", overlay=true)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
plot(fast, color=color.blue)
plot(slow, color=color.orange)

這仍然會畫出那兩條線,但現在你可以加入 strategy.entry 呼叫,而策略測試器就會開始計算交易。

策略的限制

一個策略不能呼叫只有 indicator() 能用的函式,也不能使用某些僅限 study 的輸入。多數指標程式碼可以只做最小修改就貼進一個策略裡。

回測分頁

點圖表底部的 Strategy Tester。你會看到 Overview(淨利、回撤、勝率)、Performance Summary,以及 List of Trades。這三個視圖就是你評估策略的方式。

接下來是什麼

接下來幾堂課會涵蓋實際的進出場呼叫,然後是如何解讀測試器回報的那些數字。

你剛完成了什麼

給 CFD 交易者的 TradingView PineScript》的第 10 / 17 堂課。跑完範例或讀完這段之後, 把它勾起來,然後進下一堂課。