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

條件邏輯:用 if/else 做交易訊號

if/else 區塊、switch 運算式,以及如何用它們把交易規則寫進去而不變成義大利麵。

中級閱讀時間約 7 分鐘初學 → 進階第 06 / 17 堂
在 TradingView 實際跑一次
帶持久狀態的環境分類

var bool inLong 會跨 K 線保留它的值——那就是「逐根判斷」與「真正的部位狀態」的差別。看那些進出場三角形。

//@version=5
indicator("Lesson 6 - Conditional logic", overlay=true)

ema50 = ta.ema(close, 50)

// Classify the regime on every bar (chained ternary).
regime = close > ema50 ? "uptrend"
       : close < ema50 ? "downtrend"
       : "range"

plot(ema50, "EMA 50", color=color.orange, linewidth=2)
plot(close, "Close",
     color = regime == "uptrend"   ? color.green
           : regime == "downtrend" ? color.red
           : color.gray)

// Persistent state — survives across bars, unlike a plain if.
var bool inLong = false
if not inLong and close > ema50
    inLong := true
else if inLong and close < ema50
    inLong := false

bgcolor(inLong ? color.new(color.green, 92) : color.new(color.red, 92))

plotshape(inLong and not inLong[1], "Enter long", shape.triangleup,
          location.belowbar, color=color.green)
plotshape(not inLong and inLong[1], "Exit long", shape.triangledown,
          location.abovebar, color=color.red)
如何執行
  1. 1. 在 TradingView 打開任一圖表,點選下方的 Pine Editor
  2. 2. 把編輯器裡的內容全選,用這段程式覆蓋過去,然後按 Save
  3. 3. 點選 Add to chart。如果是策略, 再打開 Strategy Tester 分頁。

if/else 區塊

Pine 的 if 陳述作用在序列上——分支是逐根 K 線判斷的。一個常見模式:

signal = close > ta.ema(close, 50) ? 1 : -1

當收盤價在 50-EMA 之上時指派 1,否則 -1。三元是雙向決策最乾淨的形式。

多分支 if/else

三個以上的分支時,if/else if/else 比較好讀:

regime = close > ta.ema(close, 200) ? "uptrend"
     : close < ta.ema(close, 200) ? "downtrend"
     : "range"

switch 運算式

Pine v5 有一個 switch 運算式,當分支由單一變數驅動時更乾淨。第一部分那個均線範例就用它:

ma = switch maType
    "SMA" => ta.sma(src, length)
    "EMA" => ta.ema(src, length)
    "WMA" => ta.wma(src, length)

狀態很重要

單純的 if 只在條件成立的那根 K 線改變一個變數。如果你需要一個跨 K 線保留的狀態(像是「我目前在做多」),用 var

var bool inLong = false
if not inLong and close > ta.ema(close, 50)
    inLong := true
else if inLong and close < ta.ema(close, 50)
    inLong := false

常見錯誤:少了 else

在一個沒有 elseif 裡面,一個變數指派只在條件成立的那根 K 線生效。在其他 K 線上,那個變數會保留它先前的值——有時那正是你要的,有時那是一個 bug。寫明確一點。

該記住什麼

序列感知的 if 加上用 var 存持久狀態,是每一個策略的脊椎。在進入函式之前先掌握它。

你剛完成了什麼

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