TradingView策略自動交易 / 使用PINE語言進行量化交易的教學 / PineScript策略串接交易所自動下單

本文内容

    教你將 TradingView 策略串接到加密貨幣交易所進行自動交易開單

準備工作

    1. 你需要1個 TradingView Pro 以上的賬戶: https://www.tradingview.com/

    2. 你需要使用 TradingView 專業版賬戶:TVCBOT專業版交易機器人

    3. 你要有一個 TradingView 交易策略,可以是 TradingView 社區策略,也可以是你自己寫的策略,亦或是別人分享的開源/閉源策略

教學開始

    如果你現在已經擁有了1個交易策略,現在你要讓OKX/BINANCE/BYBIT/BITGET等交易所跟著這個策略自動買入和賣出,那麽下面的教程就是你想要的。

    在這個教程中,我們使用 TVCBOT 專業版的 智能對接 模式連接策略進行自動化交易。

載入你的 TradingView 策略

    您需要使用一個自己的交易策略,作爲演示,以下是一個案例代碼,我們在tradingview中選擇 OKX:BTCUSDT.P 交易對,切換爲4H周期,我們要將這個代碼添加到 tradingview 的pine編輯器中,保存后添加到圖表。(請注意,這份代碼僅供學習與參考,我們不對代碼任何時候的結果提供保證,你可以自行修改)

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

//@version=4
strategy("TVCBOT BTC Automated Strategy Example", overlay=true, initial_capital=5000,pyramiding = 0, currency="USD", default_qty_type=strategy.percent_of_equity, default_qty_value=100,  commission_type=strategy.commission.percent,commission_value=0.1)

Atr(p) =>
    atr = 0.
    Tr = max(high - low, max(abs(high - close[1]), abs(low - close[1])))
    atr := nz(atr[1] + (Tr - atr[1])/p,Tr)

//TEMA
TEMA(series, length) =>
    if (length > 0)
        ema1 = ema(series, length)
        ema2 = ema(ema1, length)
        ema3 = ema(ema2, length)
        (3 * ema1) - (3 * ema2) + ema3
    else
        na
tradeType = input("LONG", title="What trades should be taken : ", options=["LONG", "SHORT", "BOTH", "NONE"])

///////////////////////////////////////////////////
/// INDICATORS
source=close

/// TREND
trend_type1 = input("TEMA", title ="First Trend Line : ", options=["LSMA", "TEMA","EMA","SMA"])
trend_type2 = input("LSMA", title ="First Trend Line : ", options=["LSMA", "TEMA","EMA","SMA"])

trend_type1_length=input(25, "Length of the First Trend Line")
trend_type2_length=input(100, "Length of the Second Trend Line")

leadLine1 = if trend_type1=="LSMA"
    linreg(close, trend_type1_length, 0)
else if trend_type1=="TEMA"
    TEMA(close,trend_type1_length)
else if trend_type1 =="EMA"
    ema(close,trend_type1_length)
else
    sma(close,trend_type1_length)

leadLine2 = if trend_type2=="LSMA"
    linreg(close, trend_type2_length, 0)
else if trend_type2=="TEMA"
    TEMA(close,trend_type2_length)
else if trend_type2 =="EMA"
    ema(close,trend_type2_length)
else
    sma(close,trend_type2_length)

