第1課-第2課macd指標/策略1.0 代碼
## macd1.0代碼和學習資料
>相關的視頻學習資料在大陸版抖音,tiktok,blibli,油管,上搜索'量化金城武'即可找到
- **macd指標1.0的代碼和注釋**
```
indicator("MACD1.0指標")
//第一步計算出收盤價的ema12
fast = ta.ema(close,12)
//第二步計算出收盤價ema26
slow = ta.ema(close,26)
//第三步計算出macd值(ema12-ema26)
macd = fast - slow
//第四步計算出macd的指數平均值
emamacd = ta.ema(macd,9)
//第五步畫出來
plot(macd)
plot(emamacd,color = color.rgb(239, 198, 33))
```
- **macd策略1.0的代碼和注釋**
```
strategy("MACD1.0指標")
//第一步計算出收盤價的ema12
fast = ta.ema(close,12)
//第二步計算出收盤價ema26
slow = ta.ema(close,26)
//第三步計算出macd值(ema12-ema26)
macd = fast - slow
//第四步計算出macd的指數平均值
emamacd = ta.ema(macd,9)
//第五步畫出來
plot(macd)
plot(emamacd,color = color.orange)
//第六步设定入场条件
shangchuan = ta.crossover(macd,emamacd) //黄金交叉
xiachuan = ta.crossover(emamacd,macd) //死亡交叉
//第七步设定出场条件
zhiying = strategy.position_avg_price * 1.02 //止盈2%(這的'strategy.position_avg_price'指的是當時的平均入場價)
zhisun = strategy.position_avg_price * 0.99 //止损1%
//第八步逻辑执行
if shangchuan
strategy.entry('long',strategy.long,comment = '做多')
strategy.exit('exit','long',limit = zhiying,stop = zhisun)
```
##作業
###上面的策略只做出了開漲的方向,讓大家做出做空的方向
以下是補充完做空的macd1.策略的代碼
```
strategy("MACD1.0指標")
//第一步計算出收盤價的ema12
fast = ta.ema(close,12)
//第二步計算出收盤價ema26
slow = ta.ema(close,26)
//第三步計算出macd值(ema12-ema26)
macd = fast - slow
//第四步計算出macd的指數平均值
emamacd = ta.ema(macd,9)
//第五步畫出來
plot(macd)
plot(emamacd,color = color.orange)
//第六步设定入场条件
shangchuan = ta.crossover(macd,emamacd) //黄金交叉
xiachuan = ta.crossover(emamacd,macd) //死亡交叉
//第七步设定出场条件
//開漲的止盈
zhiying = strategy.position_avg_price * 1.02 //止盈2%
zhisun = strategy.position_avg_price * 0.99 //止损1%
//做空的止盈止損(我們用的是當時入場的均價乘百分比(%),所以做空的止盈止損和做漲的止盈止損是不一樣的)
zy = strategy.position_avg_price * 0.98 //止盈2%
zs = strategy.position_avg_price * 1.01 //止損1%
//第八步逻辑执行
if shangchuan
strategy.entry('long',strategy.long,comment = '做多')
strategy.exit('exit','long',limit = zhiying,stop = zhisun)
if xiachuan
strategy.entry('short',strategy.short,comment = '做多')
strategy.exit('exit','short',limit = zy,stop = zs)
```
还没有人发表评论