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

警示與自動化:從訊號到通知

Pine 的警示在條件上觸發。把它們導向 email、webhook 或你券商的自動化 API,才是把迴路接起來的那一步。

進階閱讀時間約 10 分鐘初學 → 進階第 16 / 17 堂
在 TradingView 實際跑一次
簡單警示,加上結構化 JSON 內容

alertcondition 給你一個 UI 裡的手動警示。那個 alert() 呼叫會送出你可以導到 webhook 的 JSON——在圖表上按右鍵 → Add Alert 來接線。

//@version=5
indicator("Lesson 16 - Alerts", overlay=true)

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)

longSignal = ta.crossover(fast, slow)

// Simple alert — pick "Golden cross" from the alert dialog's condition list.
alertcondition(longSignal, title="Golden cross",
     message="EMA cross long on {{ticker}} at {{close}}")

// Structured JSON — route this to a webhook to automate execution.
if longSignal
    alert('{"action":"buy","ticker":"' + syminfo.ticker +
          '","price":"'  + str.tostring(close) +
          '","stop":"'   + str.tostring(close * 0.98) +
          '","target":"' + str.tostring(close * 1.04) + '"}',
          alert.freq_once_per_bar_close)

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

一個警示到底是什麼

一個 Pine 警示是一個掛在腳本上的條件。當那個條件在最新一根 K 線上成立時,TradingView 會送出一個通知——email、簡訊、推播或 webhook。對一個策略來說,內建的警示類型是「Order fills only」與「Order fills and ...」,它們在每一次模擬下單時觸發。

自訂警示模式

longSignal = ta.crossover(fast, slow)
alertcondition(longSignal, title="Long signal", message="SMA cross long on {{ticker}} at {{close}}")

alertcondition 吃一個條件(序列 bool)、一個標題,以及一個訊息模板。{{ticker}}{{close}} 這類佔位符會在觸發時被代入。

策略警示

對策略來說,用內建的警示類型「Order fills only」——Pine 會為每一次成交送出一包描述該次成交的 JSON。多數自動化平台(3Commas、Pineconnector、自訂券商)都吃這個 JSON。

webhook 目的地

TradingView 付費方案讓你把警示導到一個 webhook URL。你把警示內容 POST 到你自己的伺服器,由它轉譯成券商 API 呼叫。這就是一個 Pine 策略如何透過一家沒有原生 TradingView 整合的券商下出實單。

JSON 訊息模板

strategy.entry("Long", strategy.long, when=longSignal)
strategy.exit("X", "Long", stop=close - stopDist, limit=close + stopDist * 2)
if strategy.position_size > 0 and strategy.position_size[1] == 0
    alert('{"action":"buy","ticker":"' + syminfo.ticker + '","qty":' + str.tostring(contracts) + ',"sl":' + str.tostring(close - stopDist) + ',"tp":' + str.tostring(close + stopDist * 2) + '}', alert.freq_once_per_bar_close)

alert() 函式讓你在特定的 K 線事件上送出一個自訂 JSON 訊息。用 alert.freq_once_per_bar_close 來做到「只在 K 線收盤且條件仍然成立時觸發」——這可以避免 K 線內的洗盤。

從訊號到成交

Pine 不會下實單。這條鏈是:Pine 觸發警示 → webhook → 你的伺服器 → 券商 API → 實單成交。每一跳都是一個可能壞掉的地方,所以先在紙上測試。

該從這裡帶走什麼

策略是簡單的部分。困難的是接線。先用紙上交易跑那些警示訊息、驗證整條鏈,然後用你券商允許的最小規模上線。

你剛完成了什麼

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