p3 = plot(leadLine1, color= #53b987, title="EMA", transp = 50, linewidth = 1)
p4 = plot(leadLine2, color= #eb4d5c, title="SMA", transp = 50, linewidth = 1)
fill(p3, p4, transp = 60, color = leadLine1 > leadLine2 ? #53b987 : #eb4d5c)

//Upward Trend
UT=crossover(leadLine1,leadLine2)
DT=crossunder(leadLine1,leadLine2)

// TP/ SL/  FOR LONG
// TAKE PROFIT AND STOP LOSS
long_tp1_inp = input(15, title='Long Take Profit 1 %', step=0.1)/100
long_tp1_qty = input(20, title="Long Take Profit 1 Qty", step=1)

long_tp2_inp = input(30, title='Long Take Profit 2%', step=0.1)/100
long_tp2_qty = input(20, title="Long Take Profit 2 Qty", step=1)

long_take_level_1 = strategy.position_avg_price * (1 + long_tp1_inp)
long_take_level_2 = strategy.position_avg_price * (1 + long_tp2_inp)

long_sl_input = input(5, title='stop loss in %', step=0.1)/100
long_sl_input_level = strategy.position_avg_price * (1 - long_sl_input)

// Stop Loss
multiplier = input(3.5, "SL Mutiplier", minval=1, step=0.1)
ATR_period=input(8,"ATR period", minval=1, step=1)

// Strategy
//LONG STRATEGY CONDITION

SC = input(close, "Source", input.source)
SL1 = multiplier * Atr(ATR_period)  // Stop Loss
Trail1 = 0.0
Trail1 :=  iff(SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0), min(nz(Trail1[1], 0), SC + SL1), iff(SC > nz(Trail1[1], 0), SC - SL1, SC + SL1))
Trail1_high=highest(Trail1,50)

// iff(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0), max(nz(Trail1[1], 0), SC - SL1),

entry_long=crossover(leadLine1,leadLine2) and Trail1_high < close
exit_long = close < Trail1_high or crossover(leadLine2,leadLine1) or close < long_sl_input_level

///// BACKTEST PERIOD ///////
testStartYear = input(2016, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)

testStopYear = input(9999, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(31, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)

testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false

if testPeriod()
    if tradeType=="LONG" or tradeType=="BOTH"
        if strategy.position_size == 0 or strategy.position_size > 0
            strategy.entry("long", strategy.long, when=entry_long)
            strategy.exit("TP1", "long", qty_percent=long_tp1_qty, limit=long_take_level_1)
            strategy.exit("TP2", "long", qty_percent=long_tp2_qty, limit=long_take_level_2)
            strategy.close("long", when=exit_long, comment="close" )


// LONG POSITION

plot(strategy.position_size > 0 ? long_take_level_1 : na, style=plot.style_linebr, color=color.green, linewidth=1, title="1st Long Take Profit")
plot(strategy.position_size > 0 ? long_take_level_2 : na, style=plot.style_linebr, color=color.green, linewidth=1, title="2nd Long Take Profit")
plot(strategy.position_size > 0 ? Trail1_high : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Stop Loss")

   添加到圖表后,我們會看到如下界面(請注意不同人添加這份代碼回測信息可能不一樣):

   接下來,我們點 List of Trades(交易列表),可看到如下界面:

    看到 Contracts 這一欄了嗎?這是我們要改的。我們點鬧鐘旁邊的設定,修改 Order Size 為你要下單的BTC數量,比如你每次要做多0.01個BTC,就輸入0.01,右邊選擇 Contract 表示用幣的數量下單,然後點OK即可。

 

連接 TVCBOT 開始進行自動交易

    在上面一個步驟中,我們已經完成了tradingview的交易設定,下一步我們連接 TVCBOT 開始自動交易。

    假設你已經在 TVCBOT 專業版上連接了你的 OKX/Binance/bybit 等賬戶(如果沒有請查看TVCBOT知識庫教程網頁)。

    接下來打開你的 TVCBOT 機器人界面,按照如下界面選擇,選擇你的交易賬戶后,交易對選擇 BTC-U本位永續!!請注意!我故意選錯了,是希望你記住不要選錯,因爲我們的 tradingview 圖表用的是 BTC,所以這裏要選擇 BTC-U本位永續,請不要選錯,然後選擇策略對接,智能對接。其他的都按照我的圖片設定,如果你不明白意思,TVCBOT網頁上都會告訴你。

tvcbot tradingview bot

    按照上述設定后,點擊生成 TradingView 下單警報,出現以下界面:

    在 TradingView 找到鬧鐘圖標,添加快訊警報,按下面的圖片添加警報即可。

    主要有兩步:

     一:粘貼 消息

     二:粘貼 Webhook URL

下面是點 notification(通知)后粘貼 webhook url

粘貼完成后,警報創建完成,就可以自動交易了。如果你要停止自動交易,請在tradingview右側的快訊列表停止這個警報

Was this answer helpful? 4 Users Found This Useful (4 Votes)