見出し画像

Pine Script™ (v5) の覚書 - 4 : MTF移動平均線を表示する (3)

前回までの話。


labelを再定義して移動平均線にlabelを追加

複数の移動平均線を描くと、チャート上の線がそれぞれ何なのか分かりにくくなるので、何の線なのか確認できるようにlabelを追加する。

labelとその引数

label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) → series label

label にはたくさんの引数があるが、今回は、移動平均線を区別するために、
1.移動平均線の右(x座標: 最新のローソク足の2本右、y座標: 移動平均の最新値)
2.移動平均線と同じ色の文字(textcolor)
3.吹き出しは使わない(style)
という移動平均線用のlabelを次のように再定義する。

ma_label(x, y, labeltext="", textcolor=color.blue)=>
    var l=label.new(na, na, labeltext,textcolor=textcolor, style=label.style_none)
    l.set_xy(x,y)
    l

この ma_label は、スクリプトの最初に引数のtextdataとtextcolorでlabelオブジェクトを生成し、足が変わるごとにxyの座標(ラベルの表示位置)を更新する。
複数の移動平均線に追加すると以下となる。

//@version=5
indicator("マイスクリプト", overlay=true)

ma_label(x, y, labeltext="", textcolor=color.blue)=>
    var l=label.new(na, na, labeltext, textcolor=textcolor, style=label.style_none)
    l.set_xy(x,y)
    l

sma20=ta.sma(close,20)
sma20_4H=request.security(syminfo.tickerid, "240", ta.sma(close,20))
sma20_D=request.security(syminfo.tickerid, "D", ta.sma(close,20))

plot(sma20, "20移動平均", color.aqua,1)
mylabel1=ma_label(bar_index+2, sma20, "20移動平均", color.aqua)
plot(sma20_4H, "20移動平均(4H)", color.yellow,2)
mylabel2=ma_label(bar_index+2, sma20_4H, "20移動平均(4H)", color.yellow)
plot(sma20_D, "20移動平均(D)", color.red, 3)
mylabel3=ma_label(bar_index+2, sma20_D, "20移動平均(D)", color.red)

これをチャートへ反映してみると図1のようになる。

図1 各時間足SMAに判別用のラベルをつける


この記事が気に入ったらサポートをしてみませんか?