第4課 macd策略2.0
## macd策略2.0代碼和學習資料
>相關的視頻學習資料在大陸版抖音,tiktok,blibli,油管,上搜索'量化金城武'即可找到
- **macd策略2.0的代碼和注釋**
```
strategy("MACD2.0")
//macd指標2.0:將用上節課學到的input()函數把寫死的變量,改成可輸入參數(在設置裡可以修改)
//第一步整理哪些是我們的可輸入參數
//1:基礎ema的長度(默認是ema12,ema26)
fastlength = input.int(defval = 12,title = '快線長度')
slowlength = input.int(defval = 26,title = '慢線長度')
//2:係列值來源(默認是close)
src = input(close,title = '基礎ema的計算來源')
//3:計算macd2的長度
macdlength = input.int(defval = 9,title = '計算macd2的長度')
//4:止盈止損設置
zhiying = input.float(defval = 0.02,title = '止盈')
zhisun = input.float(defval = 0.01,title = '止損')
//第一步計算出收盤價的ema12
fast = ta.ema(src,fastlength)
//第二步計算出收盤價ema26
slow = ta.ema(src,slowlength)
//第三步計算出macd值(ema12-ema26)
macd1 = fast - slow
//第四步計算出macd的指數平均值
macd2 = ta.ema(macd1,macdlength)
//第五步畫出來
plot(macd1)
plot(macd2,color = color.orange)
//第六步设定入场条件
shangchuan = ta.crossover(macd1,macd2) //黄金交叉
xiachuan = ta.crossover(macd2,macd1) //死亡交叉
//第七步设定出场条件
zy = strategy.position_avg_price * (1+zhiying) //止盈2%
zs = strategy.position_avg_price * (1-zhisun) //止损1%
//第八步逻辑执行
if shangchuan
strategy.entry('long',strategy.long,comment = '做多')
strategy.exit('exit','long',limit = zy ,stop = zs,comment_profit = '盈',comment_loss = '损')//这里添加了止盈和止损的备注,如果订单止盈了就在图标里的备注是'盈',止损了就是'损'
```
###做空的作業提示
做空不會的,可以去看上一片第二課的文章,裡面有寫做空的代碼,只需要將我們這節課學到input()函數加進去,修改一下就可以啦~
但是!!在那篇文章中,我們的變量的名字跟這篇的又不一樣,要注意!
需要註意的是止盈止損做空的話,是不一樣的噢,做空要止盈的話是要比買入價格低的哦!
大家先試著自己寫一下,下面是加上做空的補全代碼,實在不行了,再用下面的代碼吧~(一定要試著自己先動手補全!!)
```
strategy("MACD2.0")
//macd指標2.0:將用上節課學到的input()函數把寫死的變量,改成可輸入參數(在設置裡可以修改)
//第一步整理哪些是我們的可輸入參數
//1:基礎ema的長度(默認是ema12,ema26)
fastlength = input.int(defval = 12,title = '快線長度')
slowlength = input.int(defval = 26,title = '慢線長度')
//2:係列值來源(默認是close)
src = input(close,title = '基礎ema的計算來源')
//3:計算macd2的長度
macdlength = input.int(defval = 9,title = '計算macd2的長度')
//4:止盈止損設置
zhiying = input.float(defval = 0.02,title = '止盈')
zhisun = input.float(defval = 0.01,title = '止損')
//第一步計算出收盤價的ema12
fast = ta.ema(src,fastlength)
//第二步計算出收盤價ema26
slow = ta.ema(src,slowlength)
//第三步計算出macd值(ema12-ema26)
macd1 = fast - slow
//第四步計算出macd的指數平均值
macd2 = ta.ema(macd1,macdlength)
//第五步畫出來
plot(macd1)
plot(macd2,color = color.orange)
//第六步设定入场条件
shangchuan = ta.crossover(macd1,macd2) //黄金交叉
xiachuan = ta.crossover(macd2,macd1) //死亡交叉
//第七步设定出场条件,算出買漲時候的止盈止損的價格
zy = strategy.position_avg_price * (1+zhiying) //止盈zhiying%
zs = strategy.position_avg_price * (1-zhisun) //止损zhisun%
//當做空的時候,止盈止損的價格是不一樣的
zy2 = strategy.position_avg_price * (1-zhiying) //止盈zhiying%
zs2 = strategy.position_avg_price * (1+zhisun) //止损zhisun%
//第八步逻辑执行
if shangchuan
strategy.entry('long',strategy.long,comment = '做多')
strategy.exit('exit','long',limit = zy ,stop = zs,comment_profit = '盈',comment_loss = '损')
if xiachuan
strategy.entry('short',strategy.short,comment = '做空')
strategy.exit('exit','short',limit = zy2,stop = zs2,comment_profit = '盈',comment_loss = '损')
```
1 条评论