Untitled

 avatar
unknown
plain_text
a year ago
34 kB
44
Indexable
//@version=5
indicator("Trendlines",overlay=true,max_bars_back = 500)


prd = input.int(defval=10, title='Pivot Period', minval=4, maxval=30, group='Settings')
ppsrc = input.string(defval='High/Low', title='Source', options=['High/Low', 'Close/Open'], group ='')
ChannelW = input.int(defval=5, title='Maximum Channel Width %', minval=1, maxval=8, group='Settings ')
minstrength = input.int(defval=1, title='Minimum Strength', minval=1, group='Settings ')
maxnumsr = input.int(defval=6, title='Maximum Number of S/R', minval=1, maxval=10, group='Settings ') - 1
loopback = input.int(defval=290, title='Loopback Period', minval=100, maxval=400, group='Settings ')

showch = input.bool(defval=true, title='Channel SR', inline='')
showsr = input.bool(defval=true, title='SR lines', inline='')


res_col =  input.color(defval=#ff525240,title='Resistance Color', group='Colors')
sup_col =  input.color(defval=#00e67640,title='Support Color', group='Colors')
inch_col = input.color(defval=#787b8640,title='Color When Price in Channel', group='Colors')

showpp = input.bool(defval=false, title='Show Pivot Points', group='Extras')
showsrbroken = input.bool(defval=false, title='Show Broken Support/Resistance', group='Extras')
drawhl = input(true, title='high/low')


// get Pivot High/low
float src1 = ppsrc == 'High/Low' ? high : math.max(close, open)
float src2 = ppsrc == 'High/Low' ? low : math.min(close, open)
float ph = ta.pivothigh(src1, prd, prd)
float pl = ta.pivotlow(src2, prd, prd)

// draw Pivot points
plotshape(ph and showpp, text='H', style=shape.labeldown, color=na, textcolor=#ff5252, location=location.abovebar, offset=-prd)
plotshape(pl and showpp, text='L', style=shape.labelup, color=na, textcolor=#00e676, location=location.belowbar, offset=-prd)

//calculate maximum S/R channel width
prdhighest = ta.highest(300)
prdlowest = ta.lowest(300)
cwidth = (prdhighest - prdlowest) * ChannelW / 100

// get/keep Pivot levels
var pivotvals = array.new_float(0)
var pivotlocs = array.new_float(0)
if ph or pl and showch
    array.unshift(pivotvals, ph ? ph : pl)
    array.unshift(pivotlocs, bar_index)
    for x = array.size(pivotvals) - 1 to 0 by 1
        if bar_index - array.get(pivotlocs, x) > loopback  // remove old pivot points
            array.pop(pivotvals)
            array.pop(pivotlocs)
            continue
        break


//find/create SR channel of a pivot point
get_sr_vals(ind) =>
    float lo = array.get(pivotvals, ind)
    float hi = lo
    int numpp = 0
    for y = 0 to array.size(pivotvals) - 1 by 1
        float cpp = array.get(pivotvals, y)
        float wdth = cpp <= hi ? hi - cpp : cpp - lo
        if wdth <= cwidth  // fits the max channel width?
            if cpp <= hi
                lo := math.min(lo, cpp)
                lo
            else
                hi := math.max(hi, cpp)
                hi

            numpp += 20  // each pivot point added as 20
            numpp
    [hi, lo, numpp]

// keep old SR channels and calculate/sort new channels if we met new pivot point
var suportresistance = array.new_float(20, 0)  // min/max levels
changeit(x, y) =>
    tmp = array.get(suportresistance, y * 2)
    array.set(suportresistance, y * 2, array.get(suportresistance, x * 2))
    array.set(suportresistance, x * 2, tmp)
    tmp := array.get(suportresistance, y * 2 + 1)
    array.set(suportresistance, y * 2 + 1, array.get(suportresistance, x * 2 + 1))
    array.set(suportresistance, x * 2 + 1, tmp)

if ph or pl and showch
    supres = array.new_float(0)  // number of pivot, strength, min/max levels
    stren = array.new_float(10, 0)
    // get levels and strengs
    for x = 0 to array.size(pivotvals) - 1 by 1
        [hi, lo, strength] = get_sr_vals(x)
        array.push(supres, strength)
        array.push(supres, hi)
        array.push(supres, lo)

    // add each HL to strengh
    for x = 0 to array.size(pivotvals) - 1 by 1
        h = array.get(supres, x * 3 + 1)
        l = array.get(supres, x * 3 + 2)
        s = 0
        for y = 0 to loopback by 1
            if high[y] <= h and high[y] >= l or low[y] <= h and low[y] >= l
                s += 1
                s
        array.set(supres, x * 3, array.get(supres, x * 3) + s)

    //reset SR levels
    array.fill(suportresistance, 0)
    // get strongest SRs
    src = 0
    for x = 0 to array.size(pivotvals) - 1 by 1
        stv = -1.  // value
        stl = -1  // location
        for y = 0 to array.size(pivotvals) - 1 by 1
            if array.get(supres, y * 3) > stv and array.get(supres, y * 3) >= minstrength * 20
                stv := array.get(supres, y * 3)
                stl := y
                stl
        if stl >= 0
            //get sr level
            hh = array.get(supres, stl * 3 + 1)
            ll = array.get(supres, stl * 3 + 2)
            array.set(suportresistance, src * 2, hh)
            array.set(suportresistance, src * 2 + 1, ll)
            array.set(stren, src, array.get(supres, stl * 3))

            // make included pivot points' strength zero 
            for y = 0 to array.size(pivotvals) - 1 by 1
                if array.get(supres, y * 3 + 1) <= hh and array.get(supres, y * 3 + 1) >= ll or array.get(supres, y * 3 + 2) <= hh and array.get(supres, y * 3 + 2) >= ll
                    array.set(supres, y * 3, -1)

            src += 1
            if src >= 10
                break

    for x = 0 to 8 by 1
        for y = x + 1 to 9 by 1
            if array.get(stren, y) > array.get(stren, x)
                tmp = array.get(stren, y)
                array.set(stren, y, array.get(stren, x))
                changeit(x, y)
get_level(ind) =>
    float ret = na
    if ind < array.size(suportresistance)
        if array.get(suportresistance, ind) != 0
            ret := array.get(suportresistance, ind)
            ret
    ret

get_color(ind) =>
    color ret = na
    if ind < array.size(suportresistance) and showch
        if array.get(suportresistance, ind) != 0
            ret := array.get(suportresistance, ind) > close and array.get(suportresistance, ind + 1) > close ? res_col : array.get(suportresistance, ind) < close and array.get(suportresistance, ind + 1) < close ? sup_col : inch_col
            ret
    ret

var srchannels = array.new_box(10)
for x = 0 to math.min(9, maxnumsr) by 1
    box.delete(array.get(srchannels, x))
    srcol = get_color(x * 2)
    if not na(srcol) and showch
        array.set(srchannels, x, box.new(left=bar_index, top=get_level(x * 2), right=bar_index + 1, bottom=get_level(x * 2 + 1), border_color=srcol, border_width=1, extend=extend.both, bgcolor=srcol))

resistancebroken = false
supportbroken = false

// check if it's not in a channel
not_in_a_channel = true
for x = 0 to math.min(9, maxnumsr) by 1
    if close <= array.get(suportresistance, x * 2) and close >= array.get(suportresistance, x * 2 + 1)
        not_in_a_channel := false
        not_in_a_channel

// if price is not in a channel then check broken ones
if not_in_a_channel and showch
    for x = 0 to math.min(9, maxnumsr) by 1
        if close[1] <= array.get(suportresistance, x * 2) and close > array.get(suportresistance, x * 2)
            resistancebroken := true
            resistancebroken
        if close[1] >= array.get(suportresistance, x * 2 + 1) and close < array.get(suportresistance, x * 2 + 1)
            supportbroken := true
            supportbroken

alertcondition(resistancebroken, title='Resistance Broken', message='Resistance Broken')
alertcondition(supportbroken, title='Support Broken', message='Support Broken')

plotshape(showsrbroken and resistancebroken, style=shape.triangleup, location=location.belowbar, color=#00e676, size=size.tiny)
plotshape(showsrbroken and supportbroken, style=shape.triangledown, location=location.abovebar, color=#ff5252, size=size.tiny)



rb = input.int(10, title='Period for Pivot Points', minval=10)
prd1 = input.int(284, title='Loopback Period', minval=100, maxval=500)
nump = input.int(2, title='S/R strength', minval=1)
ChannelW1 = input.int(10, title='Channel Width %', minval=5)
linestyle = input.string('Dashed', title='Line Style', options=['Solid', 'Dotted', 'Dashed'])
LineColor = input(#ff525240, title='line color')
label_location = input.int(2, title='level')

ph1 = ta.pivothigh(rb, rb)
pl1 = ta.pivotlow(rb, rb)

// S/R levels
sr_levels = array.new_float(21, na)

// if number of bars is less then the loop then pine highest() fundtion brings 'na'. we need highest/lowest to claculate channel size
// so you cannot see S/R until the number of bars is equal/greater then the "Loopback Period" 
prdhighest1 = ta.highest(prd1)
prdlowest1 = ta.lowest(prd1)
cwidth1 = (prdhighest1 - prdlowest1) * ChannelW1 / 100

//availability of the PPs
aas = array.new_bool(41, true)

// last privot points have more priority to be support/resistance, so we start from them
// if we met new Pivot Point then we calculate all supports/resistances again
u1 = 0.0
u1 := nz(u1[1])
d1 = 0.0
d1 := nz(d1[1])
highestph = 0.0
lowestpl = 0.0
highestph := highestph[1]
lowestpl := lowestpl[1]
if ph1 or pl1 and showsr
    //old S/Rs not valid anymore
    for x = 0 to array.size(sr_levels) - 1 by 1
        array.set(sr_levels, x, na)
    highestph := prdlowest1
    lowestpl := prdhighest1
    countpp = 0  // keep position of the PP
    for x = 0 to prd1 by 1
        if na(close[x])
            break
        if not na(ph1[x]) or not na(pl1[x])  // is it PP?
            highestph := math.max(highestph, nz(ph1[x], prdlowest1), nz(pl1[x], prdlowest1))
            lowestpl := math.min(lowestpl, nz(ph1[x], prdhighest1), nz(pl1[x], prdhighest1))
            countpp += 1
            if countpp > 40
                break
            if array.get(aas, countpp)  // if PP is not used in a channel
                upl = (ph1[x] ? high[x + rb] : low[x + rb]) + cwidth1
                dnl = (ph1[x] ? high[x + rb] : low[x + rb]) - cwidth1
                u1 := countpp == 1 ? upl : u1
                d1 := countpp == 1 ? dnl : d1
                // to keep the PPs which will be in current channel
                tmp = array.new_bool(41, true)
                cnt = 0  // keep which pivot point we are on
                tpoint = 0  // number of PPs in the channel 
                for xx = 0 to prd1 by 1
                    if na(close[xx])
                        break
                    if not na(ph1[xx]) or not na(pl1[xx])
                        chg = false
                        cnt += 1
                        if cnt > 40
                            break
                        if array.get(aas, cnt)  // if PP not used in other channels
                            if not na(ph1[xx])
                                if high[xx + rb] <= upl and high[xx + rb] >= dnl  // PP is in the channel?
                                    tpoint += 1
                                    chg := true
                                    chg
                            if not na(pl1[xx])
                                if low[xx + rb] <= upl and low[xx + rb] >= dnl  // PP is in the channel?
                                    tpoint += 1
                                    chg := true
                                    chg
                        // set if PP is used in the channel
                        if chg and cnt < 41
                            array.set(tmp, cnt, false)
                if tpoint >= nump  // met enough PP in the channel? mark the PP as used for a channel and set the SR level
                    for g = 0 to 40 by 1
                        if not array.get(tmp, g)
                            array.set(aas, g, false)
                    if ph1[x] and countpp < 21
                        array.set(sr_levels, countpp, high[x + rb])
                    if pl1[x] and countpp < 21
                        array.set(sr_levels, countpp, low[x + rb])
setline(level) =>
    LineStyle = linestyle == 'Solid' ? line.style_solid : linestyle == 'Dotted' ? line.style_dotted : line.style_solid
    _ret = line.new(bar_index - 1, level, bar_index, level, color=LineColor, width=1, style=LineStyle, extend=extend.both)
    _ret

if ph1 or pl1 and showsr
    var line highest_ = na
    var line lowest_ = na
    line.delete(highest_)
    line.delete(lowest_)
    if drawhl  and showsr
        highest_ := line.new(bar_index - 1, highestph, bar_index, highestph, color=#f50000e8, style=line.style_solid, width=1, extend=extend.both)
        lowest_ := line.new(bar_index - 1,  lowestpl, bar_index,  lowestpl,  color=#f8000040, style=line.style_solid, width=1, extend=extend.both)
        lowest_

    var sr_lines = array.new_line(21, na)
    for x = 0 to array.size(sr_lines) - 1 by 1
        line.delete(array.get(sr_lines, x))
        if array.get(sr_levels, x) and showsr
            array.set(sr_lines, x, setline(array.get(sr_levels, x)))

// set new labels if changed
var sr_levs = array.new_float(21, na)
if ph1 or pl1 and showsr
    for x = 0 to array.size(sr_levs) - 1 by 1
        array.set(sr_levs, x, array.get(sr_levels, x))

// define and delete old labels
label hlabel = na
label llabel = na
label.delete(hlabel[1])
label.delete(llabel[1])
var sr_labels = array.new_label(21, na)
bool resistance_broken = false
bool support_broken = false
float r_s_level = na
// set labels
for x = 0 to array.size(sr_labels) - 1 by 1
    label.delete(array.get(sr_labels, x))
    if array.get(sr_levs, x) and showsr
        if close[1] <= array.get(sr_levs, x) and close > array.get(sr_levs, x) and showsr
            resistance_broken := true
            r_s_level := array.get(sr_levs, x)
            r_s_level
        if close[1] >= array.get(sr_levs, x) and close < array.get(sr_levs, x) and showsr
            support_broken := true
            r_s_level := array.get(sr_levs, x)
            r_s_level
        lab_loc = close >= array.get(sr_levs, x) ? label.style_label_up : label.style_label_down
        array.set(sr_labels, x, label.new(x=bar_index + label_location, y=array.get(sr_levs, x), text=str.tostring(math.round_to_mintick(array.get(sr_levs, x))), color=#ff0202, textcolor=#20ff02fd, style=lab_loc))

hlabel := drawhl and showsr ? label.new(x=bar_index + label_location + math.round(math.sign(label_location)) *  100, y=highestph, text='DİRENÇ ' + str.tostring(highestph),   color=#fa0404, textcolor=#0037ff, style=label.style_label_down) : na
llabel := drawhl and showsr  ? label.new(x=bar_index + label_location + math.round(math.sign(label_location)) * 100, y=lowestpl,   text='DESTEK ' + str.tostring(lowestpl), color=#20ff02fd, textcolor=color.rgb(255, 2, 2), style=label.style_label_up) : na
alertcondition(resistance_broken,   title='Direnç',   message='Direnç,  Close Price:   {{close}}, Direnç seviyesi = n/     {{plot("RS_level")}}')
alertcondition(support_broken,      title='Destek',   message='Destek,  Close Price:   {{close}}, destek seviyesi = n/     {{plot("RS_level")}}')



//TREND ÇİZGİLERİ

// // Getting inputs
bar_back_1=input.int(title='supertrend 1',defval=21,inline='b',group='Settings')
color_upline_1=input.color(title='',defval=#7418FF,inline='b',group='Settings')
color_down_line_1=input.color(title='',defval=color.aqua,inline='b',group='Settings')
show_1=input.bool(title='Show',defval=false,inline='b',group='Settings')
bar_back_2=input.int(title='supertrend 2',defval=51,inline='b',group='Settings')
color_upline_2=input.color(title='',defval=#FF1493,inline='b',group='Settings')
color_down_line_2=input.color(title='',defval=#04E01A,inline='b',group='Settings')
show_2=input.bool(title='Show',defval=false,inline='b',group='Settings')
bar_back_3=input.int(title='supertrend 3',defval=150,inline='c',group='Settings')
color_upline_3=input.color(title='',defval=color.red,inline='c',group='Settings')
color_down_line_3=input.color(title='',defval=#FFCC00,inline='c',group='Settings')
show_3=input.bool(title='Show',defval=false,inline='c',group='Settings')
leftLenH = input.int(title="High", defval=1, minval=1, inline="d",group='Pivot')
rightLenH = input.int(title="Right", defval=1, minval=0, inline="d",group='Pivot')
leftLenL = input.int(title="Low ", defval=1, minval=1, inline="e", group='Pivot')
rightLenL = input.int(title="Left", defval=1, minval=0, inline="e",group='Pivot')
delay=input.int(title='Day       ',defval=3,group='Pivot',inline='f')
input=input.int(defval=200,title="back    ",minval=2,group='Pivot',inline='f')
pivot_high2_source=input.source(defval=high,title='high',inline='q',group='candle')
pivot_low_source=input.source(defval=low,title='low',inline='q',group='candle')
bullish_candle=input.color(title='',defval=color.green,inline='r',group='candle')
bearish_candle=input.color(title='',defval=color.maroon,inline='r',group='candle')
// //
var pivot_low=array.new_float(input,0)
var pivot_low_index=array.new_int(input,0)
var pivot_high2=array.new_float(input,0)
var pivot_high2_index=array.new_int(input,0)
counter=array.new_int(6)
array_index_num=array.new_int(6)
first_point_value=array.new_float(6)  
first_point_index=array.new_int(6)
second_point_value=array.new_float(6)  
second_point_index=array.new_int(6) 
var trend_line=array.new_line(6)
var extend_line=array.new_line(6)
ph_TR = ta.pivothigh(pivot_high2_source[delay],leftLenH, rightLenH)
pl_TR = ta.pivotlow(pivot_low_source[delay] ,leftLenL, rightLenL)
////--------- Trend line calculating-------//
import_pivot_to_array(pvt,pivot,pivot_index,rightLen)=>
    if not na(pvt)    
        if array.size(pivot)>(input-1)
            array.shift(pivot)
            array.shift(pivot_index)
            array.push(pivot,pvt)
            array.push(pivot_index,bar_index-rightLen-delay)
        else
            array.push(pivot,pvt)
            array.push(pivot_index,bar_index-rightLen-delay)
limit_start_index(counter,array_index,pivot_index)=>
    max_bar=math.max(bar_back_1,bar_back_2,bar_back_3)
    if array.size(pivot_high2_index)-1>1 and bar_index>max_bar
        count_1=0
        count_2=0
        count_3=0
        for i=array.size(pivot_index)-1 to 0
            if array.get(pivot_index,i)<bar_index-bar_back_3 and count_3==0 
                count_3:=1
                array.set(counter,array_index+2,i+1)
            if array.get(pivot_index,i)<bar_index-bar_back_2 and count_2==0 
                count_2:=1
                array.set(counter,array_index+1,i+1)
            if array.get(pivot_index,i)<bar_index-bar_back_1 and count_1==0 
                count_1:=1
                array.set(counter,array_index,i+1)
            if count_1==1 and count_2==1 and count_3==1
                break
first_point_of_line(counter,array_index_num,array_index,first_point_value,first_point_index,pivot,pivot_index,pivot_statuse)=>
    if array.get(counter,array_index)<=(input-1)
        for i=array.get(counter,array_index) to (input-1)
            if ( (array.get(pivot,i)>array.get(first_point_value,array_index) or na(array.get(first_point_value,array_index)) ) and pivot_statuse=='high' ) or
             ( (array.get(pivot,i)<array.get(first_point_value,array_index) or na(array.get(first_point_value,array_index)) ) and pivot_statuse=='low' )      
                array.set(array_index_num,array_index,i)
                array.set(first_point_value,array_index,array.get(pivot,i))
                array.set(first_point_index,array_index,array.get(pivot_index,i))
scecond_point_and_draw_line(array_index_num,array_index,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot,pivot_index,pivot_statuse) =>
    if array.get(array_index_num,array_index)<input-1
        array.set(second_point_value,array_index,array.get(pivot,array.get(array_index_num,array_index)+1))
        array.set(second_point_index,array_index,array.get(pivot_index,array.get(array_index_num,array_index)+1))
        line.delete(array.get(trend_line,array_index))
        array.set(trend_line,array_index,line.new(array.get(first_point_index,array_index),array.get(first_point_value,array_index) ,array.get(second_point_index,array_index),array.get(second_point_value,array_index) ,color=color.blue,width=1,style=line.style_arrow_right) )
        for i=(array.get(array_index_num,array_index)+1) to (input-1)
            if (line.get_price(array.get(trend_line,array_index),array.get(pivot_index,i))<array.get(pivot,i) and pivot_statuse=='high') or
             (line.get_price(array.get(trend_line,array_index),array.get(pivot_index,i))>array.get(pivot,i) and pivot_statuse=='low')
                array.set(second_point_value,array_index,array.get(pivot,i))
                array.set(second_point_index,array_index,array.get(pivot_index,i))
                line.delete(array.get(trend_line,array_index))
                array.set(trend_line,array_index,line.new(array.get(first_point_index,array_index),array.get(first_point_value,array_index) ,array.get(second_point_index,array_index),array.get(second_point_value,array_index) ,color=color.blue,width=1,style=line.style_arrow_right) )
line_edit(trend_line,extend_line,array_index,line_color)=>
    line.set_color(array.get(trend_line,array_index),line_color)
    line.set_xy2(array.get(trend_line,array_index),bar_index[delay],line.get_price(array.get(trend_line,array_index),bar_index[delay]))
    line.delete(array.get(extend_line,array_index))
    array.set(extend_line,array_index,line.new(line.get_x2(array.get(trend_line,array_index)),line.get_y2(array.get(trend_line,array_index)),bar_index,line.get_price(array.get(trend_line,array_index),bar_index),style=line.style_dashed,color=line_color,extend=extend.right))
import_pivot_to_array(ph_TR,pivot_high2,pivot_high2_index,rightLenH)
limit_start_index(counter,0,pivot_high2_index)
import_pivot_to_array(pl_TR,pivot_low,pivot_low_index,rightLenL)
limit_start_index(counter,3,pivot_low_index)
if show_1
    first_point_of_line(counter,array_index_num,0,first_point_value,first_point_index,pivot_high2,pivot_high2_index,'high')
    scecond_point_and_draw_line(array_index_num,0,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot_high2,pivot_high2_index,'high')
    line_edit(trend_line,extend_line,0,color_upline_1)
    first_point_of_line(counter,array_index_num,3,first_point_value,first_point_index,pivot_low,pivot_low_index,'low')
    scecond_point_and_draw_line(array_index_num,3,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot_low,pivot_low_index,'low')
    line_edit(trend_line,extend_line,3,color_down_line_1)
if show_2
    first_point_of_line(counter,array_index_num,1,first_point_value,first_point_index,pivot_high2,pivot_high2_index,'high')
    scecond_point_and_draw_line(array_index_num,1,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot_high2,pivot_high2_index,'high')
    line_edit(trend_line,extend_line,1,color_upline_2)
    first_point_of_line(counter,array_index_num,4,first_point_value,first_point_index,pivot_low,pivot_low_index,'low')
    scecond_point_and_draw_line(array_index_num,4,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot_low,pivot_low_index,'low')
    line_edit(trend_line,extend_line,4,color_down_line_2)
if show_3
    first_point_of_line(counter,array_index_num,2,first_point_value,first_point_index,pivot_high2,pivot_high2_index,'high')
    scecond_point_and_draw_line(array_index_num,2,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot_high2,pivot_high2_index,'high')
    line_edit(trend_line,extend_line,2,color_upline_3)
    first_point_of_line(counter,array_index_num,5,first_point_value,first_point_index,pivot_low,pivot_low_index,'low')
    scecond_point_and_draw_line(array_index_num,5,trend_line,first_point_value,first_point_index,second_point_value,second_point_index,pivot_low,pivot_low_index,'low')
    line_edit(trend_line,extend_line,5,color_down_line_3)

var int history_bars = input(title='History bars back', defval=300,group = "OTOMATİK TREND")
show_fibo = input(false,"Fibo gösterilsin mi?",group = "SEÇENEKLER")
show_ttfibo = input(false,"Trend temelli Fibo gösterilsin mi?",group = "SEÇENEKLER")
col_sup = color.new(#4ffa5a, 0)
style_sup = line.style_solid
col_res = color.new(#fa5050, 0)
style_res = line.style_solid

// Функция вычисляет цену в точке t3 для линии,
// заданной первыми четырьмя координатами (t1, p1, t2, p2)
price_at(t1, p1, t2, p2, t3) =>
    p1 + (p2 - p1) * (t3 - t1) / (t2 - t1)

// Alerts
if 1 == 1
    alert('test')
// округление
round_to_tick(x) =>
    mult = 1 / syminfo.mintick
    value = math.ceil(x * mult) / mult
    value

// Тут храним линии для удаления при появлении нового бара
var line[] supports = array.new_line()
var line[] resistances = array.new_line()
var label[] labels = array.new_label()

fire_alert_sup = false
fire_alert_res = false
fire_alert_sup := false
fire_alert_res := false
// Удаляем прошлые линии и заодно вызываем алерты
line temp_line = na
if array.size(supports) > 0
    for i = array.size(supports) - 1 to 0 by 1
        temp_line := array.get(supports, i)
        if low[1] > line.get_price(temp_line, bar_index - 1) and close < line.get_price(temp_line, bar_index)
            fire_alert_sup := true
            fire_alert_sup
        line.delete(temp_line)
        array.remove(supports, i)
if array.size(resistances) > 0
    for i = array.size(resistances) - 1 to 0 by 1
        temp_line := array.get(resistances, i)
        if high[1] < line.get_price(temp_line, bar_index - 1) and close > line.get_price(temp_line, bar_index)
            fire_alert_res := true
            fire_alert_res
        line.delete(temp_line)
        array.remove(resistances, i)
label temp_label = na
if array.size(labels) > 0
    for i = array.size(labels) - 1 to 0 by 1
        temp_label := array.get(labels, i)
        label.delete(temp_label)
        array.remove(labels, i)


alertcondition(fire_alert_sup, 'Diagonal Support Alert', 'Diagonal support crossed down')
alertcondition(fire_alert_res, 'Diagonal Resistance Alert', 'Diagonal resistance crossed up')

// Определяем экстремумы
min_values = low
max_values = high
x1 = input(title='Resolution (bars)', defval=6,group = "OTOMATİK TREND")
x2 = math.round(x1 / 2)
int minimums = 0
minimums := ta.lowestbars(min_values, x1) == -x2 ? x2 : minimums[1] + 1

int maximums = 0
maximums := ta.highestbars(max_values, x1) == -x2 ? x2 : maximums[1] + 1


int minimum1 = 0
int minimum2 = 0
int maximum1 = 0
int maximum2 = 0
int medium = 0
// Поддержка     
if barstate.islast
    //label.new(bar_index, close , style=label.style_labeldown, text=timeframe.period, color=color.new(color.red, 90))
    line last_line = na
    label last_label = na
    for k1 = 0 to 50 by 1
        if minimum1 >= history_bars
            break
        minimum1 += minimums[minimum1]
        minimum2 := minimum1 * 2
        for k2 = 0 to 50 by 1
            if minimum2 >= minimum1 * 8 or minimum2 >= history_bars
                break
            minimum2 += minimums[minimum2]

            if minimum1 >= history_bars or minimum2 >= history_bars
                break

            bar1 = bar_index - minimum1
            bar2 = bar_index - minimum2

            price1 = low[minimum1]
            price2 = low[minimum2]

            current_price = price_at(bar2, price2, bar1, price1, bar_index)
            // Если поддержка проходит ниже текущей цены
            if current_price < high[1]

                // проверяем пересечения
                crossed = 0
                medium := 0
                for k3 = 0 to 50 by 1
                    if medium >= minimum2
                        break
                    medium += minimums[medium]
                    if medium >= minimum2
                        break
                    if price_at(bar2, price2, bar1, price1, bar_index - medium) > math.min(open[medium], close[medium])
                        crossed := 1
                        break

                // если нет пересечений        
                if crossed == 0  // and overtilt == 0
                    // сравниваем с прошлой созданной линией
                    if not na(last_line)
                        last_price = price_at(line.get_x1(last_line), line.get_y1(last_line), line.get_x2(last_line), line.get_y2(last_line), bar_index)
                        if bar1 == line.get_x2(last_line)
                            if current_price > last_price
                                line.set_xy1(last_line, bar2, price2)
                                line.set_xy2(last_line, bar1, price1)
                                line.set_color(last_line, col_sup)
                                label.set_xy(last_label, bar_index, current_price)
                                label.set_text(last_label, str.tostring(round_to_tick(current_price)))
                                true
                        else
                            last_line := line.new(bar2, price2, bar1, price1, extend=extend.right, color=col_sup, style=style_sup,width = 5)
                            last_label := label.new(bar_index, current_price, color=col_sup, style=label.style_label_upper_left, text=str.tostring(round_to_tick(current_price)))
                            array.push(labels, last_label)
                            array.push(supports, last_line)
                            true
                    else
                    // добавляем линию
                        last_line := line.new(bar2, price2, bar1, price1, extend=extend.right, color=col_sup, style=style_sup,width = 5)
                        last_label := label.new(bar_index, current_price, color=col_sup, style=label.style_label_upper_left, text=str.tostring(round_to_tick(current_price)))
                        array.push(labels, last_label)
                        array.push(supports, last_line)
                        true

    last_line := na
    last_label := na
    for k1 = 0 to 100 by 1
        if maximum1 >= history_bars
            break
        maximum1 += maximums[maximum1]
        maximum2 := maximum1 * 2
        for k2 = 0 to 50 by 1
            if maximum2 >= maximum1 * 8 or maximum2 >= history_bars
                break
            maximum2 += maximums[maximum2]

            if maximum1 >= history_bars or maximum2 >= history_bars
                break

            bar1 = bar_index - maximum1
            bar2 = bar_index - maximum2

            price1 = high[maximum1]
            price2 = high[maximum2]

            current_price = price_at(bar2, price2, bar1, price1, bar_index)
            // Если сопротивоение проходит выше текущей цены
            if current_price > low[1]

                // проверяем пересечения
                crossed = 0
                medium := 0
                for k3 = 0 to 100 by 1
                    if medium >= maximum2
                        break
                    medium += maximums[medium]
                    if medium >= maximum2
                        break
                    if price_at(bar2, price2, bar1, price1, bar_index - medium) < math.max(open[medium], close[medium])
                        crossed := 1
                        break

                // если нет пересечений        
                if crossed == 0  // and overtilt == 0
                    // сравниваем с прошлой созданной линией
                    if not na(last_line)
                        last_price = price_at(line.get_x1(last_line), line.get_y1(last_line), line.get_x2(last_line), line.get_y2(last_line), bar_index)
                        if bar1 == line.get_x2(last_line)
                            if current_price < last_price
                                line.set_xy1(last_line, bar2, price2)
                                line.set_xy2(last_line, bar1, price1)
                                line.set_color(last_line, col_res)
                                label.set_xy(last_label, bar_index, current_price)
                                label.set_text(last_label, str.tostring(round_to_tick(current_price)))

                                true
                        else
                            last_line := line.new(bar2, price2, bar1, price1, extend=extend.right, color=col_res, style=style_res,width = 5)
                            last_label := label.new(bar_index, current_price, color=col_res, style=label.style_label_lower_left, text=str.tostring(round_to_tick(current_price)))
                            array.push(labels, last_label)
                            array.push(resistances, last_line)
                            true
                    else
                    // добавляем линию
                        last_line := line.new(bar2, price2, bar1, price1, extend=extend.right, color=col_res, style=style_res,width = 5)
                        last_label := label.new(bar_index, current_price, color=col_res, style=label.style_label_lower_left, text=str.tostring(round_to_tick(current_price)))

                        array.push(labels, last_label)
                        array.push(resistances, last_line)
                        true
Leave a Comment