Pine講座62 タートルズ流投資の魔術|ATRチャネル・ブレイクアウト「タートルズ流投資の魔術
カーティス・フェイス著」
で紹介されている手法の再現。
4つ目です。
この本に掲載されている手法は、
日足における長期の手法が多く
Botが流行っている昨今では
少し古めかしいものが多いです。
一方で、
「すべての手法において
現在でもトータル・プラス収益である」
この事実は
"とんでもないこと" だと思います。
(超長期のトレンドフォロー
なので分散投資が必須です)
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=3
strategy("Strategy Turtle ATR Chanel Break Out"
,default_qty_type=strategy.fixed
,default_qty_value=1
,pyramiding=4
,overlay=true)
src = close
len = input(350 ,minval=1 ,title="ma length")
atr_len = input(20 ,minval=1 ,title="band atr length")
up_n = input(7 ,minval=1 ,title="atr upper length")
low_n = input(3 ,minval=1 ,title="atr lower length")
SO_bool = input(false,type=bool ,title="loss cut")
SO_len = input(20 ,type=integer ,minval=1 ,title="loss cut ATR length")
SO_N = input(2 ,type=float ,minval=0.5 ,title="loss cut ATR*N")
MAX_N = input(1 ,type=integer ,minval=1 ,maxval=4 ,title="maximun num of unit")
LO_len = input(20 ,type=integer ,minval=1 ,title="pyramiding ATR length")
LO_N = input(10 ,type=float ,minval=0.5 ,title="pyramiding ATR*N")
Tm_bool = input(false,type=bool ,title="timed exit")
Tm_len = input(80 ,type=integer ,minval=1 ,title="timed exit length")
fromYear = input(2005 ,type=integer ,minval=1900 ,title="test start")
endYear = input(2017 ,type=integer ,minval=1900 ,title="test end")
isWork = timestamp(fromYear ,1 ,1 ,00 ,00) <= time and time < timestamp(endYear+1 ,1 ,1 ,00 ,00)
EMA = ema(close ,len)
ATR = ema(tr ,atr_len)
UPPER = EMA + ATR * up_n
LOWER = EMA - ATR * low_n
atr_SO_ = ema(tr ,SO_len)
atr_LO_ = ema(tr ,LO_len)
atr_SO = atr_SO_*SO_N
atr_LO = atr_LO_*LO_N
countTradingDays = na
countNonTradingDays = na
countTradingDays := strategy.position_size==0 ? 0 : countTradingDays[1] + 1
countNonTradingDays := strategy.position_size!=0 ? 0 : countNonTradingDays[1] + 1
entry1 = close
entry2 = close
entry3 = close
entry4 = close
entry1 := strategy.position_size==0 ? na : entry1[1]
entry2 := strategy.position_size==0 ? na : entry2[1]
entry3 := strategy.position_size==0 ? na : entry3[1]
entry4 := strategy.position_size==0 ? na : entry4[1]
lo2 = close
lo3 = close
lo4 = close
lo2 := strategy.position_size==0 ? na : lo2[1]
lo3 := strategy.position_size==0 ? na : lo3[1]
lo4 := strategy.position_size==0 ? na : lo4[1]
losscut = close
losscut := strategy.position_size==0 or SO_bool==false ? na : losscut[1]
L_EntrySig = close >= UPPER and isWork
S_EntrySig = close <= LOWER and isWork
if(strategy.position_size != 0)
L_ExitSig = (close <= EMA or S_EntrySig) and strategy.position_size > 0
S_ExitSig = (close >= EMA or L_EntrySig) and strategy.position_size < 0
TimedSig = countTradingDays > Tm_len and Tm_bool
strategy.close_all(when = L_ExitSig or S_ExitSig or TimedSig or not isWork)
if(L_ExitSig or S_ExitSig)
entry1 := na
entry2 := na
entry3 := na
entry4 := na
lo2 := na
lo3 := na
lo4 := na
losscut := na
if(strategy.position_size > 0)
lo_sig2 = lo2 < high
lo_sig3 = lo3 < high
lo_sig4 = lo4 < high
if(lo_sig2 and MAX_N >= 2)
if(SO_bool)
strategy.entry("L-Entry2" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry2")
strategy.exit("L-Entry1" ,stop=close-atr_SO)
else
strategy.entry("L-Entry2" ,strategy.long ,comment="L-Entry2")
lo2 := na
losscut := SO_bool ? close - atr_SO : na
if(lo_sig3 and MAX_N >= 3)
if(SO_bool)
strategy.entry("L-Entry3" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry3")
strategy.exit("L-Entry2" ,stop=close-atr_SO)
strategy.exit("L-Entry1" ,stop=close-atr_SO)
else
strategy.entry("L-Entry3" ,strategy.long ,comment="L-Entry3")
lo3 := na
losscut := SO_bool ? close - atr_SO : na
if(lo_sig4 and MAX_N >= 4)
if(SO_bool)
strategy.entry("L-Entry4" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry4")
strategy.exit("L-Entry3" ,stop=close-atr_SO)
strategy.exit("L-Entry2" ,stop=close-atr_SO)
strategy.exit("L-Entry1" ,stop=close-atr_SO)
else
strategy.entry("L-Entry4" ,strategy.long ,comment="L-Entry4")
lo4 := na
losscut := SO_bool ? close - atr_SO : na
if(strategy.position_size < 0)
lo_sig2 = lo2 > low
lo_sig3 = lo3 > low
lo_sig4 = lo4 > low
if(lo_sig2 and MAX_N >= 2)
if(SO_bool)
strategy.entry("S-Entry2" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry2")
strategy.exit("S-Entry1" ,stop=close+atr_SO)
else
strategy.entry("S-Entry2" ,strategy.short ,comment="S-Entry2")
lo2 := na
losscut := SO_bool ? close + atr_SO : na
if(lo_sig3 and MAX_N >= 3)
if(SO_bool)
strategy.entry("S-Entry3" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry3")
strategy.exit("S-Entry2" ,stop=close+atr_SO)
strategy.exit("S-Entry1" ,stop=close+atr_SO)
else
strategy.entry("S-Entry3" ,strategy.short ,comment="S-Entry3")
lo3 := na
losscut := SO_bool ? close + atr_SO : na
if(lo_sig4 and MAX_N >= 4)
if(SO_bool)
strategy.entry("S-Entry4" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry4")
strategy.exit("S-Entry3" ,stop=close+atr_SO)
strategy.exit("S-Entry2" ,stop=close+atr_SO)
strategy.exit("S-Entry1" ,stop=close+atr_SO)
else
strategy.entry("S-Entry4" ,strategy.short ,comment="S-Entry4")
lo4 := na
losscut := SO_bool ? close + atr_SO : na
if((L_EntrySig or S_EntrySig) and strategy.position_size==0)
countTradingDays := 0
entry1 := close
if(L_EntrySig)
if(SO_bool)
strategy.entry("L-Entry1" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry1")
else
strategy.entry("L-Entry1" ,strategy.long ,comment="L-Entry1")
lo2 := MAX_N >= 2 ? close + atr_LO : na
lo3 := MAX_N >= 3 ? close + atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close + atr_LO * 3 : na
losscut := SO_bool ? close - atr_SO : na
if(S_EntrySig)
if(SO_bool)
strategy.entry("S-Entry1" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry1")
else
strategy.entry("S-Entry1" ,strategy.short ,comment="S-Entry1")
lo2 := MAX_N >= 2 ? close - atr_LO : na
lo3 := MAX_N >= 3 ? close - atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close - atr_LO * 3 : na
losscut := SO_bool ? close + atr_SO : na
// plot(strategy.position_size ,transp=0 ,title="保有ポジションの数")
// plot(strategy.openprofit ,transp=0 ,title="未決済の損益")
// plot(strategy.netprofit ,transp=0 ,title="決済済みの損益")
// plot(strategy.closedtrades ,transp=0 ,title="決済済み取引数")
// plot(countTradingDays ,transp=0 ,title="取引日数")
// plot(countNonTradingDays ,transp=0 ,title="ノンポジ日数")
plot(entry1 ,title="entry1" ,color=blue ,transp=0 ,style=linebr)
plot(lo2 ,title="lo2" ,color=red ,transp=0 ,style=linebr)
plot(lo3 ,title="lo3" ,color=red ,transp=0 ,style=linebr)
plot(lo4 ,title="lo4" ,color=red ,transp=0 ,style=linebr)
plot(losscut ,title="losscut" ,color=red ,transp=0 ,style=linebr)
plot(atr_SO ,transp=0 ,title="ATR_SO")
plot(atr_LO ,transp=0 ,title="ATR_LO")
// plot(strategy.max_drawdown ,transp=50 ,title="最大DD")
// plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
p1 = plot(UPPER ,color=#303F9F ,title="UPPER" ,style=line ,linewidth=2, transp=0)
p2 = plot(LOWER ,color=#4CAF50 ,title="LOWER" ,style=line ,linewidth=2, transp=0)
plot(EMA ,color=red ,title="EMA" ,style=line ,linewidth=2 ,transp=0)
fill(p1 ,p2 ,color=#2196F3 ,title="fill" ,transp=60)
=====
Pinescript
Pine講座61 タートズル流投資の魔術|ボリンジャー・ブレイクアウト「タートルズ流投資の魔術
カーティス・フェイス著」
で紹介されている手法の再現。
3つ目です。
超長期においては、
シンプルなボリンジャーもワークします。
非常に面白い特性ですよね。
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=3
strategy("Strategy Turtle Bollinger Break Out"
,default_qty_type=strategy.fixed
,default_qty_value=1
,pyramiding=4
,overlay=true)
len = input(350 ,minval=1 ,title="ma length")
up_n = input(2 ,minval=1 ,title="stdev upper n")
low_n = input(2 ,minval=1 ,title="stdev lower n")
SO_bool = input(false,type=bool ,title="loss cut")
SO_len = input(20 ,type=integer ,minval=1 ,title="loss cut ATR length")
SO_N = input(2 ,type=float ,minval=0.5 ,title="loss cut ATR*N")
MAX_N = input(1 ,type=integer ,minval=1 ,maxval=4 ,title="maximun num of unit")
LO_len = input(20 ,type=integer ,minval=1 ,title="pyramiding ATR length")
LO_N = input(10 ,type=float ,minval=0.5 ,title="pyramiding ATR*N")
Tm_bool = input(false,type=bool ,title="timed exit")
Tm_len = input(80 ,type=integer ,minval=1 ,title="timed exit length")
fromYear = input(2005 ,type=integer ,minval=1900 ,title="test start")
endYear = input(2017 ,type=integer ,minval=1900 ,title="test end")
isWork = timestamp(fromYear ,1 ,1 ,00 ,00) <= time and time < timestamp(endYear+1 ,1 ,1 ,00 ,00)
SMA = sma(close ,len)
STD = stdev(close ,len)
UPPER = SMA + STD * up_n
LOWER = SMA - STD * low_n
atr_SO_ = ema(tr ,SO_len)
atr_LO_ = ema(tr ,LO_len)
atr_SO = atr_SO_*SO_N
atr_LO = atr_LO_*LO_N
countTradingDays = na
countNonTradingDays = na
countTradingDays := strategy.position_size==0 ? 0 : countTradingDays[1] + 1
countNonTradingDays := strategy.position_size!=0 ? 0 : countNonTradingDays[1] + 1
entry1 = close
entry2 = close
entry3 = close
entry4 = close
entry1 := strategy.position_size==0 ? na : entry1[1]
entry2 := strategy.position_size==0 ? na : entry2[1]
entry3 := strategy.position_size==0 ? na : entry3[1]
entry4 := strategy.position_size==0 ? na : entry4[1]
lo2 = close
lo3 = close
lo4 = close
lo2 := strategy.position_size==0 ? na : lo2[1]
lo3 := strategy.position_size==0 ? na : lo3[1]
lo4 := strategy.position_size==0 ? na : lo4[1]
losscut = close
losscut := strategy.position_size==0 or SO_bool==false ? na : losscut[1]
L_EntrySig = close >= UPPER
S_EntrySig = close <= LOWER
if(strategy.position_size != 0)
L_ExitSig = (close <= SMA or S_EntrySig) and strategy.position_size > 0
S_ExitSig = (close >= SMA or L_EntrySig) and strategy.position_size < 0
TimedSig = countTradingDays > Tm_len and Tm_bool
strategy.close_all(when = L_ExitSig or S_ExitSig or TimedSig)
if(L_ExitSig or S_ExitSig)
entry1 := na
entry2 := na
entry3 := na
entry4 := na
lo2 := na
lo3 := na
lo4 := na
losscut := na
if(strategy.position_size > 0)
lo_sig2 = lo2 < high
lo_sig3 = lo3 < high
lo_sig4 = lo4 < high
if(lo_sig2 and MAX_N >= 2)
if(SO_bool)
strategy.entry("L-Entry2" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry2")
strategy.exit("L-Entry1" ,stop=close-atr_SO)
else
strategy.entry("L-Entry2" ,strategy.long ,comment="L-Entry2")
lo2 := na
losscut := SO_bool ? close - atr_SO : na
if(lo_sig3 and MAX_N >= 3)
if(SO_bool)
strategy.entry("L-Entry3" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry3")
strategy.exit("L-Entry2" ,stop=close-atr_SO)
strategy.exit("L-Entry1" ,stop=close-atr_SO)
else
strategy.entry("L-Entry3" ,strategy.long ,comment="L-Entry3")
lo3 := na
losscut := SO_bool ? close - atr_SO : na
if(lo_sig4 and MAX_N >= 4)
if(SO_bool)
strategy.entry("L-Entry4" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry4")
strategy.exit("L-Entry3" ,stop=close-atr_SO)
strategy.exit("L-Entry2" ,stop=close-atr_SO)
strategy.exit("L-Entry1" ,stop=close-atr_SO)
else
strategy.entry("L-Entry4" ,strategy.long ,comment="L-Entry4")
lo4 := na
losscut := SO_bool ? close - atr_SO : na
if(strategy.position_size < 0)
lo_sig2 = lo2 > low
lo_sig3 = lo3 > low
lo_sig4 = lo4 > low
if(lo_sig2 and MAX_N >= 2)
if(SO_bool)
strategy.entry("S-Entry2" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry2")
strategy.exit("S-Entry1" ,stop=close+atr_SO)
else
strategy.entry("S-Entry2" ,strategy.short ,comment="S-Entry2")
lo2 := na
losscut := SO_bool ? close + atr_SO : na
if(lo_sig3 and MAX_N >= 3)
if(SO_bool)
strategy.entry("S-Entry3" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry3")
strategy.exit("S-Entry2" ,stop=close+atr_SO)
strategy.exit("S-Entry1" ,stop=close+atr_SO)
else
strategy.entry("S-Entry3" ,strategy.short ,comment="S-Entry3")
lo3 := na
losscut := SO_bool ? close + atr_SO : na
if(lo_sig4 and MAX_N >= 4)
if(SO_bool)
strategy.entry("S-Entry4" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry4")
strategy.exit("S-Entry3" ,stop=close+atr_SO)
strategy.exit("S-Entry2" ,stop=close+atr_SO)
strategy.exit("S-Entry1" ,stop=close+atr_SO)
else
strategy.entry("S-Entry4" ,strategy.short ,comment="S-Entry4")
lo4 := na
losscut := SO_bool ? close + atr_SO : na
if((L_EntrySig or S_EntrySig) and isWork and strategy.position_size==0)
countTradingDays := 0
entry1 := close
if(L_EntrySig)
if(SO_bool)
strategy.entry("L-Entry1" ,strategy.long ,stop=close-atr_SO ,comment="L-Entry1")
else
strategy.entry("L-Entry1" ,strategy.long ,comment="L-Entry1")
lo2 := MAX_N >= 2 ? close + atr_LO : na
lo3 := MAX_N >= 3 ? close + atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close + atr_LO * 3 : na
losscut := SO_bool ? close - atr_SO : na
if(S_EntrySig)
if(SO_bool)
strategy.entry("S-Entry1" ,strategy.short ,stop=close+atr_SO ,comment="S-Entry1")
else
strategy.entry("S-Entry1" ,strategy.short ,comment="S-Entry1")
lo2 := MAX_N >= 2 ? close - atr_LO : na
lo3 := MAX_N >= 3 ? close - atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close - atr_LO * 3 : na
losscut := SO_bool ? close + atr_SO : na
// plot(strategy.position_size ,transp=0 ,title="保有ポジションの数")
// plot(strategy.openprofit ,transp=0 ,title="未決済の損益")
// plot(strategy.netprofit ,transp=0 ,title="決済済みの損益")
// plot(strategy.closedtrades ,transp=0 ,title="決済済み取引数")
// plot(countTradingDays ,transp=0 ,title="取引日数")
// plot(countNonTradingDays ,transp=0 ,title="ノンポジ日数")
plot(entry1 ,title="entry1" ,color=blue ,transp=0 ,style=linebr)
plot(lo2 ,title="lo2" ,color=red ,transp=0 ,style=linebr)
plot(lo3 ,title="lo3" ,color=red ,transp=0 ,style=linebr)
plot(lo4 ,title="lo4" ,color=red ,transp=0 ,style=linebr)
plot(losscut ,title="losscut" ,color=red ,transp=0 ,style=linebr)
plot(atr_SO ,transp=0 ,title="ATR_SO")
plot(atr_LO ,transp=0 ,title="ATR_LO")
// plot(strategy.max_drawdown ,transp=50 ,title="最大DD")
// plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
p1 = plot(UPPER ,color=#303F9F ,title="UPPER" ,style=line ,linewidth=2, transp=0)
p2 = plot(LOWER ,color=#4CAF50 ,title="LOWER" ,style=line ,linewidth=2, transp=0)
plot(SMA ,color=red ,title="EMA" ,style=line ,linewidth=2 ,transp=0)
fill(p1 ,p2 ,color=#2196F3 ,title="fill" ,transp=60)
=====
Pine講座60 タートルズ流投資の魔術|トリプル移動平均「タートルズ流投資の魔術
カーティス・フェイス著」
で紹介されている手法の再現。
2つ目です。
意外なことに
超長期の時間軸においては、
3本の移動平均よりも
2本の方が優位であったりします。
ご興味がある方は、
ぜひ、色んな銘柄で比較してみてください。
※ 以前、作成したコードなので、
少し古い部分もあるかと思います
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=3
strategy("Strategy Turtle Triple EMA"
,default_qty_type=strategy.fixed
,default_qty_value=1
,pyramiding=4
,overlay=true)
src = close
S = input(150 ,minval=1 ,title="short_")
M = input(250 ,minval=1 ,title="middle_")
L = input(350 ,minval=1 ,title="long_")
MAX_N = input(1 ,type=integer ,minval=1 ,maxval=4 ,title="maximun num of unit")
LO_len = input(20 ,type=integer ,minval=1 ,title="pyramiding ATR length")
LO_N = input(1 ,type=float ,minval=0.5 ,title="pyramiding ATR*N")
fromYear = input(2005 ,type=integer ,minval=1900 ,title="test start")
endYear = input(2017 ,type=integer ,minval=1900 ,title="test end")
isWork = timestamp(fromYear ,1 ,1 ,00 ,00) <= time and time < timestamp(endYear+1 ,1 ,1 ,00 ,00)
S_ = ema(close ,S)
M_ = ema(close ,M)
L_ = ema(close ,L)
atr_LO_ = ema(tr ,LO_len)
atr_LO = atr_LO_*LO_N
countTradingDays = na
countNonTradingDays = na
countTradingDays := strategy.position_size==0 ? 0 : countTradingDays[1] + 1
countNonTradingDays := strategy.position_size!=0 ? 0 : countNonTradingDays[1] + 1
entry1 = close
entry2 = close
entry3 = close
entry4 = close
entry1 := strategy.position_size==0 ? na : entry1[1]
entry2 := strategy.position_size==0 ? na : entry2[1]
entry3 := strategy.position_size==0 ? na : entry3[1]
entry4 := strategy.position_size==0 ? na : entry4[1]
lo2 = close
lo3 = close
lo4 = close
lo2 := strategy.position_size==0 ? na : lo2[1]
lo3 := strategy.position_size==0 ? na : lo3[1]
lo4 := strategy.position_size==0 ? na : lo4[1]
L_EntrySig = S_ >= M_ and S_ >= L_ and M_ >= L_
S_EntrySig = S_ <= M_ and S_ <= L_ and S_ <= L_
lo_sig2 = strategy.position_size>0 ? lo2 < high : strategy.position_size<0 ? lo2 > low : na
lo_sig3 = strategy.position_size>0 ? lo3 < high : strategy.position_size<0 ? lo3 > low : na
lo_sig4 = strategy.position_size>0 ? lo4 < high : strategy.position_size<0 ? lo4 > low : na
if(strategy.position_size != 0)
L_ExitSig = S_ <= M_ and strategy.position_size > 0
S_ExitSig = S_ >= M_ and strategy.position_size < 0
strategy.close_all(when = L_ExitSig or S_ExitSig)
if(L_ExitSig or S_ExitSig)
entry1 := na
entry2 := na
entry3 := na
entry4 := na
lo2 := na
lo3 := na
lo4 := na
if(strategy.position_size > 0)
if(lo_sig2 and MAX_N >= 2)
lo2 := na
strategy.entry("L-Entry2" ,strategy.long ,comment="L-Entry2")
if(lo_sig3 and MAX_N >= 3)
lo3 := na
strategy.entry("L-Entry3" ,strategy.long ,comment="L-Entry3")
if(lo_sig4 and MAX_N >= 4)
lo4 := na
strategy.entry("L-Entry4" ,strategy.long ,comment="L-Entry4")
if(strategy.position_size < 0)
if(lo_sig2 and MAX_N >= 2)
lo2 := na
strategy.entry("S-Entry2" ,strategy.short ,comment="S-Entry2")
if(lo_sig3 and MAX_N >= 3)
lo3 := na
strategy.entry("S-Entry3" ,strategy.short ,comment="S-Entry3")
if(lo_sig4 and MAX_N >= 4)
lo4 := na
strategy.entry("S-Entry4" ,strategy.short ,comment="S-Entry4")
if((L_EntrySig or S_EntrySig) and isWork and strategy.position_size==0)
countTradingDays := 0
entry1 := close
if(L_EntrySig)
strategy.entry("L-Entry1" ,strategy.long ,comment="L-Entry1")
lo2 := MAX_N >= 2 ? close + atr_LO : na
lo3 := MAX_N >= 3 ? close + atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close + atr_LO * 3 : na
if(S_EntrySig)
strategy.entry("S-Entry1" ,strategy.short ,comment="S-Entry1")
lo2 := MAX_N >= 2 ? close - atr_LO : na
lo3 := MAX_N >= 3 ? close - atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close - atr_LO * 3 : na
// plot(strategy.position_size ,transp=0 ,title="保有ポジションの数")
// plot(strategy.openprofit ,transp=0 ,title="未決済の損益")
// plot(strategy.netprofit ,transp=0 ,title="決済済みの損益")
// plot(strategy.closedtrades ,transp=0 ,title="決済済み取引数")
// plot(countTradingDays ,transp=0 ,title="取引日数")
// plot(countNonTradingDays ,transp=0 ,title="ノンポジ日数")
plot(entry1 ,title="entry1" ,color=blue ,transp=0 ,style=linebr)
plot(lo2 ,title="lo2" ,color=red ,transp=0 ,style=linebr)
plot(lo3 ,title="lo3" ,color=red ,transp=0 ,style=linebr)
plot(lo4 ,title="lo4" ,color=red ,transp=0 ,style=linebr)
plot(atr_LO ,transp=0 ,title="ATR_LO")
// plot(strategy.max_drawdown ,transp=50 ,title="最大DD")
// plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
plot(L_ ,color=#303F9F ,title="長期EMA" ,style=line ,linewidth=2, transp=0)
plot(M_ ,color=#4CAF50 ,title="中期EMA" ,style=line ,linewidth=2, transp=0)
plot(S_ ,color=red ,title="短期EMA" ,style=line ,linewidth=2, transp=0)
=====
Pine講座59 タートルズ流投資の魔術|ダブル移動平均ここからは、
タートルズ流投資の魔術
カーティス・フェイス著
で紹介されている手法を
再現していきたいと思います。
1つ目の手法は、
長期のダブル移動平均です。
非常にシンプルな手法ですが、
長期にするだけで意外と勝てます。
※ 以前、作成したコードなので、
少し古い部分もあるかと思います
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=3
strategy("Strategy Turtle Double EMA"
,default_qty_type=strategy.fixed
,default_qty_value=1
,pyramiding=4
,overlay=true)
src = close
M = input(50 ,minval=1 ,title="middle_") // 900/6/25 = 6ヶ月
L = input(350 ,minval=1 ,title="long_") // 1800/6/25 = 12ヶ月
MAX_N = input(1 ,type=integer ,minval=1 ,maxval=4 ,title="maximun num of unit")
LO_len = input(20 ,type=integer ,minval=1 ,title="pyramiding ATR length")
LO_N = input(1 ,type=float ,minval=0.5 ,title="pyramiding ATR*N")
fromYear = input(2005 ,type=integer ,minval=1900 ,title="test start")
endYear = input(2017 ,type=integer ,minval=1900 ,title="test end")
isWork = timestamp(fromYear ,1 ,1 ,00 ,00) <= time and time < timestamp(endYear+1 ,1 ,1 ,00 ,00)
M_ = ema(close ,M)
L_ = ema(close ,L)
atr_LO_ = ema(tr ,LO_len)
atr_LO = atr_LO_*LO_N
countTradingDays = na
countNonTradingDays = na
countTradingDays := strategy.position_size==0 ? 0 : countTradingDays[1] + 1
countNonTradingDays := strategy.position_size!=0 ? 0 : countNonTradingDays[1] + 1
entry1 = close
entry2 = close
entry3 = close
entry4 = close
entry1 := strategy.position_size==0 ? na : entry1[1]
entry2 := strategy.position_size==0 ? na : entry2[1]
entry3 := strategy.position_size==0 ? na : entry3[1]
entry4 := strategy.position_size==0 ? na : entry4[1]
lo2 = close
lo3 = close
lo4 = close
lo2 := strategy.position_size==0 ? na : lo2[1]
lo3 := strategy.position_size==0 ? na : lo3[1]
lo4 := strategy.position_size==0 ? na : lo4[1]
L_EntrySig = M_ >= L_
S_EntrySig = M_ <= L_
lo_sig2 = strategy.position_size>0 ? lo2 < high : strategy.position_size<0 ? lo2 > low : na
lo_sig3 = strategy.position_size>0 ? lo3 < high : strategy.position_size<0 ? lo3 > low : na
lo_sig4 = strategy.position_size>0 ? lo4 < high : strategy.position_size<0 ? lo4 > low : na
if(strategy.position_size != 0)
L_ExitSig = S_EntrySig and strategy.position_size > 0
S_ExitSig = L_EntrySig and strategy.position_size < 0
strategy.close_all(when = L_ExitSig or S_ExitSig)
if(L_ExitSig or S_ExitSig)
entry1 := na
entry2 := na
entry3 := na
entry4 := na
lo2 := na
lo3 := na
lo4 := na
if(strategy.position_size > 0)
if(lo_sig2 and MAX_N >= 2)
lo2 := na
strategy.entry("L-Entry2" ,strategy.long ,comment="L-Entry2")
if(lo_sig3 and MAX_N >= 3)
lo3 := na
strategy.entry("L-Entry3" ,strategy.long ,comment="L-Entry3")
if(lo_sig4 and MAX_N >= 4)
lo4 := na
strategy.entry("L-Entry4" ,strategy.long ,comment="L-Entry4")
if(strategy.position_size < 0)
if(lo_sig2 and MAX_N >= 2)
lo2 := na
strategy.entry("S-Entry2" ,strategy.short ,comment="S-Entry2")
if(lo_sig3 and MAX_N >= 3)
lo3 := na
strategy.entry("S-Entry3" ,strategy.short ,comment="S-Entry3")
if(lo_sig4 and MAX_N >= 4)
lo4 := na
strategy.entry("S-Entry4" ,strategy.short ,comment="S-Entry4")
if((L_EntrySig or S_EntrySig) and isWork and strategy.position_size==0)
countTradingDays := 0
entry1 := close
if(L_EntrySig)
strategy.entry("L-Entry1" ,strategy.long ,comment="L-Entry1")
lo2 := MAX_N >= 2 ? close + atr_LO : na
lo3 := MAX_N >= 3 ? close + atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close + atr_LO * 3 : na
if(S_EntrySig)
strategy.entry("S-Entry1" ,strategy.short ,comment="S-Entry1")
lo2 := MAX_N >= 2 ? close - atr_LO : na
lo3 := MAX_N >= 3 ? close - atr_LO * 2 : na
lo4 := MAX_N >= 4 ? close - atr_LO * 3 : na
plot(strategy.position_size ,transp=0 ,title="保有ポジションの数")
plot(strategy.openprofit ,transp=0 ,title="未決済の損益")
plot(strategy.netprofit ,transp=0 ,title="決済済みの損益")
plot(strategy.closedtrades ,transp=0 ,title="決済済み取引数")
plot(countTradingDays ,transp=0 ,title="取引日数")
plot(countNonTradingDays ,transp=0 ,title="ノンポジ日数")
plot(entry1 ,title="entry1" ,color=blue ,transp=0 ,style=linebr)
plot(lo2 ,title="lo2" ,color=red ,transp=0 ,style=linebr)
plot(lo3 ,title="lo3" ,color=red ,transp=0 ,style=linebr)
plot(lo4 ,title="lo4" ,color=red ,transp=0 ,style=linebr)
plot(atr_LO ,transp=0 ,title="ATR_LO")
// plot(strategy.max_drawdown ,transp=50 ,title="最大DD")
// plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
plot(L_ ,color=#303F9F ,title="長期EMA" ,style=line ,linewidth=2, transp=0)
plot(M_ ,color=#4CAF50 ,title="中期EMA" ,style=line ,linewidth=2, transp=0)
=====
Pine講座58 バックテストにトレンドフィルターを追加するトレンドフィルターといっても、
エントリーの条件を増やすだけです。
今回は、タートルズのトレンドフィルターを参考に
エントリーの条件を追加してみました。
メインのロジックとの相性もありますが、
成績が大幅に向上することもあります。
・余分なトレードが減って損失が減る
・エッジの強化
上記のいずれかを満たすと
成績の向上につながると思います。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=2
strategy("HullMA Strategy の解説", overlay=true)
n=input(title="period",type=integer,defval=20)
// トレンドフィルターの計算値
_n=input(title="period",type=integer,defval=50)
__n=input(title="period",type=integer,defval=350)
n2ma=2*wma(close,round(n/2))
nma=wma(close,n)
diff=n2ma-nma
sqn=round(sqrt(n))
n2ma1=2*wma(close[1],round(n/2))
nma1=wma(close[1],n)
diff1=n2ma1-nma1
n1=wma(diff,sqn)
n2=wma(diff1,sqn)
c=n1>n2?green:red
// トレンドフィルター用のHullMA①
_n2ma=2*wma(close,round(_n/2))
_nma=wma(close,_n)
_diff=_n2ma-_nma
_sqn=round(sqrt(_n))
_n2ma1=2*wma(close[1],round(_n/2))
_nma1=wma(close[1],_n)
_diff1=_n2ma1-_nma1
_n1=wma(_diff,_sqn)
_n2=wma(_diff1,_sqn)
_c=_n1>_n2?green:red
// トレンドフィルター用のHullMA②
__n2ma=2*wma(close,round(__n/2))
__nma=wma(close,__n)
__diff=__n2ma-__nma
__sqn=round(sqrt(__n))
__n2ma1=2*wma(close[1],round(__n/2))
__nma1=wma(close[1],__n)
__diff1=__n2ma1-__nma1
__n1=wma(__diff,__sqn)
__n2=wma(__diff1,__sqn)
__c=__n1>__n2?green:red
ma=plot(n1,color=c)
// トレンドフィルターも描画
_ma=plot(_n1,color=_c)
__ma=plot(__n1,color=__c)
// and でトレンドフィルターの条件を追加
longCondition = n1>n2 and _n1>__n1
if (longCondition)
strategy.entry("Long", strategy.long)
shortCondition = n1<n2 and _n1<__n1
if (shortCondition)
strategy.entry("Short", strategy.short)
=====
Pine講座57 バックテスト|HullMA Strategyの解説HullMA は反応が良いのに線形はなめらか。
今まで勉強したことのないインジケーターですが、
ちょうどストラテジーをみつけたので解説してみようと思います。
次回はこのストラテジーに
トレンドフィルターを加えてみたいと思います。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=2
strategy("HullMA Strategy の解説", overlay=true)
// ハル移動平均の計算期間
n=input(title="period",type=integer,defval=20)
// ハル移動平均の算出
n2ma=2*wma(close,round(n/2))
nma=wma(close,n)
diff=n2ma-nma
sqn=round(sqrt(n))
n2ma1=2*wma(close ,round(n/2))
nma1=wma(close ,n)
diff1=n2ma1-nma1
n1=wma(diff,sqn)
n2=wma(diff1,sqn)
c=n1>n2?green:red
// ハル移動平均の描画
ma=plot(n1,color=c)
// 売買(シンプルな途転戦略)
longCondition = n1>n2
if (longCondition)
strategy.entry("Long", strategy.long)
shortCondition = longCondition != true
if (shortCondition)
strategy.entry("Short", strategy.short)
=====
Pine講座56 バックテストで資金管理昨日のコードに
資金管理を追加してみます。
具体的には、
まず以下を設定し
・初期資金
・lot
・1エントリーの資金に対する割合
・複利と単利の別
以下から取引量を算出
・単利の場合、初期資金
・複利の場合、残高
・atr
そして、
エントリー時に取引量を反映
ということを行っています。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy(
title="Strategy Code Example"
,shorttitle="Strategy Code Example"
,overlay=true
,pyramiding=0
,initial_capital=1000000
,default_qty_type=strategy.fixed
,default_qty_value=1)
// Revision: 1
// Author: @JayRogers
//
// *** THIS IS JUST AN EXAMPLE OF STRATEGY RISK MANAGEMENT CODE IMPLEMENTATION ***
// 設定項目と初期値
////
// 移動平均
maFastSource = input(defval=open, title="Fast MA Source")
maFastLength = input(defval=14, title="Fast MA Period", minval=1)
maSlowSource = input(defval=open, title="Slow MA Source")
maSlowLength = input(defval=21, title="Slow MA Period", minval=1)
// リスク管理
tradeInvert = input(defval=false, title="Invert Trade Direction?")
inpTakeProfit = input(defval=1000, title="Take Profit", minval=0)
inpStopLoss = input(defval=200, title="Stop Loss", minval=0)
inpTrailStop = input(defval=200, title="Trailing Stop Loss", minval=0)
inpTrailOffset = input(defval=0, title="Trailing Stop Loss Offset", minval=0)
// 資金管理
lot = input( defval=1000 )
unit_val_pct = input( defval=0.01 )
interest_type = input( defval="compound" ,options= )
// リスク管理の値を整える(0→ na )
// 整えないと挙動がおかしくなる
//(0を渡すと「価格0で決済」みたいなことになる)
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
// 資金管理
atr = ema( tr ,20 )
unit_val_src = interest_type=="compound" ? strategy.initial_capital + strategy.netprofit : strategy.initial_capital
unit_val = unit_val_src * unit_val_pct
amount = round( unit_val / atr / lot ) * lot
// 移動平均の算出と描画
maFast = ema(maFastSource, maFastLength)
maSlow = ema(maSlowSource, maSlowLength)
fast = plot(maFast, title="Fast MA", color=color.green, linewidth=2, style=plot.style_line, transp=50)
slow = plot(maSlow, title="Slow MA", color=color.red, linewidth=2, style=plot.style_line, transp=50)
// エントリーのロジック
// tradeInertがtrueのときはロジックを反転
aboveBelow = maFast >= maSlow ? true : false
tradeDirection = tradeInvert ? aboveBelow ? false : true : aboveBelow ? true : false
// 売買
// hogehoge()=> で関数化しているけど、挙動は変数とかわらない
enterLong() =>
not tradeDirection[1] and tradeDirection
exitLong() =>
tradeDirection[1] and not tradeDirection
strategy.entry(id="Long", qty=amount, long=true, when=enterLong())
strategy.close(id="Long", when=exitLong())
strategy.entry(id="Short", qty=amount, long=false, when=exitLong())
strategy.close(id="Short", when=enterLong())
// ここで
// 利益確定、ロスカット、トレーリングストップ
// を設定している
strategy.exit("Exit Long", from_entry="Long", profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset)
strategy.exit("Exit Short", from_entry="Short", profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset)
=====
Pine講座55 バックテスト|Strategy Code Example - Risk Management の解説JayRogersさんの
Strategy Code Example - Risk Management
の解説です。
前回、前々回に解説して
利益確定やロスカットを含む
リスク管理のサンプルですね。
トレーリングストップや
トレーリングストップのオフセットを
設定することもできます。
明日は、これに取引量を算出する
ロジックも付け足してみようと思います。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=2
strategy(title = "Strategy Code Example", shorttitle = "Strategy Code Example", overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, currency = currency.GBP)
// Revision: 1
// Author: @JayRogers
//
// *** THIS IS JUST AN EXAMPLE OF STRATEGY RISK MANAGEMENT CODE IMPLEMENTATION ***
// 設定項目と初期値
////
// 移動平均
maFastSource = input(defval = open, title = "Fast MA Source")
maFastLength = input(defval = 14, title = "Fast MA Period", minval = 1)
maSlowSource = input(defval = open, title = "Slow MA Source")
maSlowLength = input(defval = 21, title = "Slow MA Period", minval = 1)
// リスク管理
tradeInvert = input(defval = false, title = "Invert Trade Direction?")
inpTakeProfit = input(defval = 1000, title = "Take Profit", minval = 0)
inpStopLoss = input(defval = 200, title = "Stop Loss", minval = 0)
inpTrailStop = input(defval = 200, title = "Trailing Stop Loss", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset", minval = 0)
// リスク管理の値を整える(0→ na )
// 整えないと挙動がおかしくなる
//(0を渡すと「価格0で決済」みたいなことになる)
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
// 移動平均の算出と描画
maFast = ema(maFastSource, maFastLength)
maSlow = ema(maSlowSource, maSlowLength)
fast = plot(maFast, title = "Fast MA", color = green, linewidth = 2, style = line, transp = 50)
slow = plot(maSlow, title = "Slow MA", color = red, linewidth = 2, style = line, transp = 50)
// エントリーのロジック
// tradeInertがtrueのときはロジックを反転
aboveBelow = maFast >= maSlow ? true : false
tradeDirection = tradeInvert ? aboveBelow ? false : true : aboveBelow ? true : false
// 売買
// hogehoge()=> で関数化しているけど、挙動は変数とかわらない
enterLong() => not tradeDirection[1] and tradeDirection
exitLong() => tradeDirection[1] and not tradeDirection
strategy.entry(id = "Long", long = true, when = enterLong())
strategy.close(id = "Long", when = exitLong())
enterShort() => tradeDirection[1] and not tradeDirection
exitShort() => not tradeDirection[1] and tradeDirection
strategy.entry(id = "Short", long = false, when = enterShort())
strategy.close(id = "Short", when = exitShort())
// ここで
// 利益確定、ロスカット、トレーリングストップ
// を設定している
strategy.exit("Exit Long", from_entry = "Long", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Short", from_entry = "Short", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
=====
Pine講座54 期間を区切ってバックテストを行う期間を区切って
バックテストを行うこともできます。
検証を比較する際に、
銘柄によって期間がまちまちだと
正確に行うことができません。
検証の各条件を揃えることで、
Pineスクリプトであってもしっかりと比較することができます。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy( "STOP LIMIT の解説" ,overlay=true )
is_test_datetime = timestamp(2019,9,5,0,0) <= time and time <= timestamp(2019,9,6,0,0)
bgcolor( is_test_datetime ? color.gray : color.white )
entry1 = close < open
float a = na
float b = na
float c = na
if( entry1 and is_test_datetime and strategy.position_size==0 )
a := high
b := a + tr * 3
c := a - tr * 3
strategy.entry( "Entry1" ,strategy.long ,1 ,stop=a )
strategy.exit( "Exit1" ,"Entry1" ,stop=c ,limit=b )
=====
Pine講座52 バックテストで指値注文上位のストラテジーは古いものが多いので、
成行注文のものが多いですね。
version3、version4では
指値注文も使うことができます。
手法によっていは、
すこしだけ有利になるかもしれません。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy( "STOP LIMIT の解説" ,overlay=true )
entry1 = time[1] < timestamp(2019,9,4,6,00) and time >= timestamp(2019,9,4,6,00)
exit1 = time[1] < timestamp(2019,9,4,9,00) and time >= timestamp(2019,9,4,9,00)
entry2 = time[1] < timestamp(2019,9,4,12,00) and time >= timestamp(2019,9,4,12,00)
diff = time - time[1]
if( entry1 )
line.new( bar_index ,high+tr*5 ,bar_index ,low-tr*5 ,color=color.red )
strategy.entry( "Entry1" ,strategy.long ,1 ,when=entry1 )
if( exit1 )
line.new( bar_index ,high+tr*2 ,bar_index ,low-tr*2 ,color=color.red )
strategy.close( "Entry1" ,exit1 )
if( entry2 )
line.new( bar_index ,high+tr*5 ,bar_index ,low-tr*5 ,color=color.red )
strategy.entry( "Entry2" ,strategy.long ,1 )
line.new( time ,close-tr*3 ,time+diff*30 ,close-tr*3 ,xloc=xloc.bar_time ,color=color.red )
line.new( time ,close+tr*3 ,time+diff*30 ,close+tr*3 ,xloc=xloc.bar_time ,color=color.red )
strategy.exit( "Exit2" ,"Entry2" ,stop=close-tr*3 ,limit=close+tr*3 )
=====
Pine講座53 バックテストでエントリーも指値注文昨日の続きですが、
もちろんエントリーも指値(逆指値)で入ることができます。
・ブレイクアウト系
・逆張り系
・価格の明確な利益確定
・明確なロスカット
このあたりは、
ちゃんと指値注文を使ってあげると
少しだけ幸せになれるかもしれません。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy( "STOP LIMIT の解説" ,overlay=true )
entry1 = time[1] < timestamp(2019,9,5,6,00) and time >= timestamp(2019,9,5,6,00)
diff = time - time[1]
float entry_price = na
float exit_limit = na
float exit_stop = na
if( entry1 )
entry_price := high
exit_limit := entry_price + tr * 3
exit_stop := entry_price - tr * 3
line.new( time ,entry_price ,time+diff*30 ,entry_price ,xloc=xloc.bar_time ,color=color.red )
line.new( time ,exit_limit ,time+diff*30 ,exit_limit ,xloc=xloc.bar_time ,color=color.red )
line.new( time ,exit_stop ,time+diff*30 ,exit_stop ,xloc=xloc.bar_time ,color=color.red )
strategy.entry( "Entry1" ,strategy.long ,1 ,stop=entry_price )
strategy.exit( "Exit1" ,"Entry1" ,stop=exit_stop ,limit=exit_limit )
=====
Pine講座㊿ バックテスト|ZigZag PA Strategy V4.1 の解説(パターンとフィボナッチによる売買)すごいストラテジーを見つけました。
1.ジグザグを算出
2.フィボナッチを算出
3.ジグザグでパターンを認識
4.パターンとフィボナッチの条件を満たせばエントリー
5.フィボナッチによる利確と損切り
これをひとつのストラテジーで実現しています。
これはめちゃくちゃ勉強になりました。
エリオット波動とかパターン分析の良いところは、
・すばやいエントリーと決済
・明確な値幅が算出できる
あたりだと考えています。
価格を加工すればするほど、
それをエントリーや決済の基準にするのは
難しくなるイメージです。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=2
// ストラテジーの宣言
// ピラミッティングなし、通貨:usd、元金10万ドル
strategy(title='[STRATEGY][RS]ZigZag PA Strategy V4.1', shorttitle='S', overlay=true, pyramiding=0, initial_capital=100000, currency=currency.USD)
//
// 設定項目
////
// 平均足を使うか
useHA = input(false, title='Use Heikken Ashi Candles')
// 代わりの時間軸を使うか(Alt=altemate?)
useAltTF = input(true, title='Use Alt Timeframe')
tf = input('60', title='Alt Timeframe')
// チャートに表示するしない
showPatterns = input(true, title='Show Patterns')
showFib0000 = input(title='Display Fibonacci 0.000:', type=bool, defval=true)
showFib0236 = input(title='Display Fibonacci 0.236:', type=bool, defval=true)
showFib0382 = input(title='Display Fibonacci 0.382:', type=bool, defval=true)
showFib0500 = input(title='Display Fibonacci 0.500:', type=bool, defval=true)
showFib0618 = input(title='Display Fibonacci 0.618:', type=bool, defval=true)
showFib0764 = input(title='Display Fibonacci 0.764:', type=bool, defval=true)
showFib1000 = input(title='Display Fibonacci 1.000:', type=bool, defval=true)
// ジグザグを算出する関数を作成
// 頂点にあたるときのみ、その値を返す
// 頂点以外のときはnaを返す
// ロジック:反対の足が2本連続 → 転換とする
////
zigzag() =>
_isUp = close >= open
_isDown = close <= open
_direction = _isUp[1] and _isDown ? -1 : _isDown[1] and _isUp ? 1 : nz(_direction[1])
_zigzag = _isUp[1] and _isDown and _direction[1] != -1 ? highest(2) : _isDown[1] and _isUp and _direction[1] != 1 ? lowest(2) : na
// ジグザグの算出と描画
// 平均足と時間軸の設定はここで反映
////
_ticker = useHA ? heikenashi(tickerid) : tickerid
sz = useAltTF ? (change(time(tf)) != 0 ? security(_ticker, tf, zigzag()) : na) : zigzag()
plot(sz, title='zigzag', color=black, linewidth=2)
//
// パターンを識別する
////
// ジグザグが発生したときのジグザグの値を取得
x = valuewhen(sz, sz, 4)
a = valuewhen(sz, sz, 3)
b = valuewhen(sz, sz, 2) //3つ前
c = valuewhen(sz, sz, 1) //前々回
d = valuewhen(sz, sz, 0) //前回
xab = (abs(b-a)/abs(x-a))
xad = (abs(a-d)/abs(x-a))
abc = (abs(b-c)/abs(a-b))
bcd = (abs(c-d)/abs(b-c))
// 5つの点の比率からパターンを判断する関数
isBat(_mode)=>
_xab = xab >= 0.382 and xab <= 0.5
_abc = abc >= 0.382 and abc <= 0.886
_bcd = bcd >= 1.618 and bcd <= 2.618
_xad = xad <= 0.618 and xad <= 1.000 // 0.886
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isAntiBat(_mode)=>
_xab = xab >= 0.500 and xab <= 0.886 // 0.618
_abc = abc >= 1.000 and abc <= 2.618 // 1.13 --> 2.618
_bcd = bcd >= 1.618 and bcd <= 2.618 // 2.0 --> 2.618
_xad = xad >= 0.886 and xad <= 1.000 // 1.13
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isAltBat(_mode)=>
_xab = xab <= 0.382
_abc = abc >= 0.382 and abc <= 0.886
_bcd = bcd >= 2.0 and bcd <= 3.618
_xad = xad <= 1.13
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isButterfly(_mode)=>
_xab = xab <= 0.786
_abc = abc >= 0.382 and abc <= 0.886
_bcd = bcd >= 1.618 and bcd <= 2.618
_xad = xad >= 1.27 and xad <= 1.618
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isAntiButterfly(_mode)=>
_xab = xab >= 0.236 and xab <= 0.886 // 0.382 - 0.618
_abc = abc >= 1.130 and abc <= 2.618 // 1.130 - 2.618
_bcd = bcd >= 1.000 and bcd <= 1.382 // 1.27
_xad = xad >= 0.500 and xad <= 0.886 // 0.618 - 0.786
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isABCD(_mode)=>
_abc = abc >= 0.382 and abc <= 0.886
_bcd = bcd >= 1.13 and bcd <= 2.618
_abc and _bcd and (_mode == 1 ? d < c : d > c)
isGartley(_mode)=>
_xab = xab >= 0.5 and xab <= 0.618 // 0.618
_abc = abc >= 0.382 and abc <= 0.886
_bcd = bcd >= 1.13 and bcd <= 2.618
_xad = xad >= 0.75 and xad <= 0.875 // 0.786
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isAntiGartley(_mode)=>
_xab = xab >= 0.500 and xab <= 0.886 // 0.618 -> 0.786
_abc = abc >= 1.000 and abc <= 2.618 // 1.130 -> 2.618
_bcd = bcd >= 1.500 and bcd <= 5.000 // 1.618
_xad = xad >= 1.000 and xad <= 5.000 // 1.272
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isCrab(_mode)=>
_xab = xab >= 0.500 and xab <= 0.875 // 0.886
_abc = abc >= 0.382 and abc <= 0.886
_bcd = bcd >= 2.000 and bcd <= 5.000 // 3.618
_xad = xad >= 1.382 and xad <= 5.000 // 1.618
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isAntiCrab(_mode)=>
_xab = xab >= 0.250 and xab <= 0.500 // 0.276 -> 0.446
_abc = abc >= 1.130 and abc <= 2.618 // 1.130 -> 2.618
_bcd = bcd >= 1.618 and bcd <= 2.618 // 1.618 -> 2.618
_xad = xad >= 0.500 and xad <= 0.750 // 0.618
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isShark(_mode)=>
_xab = xab >= 0.500 and xab <= 0.875 // 0.5 --> 0.886
_abc = abc >= 1.130 and abc <= 1.618 //
_bcd = bcd >= 1.270 and bcd <= 2.240 //
_xad = xad >= 0.886 and xad <= 1.130 // 0.886 --> 1.13
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isAntiShark(_mode)=>
_xab = xab >= 0.382 and xab <= 0.875 // 0.446 --> 0.618
_abc = abc >= 0.500 and abc <= 1.000 // 0.618 --> 0.886
_bcd = bcd >= 1.250 and bcd <= 2.618 // 1.618 --> 2.618
_xad = xad >= 0.500 and xad <= 1.250 // 1.130 --> 1.130
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
is5o(_mode)=>
_xab = xab >= 1.13 and xab <= 1.618
_abc = abc >= 1.618 and abc <= 2.24
_bcd = bcd >= 0.5 and bcd <= 0.625 // 0.5
_xad = xad >= 0.0 and xad <= 0.236 // negative?
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isWolf(_mode)=>
_xab = xab >= 1.27 and xab <= 1.618
_abc = abc >= 0 and abc <= 5
_bcd = bcd >= 1.27 and bcd <= 1.618
_xad = xad >= 0.0 and xad <= 5
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isHnS(_mode)=>
_xab = xab >= 2.0 and xab <= 10
_abc = abc >= 0.90 and abc <= 1.1
_bcd = bcd >= 0.236 and bcd <= 0.88
_xad = xad >= 0.90 and xad <= 1.1
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isConTria(_mode)=>
_xab = xab >= 0.382 and xab <= 0.618
_abc = abc >= 0.382 and abc <= 0.618
_bcd = bcd >= 0.382 and bcd <= 0.618
_xad = xad >= 0.236 and xad <= 0.764
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
isExpTria(_mode)=>
_xab = xab >= 1.236 and xab <= 1.618
_abc = abc >= 1.000 and abc <= 1.618
_bcd = bcd >= 1.236 and bcd <= 2.000
_xad = xad >= 2.000 and xad <= 2.236
_xab and _abc and _bcd and _xad and (_mode == 1 ? d < c : d > c)
// 売りパターンが出現したところに印を表示
plotshape(not showPatterns ? na : isABCD(-1) and not isABCD(-1)[1], text=" AB=CD", title='Bear ABCD', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0, offset=-2)
plotshape(not showPatterns ? na : isBat(-1) and not isBat(-1)[1], text="Bat", title='Bear Bat', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0, offset=-2)
plotshape(not showPatterns ? na : isAntiBat(-1) and not isAntiBat(-1)[1], text="Anti Bat", title='Bear Anti Bat', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0, offset=-2)
plotshape(not showPatterns ? na : isAltBat(-1) and not isAltBat(-1)[1], text="Alt Bat", title='Bear Alt Bat', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isButterfly(-1) and not isButterfly(-1)[1], text="Butterfly", title='Bear Butterfly', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isAntiButterfly(-1) and not isAntiButterfly(-1)[1], text="Anti Butterfly", title='Bear Anti Butterfly', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isGartley(-1) and not isGartley(-1)[1], text="Gartley", title='Bear Gartley', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isAntiGartley(-1) and not isAntiGartley(-1)[1], text="Anti Gartley", title='Bear Anti Gartley', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isCrab(-1) and not isCrab(-1)[1], text="Crab", title='Bear Crab', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isAntiCrab(-1) and not isAntiCrab(-1)[1], text="Anti Crab", title='Bear Anti Crab', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isShark(-1) and not isShark(-1)[1], text="Shark", title='Bear Shark', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isAntiShark(-1) and not isAntiShark(-1)[1], text="Anti Shark", title='Bear Anti Shark', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : is5o(-1) and not is5o(-1)[1], text="5-O", title='Bear 5-O', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isWolf(-1) and not isWolf(-1)[1], text="Wolf Wave", title='Bear Wolf Wave', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isHnS(-1) and not isHnS(-1)[1], text="Head and Shoulders", title='Bear Head and Shoulders', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isConTria(-1) and not isConTria(-1)[1], text="Contracting Triangle", title='Bear Contracting triangle', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
plotshape(not showPatterns ? na : isExpTria(-1) and not isExpTria(-1)[1], text="Expanding Triangle", title='Bear Expanding Triangle', style=shape.labeldown, color=maroon, textcolor=white, location=location.top, transp=0)
// 買いパターンが出現したところに印を表示
plotshape(not showPatterns ? na : isABCD(1) and not isABCD(1)[1], text="AB=CD ", title='Bull ABCD', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isBat(1) and not isBat(1)[1], text="Bat", title='Bull Bat', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isAntiBat(1) and not isAntiBat(1)[1], text="Anti Bat", title='Bull Anti Bat', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isAltBat(1) and not isAltBat(1)[1], text="Alt Bat", title='Bull Alt Bat', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isButterfly(1) and not isButterfly(1)[1], text="Butterfly", title='Bull Butterfly', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isAntiButterfly(1) and not isAntiButterfly(1)[1], text="Anti Butterfly", title='Bull Anti Butterfly', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isGartley(1) and not isGartley(1)[1], text="Gartley", title='Bull Gartley', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isAntiGartley(1) and not isAntiGartley(1)[1], text="Anti Gartley", title='Bull Anti Gartley', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isCrab(1) and not isCrab(1)[1], text="Crab", title='Bull Crab', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isAntiCrab(1) and not isAntiCrab(1)[1], text="Anti Crab", title='Bull Anti Crab', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isShark(1) and not isShark(1)[1], text="Shark", title='Bull Shark', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isAntiShark(1) and not isAntiShark(1)[1], text="Anti Shark", title='Bull Anti Shark', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : is5o(1) and not is5o(1)[1], text="5-O", title='Bull 5-O', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isWolf(1) and not isWolf(1)[1], text="Wolf Wave", title='Bull Wolf Wave', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isHnS(1) and not isHnS(1)[1], text="Head and Shoulders", title='Bull Head and Shoulders', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isConTria(1) and not isConTria(1)[1], text="Contracting Triangle", title='Bull Contracting Triangle', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
plotshape(not showPatterns ? na : isExpTria(1) and not isExpTria(1)[1], text="Expanding Triangle", title='Bull Expanding Triangle', style=shape.labelup, color=green, textcolor=white, location=location.bottom, transp=0)
//前回と前回のジグザグの値からフィボナッチを描画
fib_range = abs(d-c)
fib_0000 = not showFib0000 ? na : d > c ? d-(fib_range*0.000):d+(fib_range*0.000)
fib_0236 = not showFib0236 ? na : d > c ? d-(fib_range*0.236):d+(fib_range*0.236)
fib_0382 = not showFib0382 ? na : d > c ? d-(fib_range*0.382):d+(fib_range*0.382)
fib_0500 = not showFib0500 ? na : d > c ? d-(fib_range*0.500):d+(fib_range*0.500)
fib_0618 = not showFib0618 ? na : d > c ? d-(fib_range*0.618):d+(fib_range*0.618)
fib_0764 = not showFib0764 ? na : d > c ? d-(fib_range*0.764):d+(fib_range*0.764)
fib_1000 = not showFib1000 ? na : d > c ? d-(fib_range*1.000):d+(fib_range*1.000)
plot(title='Fib 0.000', series=fib_0000, color=fib_0000 != fib_0000[1] ? na : black)
plot(title='Fib 0.236', series=fib_0236, color=fib_0236 != fib_0236[1] ? na : red)
plot(title='Fib 0.382', series=fib_0382, color=fib_0382 != fib_0382[1] ? na : olive)
plot(title='Fib 0.500', series=fib_0500, color=fib_0500 != fib_0500[1] ? na : lime)
plot(title='Fib 0.618', series=fib_0618, color=fib_0618 != fib_0618[1] ? na : teal)
plot(title='Fib 0.764', series=fib_0764, color=fib_0764 != fib_0764[1] ? na : blue)
plot(title='Fib 1.000', series=fib_1000, color=fib_1000 != fib_1000[1] ? na : black)
// 代わりの時間軸を使っている場合、その足が更新されるタイミングで背景に黒を入れる
bgcolor(not useAltTF ? na : change(time(tf)) != 0 ? black : na)
//
// 売買のロジック
////
//「fib_rangeに対する指定された比率の幅」を返す関数
f_last_fib( _rate ) => d > c ? d - ( fib_range * _rate ) : d + ( fib_range * _rate )
// ターゲット1の設定項目と初期値
////
// 上から
// 取引量
// エントリーの基準(0.236を超えていない)
// 利益確定幅
// ロスカット幅
target01_trade_size = input(title='Target 1 - Trade size:', type=float, defval=10000.00)
target01_ew_rate = input(title='Target 1 - Fib. Rate to use for Entry Window:', type=float, defval=0.236)
target01_tp_rate = input(title='Target 1 - Fib. Rate to use for TP:', type=float, defval=0.618)
target01_sl_rate = input(title='Target 1 - Fib. Rate to use for SL:', type=float, defval=-0.236)
// ターゲット2の設定
////
target02_active = input(title='Target 2 - Active?', type=bool, defval=false)
target02_trade_size = input(title='Target 2 - Trade size:', type=float, defval=10000.00)
target02_ew_rate = input(title='Target 2 - Fib. Rate to use for Entry Window:', type=float, defval=0.236)
target02_tp_rate = input(title='Target 2 - Fib. Rate to use for TP:', type=float, defval=1.618)
target02_sl_rate = input(title='Target 2 - Fib. Rate to use for SL:', type=float, defval=-0.236)
// 買いのパターン
buy_patterns_00 = isABCD(1) or isBat(1) or isAltBat(1) or isButterfly(1) or isGartley(1) or isCrab(1) or isShark(1) or is5o(1) or isWolf(1) or isHnS(1) or isConTria(1) or isExpTria(1)
buy_patterns_01 = isAntiBat(1) or isAntiButterfly(1) or isAntiGartley(1) or isAntiCrab(1) or isAntiShark(1)
// 売りのパターン
sel_patterns_00 = isABCD(-1) or isBat(-1) or isAltBat(-1) or isButterfly(-1) or isGartley(-1) or isCrab(-1) or isShark(-1) or is5o(-1) or isWolf(-1) or isHnS(-1) or isConTria(-1) or isExpTria(-1)
sel_patterns_01 = isAntiBat(-1) or isAntiButterfly(-1) or isAntiGartley(-1) or isAntiCrab(-1) or isAntiShark(-1)
// ターゲット1の売買
////
// 買いのパターン & エントリーの基準を満たす → 買いエントリー
// 利確・損切りを超える → 買いの決済
target01_buy_entry = (buy_patterns_00 or buy_patterns_01) and close <= f_last_fib(target01_ew_rate)
target01_buy_close = high >= f_last_fib(target01_tp_rate) or low <= f_last_fib(target01_sl_rate)
strategy.entry('target01_buy', long=strategy.long, qty=target01_trade_size, comment='buy 01', when=target01_buy_entry)
strategy.close('target01_buy', when=target01_buy_close)
// 売りのパターン & エントリーの基準を満たす → 売りエントリー
// 利確・損切りを超える → 売りの決済
target01_sel_entry = (sel_patterns_00 or sel_patterns_01) and close >= f_last_fib(target01_ew_rate)
target01_sel_close = low <= f_last_fib(target01_tp_rate) or high >= f_last_fib(target01_sl_rate)
strategy.entry('target01_sell', long=strategy.short, qty=target01_trade_size, comment='sell 01', when=target01_sel_entry)
strategy.close('target01_sell', when=target01_sel_close)
// ターゲット2の売買
////
target02_buy_entry = target02_active and (buy_patterns_00 or buy_patterns_01) and close <= f_last_fib(target02_ew_rate)
target02_buy_close = target02_active and high >= f_last_fib(target02_tp_rate) or low <= f_last_fib(target02_sl_rate)
strategy.entry('target02_buy', long=strategy.long, qty=target02_trade_size, comment='buy 02', when=target02_buy_entry)
strategy.close('target02_buy', when=target02_buy_close)
target02_sel_entry = target02_active and (sel_patterns_00 or sel_patterns_01) and close >= f_last_fib(target02_ew_rate)
target02_sel_close = target02_active and low <= f_last_fib(target02_tp_rate) or high >= f_last_fib(target02_sl_rate)
strategy.entry('target02_sell', long=strategy.short, qty=target02_trade_size, comment='sell 02', when=target02_sel_entry)
strategy.close('target02_sell', when=target02_sel_close)
=====
Pine講座51 バックテストにおけるSecurity関数について昨日のストラテジーが、あまりにも真っ当で
それにも関わらず "すごそう" に見えるので
少し精査をしています。
・15分足の検証
・1時間足のジグザグをもとにフォーメーション分析
・フォーメーションによって売買
・フィボナッチで利確・損切り
・1時間足の価格を取得するのに Security( ) を使っている
この Security( ) が曲者でして、
Pineスクリプト上で、価格を先読みすることができてしまいます。
以下で紹介するコードの
lookahead=barmerge.lookahead_on
の部分ですね。
ここが「on」になっていると
先読みできてしまう状態です。
昨日のコードはonになってしまっている状態で、
offにするにはversion3以上の検証を行う必要があります。
しかし、あのコードはversion2までしか動かないのですね。
zigzagの箇所がやや複雑なので、
わりとガッツリ作り直す必要があります。
=====
//@version=4
study( "Security() の解説" ,overlay=true )
plot( security( syminfo.tickerid ,"240" ,high ,lookahead=barmerge.lookahead_off ) ,color=color.red )
plot( security( syminfo.tickerid ,"240" ,high ,lookahead=barmerge.lookahead_on ) ,color=color.blue )
plot( change(time("240")) != 0 ? security( syminfo.tickerid ,"240" ,high ,lookahead=barmerge.lookahead_off ) : na ,color=color.green ,style=plot.style_linebr ,linewidth=3 )
plot( change(time("240")) != 0 ? security( syminfo.tickerid ,"240" ,high ,lookahead=barmerge.lookahead_on ) : na ,color=color.purple ,style=plot.style_linebr ,linewidth=3 )
=====
Pine講座㊾ バックテスト|Moving Average Cross and/or Bbands bot の解説今回はCryptoRoxさんの
Moving Average Cross and/or Bbands bot を題材に解説しています。
このストラテジーはアイデアが満載で、
(儲かるかは別として)非常に良いコードだと思います。
利確損切り幅をチャート上に表示する方法など、
個人的にも勉強になる点がいくつかありました。
このストラテジーには以下のような機能があります。
・MAロジックのON/OFF
・BBロジックのON/OFF
(組み合わせることもできる)
・平均足のON/OFF
・検証期間の調整
・ピラミッティングの回数の調整
・取引対象によって取引量を変更
・利益確定幅の指定
・ロスカット幅の指定
・トレーリングストップの指定
(利確、損切り、トレーリングストップがない場合は途転売買)
ただし、注文は成行しか使っていないですね。
Pineスクリプトのストラテジーでは指値、逆指値を使うこともできます。
・どういう動きになるか
・どういう設定をしたら良いのか
あたりを、次回以降、
何回かに分けて解説してみようと思います。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=3
strategy("Moving Average Cross and/or Bbands bot by CryptoRox の解説", overlay=true, pyramiding=1000)
//
// 取引量の設定
////
qty = 1
isALT = input(false, "Altcoin")
if isALT
qty:= 100000000
isForex = input(false, "Forex")
if isForex
qty:= 10000
//
// 検証期間の設定
////
testStartYear = input(1, "Backtest Start Year")
testStartMonth = input(8, "Backtest Start Month")
testStartDay = input(25, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
testStopYear = input(999999, "Backtest Stop Year")
testStopMonth = input(9, "Backtest Stop Month")
testStopDay = input(26, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
//
// ローソク足と平均足を切り替える
////
isHA = false
data = isHA ? heikinashi(tickerid) : tickerid
o = security(data, period, open)
h = security(data, period, high)
l = security(data, period, low)
c = security(data, period, close)
// ローソク足を描画
col = c > o ? green : red
plotcandle(o, h, l, c, "Heiken Ashi", col, black)
//
// エントリーの判断
////
// 買いシグナルと売りシグナルを入れる変数
long = na
short = na
// MAだけのロジック(設定ONのとき)
////
// ON/OFF と 計算用の数値の設定
useMA = input(true, "Use Moving Average Cross")
ma1Input = input(50, "Moving Average 1")
ma2Input = input(200, "Moving Average 2")
// MAの算出
ma1 = sma(c, ma1Input)
ma2 = sma(c, ma2Input)
// 描画用の計算値の入れ物
ma1Plot = na
ma2Plot = na
// MAロジックの根拠(買いシグナル、売りシグナル)
maLong = c > ma1 and ma1 > ma2
maShort = c < ma1 and ma1 < ma2
// MAロジックON → データの格納とシグナルの判断
if useMA
ma1Plot := ma1
ma2Plot := ma2
long := maLong
short := maShort
// 描画(MAロジックOFFのときは描画されない)
plot(ma1Plot, "ma1", blue)
plot(ma2Plot, "ma2", orange)
// ボリンジャーバンドロジック
////
// ON/OFF と 計算用の数値の設定
useBbands = input(false, "Use Bollinger Bands")
bblength = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)
// テクニカルの算出
basis = sma(c, bblength)
dev = mult * stdev(c, bblength)
upper = basis + dev
lower = basis - dev
// 描画用の計算値の入れ物
basisPlot = na
p1Plot = na
p2Plot = na
// BBロジックON → データの格納とシグナルの判断
if useBbands
long := c < lower
short := c > upper
basisPlot := basis
p1Plot := upper
p2Plot := lower
// BBロジックとMAロジックがON → シグナルの判断(上書く)
if useBbands and useMA
long := c < lower and maLong
short := c > upper and maShort
// 描画(BBロジックがOFFのときは描画されない)
plot(basisPlot, color=red)
p1 = plot(p1Plot, color=blue)
p2 = plot(p2Plot, color=blue)
fill(p1, p2)
//
// 売買のロジック
////
// エントリーシグナルの数をカウントする
sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])
if long
sectionLongs := sectionLongs + 1
sectionShorts := 0
if short
sectionLongs := 0
sectionShorts := sectionShorts + 1
// ピラミッティングの設定値
pyrl = input(1, "Pyramiding less than") // If your count is less than this number
pyre = input(0, "Pyramiding equal to") // If your count is equal to this number
pyrg = input(1000000, "Pyramiding greater than") // If your count is greater than this number
// シグナルとピラミッティングの制限を確認
longCondition = long and sectionLongs <= pyrl or long and sectionLongs >= pyrg or long and sectionLongs == pyre
shortCondition = short and sectionShorts <= pyrl or short and sectionShorts >= pyrg or short and sectionShorts == pyre
// エントリーの価格を記録する
last_open_longCondition = na
last_open_shortCondition = na
last_open_longCondition := longCondition ? close : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? close : nz(last_open_shortCondition[1])
// ピラミッティングの制限を含めたエントリーのシグナルを数える
sectionLongConditions = 0
sectionLongConditions := nz(sectionLongConditions[1])
sectionShortConditions = 0
sectionShortConditions := nz(sectionShortConditions[1])
if longCondition
sectionLongConditions := sectionLongConditions + 1
sectionShortConditions := 0
if shortCondition
sectionLongConditions := 0
sectionShortConditions := sectionShortConditions + 1
// 最後のエントリーの時間を記録
last_longCondition = na
last_shortCondition = na
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])
in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition
// エントリー後の最高値、最安値などの記録
last_high = na
last_low = na
last_high_short = na
last_low_short = na
last_high := not in_longCondition ? na : in_longCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : nz(last_high[1])
last_high_short := not in_shortCondition ? na : in_shortCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : nz(last_high[1])
last_low := not in_shortCondition ? na : in_shortCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : nz(last_low[1])
last_low_short := not in_longCondition ? na : in_longCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : nz(last_low[1])
// トレーリングストップの設定
////
// 設定
isTS = input(false, "Trailing Stop")
tsi = input(0, "Activate Trailing Stop Price") / qty
ts = input(0, "Trailing Stop") / qty
// 判断
long_ts = isTS and not na(last_high) and crossunder(low, last_high - ts) and longCondition == 0 and high >= (last_open_longCondition + tsi)
short_ts = isTS and not na(last_low) and crossover(high, last_low + ts) and shortCondition == 0 and low <= (last_open_shortCondition - tsi)
// 描画
tsColor = isTS and in_longCondition and last_high >= (last_open_longCondition + tsi) ? blue : isTS and in_shortCondition and last_low <= (last_open_shortCondition - tsi) ? blue : white
tsiColor = isTS and in_longCondition and last_high >= (last_open_longCondition + tsi) ? white : isTS and in_shortCondition and last_low <= (last_open_shortCondition - tsi) ? white : blue
plot(isTS and in_longCondition ? last_open_longCondition + tsi : na, "Long Trailing", tsiColor, style=3, linewidth=2)
plot(isTS and in_shortCondition ? last_open_shortCondition - tsi : na, "Short Trailing", tsiColor, style=3, linewidth=2)
plot(isTS and in_longCondition and last_high >= (last_open_longCondition + tsi) ? last_high - ts : na, "Long Trailing", tsColor, style=2, linewidth=2)
plot(isTS and in_shortCondition and last_low <= (last_open_shortCondition - tsi) ? last_low + ts : na, "Short Trailing", tsColor, style=2, linewidth=2)
// 利益確定の設定
////
// 設定
isTP = input(false, "Take Profit")
tp = input(0, "Take Profit") / qty
// シグナル
long_tp = isTP and crossover(high, last_open_longCondition + tp) and longCondition == 0
short_tp = isTP and crossunder(low, last_open_shortCondition - tp) and shortCondition == 0
// 描画
tpColor = isTP and in_longCondition ? purple : isTP and in_shortCondition ? purple : white
plot(isTP and in_longCondition and last_high < last_open_longCondition + tp ? last_open_longCondition + tp : na, "Long TP", tpColor, style=3, linewidth=2)
plot(isTP and in_shortCondition and last_low > last_open_shortCondition - tp ? last_open_shortCondition - tp : na, "Short TP", tpColor, style=3, linewidth=2)
// ロスカットの設定
////
// 設定
isSL = input(false, "Stop Loss")
sl = input(0, "Stop Loss") / qty
// 判断
long_sl = isSL and crossunder(low, last_open_longCondition - sl) and longCondition == 0
short_sl = isSL and crossover(high, last_open_shortCondition + sl) and shortCondition == 0
// 描画
slColor = isSL and in_longCondition and last_low_short > last_open_longCondition - sl ? red : isSL and in_shortCondition and last_high_short < last_open_shortCondition + sl ? red : white
plot(isSL and in_longCondition ? last_open_longCondition - sl : na, "Long SL", slColor, style=3, linewidth=2)
plot(isSL and in_shortCondition ? last_open_shortCondition + sl : na, "Short SL", slColor, style=3, linewidth=2)
// 仮想マージンコール
////
isMargin = input(false, "Margin Call")
leverage = input(1, "Leverage")
long_call = last_open_longCondition - (0.8 + 0.2 * (1/leverage)) / leverage * last_open_longCondition
short_call = last_open_shortCondition + (0.78 + 0.2 * (1/leverage)) / leverage * last_open_shortCondition
long_call_signal = isMargin and crossunder(low, long_call)
short_call_signal = isMargin and crossunder(high, short_call)
marginColor = isMargin and in_longCondition and last_low_short > long_call ? black : isMargin and in_shortCondition and last_high_short < short_call ? black : white
plot(isMargin and in_longCondition ? long_call : na, "Long Margin", marginColor, style=3, linewidth=2)
plot(isMargin and in_shortCondition ? short_call : na, "Short Margin", marginColor, style=3, linewidth=2)
// ポジションの平均価格の算出
////
totalLongs = 0.0
totalLongs := nz(totalLongs[1])
totalShorts = 0.0
totalShorts := nz(totalShorts[1])
averageLongs = 0.0
averageLongs := nz(averageLongs[1])
averageShorts = 0.0
averageShorts := nz(averageShorts[1])
if longCondition
totalLongs := totalLongs + last_open_longCondition
totalShorts := 0.0
if shortCondition
totalLongs := 0.0
totalShorts := totalShorts + last_open_shortCondition
averageLongs := totalLongs / sectionLongConditions
averageShorts := totalShorts / sectionShortConditions
// 利益・損失幅の描画
longProfit = averageLongs > 0 and close >= averageLongs ? green : red
shortProfit = averageShorts > 0 and close <= averageShorts ? green : red
plot1 = plot(averageLongs > 0 ? averageLongs : na, color=white)
plot2 = plot(close, color=white)
plot3 = plot(averageShorts > 0 ? averageShorts : na, color=white)
fill(plot1, plot2, color=longProfit, transp=50)
fill(plot2, plot3, color=shortProfit, transp=50)
//Enable this to double your order size every time your pyramid on top of an existing position. (Martingale strategy)
// useMartin = input(true, "Martingale")
// longMartin = 0
// longMartin := nz(longMartin[1])
// shortMartin = 0
// shortMartin := nz(shortMartin[1])
// // Check to see if this is our first order, set the order qty to 1
// if longCondition and sectionLongConditions == 1
// longMartin := longMartin + 1
// shortMartin := 0
// if shortCondition and sectionShortConditions == 1
// longMartin := 0
// shortMartin := shortMartin + 1
// confirm that this order is being added to an existing order
// if longCondition and sectionLongConditions > 1
// longMartin := longMartin * 2
// if shortCondition and sectionShortConditions > 1
// shortMartin := shortMartin * 2
// 決済シグナルの判断(利確 or 損切り or トレーリングストップ or 途転)
////
long_close = long_tp or long_sl or long_ts or long_call_signal ? 1 : 0
short_close = short_tp or short_sl or short_ts or short_call_signal ? 1 : 0
// 決済時間の記録
last_long_close = na
last_short_close = na
last_long_close := long_close ? time : nz(last_long_close[1])
last_short_close := short_close ? time : nz(last_short_close[1])
// エントリーと決済の時間を確認
if long_close and last_long_close[1] > last_longCondition
long_close := 0
if short_close and last_short_close[1] > last_shortCondition
short_close := 0
// 検証期間内ならトレード
if testPeriod()
strategy.entry("Long", strategy.long, qty=qty, when=longCondition)
strategy.entry("Short", strategy.short, qty=qty, when=shortCondition)
strategy.close("Long", when=long_close)
strategy.close("Short", when=short_close)
=====
Pine講座㊽ バックテスト|[STRATEGY][RS]MicuRobert EMA cross V2 の解説・LazyBearさんの反応の早いMAのクロスによるエントリー
・トレイリングストップ
上記を組み合わせたストラテジーですね。
トレンドが多くてノイズが少ない銘柄&足種で有効だと思います。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=2
strategy(title=' MicuRobert EMA cross V2 の解説', overlay=true, pyramiding=0, initial_capital=100000)
//
// 設定
////
// セッションタイムを区切るかどうか
USE_TRADESESSION = input(title='Use Trading Session?', type=bool, defval=true)
// トレーリングストップを使うか
USE_TRAILINGSTOP = input(title='Use Trailing Stop?', type=bool, defval=true)
// セッションの時間を指定
// 設定を元にセッションの判断と背景色の指定
trade_session = input(title='Trade Session:', type=string, defval='0400-1500', confirm=false)
istradingsession = not USE_TRADESESSION ? false : not na(time('1', trade_session))
bgcolor(istradingsession?gray:na)
// 取引量の指定
trade_size = input(title='Trade Size:', type=float, defval=10000.00)
// 利確幅と損切り幅
tp = input(title='Take profit in pips:', type=float, defval=55.0) * (syminfo.mintick*10)
sl = input(title='Stop loss in pips:', type=float, defval=22.0) * (syminfo.mintick*10)
// 平均線の計算値
ma_length00 = input(title='EMA length:', type=integer, defval=5)
ma_length01 = input(title='DEMA length:', type=integer, defval=34)
// 計算の元とする価格
price = input(title='Price source:', type=source, defval=open)
//
// ストラテジーに必要なデータの算出と記録、描画まで
////
// LazyBearさんによる反応が早い移動平均線の計算式
// ||--- NO LAG EMA, Credit LazyBear: ---||
f_LB_zlema(_src, _length)=>
_ema1=ema(_src, _length)
_ema2=ema(_ema1, _length)
_d=_ema1-_ema2
_zlema=_ema1+_d
// ||-------------------------------------||
// 平均線の算出と描画
ma00 = f_LB_zlema(price, ma_length00)
ma01 = f_LB_zlema(price, ma_length01)
plot(title='M0', series=ma00, color=black)
plot(title='M1', series=ma01, color=black)
// エントリーしたかどうかの判別
isnewbuy = change(strategy.position_size)>0 and change(strategy.opentrades)>0
isnewsel = change(strategy.position_size)<0 and change(strategy.opentrades)>0
// 新たなエントリー → 価格を記録 → ポジションがあるときだけチャートに描画
buy_entry_price = isnewbuy ? price : buy_entry_price[1]
sel_entry_price = isnewsel ? price : sel_entry_price[1]
plot(title='BE', series=buy_entry_price, style=circles, color=strategy.position_size <= 0 ? na : aqua)
plot(title='SE', series=sel_entry_price, style=circles, color=strategy.position_size >= 0 ? na : aqua)
// 新たなエントリー → 高値・安値を記録 → ポジションがあるときだけ描画
// トレーリングストップに使う
buy_appex = na(buy_appex[1]) ? price : isnewbuy ? high : high >= buy_appex[1] ? high : buy_appex[1]
sel_appex = na(sel_appex[1]) ? price : isnewsel ? low : low <= sel_appex[1] ? low : sel_appex[1]
plot(title='BA', series=buy_appex, style=circles, color=strategy.position_size <= 0 ? na : teal)
plot(title='SA', series=sel_appex, style=circles, color=strategy.position_size >= 0 ? na : teal)
// トレーリングストップの価格を算出 → ポジションがあるときだけ描画
buy_ts = buy_appex - sl
sel_ts = sel_appex + sl
plot(title='Bts', series=buy_ts, style=circles, color=strategy.position_size <= 0 ? na : red)
plot(title='Sts', series=sel_ts, style=circles, color=strategy.position_size >= 0 ? na : red)
//
// トレーディング
////
// エントリーの条件1:移動平均線のGC
buy_cond1 = crossover(ma00, ma01) and (USE_TRADESESSION ? istradingsession : true)
// エントリーの条件2:価格と移動平均線のGC
buy_cond0 = crossover(price, ma00) and ma00 > ma01 and (USE_TRADESESSION ? istradingsession : true)
// ①か②を満たしたところでエントリーとする
buy_entry = buy_cond1 or buy_cond0
// トレーリングストップがONの場合:安値がストップを下回ったところ、もしくは利確幅を超えたら決済
// OFFの場合:固定のストップを下回るか、利確幅を超えたら決済
buy_close = (not USE_TRAILINGSTOP ? low <= buy_entry_price - sl: low <= buy_ts) or high>=buy_entry_price+tp//high>=last_traded_price + tp or low<=last_traded_price - sl //high >= hh or
// 売りは上記の逆
sel_cond1 = crossunder(ma00, ma01) and (USE_TRADESESSION ? istradingsession : true)
sel_cond0 = crossunder(price, ma00) and ma00 < ma01 and (USE_TRADESESSION ? istradingsession : true)
sel_entry = sel_cond1 or sel_cond0
sel_close = (not USE_TRAILINGSTOP ? high >= sel_entry_price + sl : high >= sel_ts) or low<=sel_entry_price-tp//low<=last_traded_price - tp or high>=last_traded_price + sl //low <= ll or
// すべて成行注文
strategy.entry('buy', long=strategy.long, qty=trade_size, comment='buy', when=buy_entry)
strategy.close('buy', when=buy_close)
strategy.entry('sell', long=strategy.short, qty=trade_size, comment='sell', when=sel_entry)
strategy.close('sell', when=sel_close)
=====
Pine講座㊼ バックテスト|20 years old Turtles strategy still work!! の解説trm0さんによるストラテジーです。
20年前のタートルズのストラテジーが今でも通用する!
というインジケーター名ですね。
バージョン2のコードなので、随分と古いようです。
今ならもっと違う書き方ができそうな気がします。
タートルズはドンチャンチャネルを複数組み合わせていました。
タートルズの手法は、
・もみあいが少ない
・トレンドが大きい
このあたりがクリアできる銘柄でないと
トータル利益を実現するのが難しいですね。
単一銘柄では難しいですが、
流動性がある20銘柄くらいでの分散投資を
長期で回すとうまくいくイメージを持っています。
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=2
//coded by tmr0
//original idea from «Way of the Turtle: The Secret Methods that Turned Ordinary People into Legendary Traders» (2007) CURTIS FAITH
strategy("20 years old Turtles strategy by tmr0 の解説", shorttitle = "Turtles", overlay=true, pyramiding=5, default_qty_type= strategy.cash, default_qty_value = 1000)
//計算用の数値を設定
//早いエントリーの基準
enter_fast = input(20, minval=1)
//早いエントリーの決済
exit_fast = input(10, minval=1)
//遅いエントリーの基準
enter_slow = input(55, minval=1)
//遅いエントリーの決済
exit_slow = input(20, minval=1)
//計算
fastL = highest(enter_fast)
fastLC = lowest(exit_fast)
fastS = lowest(enter_fast)
fastSC = highest(exit_fast)
slowL = highest(enter_slow)
slowLC = lowest(exit_slow)
slowS = lowest(enter_slow)
slowSC = highest(exit_slow)
//エントリーと決済の判断
enterL1 = high > fastL[1]
exitL1 = low <= fastLC[1]
enterS1 = low < fastS[1]
exitS1 = high >= fastSC[1]
enterL2 = high > slowL[1]
exitL2 = low <= slowLC[1]
enterS2 = low < slowS[1]
exitS2 = high >= slowSC[1]
strategy.entry("fast L", strategy.long, when = enterL1)
strategy.entry("fast S", strategy.short, when = enterS1)
strategy.close("fast L", when = exitL1)
strategy.close("fast S", when = exitS1)
strategy.entry("slow L", strategy.long, when = enterL2)
strategy.entry("slow S", strategy.short, when = enterS2)
strategy.close("slow L", when = exitL2)
strategy.close("slow S", when = exitS2)
//確認用で描画
plot( fastL )
plot( fastS )
plot( fastLC )
plot( fastSC )
plot( slowL ,color=red )
plot( slowLC ,color=red )
=====
Pine講座㊻ バックテスト|GetTrendStrategy(win% 88、RR 4)今日からユーザーが作成したストラテジーを
解説していきたいと思います。
今回は、GetTrendStrategy。
ストラテジーの中では珍しく5342いいねをつけています。
試してみたところ、
勝率:88%
RR:4
と信じられないくらい
優秀でビックリしましたが、
コードを見てみると、
Pineスクリプトの抜け穴を利用しただけのストラテジーでした。
残念。
=====
//@version=2
strategy("GetTrendStrategy の解説", overlay=true)
//securityで取得する時間軸
tim=input('160')
//security関数で160分足のopen/closeを取得
out1 = security(tickerid, tim, open)
out2 = security(tickerid, tim, close)
//確認用で描画
plot(out1,color=red)
plot(out2,color=green)
//160分足が陰線 → 陽線で買いエントリー
longCondition = crossover(security(tickerid, tim, close),security(tickerid, tim, open))
if (longCondition)
strategy.entry("long", strategy.long)
//陽線 → 陰線で売り
shortCondition = crossunder(security(tickerid, tim, close),security(tickerid, tim, open))
if (shortCondition)
strategy.entry("short", strategy.short)
=====
このストラテジーは、
security関数で答えがわかってる状態で売買をしています。
勝てて当然ですね。
むしろ、勝率が100%でないことが不思議です。
Pine講座㊺ バックテスト|Consecutive Up/Down Strategy の解説連続陽線・連続陰線で途転売買していくストラテジーです。
これで、内蔵のストラテジーはすべて完了です!
次回以降は、サードパーティのものを確認して、
Pine講座もそろそろお終いですね。
※ TradingView内蔵のストラテジーを
上から順番に解説しています
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy( "Consecutive Up/Down Strategy の解説", overlay=false )
//連続の数を設定
consecutiveBarsUp = input(3)
consecutiveBarsDown = input(3)
price = close
//連続上昇をカウント
ups = 0.0
ups := price > price[1] ? nz(ups[1]) + 1 : 0
//連続下降をカウント
dns = 0.0
dns := price < price[1] ? nz(dns[1]) + 1 : 0
//連続上昇が設定値以上のとき
if (ups >= consecutiveBarsUp)
//買いエントリー
strategy.entry("ConsUpLE", strategy.long, comment="ConsUpLE")
//連続下降が設定値以上のとき
if (dns >= consecutiveBarsDown)
//売りエントリー
strategy.entry("ConsDnSE", strategy.short, comment="ConsDnSE")
plot( ups ,color=color.red )
plot( dns ,color=color.blue )
=====
Pine講座㊹ バックテスト|Volty Expan Close Strategy の解説勢いがある値動きが出てきたときに、
その方向に順張りするロジックです。
自動売買は、一般的なテクニカル指標よりも、
実際の値動きに近い判断をするスキームの方が
良い結果がでる印象があります。
※ TradingView内蔵のストラテジーを
上から順番に解説しています
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy("Volty Expan Close Strategy の解説", overlay=true)
//計算用の数値の設定
length = input(5)
numATRs = input(0.75)
// ATR × N の算出
atrs = sma(tr, length)*numATRs
//算出に足る期間があることを確認
if (not na(close[length]))
//バンドの上に買いの逆指値、下に売りの逆指値を設置
strategy.entry("VltClsLE", strategy.long, stop=close+atrs, comment = "VltClsLE")
strategy.entry("VltClsSE", strategy.short, stop=close-atrs, comment = "VltClsSE")
//確認用で描画
plot( close + atrs )
plot( close - atrs )
=====
Pine講座㊸ バックテスト|Pivot Extension Startegy の解説Pivot high、Pivot lowを検出して
順張りしていくStrategyです。
※ TradingView内蔵のストラテジーを
上から順番に解説しています
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy( "Pivot Extension Strategy の解説" ,overlay=true )
//計算用の設定値
leftBars = input(4)
rightBars = input(2)
//pivot high、pivot lowの算出
ph = pivothigh(leftBars, rightBars)
pl = pivotlow(leftBars, rightBars)
//pivot lowに該当する数値がある
if (not na(pl))
//成行で買いエントリー
strategy.entry("PivExtLE", strategy.long, comment="PivExtLE")
//pivot highに該当する数値がある
if (not na(ph))
//成行で売りエントリー
strategy.entry("PivExtSE", strategy.short, comment="PivExtSE")
//確認用で描画
plot( ph ,style=plot.style_circles ,color=color.red ,linewidth=3 )
plot( pl ,style=plot.style_circles ,color=color.red ,linewidth=3 )
=====
Pine講座㊹ バックテスト|Pivot Reversal Strategy の解説pivot high、pivot lowのブレイクによる途転売買ですね。
割と成績が良さそうです。
※ TradingView内蔵のストラテジーを
上から順番に解説しています
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy( "Pivot Reversal Strategy の解説", overlay=true )
//計算用の数値の設定
leftBars = input(4)
rightBars = input(2)
//pivot high と pivot low の算出
//検出すると値が入り、ないときはna
swh = pivothigh( leftBars, rightBars )
swl = pivotlow( leftBars, rightBars )
//swhの値の有無を確認
swh_cond = not na(swh)
//最新のswh価格を格納しておく
hprice = 0.0
hprice := swh_cond ? swh : hprice
//Long Entry の判断
//pivot high が検出されたら発火
le = false
le := swh_cond ? true : (le and high > hprice ? false : le )
if (le)
//pivot high の1ティック上で逆指値
strategy.entry("PivRevLE", strategy.long, comment="PivRevLE", stop=hprice + syminfo.mintick)
//以下、買いエントリーの逆
swl_cond = not na(swl)
lprice = 0.0
lprice := swl_cond ? swl : lprice
se = false
se := swl_cond ? true : (se and low < lprice ? false : se )
if (se)
strategy.entry("PivRevSE", strategy.short, comment="PivRevSE", stop=lprice - syminfo.mintick)
//確認用で描画
plot( swh ,offset=-2 ,style=plot.style_circles ,linewidth=3 ,color=color.red )
plot( swl ,offset=-2 ,style=plot.style_circles ,linewidth=3 ,color=color.red )
plot( hprice )
plot( lprice )
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
=====
Pine講座㊸ バックテスト|Price Channel Strategy(チャネルブレイクアウトで途転)エントリーのロジックは
タートルズが用いていた手法と同じものです。
ひたすら途転していきます。
トレンドがないと勝てない戦略ですね。
※ TradingView内蔵のストラテジーを
上から順番に解説しています
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
=====
//@version=4
strategy("Price Channel Strategy の解説", overlay=true)
length = input(20)
//期間の最高値を算出
hh = highest( high, length )
//期間の最安値を算出
ll = lowest( low, length )
//設定期間以上、ローソク足が生成されていることを確認
if ( not na( close[length] ) )
//常にレンジの上限・下限に逆指値注文を入れておく
strategy.entry( "PChLE", strategy.long, comment="PChLE", stop=hh )
strategy.entry( "PChSE", strategy.short, comment="PChSE", stop=ll )
//確認用で描画
plot( hh ,offset=1 )
plot( ll ,offset=1 )
=====
Pine講座㊷ バックテスト|OutSide Bar Strategy の解説(つつみ足の途転戦略)今回はつつみ足の戦略です。
テクニカル指標を算出する必要がないので、
コードも非常にシンプルですね。
※ TradingView内蔵のストラテジーを
上から順番に解説しています
※ 解説はコードの中で
※ コピペする場合は以下の変更を行ってください
[](全角の角括弧)→(半角の角括弧)
(全角スペース)→(半角スペース)
==========
//@version=4
strategy("OutSide Bar Strategy の解説", overlay=true)
//つつみ足を検出したら
if (high > high[1] and low < low[1])
//陽線の場合
if (close > open)
//成行の買い注文
strategy.entry("OutBarLE", strategy.long, comment="OutBarLE")
//陰線の場合
if (close < open)
//成行の売り注文
strategy.entry("OutBarSE", strategy.short, comment="OutBarSE")
==========