從零開始自製TradingView Strategy

four_dreams
10 min readSep 5, 2021

--

相信大家都知道在TradingView上能夠編寫自己的Indicator和Strategy,但可能因沒有太多Programming背景而卻步。所以此教學希望能讓大家了解到如何好好利用TradingView來寫屬於自己的Strategy。

教學開始前,先說明一下其實筆者我也沒有很多Programming背景,所以缺乏Programming能力絕對不是問題,不過話說回來,一般的數學、邏輯技巧也是需要的。

而今天這篇文章主要介紹如何編寫Strategy(策略)。

TradingView Language介紹

TradingView 上的 Programming Language 叫Pine Script,我們會使用到的Pine Script版本是v4。而有關Pine script的詳細介紹,可以參考以下鏈接:

Introduction — Pine Script User Manual 4 documentation (tradingview.com)

Pine Script 4 User Manual — Pine Script User Manual 4 documentation (tradingview.com)

背景設定

在開始教學之前,先要進行一些背景設定

  1. 在TradingView界面中,先點選下方的Pine Editor

2. 下方的Pine Editor界面就是我們的操作範圍

打開後你會發現有幾行句子,注意到第1,3行的句子是黑白的,並在句子前都有加上“//”,

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=4

這就代表這行code只是comment和標示之用,並不會實際上執行。

而請把以下第4,5行的句子刪除,我們不需要這兩句。

study(“My Script”)
plot(close)

正式開始

這次教學會參考到這個 Sample Script:

PB strategy by four_dreams — TradingView

建議大家先把上面Strategy的source code copy到自己的Pine Editor後再繼續看下去。

Trading View Strategy 並無任何的編程規定,但是為了教學需要,我先把一個Strategy分為四部分:

  1. 定義 (Define)
  2. 指標 (Indicators)
  3. 條件 (Condition)
  4. 交易 (Trading)

定義 (Define)

//Define
strategy(“PB strategy”, overlay=true, max_bars_back = 200, pyramiding = 0, initial_capital = 100000, commission_type = “percent”, commission_value = 0.016)

Code一開首先要為你的Strategy 定義,這時候你需要使用到 “strategy()” function,代表你接下來的程序都是一條策略(Strategy),而不是指標(Indicator)。

一個很有用的技巧是,當你在TrangView使用任何預設fuction時(Code上有顏色的都是預設fuction),可以Control+Mouse left click 按它一下,這時候TrandView會彈出一個關於那個function的教學幫助你。

試試看Control+Mouse left click按一下strategy()。

這時候你就可以參考TrandView提供的教學,裡面有對於strategy() function參數的詳細介紹。值得注意的是,很多function都提供很多parameters,但是你只需要輸入Required的就可以了,像是strategy(),只有Title是required的。

strategy(“PB strategy”, overlay=true, max_bars_back = 200, pyramiding = 0, initial_capital = 100000, commission_type = “percent”, commission_value = 0.016)

那回到我寫的這段strategy function,後面的函數是什麼意思呢?(其實Reference manual也有答案)
“PB strategy” 就是Title,至於overlay、max_bars_back、pyramiding、initial_capita、commission_type、 commission_value 都是與回測 Backtesting有關的參數,在此先不解釋了。

指標 (Indicators)

通常一個Strategy都是不同指標的混合,這個交易策略會使用到ema來判斷入場和atr來判斷開倉大小。

//Indicators
ema12=ema(close, 12)
sma17=sma(close, 17)
plot(ema12, color=color.green, title=”EMA(12)”)
plot(sma17, color=color.red, title=”SMA(17)”)
atr=atr(14)

TradingView的好處是它為你預設了很多指標的function,例如sma、ema、atr、supertrend等,只要把它call出來就可以了。例如ema(),control+left click就可以看到它的參數ema(source, period)。

這時候先把你的ema assign到一個variable上: ema12=ema(close, 12)
之後想使用到12週期ema的數值時,使用ema12這個variable就可以。
在這時你可以把你之後會用到的所有指標先call出來,方便整理。

而plot function則是把指標畫在圖上而已。

條件 (Condition)

//Condition
longCondition = crossover(ema12, sma17)
shortCondition = crossunder(ema12, sma17)

交易的邏輯離不開幾種,其中一個最常見的就是指標交叉,也就是這個strategy的邏輯:當12ema上穿過17ema時,開多;17ema上穿過12ema時,開空。

crossover()crossunder() function正正能方便的判斷交叉。

crossover(x, y) ->當x上穿y時,數值為True,其餘時間為False

crossover(x, y) ->當x下穿y時,數值為False,其餘時間為True

同樣地,把crossover() crossunder() function assign到一個variable中,之後就可以使用longCondition和shortCondition兩個vairable來交易。

交易 (Trading)

//Trading

usr_risk = input(title=”Equity Risk (%)”,type=input.integer,minval=1,maxval=100,step=1,defval=1,confirm=false)
atr_mult = input(title=”Stop Loss (x*ATR, Float)”,type=input.float,minval=0.1,maxval=100,step=0.1,defval=0.5,confirm=false)

if (longCondition)
risk = usr_risk * 0.01 * strategy.equity
stopLoss = low[1] — atr[1] * atr_mult
entryPrice = high[1]
units = risk / (entryPrice — stopLoss)
strategy.order(“long”, strategy.long, units)
strategy.exit(“exit”,”long”, stop =sma17-atr)

if (shortCondition)
risk = usr_risk * 0.01 * strategy.equity
stopLoss = high[1] + atr[1] * atr_mult
entryPrice = low[1]
units = risk / (stopLoss — entryPrice)
strategy.entry(“short”, strategy.short, units)
strategy.exit(“exit”,”short”, stop=sma17+atr)

usr_risk和atr_mult是我用來計算倉位大小的,可以先不理。

因為我們只想在12ema上穿過17ema時做多(longCondition為True);和在17ema上穿過12ema時做空(shortCondition為True)。這時候,就需要到if() function。一個if() function是這樣設置的:

y=0
if (condition)
x=1
y=x+10

當括號裡的condition為True時,就會執行if function裡面的指令,而當你想把指令放到if function裡面是,要先按tab一下。

好,那設置好了開單條件後,如何真正開單呢?

這時候需要下面兩個function:

strategy.order() ->開單
strategy.exit() ->平倉

在strategy.order()中,有幾個required parameters:

strategy.order(“id”, strategy.long ,units)

id=為此單的識別id,平倉時需要
strategy.long=此單的方向,strategy.long是開多;strategy.short是開空
units=此單的大小

strategy.exit(“idforthisorder”, “id”, stop=sma17-atr)

idforthisorder=為此單的識別id
id=你要平倉的單
stop=止蝕位(當觸及止蝕時就會平倉)

那其實開多與開空是一樣的,只需要變動strategy.order中的strategy.long就可以。不過記得不同方向的單要使用不同的id。

大功告成!

這時候按save,在按Add to Chart就可以在主圖上看到自己的strategy啦。其實Tradingview上還有很多的可能性,例如訂立跟踪止損、限價單、截取其他圖表數據等等,還有待大家發掘。

--

--