Abnormal bar % v.1
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EmoeTeam

//@version=5
indicator(title = "AbNorBar & VolBar", shorttitle="Bares", overlay=true)

//1. Блок по ATR

//1.1 Общие исходные данные которые можно менять

//Модуль про другие акции и их трендовое движение на выбраннном тайм фрейме

emas = input.bool(true, 'Hide EMA', tooltip = "EMA10, EMA20, EMA50, EMA100, EMA200")
blue_chips = input(false, 'Show blue chips', tooltip = "Show values of ablue chips")
tracking = input.timeframe('60', 'Time frame tracking', options = ['30', '60', '120', '240', 'D', '3D', 'W'])

// ATR
period = input.int(title="ATR Period", defval=14, minval=1, group = "ATR module input data", tooltip = "Select the number of bars on the basis of which the calculation will take place")
decimalsAtr = input.int(3, options=[1,2,3,4,5,6], title="Character count", tooltip = 'Number of decimal places and color on the ATR direction: green for rising ATRs, red for falling ones)', inline = 'ATR_group')
up_col_atr = input.color(#55b843ec,'Colors', inline = 'ATR_group')
dn_col_atr = input.color(#bc372d,'', inline = 'ATR_group')
neu_col_atr = input.color(#e3b80a,'', inline = 'ATR_group')

viewATR = input(false, 'Hide ATR', tooltip = 'Hide ATR data')

//1.2 Расчет Atr. Выделение цветом и абсолютные показатели atr, для рабочего ТФ.

atr_calc = ta.atr(period) 
atr_view = math.round(atr_calc, decimalsAtr)
SL_x1 = math.round(1.7 * atr_view, decimalsAtr)
SL_x2 = math.round(2.2 * atr_view, decimalsAtr)
SL_x3 = math.round(3.2 * atr_view, decimalsAtr)

timeframe = "60"
atr_day = ta.atr(5)
ticker = ticker.new(syminfo.prefix, syminfo.ticker, session = session.regular)
atr60 = request.security(ticker, "60", atr_day, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)


//2. Блок про VolColor (выделяем разным цветом бары взависимости от текущего объема)
//VolBar is based on the script Vol Color Bars (2015) by IldarAkhmetgaleev

//2.1 Общие исходные данные которые можно менять

std_period = input.int(49, minval=6, title='Period volume', group = "The color of the bars depending on the volume", tooltip = "The volume calculation will be for the specified number of bars. Defolt : 49 bars = 240 min + 1 bar (for 5 min Time Frame")

col1 = input.color(#E62117, title = "Extr", inline = "col_group")
col2 = input.color(#E66F17, title = "High", inline = "col_group")
col3 = input.color(#ffffff, title = "Norm", inline = "col_group")
col4 = input.color(#0E8F81, title = "Low", inline = "col_group")
col5 = input.color(#12B225, title = "No", tooltip = 'Extr - extrime high volume * High - volume is high  Norm - volume is normal * Low - volume is low ***** No - almost no volume', inline = "col_group")

thresshold1 = input.int(200, minval=0, title='h', inline = "thress") / 100
thresshold2 = input.int(300, minval=0, title='h2', inline = "thress") / 100
thresshold3 = input.int(50, minval=0, title='L', inline = "thress") / 100
thresshold4 = input.int(25, minval=0, title='L2', inline = "thress", tooltip = "Volume levels") / 100

colBar = input(false, 'Show Color Bar', tooltip = 'Выделять бары цветом (bar color)')

//2.2 Расчет и определение цвета бара на основание объема.

avg = ta.stdev(volume, std_period)
highvol1 = volume > avg * thresshold1
highvol2 = volume > avg * thresshold2
lowvol1 = volume < avg * thresshold3
lowvol2 = volume < avg * thresshold4

color_bar = colBar ? highvol2 ? col1 : highvol1 ? col2 : lowvol2 ? col5 : lowvol1 ? col4 : col3 : na

//2.3 Вывод данных о цвете на экран

barcolor (color_bar, editable = false)

//2.4 Сигнал
alertcondition(volume < avg * thresshold3, title = "Low volume", message = "Low volume, maybe there is accumulation before the next impulse. Низкий объем, возможено идет накопление перед импульсом.")
  
//3. Блок про аномальный бар (Abnormal Bar)

//3.1 Исходные данные для расчета аномального бара

bar_period = input.int(14, minval=5, title='Calculate the average for the period', group = "Input data for the search for anomalous bars", tooltip = "Select the number of bars, but on the basis of which the calculation will be made")
decimals = input.int(2, title="character count", tooltip = 'Number of decimal places, when displaying data on the graph')
abnormal = input.int(50, title ="anomalous bar", tooltip = 'Bar greater than the average value by a specified value (in %) - consider an abnormal bar')
Ext_col = input.color(#da3434f5,'Extr', inline = 'Abnorm_group')
//Hi_col = input.color(#dc8e1a,'High', inline = 'Abnorm_group')
//Low_col = input.color(#27ace1,'Low', inline = 'Abnorm_group', tooltip = "Color: abnormal bar > avg.bar more than 105% - ext_color; > avg.bar 40-75% - hi_color; > avg.bar up to 40% - low_color")
abnormallyBar = input(false, 'Show normal bars', tooltip = "Show values of abnormal bars")

//3.2 Расчеты для определения аномальных баров.

avg_bar_abs = ta.rma((high-low), bar_period)
avg_bar = ta.rma((high*100/low)-100, bar_period) //Средний размер бара, за выбранный период (в процентах)
avg_bar_dec = math.round(avg_bar, decimals)
sup_res = avg_bar_abs * 2

abnorm_bar = (avg_bar + avg_bar * abnormal/100) //определение аномального бара
abnorm_bar_dec = math.round(avg_bar, decimals) //округление, значения анамального бара

cur_bar = ((high*100/low)-100)
cur_bar_dec = math.round(cur_bar, decimals)
cur_bar_abs = (high-low)

up_atr_text_col = cur_bar_abs < atr_calc
dn_atr_text_col = cur_bar_abs > atr_calc

atr_text_col = up_atr_text_col ? up_col_atr : dn_atr_text_col ? dn_col_atr : neu_col_atr

//3.3 Вывод данных на график

//1.3 Вывод на экран. Значение текущего ATR, значения для SL и направление движения ATR (цвет - зеленый atr растет, красный - atr, снижается)

var CELL_TOOLTIP = "Cell color depends on the ATR direction: green for rising ATRs, red for falling one. Not to be confused with the direction of the TREND.  ATR - shows the volatility !!!"

color_bg_atr = (atr_calc > atr_calc[2] and atr_calc[2] > atr_calc[4] and atr_calc > atr_calc[4] ? up_col_atr :
  atr_calc < atr_calc[2] and atr_calc[2] < atr_calc[4] and atr_calc < atr_calc[4] ? dn_col_atr : neu_col_atr)

var tb_ATR = table.new(position.bottom_left, 7, 7, border_width = 2)

if barstate.islast and not viewATR
    headerColor = color.new(#42434c, 50)
    table.cell(tb_ATR, 0, 0, (str.tostring(atr60, '#.##')), text_color = color.yellow, text_size = size.small, tooltip = "ATR ticker - 1H")
    table.cell(tb_ATR, 1, 0, (str.tostring(atr_view, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "ATR ticker  !!!" + CELL_TOOLTIP)
    //table.cell(tb_ATR, 0, 1, "ATR", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP)
    table.cell(tb_ATR, 2, 0, (str.tostring(SL_x1, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "1.7 x ATR ticker")
    //table.cell(tb_ATR, 1, 1, "1,5x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP)
    table.cell(tb_ATR, 3, 0, (str.tostring(SL_x2, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "2.2 x ATR ticker")
    //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP)
    table.cell(tb_ATR, 4, 0, (str.tostring(SL_x3, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "3.2 x ATR ticker")
    //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP)
    table.cell(tb_ATR, 5, 0, "🪫 ", text_size = size.small, text_halign = text.align_right)
    //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP)
    table.cell(tb_ATR, 6, 0, (str.tostring(cur_bar_abs, '#.####')), text_color = atr_text_col, text_size = size.normal, text_halign = text.align_left, tooltip ="ATR progress of the current bar")
    //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP)
    //table.cell(tb_ATR, 0, 1, '' , height = 2.5)
    //table.cell(tb_ATR, 0, 5, '' , height = 3)

if abnormallyBar ? cur_bar > avg_bar and  cur_bar >= abnorm_bar and cur_bar > avg_bar + avg_bar * 1.05 : na
    label_perc = label.new(bar_index, low, text=str.tostring(cur_bar_dec)+"\n", yloc=yloc.abovebar, textcolor = Ext_col, size = size.small, tooltip = "bar(%) more than average > 105% - ext_color", textalign = text.align_right)
    label.set_style(label_perc, label.style_none)
    label.set_text_font_family(label_perc, font.family_default)
//else if abnormallyBar ? cur_bar > avg_bar and  cur_bar >= abnorm_bar and cur_bar > avg_bar + avg_bar * 0.75 : na
    //label_perc = label.new(bar_index, low, text=str.tostring(cur_bar_dec)+"\n", yloc=yloc.abovebar, textcolor = Hi_col, size = size.small, tooltip = "bar(%) over average value between 40 and 75% - hi_color", textalign = text.align_right)
    //label.set_style(label_perc, label.style_none)
    //label.set_text_font_family(label_perc, font.family_default)
//else if abnormallyBar ? cur_bar > avg_bar and  cur_bar >= abnorm_bar and cur_bar > avg_bar + avg_bar * 0.4 : na
    //label_perc = label.new(bar_index, low, text=str.tostring(cur_bar_dec)+"\n", yloc=yloc.abovebar, textcolor = Low_col, size = size.small, tooltip = "bar(%) more than average value up to 40%  - low_color", textalign = text.align_right)
    //label.set_style(label_perc, label.style_none)
    //label.set_text_font_family(label_perc, font.family_default)

//var tb_temp = table.new(position.top_right, 5, 5)
//if barstate.islast
    //table.cell (tb_temp, 0, 0, "avg_bar : " +(str.tostring(avg_bar, '#.##')) + "%", text_size = size.small) 
    //table.cell (tb_temp, 0, 0, "", height = 2.5, text_size = size.small)
    //table.cell (tb_temp, 1, 0, (str.tostring(avg_bar_abs, '#.####')), text_size = size.small) 
    //table.cell (tb_temp, 1, 0,  "x2 - " + (str.tostring(sup_res, '#.####')), text_size = size.small, text_color = color.yellow) 


//3.4 Сигналы
alertcondition(cur_bar > avg_bar + avg_bar * 1.05, title = "ExTreme abnormal Bar", message = "ExTreme abnormal Bar, the current value is 105% higher than the average value  - Экстримальный бар")
//alertcondition(cur_bar > avg_bar + avg_bar * 0.75, title = "Abnormal Bar", message = "Abnormal Bar, the current value is 75% higher than the average value - Высокий бар")

alertcondition(color_bg_atr == up_col_atr, title = "Волотильность растет" , message = "Волатильность растет")
alertcondition(color_bg_atr == dn_col_atr, title = "Волотильность падает" , message = "Волатильность падает")
alertcondition(color_bar == col5, title = "Нет объемов" , message = "Объемов практически нет, оценить ситуацию по тикеру")

// 4 Ориентация по другим тикерам
// code author - @AzzraelCode

fn(ticker) => request.security(ticker, tracking, open/close)

var per = 9
var tickers = array.from('LKOH', 'SBER', 'GAZP', 'GMKN', 'NLMK', 'NVTK', 'YNDX', 'ROSN', 'TATN', 'SNGS', 'MGNT', 'TCSG', 'PLZL', 'POLY', 'IMOEX', 'RTSI', 'ALRS', 'CHMF', 'RUAL', 'MAGN', 'VTBR', 'VKCO', 'OZON', 'FIVE', 'RASP', 'MX1')
vals = array.from(fn('LKOH'), fn('SBER'), fn('GAZP'), fn('GMKN'), fn('NLMK'), fn('NVTK'), fn('YNDX'), fn('ROSN'), fn('TATN'), fn('SNGS'), fn('MGNT'), fn('TCSG'), fn('PLZL'), fn('POLY'), fn('IMOEX'), fn('RTSI'), fn('ALRS'), fn('CHMF'), fn('RUAL'), fn ('MAGN'), fn('VTBR'), fn('VKCO'), fn('OZON'), fn('FIVE'), fn('RASP'), fn('MX1'))

var size = array.size(tickers)
var tbl3 = table.new(position.bottom_right, 30, 30, border_width=1)

if barstate.islast and blue_chips
    for i=0 to array.size(tickers)-1
        
        col = i % per
        row = math.ceil((i+1)/per)-1
        //col = math.ceil((i+1)/per)-1
        //row = i % per
        
        ticker := array.get(tickers, i)
        val = array.get(vals, i)
        
        table.cell(tbl3, col, row, ticker, text_halign=text.align_center, bgcolor=val > 1 ? color.rgb(156, 57, 57, 10):color.rgb(48, 150, 51, 10), text_color=color.white, text_size=size.small)

/// EMAS ///
//вводные данные

out1 = ta.ema(close, 8) 
out2 = ta.ema(close, 21)
out3 = ta.ema(close, 50)
out4 = ta.ema(close, 18)
out5 = ta.ema(close, 200)

//Вывод на экран

view10 = plot(emas ? out1 : na, title="ema 8", color=color.rgb(29, 120, 15, 2), linewidth=2, offset = 3)
view20 = plot(emas ? out2 : na, title="ema 21", color=color.rgb(193, 27, 27, 12), linewidth=2, offset = 5)
view50 = plot(emas ? out3 : na, title="ema 50", color=color.rgb(43, 27, 227, 10), linewidth=2, offset = 5)
view100 = plot(emas ? out4 : na, title="ema 18", color=color.rgb(30, 207, 227, 14), linewidth=2, offset = 3)
view200 = plot(emas ? out5 : na, title="ema 200", color=color.rgb(207, 139, 22, 11), linewidth=2, offset = 8)

//Границы недели
useGMTOffsetInput = input.bool(false, "Use GMT Offset?", group="Timezone")
gmtOffsetInput = input.int(0, "GMT Offset", minval=-24, maxval=24, step=1, group="Timezone")

showMon = input(true, title="Show Monday?")

stateSession = syminfo.session

timezoneString = "GMT" + (gmtOffsetInput > 0 ? "+" : "") + str.tostring(gmtOffsetInput)
stateTimeZone = useGMTOffsetInput ? timezoneString : syminfo.timezone

isMon() => dayofweek(time('D', stateSession, stateTimeZone)) == dayofweek.monday

defTransp = 70
bgcolor(showMon and isMon() ? color.new(color.silver, defTransp) : na, title="Monday color")
