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

進場與出場:strategy.entry、strategy.exit

下單的基本元素:如何開倉、設停損、停利,以及在訊號上反手。

中級閱讀時間約 10 分鐘初學 → 進階第 11 / 17 堂
在 TradingView 實際跑一次
括號單:2% 停損、4% 目標

strategy.exit 在一個呼叫裡把停損與目標一起掛到那個進場 id 上。停損是從 strategy.position_avg_price——實際成交價——算的。

//@version=5
strategy("Lesson 11 - Entries and exits", 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)

// Open on the cross.
strategy.entry("Long", strategy.long, when=ta.crossover(fast, slow))

// Bracket: stop 2% below fill, target 4% above fill.
strategy.exit("Long TP/SL", "Long",
     stop  = strategy.position_avg_price * 0.98,
     limit = strategy.position_avg_price * 1.04)

// Also flatten if the EMAs cross back down.
strategy.close("Long", when=ta.crossunder(fast, slow))
如何執行
  1. 1. 在 TradingView 打開任一圖表,點選下方的 Pine Editor
  2. 2. 把編輯器裡的內容全選,用這段程式覆蓋過去,然後按 Save
  3. 3. 點選 Add to chart。如果是策略, 再打開 Strategy Tester 分頁。

strategy.entry:開倉或反手

strategy.entry("Long", strategy.long) 用策略的預設大小開一個多單。如果你已經在做空,它會反手。字串 "Long" 是進場 id——每個方向必須唯一,出場才能對準它。

strategy.close:全部出場

strategy.close("Long") 關閉任何以 id「Long」進場的未平倉部位。strategy.close_all 則不管 id 關掉一切。

strategy.exit:停損與目標一起

strategy.exit 是做括號式停損與目標的主力:

strategy.entry("Long", strategy.long, when=ta.crossover(fast, slow))
strategy.exit("Long TP/SL", "Long", profit=200, loss=100)

profitloss 預設以 tick 為單位——見 profit_typeloss_type 可以切換成 point、百分比、金額或 ATR 倍數。

百分比停損

strategy.exit("X", "Long", stop=close * 0.98, limit=close * 1.04) 設定 2% 停損與 4% 目標。這裡的 close 是進場那根 K 線的收盤價——Pine 會在下出場單時把那個值快照下來。

ATR 停損

atrVal = ta.atr(14)
strategy.exit("X", "Long", stop=close - 2 * atrVal, limit=close + 4 * atrVal)

這讓停損隨近期波動調整。許多零售 CFD 交易者用 1.5x–3x ATR 當停損。

移動停損

strategy.exit 支援 trail_pointstrail_offset,以及一個 trail_price 觸發價。移動停損只朝對你有利的方向移動並鎖住獲利。當你想要騎一段趨勢、只在動能消退時出場,它是正確的工具。

冪等性

你可以在每一根 K 線呼叫 strategy.entry——Pine 知道如果部位已經在目標狀態就要跳過那個呼叫。strategy.exit 也一樣——連續設兩次相同的出場沒有問題。

反手

要在相反訊號上把多單翻成空單,只要呼叫 strategy.entry("Short", strategy.short)。Pine 會先關掉多單、再開空單,在一個合成操作裡完成。Pine 裡沒有「先關再進」的兩步驟。

你剛完成了什麼

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