交易策略程式碼教學 - 順勢指標
演算法交易策略並不像大家想像中那麼困難, 文章中會以四個步驟來教大家如何使用演算法交易策略來寫程式碼。 所有的程式碼交 使用TradingView平台中的pine script頁面來操作喔!
Introduction of CCI indicator
Developed by Donald Lambert, the Commodity Channel Index (CCI) is a momentum-based oscillator used to help determine when an investment vehicle is reaching a condition of being overbought or oversold. It is also used to assess price trend direction and strength. This information allows traders to determine if they want to enter or exit a trade, refrain from taking a trade, or add to an existing position.
下方是完整的程式碼
//@version=4
strategy("Yaonology CCI Tutoring", overlay=false, default_qty_type= strategy.percent_of_equity ,default_qty_value=100, currency=currency.USD, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0)
period = input(title = "period",defval=20)
tp = (high+low+close)/3
avg_tp = sma(tp,period)
mean_dev = sma(abs(tp-avg_tp),period)
CCI = (tp-avg_tp)/(0.015*mean_dev)
plot(CCI, color = color.blue)
plot(100,color = color.red)
plot(-100,color = color.green)
if CCI < -100 and CCI[1] > -100
strategy.entry(id = "long",long = true)
if CCI > 100 and CCI[1] < 100
strategy.close(id = "long")
步驟一: 初始設定
//@version=4
strategy(“Yaonology CCI Tutoring“, overlay=false, default_qty_type= strategy.percent_of_equity ,default_qty_value=100,currency=currency.USD,initial_capital=10000,commission_type=strategy.commission.percent,commission_value=0)
strategy : 策略名稱 (Yaonology設為 Yaonology CCI Tutoring)
overlay : 不重疊 – False
default_qty_type : 此為設定交易量的單位形式 (此我們設定percent of equity)
default_qty_value : 設定量的多寡 –100
currency: 幣值 (此設為USD)
initial_capital : 最初交易的價格 (設定10000)
commission_type : 佣金的計算方式 –percent
commission_value : 佣金的價值 (此沒有佣金,因此設定0)
步驟二:參數設定
第一部分:
period = input(title = “period“,defval=20)
預設長度是連續20個交易日。
可以在設置->輸入中修改參數
第2部分:策略指數移動平均線
tp = (high+low+close)/3
tp是一天的典型價格,這是一天中三個關鍵價格的平均值:
high:當日最高價
low:當日最低價
close: 當日收盤價
avg_tp = sma(tp,period)
計算上述指定期間內典型價格的移動平均值(基礎預設為20)
mean_dev = sma(abs(tp-avg_tp),period)
計算平均價格與上述平均平均價格之間的偏差的平均值(avg_tp)
CCI = (tp-avg_tp)/(0.015*mean_dev)
計算每天的CCI指標,其中0.015是廣泛認可的標準化係數
步驟三:繪圖
plot(CCI, color = color.blue)
-這條線被設置為藍色
plot(100,color = color.red)
–這條線標記進入多頭的值設為紅色
plot(-100,color = color.green)
–這條線標記了退出當前位置的值設為綠色
步驟五 :買賣條件
最後,我們需要根據繪製的順勢指標指數來決定何時買入或賣出:
if CCI < -100 and CCI[1] > -100
strategy.entry(id = “long“,long = true)
= >[1] 表示前一天;
如果適用此條件,此時可以買入股票
Strategy.entry: 表示指令進入市場
id: 表示此單的名稱設定 在此我們將名稱設定為 long
long: 表示看多市場趨勢,此時為進場狀態,因此設定為true
if CCI > 100 and CCI[1] < 100
strategy.close(id = “long“)
=:>[1] 表示前一天
如果適用此條件,此時可以賣出股票
Strategy.close:表示指令離開市場
而id 為和進場同一張單的指令,因此名字需設為同一個。
完成後圖形

Net Profit(淨利潤):將策略應用於歷史市場的總淨利潤
Total Closed Trades(已完成交易總數):失敗交易總數
Percent profitable(獲利百分比):獲利為正的交易百分比
Profit factor(賺賠比): 總獲利 / 總損失
Max Drawdown(最大虧損):將策略應用於歷史市場的總損失(以標普500為例)
Average Number of Days In Trades(平均交易天數):通過將策略應用於歷史市場而進入和退出之間的平均天數
#Algorithmtradingstrategy #codingtutorial #SPY500 #CCIindicator