0% found this document useful (0 votes)
116 views259 pages

15th Jan 25

Uploaded by

Stanley Rajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views259 pages

15th Jan 25

Uploaded by

Stanley Rajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 259

//@version=2

////////////////////////////////////////////////////////////

// Copyright by HPotter v1.0 21/08/2018

// Simply input the vales of the high, low and closing price of the previous

// period to calculate the Woodie pivot point and the associated resistance

// and support levels for the present period.

//

// WARNING:

// - This script to change bars colors.

////////////////////////////////////////////////////////////

study(title="Woodie Pivot Points Strategy", overlay = true)

width = input(2, minval=1)

xHigh = security(tickerid,"D", high[1])

xLow = security(tickerid,"D", low[1])

xClose = security(tickerid,"D", close[1])

xPP = (xHigh+xLow+(xClose*2)) / 4

pos = iff(close[1] < xPP[1] and close > xPP, 1,

iff(close < xPP, -1, nz(pos[1], 0)))

barcolor(pos == -1 ? red: pos == 1 ? green : blue )

plot(xPP, color=blue, title="WPP", style = circles, linewidth = width)


// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
https://creativecommons.org/licenses/by-nc-sa/4.0/

// © LuxAlgo

//@version=5

indicator("Smart Money Concepts [LuxAlgo]", "Smart Money Concepts [LuxAlgo]"

, overlay = true

, max_labels_count = 500

, max_lines_count = 500

, max_boxes_count = 500

, max_bars_back = 500)

//-----------------------------------------------------------------------------{

//Constants

//-----------------------------------------------------------------------------{

color TRANSP_CSS = #ffffff00

//Tooltips

string MODE_TOOLTIP = 'Allows to display historical Structure or only the recent ones'
string STYLE_TOOLTIP = 'Indicator color theme'

string COLOR_CANDLES_TOOLTIP = 'Display additional candles with a color reflecting the current trend detected by structure'

string SHOW_INTERNAL = 'Display internal market structure'

string CONFLUENCE_FILTER = 'Filter non significant internal structure breakouts'

string SHOW_SWING = 'Display swing market Structure'

string SHOW_SWING_POINTS = 'Display swing point as labels on the chart'

string SHOW_SWHL_POINTS = 'Highlight most recent strong and weak high/low points on the chart'

string INTERNAL_OB = 'Display internal order blocks on the chart\n\nNumber of internal order blocks to display on the chart'

string SWING_OB = 'Display swing order blocks on the chart\n\nNumber of internal swing blocks to display on the chart'

string FILTER_OB = 'Method used to filter out volatile order blocks \n\nIt is recommended to use the cumulative mean range method when a low
amount of data is available'

string SHOW_EQHL = 'Display equal highs and equal lows on the chart'

string EQHL_BARS = 'Number of bars used to confirm equal highs and equal lows'

string EQHL_THRESHOLD = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows\n\nLower values will return fewer but
more pertinent results'

string SHOW_FVG = 'Display fair values gaps on the chart'

string AUTO_FVG = 'Filter out non significant fair value gaps'

string FVG_TF = 'Fair value gaps timeframe'

string EXTEND_FVG = 'Determine how many bars to extend the Fair Value Gap boxes on chart'

string PED_ZONES = 'Display premium, discount, and equilibrium zones on chart'


//-----------------------------------------------------------------------------{

//Settings

//-----------------------------------------------------------------------------{

//General

//----------------------------------------{

mode = input.string('Historical'

, options = ['Historical', 'Present']

, group = 'Smart Money Concepts'

, tooltip = MODE_TOOLTIP)

style = input.string('Colored'

, options = ['Colored', 'Monochrome']

, group = 'Smart Money Concepts'

, tooltip = STYLE_TOOLTIP)

show_trend = input(false, 'Color Candles'

, group = 'Smart Money Concepts'

, tooltip = COLOR_CANDLES_TOOLTIP)

//----------------------------------------}
//Internal Structure

//----------------------------------------{

show_internals = input(true, 'Show Internal Structure'

, group = 'Real Time Internal Structure'

, tooltip = SHOW_INTERNAL)

show_ibull = input.string('All', 'Bullish Structure'

, options = ['All', 'BOS', 'CHoCH']

, inline = 'ibull'

, group = 'Real Time Internal Structure')

swing_ibull_css = input(#089981, ''

, inline = 'ibull'

, group = 'Real Time Internal Structure')

//Bear Structure

show_ibear = input.string('All', 'Bearish Structure'

, options = ['All', 'BOS', 'CHoCH']

, inline = 'ibear'

, group = 'Real Time Internal Structure')


swing_ibear_css = input(#f23645, ''

, inline = 'ibear'

, group = 'Real Time Internal Structure')

ifilter_confluence = input(false, 'Confluence Filter'

, group = 'Real Time Internal Structure'

, tooltip = CONFLUENCE_FILTER)

internal_structure_size = input.string('Tiny', 'Internal Label Size'

, options = ['Tiny', 'Small', 'Normal']

, group = 'Real Time Internal Structure')

//----------------------------------------}

//Swing Structure

//----------------------------------------{

show_Structure = input(true, 'Show Swing Structure'

, group = 'Real Time Swing Structure'

, tooltip = SHOW_SWING)
//Bull Structure

show_bull = input.string('All', 'Bullish Structure'

, options = ['All', 'BOS', 'CHoCH']

, inline = 'bull'

, group = 'Real Time Swing Structure')

swing_bull_css = input(#089981, ''

, inline = 'bull'

, group = 'Real Time Swing Structure')

//Bear Structure

show_bear = input.string('All', 'Bearish Structure'

, options = ['All', 'BOS', 'CHoCH']

, inline = 'bear'

, group = 'Real Time Swing Structure')

swing_bear_css = input(#f23645, ''

, inline = 'bear'

, group = 'Real Time Swing Structure')


swing_structure_size = input.string('Small', 'Swing Label Size'

, options = ['Tiny', 'Small', 'Normal']

, group = 'Real Time Swing Structure')

//Swings

show_swings = input(false, 'Show Swings Points'

, inline = 'swings'

, group = 'Real Time Swing Structure'

, tooltip = SHOW_SWING_POINTS)

length = input.int(50, ''

, minval = 10

, inline = 'swings'

, group = 'Real Time Swing Structure')

show_hl_swings = input(true, 'Show Strong/Weak High/Low'

, group = 'Real Time Swing Structure'

, tooltip = SHOW_SWHL_POINTS)

//----------------------------------------}
//Order Blocks

//----------------------------------------{

show_iob = input(true, 'Internal Order Blocks'

, inline = 'iob'

, group = 'Order Blocks'

, tooltip = INTERNAL_OB)

iob_showlast = input.int(5, ''

, minval = 1

, inline = 'iob'

, group = 'Order Blocks')

show_ob = input(false, 'Swing Order Blocks'

, inline = 'ob'

, group = 'Order Blocks'

, tooltip = SWING_OB)

ob_showlast = input.int(5, ''

, minval = 1

, inline = 'ob'
, group = 'Order Blocks')

ob_filter = input.string('Atr', 'Order Block Filter'

, options = ['Atr', 'Cumulative Mean Range']

, group = 'Order Blocks'

, tooltip = FILTER_OB)

ibull_ob_css = input.color(color.new(#3179f5, 80), 'Internal Bullish OB'

, group = 'Order Blocks')

ibear_ob_css = input.color(color.new(#f77c80, 80), 'Internal Bearish OB'

, group = 'Order Blocks')

bull_ob_css = input.color(color.new(#1848cc, 80), 'Bullish OB'

, group = 'Order Blocks')

bear_ob_css = input.color(color.new(#b22833, 80), 'Bearish OB'

, group = 'Order Blocks')

//----------------------------------------}
//EQH/EQL

//----------------------------------------{

show_eq = input(true, 'Equal High/Low'

, group = 'EQH/EQL'

, tooltip = SHOW_EQHL)

eq_len = input.int(3, 'Bars Confirmation'

, minval = 1

, group = 'EQH/EQL'

, tooltip = EQHL_BARS)

eq_threshold = input.float(0.1, 'Threshold'

, minval = 0

, maxval = 0.5

, step = 0.1

, group = 'EQH/EQL'

, tooltip = EQHL_THRESHOLD)

eq_size = input.string('Tiny', 'Label Size'

, options = ['Tiny', 'Small', 'Normal']


, group = 'EQH/EQL')

//----------------------------------------}

//Fair Value Gaps

//----------------------------------------{

show_fvg = input(false, 'Fair Value Gaps'

, group = 'Fair Value Gaps'

, tooltip = SHOW_FVG)

fvg_auto = input(true, "Auto Threshold"

, group = 'Fair Value Gaps'

, tooltip = AUTO_FVG)

fvg_tf = input.timeframe('', "Timeframe"

, group = 'Fair Value Gaps'

, tooltip = FVG_TF)

bull_fvg_css = input.color(color.new(#00ff68, 70), 'Bullish FVG'

, group = 'Fair Value Gaps')


bear_fvg_css = input.color(color.new(#ff0008, 70), 'Bearish FVG'

, group = 'Fair Value Gaps')

fvg_extend = input.int(1, "Extend FVG"

, minval = 0

, group = 'Fair Value Gaps'

, tooltip = EXTEND_FVG)

//----------------------------------------}

//Previous day/week high/low

//----------------------------------------{

//Daily

show_pdhl = input(false, 'Daily'

, inline = 'daily'

, group = 'Highs & Lows MTF')

pdhl_style = input.string('⎯⎯⎯', ''

, options = ['⎯⎯⎯', '----', '····']

, inline = 'daily'

, group = 'Highs & Lows MTF')


pdhl_css = input(#2157f3, ''

, inline = 'daily'

, group = 'Highs & Lows MTF')

//Weekly

show_pwhl = input(false, 'Weekly'

, inline = 'weekly'

, group = 'Highs & Lows MTF')

pwhl_style = input.string('⎯⎯⎯', ''

, options = ['⎯⎯⎯', '----', '····']

, inline = 'weekly'

, group = 'Highs & Lows MTF')

pwhl_css = input(#2157f3, ''

, inline = 'weekly'

, group = 'Highs & Lows MTF')

//Monthly
show_pmhl = input(false, 'Monthly'

, inline = 'monthly'

, group = 'Highs & Lows MTF')

pmhl_style = input.string('⎯⎯⎯', ''

, options = ['⎯⎯⎯', '----', '····']

, inline = 'monthly'

, group = 'Highs & Lows MTF')

pmhl_css = input(#2157f3, ''

, inline = 'monthly'

, group = 'Highs & Lows MTF')

//----------------------------------------}

//Premium/Discount zones

//----------------------------------------{

show_sd = input(false, 'Premium/Discount Zones'

, group = 'Premium & Discount Zones'

, tooltip = PED_ZONES)
premium_css = input.color(#f23645, 'Premium Zone'

, group = 'Premium & Discount Zones')

eq_css = input.color(#b2b5be, 'Equilibrium Zone'

, group = 'Premium & Discount Zones')

discount_css = input.color(#089981, 'Discount Zone'

, group = 'Premium & Discount Zones')

//-----------------------------------------------------------------------------}

//Functions

//-----------------------------------------------------------------------------{

n = bar_index

atr = ta.atr(200)

cmean_range = ta.cum(high - low) / n

//HL Output function

hl() => [high, low]


//Get ohlc values function

get_ohlc()=> [close[1], open[1], high, low, high[2], low[2]]

//Display Structure function

display_Structure(x, y, txt, css, dashed, down, lbl_size)=>

structure_line = line.new(x, y, n, y

, color = css

, style = dashed ? line.style_dashed : line.style_solid)

structure_lbl = label.new(int(math.avg(x, n)), y, txt

, color = TRANSP_CSS

, textcolor = css

, style = down ? label.style_label_down : label.style_label_up

, size = lbl_size)

if mode == 'Present'

line.delete(structure_line[1])

label.delete(structure_lbl[1])

//Swings detection/measurements
swings(len)=>

var os = 0

upper = ta.highest(len)

lower = ta.lowest(len)

os := high[len] > upper ? 0 : low[len] < lower ? 1 : os[1]

top = os == 0 and os[1] != 0 ? high[len] : 0

btm = os == 1 and os[1] != 1 ? low[len] : 0

[top, btm]

//Order block coordinates function

ob_coord(use_max, loc, target_top, target_btm, target_left, target_type)=>

min = 99999999.

max = 0.

idx = 1

ob_threshold = ob_filter == 'Atr' ? atr : cmean_range


//Search for highest/lowest high within the structure interval and get range

if use_max

for i = 1 to (n - loc)-1

if (high[i] - low[i]) < ob_threshold[i] * 2

max := math.max(high[i], max)

min := max == high[i] ? low[i] : min

idx := max == high[i] ? i : idx

else

for i = 1 to (n - loc)-1

if (high[i] - low[i]) < ob_threshold[i] * 2

min := math.min(low[i], min)

max := min == low[i] ? high[i] : max

idx := min == low[i] ? i : idx

array.unshift(target_top, max)

array.unshift(target_btm, min)

array.unshift(target_left, time[idx])

array.unshift(target_type, use_max ? -1 : 1)
//Set order blocks

display_ob(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size)=>

for i = 0 to math.min(show_last-1, size-1)

get_box = array.get(boxes, i)

box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top, i))

box.set_rightbottom(get_box, array.get(target_left, i), array.get(target_btm, i))

box.set_extend(get_box, extend.right)

color css = na

if swing

if style == 'Monochrome'

css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) : color.new(#5d606b, 80)

border_css = array.get(target_type, i) == 1 ? #b2b5be : #5d606b

box.set_border_color(get_box, border_css)

else

css := array.get(target_type, i) == 1 ? bull_ob_css : bear_ob_css

box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)

else

if style == 'Monochrome'

css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) : color.new(#5d606b, 80)

else

css := array.get(target_type, i) == 1 ? ibull_ob_css : ibear_ob_css

box.set_border_color(get_box, css)

box.set_bgcolor(get_box, css)

//Line Style function

get_line_style(style) =>

out = switch style

'⎯⎯⎯' => line.style_solid

'----' => line.style_dashed

'····' => line.style_dotted

//Set line/labels function for previous high/lows

phl(h, l, tf, css)=>

var line high_line = line.new(na,na,na,na


, xloc = xloc.bar_time

, color = css

, style = get_line_style(pdhl_style))

var label high_lbl = label.new(na,na

, xloc = xloc.bar_time

, text = str.format('P{0}H', tf)

, color = TRANSP_CSS

, textcolor = css

, size = size.small

, style = label.style_label_left)

var line low_line = line.new(na,na,na,na

, xloc = xloc.bar_time

, color = css

, style = get_line_style(pdhl_style))

var label low_lbl = label.new(na,na

, xloc = xloc.bar_time

, text = str.format('P{0}L', tf)


, color = TRANSP_CSS

, textcolor = css

, size = size.small

, style = label.style_label_left)

hy = ta.valuewhen(h != h[1], h, 1)

hx = ta.valuewhen(h == high, time, 1)

ly = ta.valuewhen(l != l[1], l, 1)

lx = ta.valuewhen(l == low, time, 1)

if barstate.islast

ext = time + (time - time[1])*20

//High

line.set_xy1(high_line, hx, hy)

line.set_xy2(high_line, ext, hy)

label.set_xy(high_lbl, ext, hy)


//Low

line.set_xy1(low_line, lx, ly)

line.set_xy2(low_line, ext, ly)

label.set_xy(low_lbl, ext, ly)

//-----------------------------------------------------------------------------}

//Global variables

//-----------------------------------------------------------------------------{

var trend = 0, var itrend = 0

var top_y = 0., var top_x = 0

var btm_y = 0., var btm_x = 0

var itop_y = 0., var itop_x = 0

var ibtm_y = 0., var ibtm_x = 0

var trail_up = high, var trail_dn = low

var trail_up_x = 0, var trail_dn_x = 0


var top_cross = true, var btm_cross = true

var itop_cross = true, var ibtm_cross = true

var txt_top = '', var txt_btm = ''

//Alerts

bull_choch_alert = false

bull_bos_alert = false

bear_choch_alert = false

bear_bos_alert = false

bull_ichoch_alert = false

bull_ibos_alert = false

bear_ichoch_alert = false

bear_ibos_alert = false

bull_iob_break = false

bear_iob_break = false
bull_ob_break = false

bear_ob_break = false

eqh_alert = false

eql_alert = false

//Structure colors

var bull_css = style == 'Monochrome' ? #b2b5be

: swing_bull_css

var bear_css = style == 'Monochrome' ? #b2b5be

: swing_bear_css

var ibull_css = style == 'Monochrome' ? #b2b5be

: swing_ibull_css

var ibear_css = style == 'Monochrome' ? #b2b5be

: swing_ibear_css
//Labels size

var internal_structure_lbl_size = internal_structure_size == 'Tiny'

? size.tiny

: internal_structure_size == 'Small'

? size.small

: size.normal

var swing_structure_lbl_size = swing_structure_size == 'Tiny'

? size.tiny

: swing_structure_size == 'Small'

? size.small

: size.normal

var eqhl_lbl_size = eq_size == 'Tiny'

? size.tiny

: eq_size == 'Small'

? size.small

: size.normal

//Swings
[top, btm] = swings(length)

[itop, ibtm] = swings(5)

//-----------------------------------------------------------------------------}

//Pivot High

//-----------------------------------------------------------------------------{

var line extend_top = na

var label extend_top_lbl = label.new(na, na

, color = TRANSP_CSS

, textcolor = bear_css

, style = label.style_label_down

, size = size.tiny)

if top

top_cross := true

txt_top := top > top_y ? 'HH' : 'LH'

if show_swings
top_lbl = label.new(n-length, top, txt_top

, color = TRANSP_CSS

, textcolor = bear_css

, style = label.style_label_down

, size = swing_structure_lbl_size)

if mode == 'Present'

label.delete(top_lbl[1])

//Extend recent top to last bar

line.delete(extend_top[1])

extend_top := line.new(n-length, top, n, top

, color = bear_css)

top_y := top

top_x := n - length

trail_up := top

trail_up_x := n - length
if itop

itop_cross := true

itop_y := itop

itop_x := n - 5

//Trailing maximum

trail_up := math.max(high, trail_up)

trail_up_x := trail_up == high ? n : trail_up_x

//Set top extension label/line

if barstate.islast and show_hl_swings

line.set_xy1(extend_top, trail_up_x, trail_up)

line.set_xy2(extend_top, n + 20, trail_up)

label.set_x(extend_top_lbl, n + 20)

label.set_y(extend_top_lbl, trail_up)

label.set_text(extend_top_lbl, trend < 0 ? 'Strong High' : 'Weak High')

//-----------------------------------------------------------------------------}
//Pivot Low

//-----------------------------------------------------------------------------{

var line extend_btm = na

var label extend_btm_lbl = label.new(na, na

, color = TRANSP_CSS

, textcolor = bull_css

, style = label.style_label_up

, size = size.tiny)

if btm

btm_cross := true

txt_btm := btm < btm_y ? 'LL' : 'HL'

if show_swings

btm_lbl = label.new(n - length, btm, txt_btm

, color = TRANSP_CSS

, textcolor = bull_css

, style = label.style_label_up

, size = swing_structure_lbl_size)
if mode == 'Present'

label.delete(btm_lbl[1])

//Extend recent btm to last bar

line.delete(extend_btm[1])

extend_btm := line.new(n - length, btm, n, btm

, color = bull_css)

btm_y := btm

btm_x := n-length

trail_dn := btm

trail_dn_x := n-length

if ibtm

ibtm_cross := true

ibtm_y := ibtm

ibtm_x := n - 5
//Trailing minimum

trail_dn := math.min(low, trail_dn)

trail_dn_x := trail_dn == low ? n : trail_dn_x

//Set btm extension label/line

if barstate.islast and show_hl_swings

line.set_xy1(extend_btm, trail_dn_x, trail_dn)

line.set_xy2(extend_btm, n + 20, trail_dn)

label.set_x(extend_btm_lbl, n + 20)

label.set_y(extend_btm_lbl, trail_dn)

label.set_text(extend_btm_lbl, trend > 0 ? 'Strong Low' : 'Weak Low')

//-----------------------------------------------------------------------------}

//Order Blocks Arrays

//-----------------------------------------------------------------------------{

var iob_top = array.new_float(0)

var iob_btm = array.new_float(0)

var iob_left = array.new_int(0)


var iob_type = array.new_int(0)

var ob_top = array.new_float(0)

var ob_btm = array.new_float(0)

var ob_left = array.new_int(0)

var ob_type = array.new_int(0)

//-----------------------------------------------------------------------------}

//Pivot High BOS/CHoCH

//-----------------------------------------------------------------------------{

//Filtering

var bull_concordant = true

if ifilter_confluence

bull_concordant := high - math.max(close, open) > math.min(close, open - low)

//Detect internal bullish Structure

if ta.crossover(close, itop_y) and itop_cross and top_y != itop_y and bull_concordant

bool choch = na
if itrend < 0

choch := true

bull_ichoch_alert := true

else

bull_ibos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_internals

if show_ibull == 'All' or (show_ibull == 'BOS' and not choch) or (show_ibull == 'CHoCH' and choch)

display_Structure(itop_x, itop_y, txt, ibull_css, true, true, internal_structure_lbl_size)

itop_cross := false

itrend := 1

//Internal Order Block

if show_iob

ob_coord(false, itop_x, iob_top, iob_btm, iob_left, iob_type)

//Detect bullish Structure


if ta.crossover(close, top_y) and top_cross

bool choch = na

if trend < 0

choch := true

bull_choch_alert := true

else

bull_bos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_Structure

if show_bull == 'All' or (show_bull == 'BOS' and not choch) or (show_bull == 'CHoCH' and choch)

display_Structure(top_x, top_y, txt, bull_css, false, true, swing_structure_lbl_size)

//Order Block

if show_ob

ob_coord(false, top_x, ob_top, ob_btm, ob_left, ob_type)

top_cross := false
trend := 1

//-----------------------------------------------------------------------------}

//Pivot Low BOS/CHoCH

//-----------------------------------------------------------------------------{

var bear_concordant = true

if ifilter_confluence

bear_concordant := high - math.max(close, open) < math.min(close, open - low)

//Detect internal bearish Structure

if ta.crossunder(close, ibtm_y) and ibtm_cross and btm_y != ibtm_y and bear_concordant

bool choch = false

if itrend > 0

choch := true

bear_ichoch_alert := true

else

bear_ibos_alert := true
txt = choch ? 'CHoCH' : 'BOS'

if show_internals

if show_ibear == 'All' or (show_ibear == 'BOS' and not choch) or (show_ibear == 'CHoCH' and choch)

display_Structure(ibtm_x, ibtm_y, txt, ibear_css, true, false, internal_structure_lbl_size)

ibtm_cross := false

itrend := -1

//Internal Order Block

if show_iob

ob_coord(true, ibtm_x, iob_top, iob_btm, iob_left, iob_type)

//Detect bearish Structure

if ta.crossunder(close, btm_y) and btm_cross

bool choch = na

if trend > 0

choch := true

bear_choch_alert := true
else

bear_bos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_Structure

if show_bear == 'All' or (show_bear == 'BOS' and not choch) or (show_bear == 'CHoCH' and choch)

display_Structure(btm_x, btm_y, txt, bear_css, false, false, swing_structure_lbl_size)

//Order Block

if show_ob

ob_coord(true, btm_x, ob_top, ob_btm, ob_left, ob_type)

btm_cross := false

trend := -1

//-----------------------------------------------------------------------------}

//Order Blocks

//-----------------------------------------------------------------------------{

//Set order blocks


var iob_boxes = array.new_box(0)

var ob_boxes = array.new_box(0)

//Delete internal order blocks box coordinates if top/bottom is broken

for element in iob_type

index = array.indexof(iob_type, element)

if close < array.get(iob_btm, index) and element == 1

array.remove(iob_top, index)

array.remove(iob_btm, index)

array.remove(iob_left, index)

array.remove(iob_type, index)

bull_iob_break := true

else if close > array.get(iob_top, index) and element == -1

array.remove(iob_top, index)

array.remove(iob_btm, index)

array.remove(iob_left, index)

array.remove(iob_type, index)

bear_iob_break := true
//Delete internal order blocks box coordinates if top/bottom is broken

for element in ob_type

index = array.indexof(ob_type, element)

if close < array.get(ob_btm, index) and element == 1

array.remove(ob_top, index)

array.remove(ob_btm, index)

array.remove(ob_left, index)

array.remove(ob_type, index)

bull_ob_break := true

else if close > array.get(ob_top, index) and element == -1

array.remove(ob_top, index)

array.remove(ob_btm, index)

array.remove(ob_left, index)

array.remove(ob_type, index)

bear_ob_break := true

iob_size = array.size(iob_type)
ob_size = array.size(ob_type)

if barstate.isfirst

if show_iob

for i = 0 to iob_showlast-1

array.push(iob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))

if show_ob

for i = 0 to ob_showlast-1

array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))

if iob_size > 0

if barstate.islast

display_ob(iob_boxes, iob_top, iob_btm, iob_left, iob_type, iob_showlast, false, iob_size)

if ob_size > 0

if barstate.islast

display_ob(ob_boxes, ob_top, ob_btm, ob_left, ob_type, ob_showlast, true, ob_size)

//-----------------------------------------------------------------------------}

//EQH/EQL
//-----------------------------------------------------------------------------{

var eq_prev_top = 0.

var eq_top_x = 0

var eq_prev_btm = 0.

var eq_btm_x = 0

if show_eq

eq_top = ta.pivothigh(eq_len, eq_len)

eq_btm = ta.pivotlow(eq_len, eq_len)

if eq_top

max = math.max(eq_top, eq_prev_top)

min = math.min(eq_top, eq_prev_top)

if max < min + atr * eq_threshold

eqh_line = line.new(eq_top_x, eq_prev_top, n-eq_len, eq_top

, color = bear_css

, style = line.style_dotted)
eqh_lbl = label.new(int(math.avg(n-eq_len, eq_top_x)), eq_top, 'EQH'

, color = #00000000

, textcolor = bear_css

, style = label.style_label_down

, size = eqhl_lbl_size)

if mode == 'Present'

line.delete(eqh_line[1])

label.delete(eqh_lbl[1])

eqh_alert := true

eq_prev_top := eq_top

eq_top_x := n-eq_len

if eq_btm

max = math.max(eq_btm, eq_prev_btm)

min = math.min(eq_btm, eq_prev_btm)

if min > max - atr * eq_threshold


eql_line = line.new(eq_btm_x, eq_prev_btm, n-eq_len, eq_btm

, color = bull_css

, style = line.style_dotted)

eql_lbl = label.new(int(math.avg(n-eq_len, eq_btm_x)), eq_btm, 'EQL'

, color = #00000000

, textcolor = bull_css

, style = label.style_label_up

, size = eqhl_lbl_size)

eql_alert := true

if mode == 'Present'

line.delete(eql_line[1])

label.delete(eql_lbl[1])

eq_prev_btm := eq_btm

eq_btm_x := n-eq_len

//-----------------------------------------------------------------------------}
//Fair Value Gaps

//-----------------------------------------------------------------------------{

var bullish_fvg_max = array.new_box(0)

var bullish_fvg_min = array.new_box(0)

var bearish_fvg_max = array.new_box(0)

var bearish_fvg_min = array.new_box(0)

float bullish_fvg_avg = na

float bearish_fvg_avg = na

bullish_fvg_cnd = false

bearish_fvg_cnd = false

[src_c1, src_o1, src_h, src_l, src_h2, src_l2] =

request.security(syminfo.tickerid, fvg_tf, get_ohlc())

if show_fvg

delta_per = (src_c1 - src_o1) / src_o1 * 100


change_tf = timeframe.change(fvg_tf)

threshold = fvg_auto ? ta.cum(math.abs(change_tf ? delta_per : 0)) / n * 2

:0

//FVG conditions

bullish_fvg_cnd := src_l > src_h2

and src_c1 > src_h2

and delta_per > threshold

and change_tf

bearish_fvg_cnd := src_h < src_l2

and src_c1 < src_l2

and -delta_per > threshold

and change_tf

//FVG Areas

if bullish_fvg_cnd

array.unshift(bullish_fvg_max, box.new(n-1, src_l, n + fvg_extend, math.avg(src_l, src_h2)

, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))

array.unshift(bullish_fvg_min, box.new(n-1, math.avg(src_l, src_h2), n + fvg_extend, src_h2

, border_color = bull_fvg_css

, bgcolor = bull_fvg_css))

if bearish_fvg_cnd

array.unshift(bearish_fvg_max, box.new(n-1, src_h, n + fvg_extend, math.avg(src_h, src_l2)

, border_color = bear_fvg_css

, bgcolor = bear_fvg_css))

array.unshift(bearish_fvg_min, box.new(n-1, math.avg(src_h, src_l2), n + fvg_extend, src_l2

, border_color = bear_fvg_css

, bgcolor = bear_fvg_css))

for bx in bullish_fvg_min

if low < box.get_bottom(bx)

box.delete(bx)

box.delete(array.get(bullish_fvg_max, array.indexof(bullish_fvg_min, bx)))


for bx in bearish_fvg_max

if high > box.get_top(bx)

box.delete(bx)

box.delete(array.get(bearish_fvg_min, array.indexof(bearish_fvg_max, bx)))

//-----------------------------------------------------------------------------}

//Previous day/week high/lows

//-----------------------------------------------------------------------------{

//Daily high/low

[pdh, pdl] = request.security(syminfo.tickerid, 'D', hl()

, lookahead = barmerge.lookahead_on)

//Weekly high/low

[pwh, pwl] = request.security(syminfo.tickerid, 'W', hl()

, lookahead = barmerge.lookahead_on)

//Monthly high/low

[pmh, pml] = request.security(syminfo.tickerid, 'M', hl()

, lookahead = barmerge.lookahead_on)
//Display Daily

if show_pdhl

phl(pdh, pdl, 'D', pdhl_css)

//Display Weekly

if show_pwhl

phl(pwh, pwl, 'W', pwhl_css)

//Display Monthly

if show_pmhl

phl(pmh, pml, 'M', pmhl_css)

//-----------------------------------------------------------------------------}

//Premium/Discount/Equilibrium zones

//-----------------------------------------------------------------------------{

var premium = box.new(na, na, na, na

, bgcolor = color.new(premium_css, 80)

, border_color = na)

var premium_lbl = label.new(na, na


, text = 'Premium'

, color = TRANSP_CSS

, textcolor = premium_css

, style = label.style_label_down

, size = size.small)

var eq = box.new(na, na, na, na

, bgcolor = color.rgb(120, 123, 134, 80)

, border_color = na)

var eq_lbl = label.new(na, na

, text = 'Equilibrium'

, color = TRANSP_CSS

, textcolor = eq_css

, style = label.style_label_left

, size = size.small)

var discount = box.new(na, na, na, na

, bgcolor = color.new(discount_css, 80)

, border_color = na)
var discount_lbl = label.new(na, na

, text = 'Discount'

, color = TRANSP_CSS

, textcolor = discount_css

, style = label.style_label_up

, size = size.small)

//Show Premium/Discount Areas

if barstate.islast and show_sd

avg = math.avg(trail_up, trail_dn)

box.set_lefttop(premium, math.max(top_x, btm_x), trail_up)

box.set_rightbottom(premium, n, .95 * trail_up + .05 * trail_dn)

label.set_xy(premium_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_up)

box.set_lefttop(eq, math.max(top_x, btm_x), .525 * trail_up + .475*trail_dn)

box.set_rightbottom(eq, n, .525 * trail_dn + .475 * trail_up)


label.set_xy(eq_lbl, n, avg)

box.set_lefttop(discount, math.max(top_x, btm_x), .95 * trail_dn + .05 * trail_up)

box.set_rightbottom(discount, n, trail_dn)

label.set_xy(discount_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_dn)

//-----------------------------------------------------------------------------}

//Trend

//-----------------------------------------------------------------------------{

var color trend_css = na

if show_trend

if style == 'Colored'

trend_css := itrend == 1 ? bull_css : bear_css

else if style == 'Monochrome'

trend_css := itrend == 1 ? #b2b5be : #5d606b

plotcandle(open, high, low, close

, color = trend_css

, wickcolor = trend_css
, bordercolor = trend_css

, editable = false)

//-----------------------------------------------------------------------------}

//Alerts

//-----------------------------------------------------------------------------{

//Internal Structure

alertcondition(bull_ibos_alert, 'Internal Bullish BOS', 'Internal Bullish BOS formed')

alertcondition(bull_ichoch_alert, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed')

alertcondition(bear_ibos_alert, 'Internal Bearish BOS', 'Internal Bearish BOS formed')

alertcondition(bear_ichoch_alert, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed')

//Swing Structure

alertcondition(bull_bos_alert, 'Bullish BOS', 'Internal Bullish BOS formed')

alertcondition(bull_choch_alert, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')

alertcondition(bear_bos_alert, 'Bearish BOS', 'Bearish BOS formed')

alertcondition(bear_choch_alert, 'Bearish CHoCH', 'Bearish CHoCH formed')


//order Blocks

alertcondition(bull_iob_break, 'Bullish Internal OB Breakout', 'Price broke bullish internal OB')

alertcondition(bear_iob_break, 'Bearish Internal OB Breakout', 'Price broke bearish internal OB')

alertcondition(bull_ob_break, 'Bullish Swing OB Breakout', 'Price broke bullish swing OB')

alertcondition(bear_ob_break, 'Bearish Swing OB Breakout', 'Price broke bearish swing OB')

//EQH/EQL

alertcondition(eqh_alert, 'Equal Highs', 'Equal highs detected')

alertcondition(eql_alert, 'Equal Lows', 'Equal lows detected')

//FVG

alertcondition(bullish_fvg_cnd, 'Bullish FVG', 'Bullish FVG formed')

alertcondition(bearish_fvg_cnd, 'Bearish FVG', 'Bearish FVG formed')

//-----------------------------------------------------------------------------}

//@version=5

strategy("Divergence Indicator / Strategy", shorttitle="Divergence", overlay = true)


UseInd = input.bool(false, "Use as an Indicator")

UseStr = input.bool(false, "Use as a Strategy")

enableDivbuy=input.bool(true, "Use Divergence", group="BUY OPTIONS")

enableImprBull=input.bool(false, "Use Div Imrpovements", group="BUY OPTIONS")

enableBias2long=input.bool(false, "Use SMI Multi TF filter", group="BUY OPTIONS")

enableMAlong=input.bool(false, "Use MA filter", group="BUY OPTIONS")

enableTlong=input.bool(false, "Filter Days and Hours", group="BUY OPTIONS")

enableDivsell=input.bool(true, "Use Divergence", group="SELL OPTIONS")

enableImprBear=input.bool(false, "Use Div Imrpovements", group="SELL OPTIONS")

enableBias2short=input.bool(false, "Use SMI Multi TF Filter", group="SELL OPTIONS")

enableMAshort=input.bool(false, "Use MA filter", group="SELL OPTIONS")

enableTshort=input.bool(false, "Filter Days and Hours", group="SELL OPTIONS")


emaEma(source, length) => ta.ema(ta.ema(source, length), length)

// === INPUTS

// || General Input:

method = input.string(defval='RSI', options=['RSI', 'Brown Composite Index', 'MACD', 'Stochastic', 'Volume', 'OBV', 'Accumulation/Distribution', 'Fisher
Transform', 'CCI', 'BB %B', 'Ideal RSI', 'Elders Force Index', 'Trend Acc Volume', 'ROC', 'MFI', 'Chande composite Momentum Index', 'Linear regression slope',
'SMI'], group = "Divergencies")

uHidb = input(false, title='Use Hidden Divergence for buy', group="Divergencies")

uHids = input(false, title='Use Hidden Divergence for sell', group="Divergencies")

uRegb = input(true, title='Use Regular Divergence for buy', group="Divergencies")

uRegs = input(true, title='Use Regular Divergence for sell', group="Divergencies")

// || RSI / STOCH / VOLUME / ACC/DIST/ FISHER/ CCI/ BB %B Input/ Elders Force Index/ ROC/ MFI/ Chande composite MI:

rsi_smooth = input(title='Length for Method (except MACD):', defval=20, group="Divergencies")

high_src = input(high,title="High Source", group="Divergencies")

low_src = input(low,title="Low Source", group="Divergencies")

lbR = input(title='Right Lookback for a Pivot', defval=2)

lbL = input(title='Left Lookback for a Pivot', defval=5)


rangeUpper = input(title='Maximum Range for Prev Extremum', defval=40)

rangeLower = input(title='Minimum Range for Prev Extremum', defval=6)

bearColor = color.red

bullColor = color.green

hiddenBullColor = color.new(color.green, 80)

hiddenBearColor = color.new(color.red, 80)

textColor = color.white

noneColor = color.new(color.white, 100)

// MACD Input:

macd_src = input(title='MACD Source:', defval=close, group="Div MACD")

macd_fast = input(title='MACD Fast:', defval=12, group="Div MACD")

macd_slow = input(title='MACD Slow:', defval=26, group="Div MACD")

macd_smooth = input(title='MACD Smooth Signal:', defval=9, group="Div MACD")

// Constance Brown Composite Index

r=ta.rsi(close, rsi_smooth)

rsidelta = ta.mom(r, 9)

rsisma = ta.sma(r, 3)
s=rsidelta+rsisma

// MACD FUNCTION

f_macd(_src, _fast, _slow, _smooth) =>

_fast_ma = ta.sma(_src, _fast)

_slow_ma = ta.sma(_src, _slow)

_macd = _fast_ma - _slow_ma

_signal = ta.ema(_macd, _smooth)

_hist = _macd - _signal

_hist

// START ACC/DIST FUNCTION

f_accdist(_smooth) =>

_return = ta.sma(ta.cum(close == high and close == low or high == low ? 0 : (2 * close - low - high) / (high - low) * volume), _smooth)

_return

// START FISHER FUNCTION

f_fisher(_src, _window) =>

_h = ta.highest(_src, _window)
_l = ta.lowest(_src, _window)

_value0 = 0.0

_value0 := .66 * ((_src - _l) / math.max(_h - _l, .001) - .5) + .67 * nz(_value0[1])

_value1 = _value0 > .99 ? .999 : _value0 < -.99 ? -.999 : _value0

_fisher = 0.0

_fisher := .5 * math.log((1 + _value1) / math.max(1 - _value1, .001)) + .5 * nz(_fisher[1])

_fisher

// Rolling Moving Average

irma(p, l) =>

irma = 0.0

irma := (nz(irma[1]) * (l - 1) + p) / l

irma

// Ideal RSI function

irsi(p, l) =>

upi = irma(math.max(ta.change(p), 0), l)

downi = irma(-math.min(ta.change(p), 0), l)

irsi = downi == 0 ? 100 : upi == 0 ? 0 : 100 - 100 / (1 + upi / downi)

irsi
// Linear regression

lrs(p, l) =>

lrc = ta.linreg(p, l, 0)

lrc1 = ta.linreg(p,l,1)

lrs = (lrc-lrc1)

lrs

//

idealRSI(p) =>

C1 = 0.0962

C2 = 0.5769

Df = 0.5

Period = 0.0

I2 = 0.0

Q2 = 0.0

Re = 0.0

Im = 0.0

SmoothPeriod = 0.0
C3 = nz(Period[1]) * 0.075 + 0.54

smooth = (hl2 * 4.0 + hl2[1] * 3.0 + hl2[2] * 2.0 + hl2[3]) / 10.0

dDeTrend = (smooth * C1 + nz(smooth[2]) * C2 - nz(smooth[4]) * C2 - nz(smooth[6]) * C1) * C3

Q1 = (dDeTrend * C1 + nz(dDeTrend[2]) * C2 - nz(dDeTrend[4]) * C2 - nz(dDeTrend[6]) * C1) * C3

I1 = nz(dDeTrend[3])

jI = (I1 * C1 + nz(I1[2]) * C2 - nz(I1[4]) * C2 - nz(I1[6]) * C1) * C3

jQ = (Q1 * C1 + nz(Q1[2]) * C2 - nz(Q1[4]) * C2 - nz(Q1[6]) * C1) * C3

I2_ = I1 - jQ

Q2_ = Q1 + jI

I2 := 0.2 * I2_ + 0.8 * nz(I2[1])

Q2 := 0.2 * Q2_ + 0.8 * nz(Q2[1])

Re_ = I2 * nz(I2[1]) + Q2 * nz(Q2[1])

Im_ = I2 * nz(Q2[1]) - Q2 * nz(I2[1])

Re := 0.2 * Re_ + 0.8 * nz(Re[1])

Im := 0.2 * Im_ + 0.8 * nz(Im[1])

dp_ = Re != 0 and Im != 0 ? 6.28318 / math.atan(Im / Re) : 0

II = nz(Period[1])

dp = math.max(math.max(math.min(math.min(dp_, 1.5 * II), 50), 0.6667 * II), 6)

Period := dp * 0.2 + nz(Period[1]) * 0.8

SmoothPeriod := 0.33 * Period + nz(SmoothPeriod[1]) * 0.67


rsiLen = math.round(SmoothPeriod * Df - 1) // Get variable RSI length from discriminator

idealRSI = irsi(p, rsiLen) // Generate RSI.

idealRSI

// --- Bollinger Band Vdub BB %B

pcBB(p, l) =>

basis = ta.sma(p, l)

dev = 0.1 * ta.stdev(p, l)

upper = basis + dev

lower = basis - dev

pcBB = (p - lower) / (upper - lower)

pcBB

forceIndex(p, l) =>

f = (p - p[1]) * volume

//Trend Volume Accumulation

TVA(p, l) =>

ma1 = ta.ema(p, l) // Get the MA series


direction = 0

rising_1 = ta.rising(ma1, 3)

falling_1 = ta.falling(ma1, 3)

direction := open < close ? 1 : open > close ? -1 : nz(direction[1])

tva = 0.0

tva := direction > 0 ? nz(tva[1]) >= 0 ? nz(tva[1]) + volume : volume : direction < 0 ? nz(tva[1]) <= 0 ? nz(tva[1]) - volume : -volume : nz(tva[1])

tva

//Stoch momentum

SMI(p, l) =>

highestHigh = ta.highest(l)

lowestLow = ta.lowest(l)

highestLowestRange = highestHigh - lowestLow

relativeRange = close - (highestHigh + lowestLow) / 2

smi = 200 * (emaEma(relativeRange, 3) / emaEma(highestLowestRange, 3))

smiPP = ta.ema(smi, 3)

smiPP

// Chande composite MI function


calc_dema(src, length) =>

e1 = ta.ema(src, length)

e2 = ta.ema(e1, length)

2 * e1 - e2

chande(p, l) =>

cmo51 = math.sum(p > p[1] ? p - p[1] : 0, 5)

cmo52 = math.sum(p < p[1] ? p[1] - p : 0, 5)

cmo5 = calc_dema(100 * nz((cmo51 - cmo52) / (cmo51 + cmo52)), 3)

cmo101 = math.sum(p > p[1] ? p - p[1] : 0, 10)

cmo102 = math.sum(p < p[1] ? p[1] - p : 0, 10)

cmo10 = calc_dema(100 * nz((cmo101 - cmo102) / (cmo101 + cmo102)), 3)

cmo201 = math.sum(p > p[1] ? p - p[1] : 0, 20)

cmo202 = math.sum(p < p[1] ? p[1] - p : 0, 20)

cmo20 = calc_dema(100 * nz((cmo201 - cmo202) / (cmo201 + cmo202)), 3)

dmi = (ta.stdev(p, 5) * cmo5 + ta.stdev(p, 10) * cmo10 + ta.stdev(p, 20) * cmo20) / (ta.stdev(p, 5) + ta.stdev(p, 10) + ta.stdev(p, 20))

chande = 0.0

chande := ta.ema(dmi, l)

chande

// === End of Functions.


// || Method selection

oscilator_high = float(na)

oscilator_low = float(na)

if method == 'RSI'

oscilator_high := ta.rsi(high_src, rsi_smooth)

oscilator_low := ta.rsi(low_src, rsi_smooth)

oscilator_low

if method == 'Brown Composite Index'

oscilator_high := s

oscilator_low := s

oscilator_low

if method == 'MACD'

oscilator_high := f_macd(macd_src, macd_fast, macd_slow, macd_smooth)

oscilator_low := f_macd(macd_src, macd_fast, macd_slow, macd_smooth)

oscilator_low

if method == 'Stochastic'

oscilator_high := ta.stoch(close, high, low, rsi_smooth)

oscilator_low := ta.stoch(close, high, low, rsi_smooth)


oscilator_low

if method == 'Volume'

oscilator_high := ta.sma(volume, rsi_smooth)

oscilator_low := ta.sma(volume, rsi_smooth)

oscilator_low

if method == 'OBV'

oscilator_high := ta.obv

oscilator_low := ta.obv

oscilator_low

if method == 'Accumulation/Distribution'

oscilator_high := f_accdist(rsi_smooth)

oscilator_low := f_accdist(rsi_smooth)

oscilator_low

if method == 'Fisher Transform'

oscilator_high := f_fisher(high_src, rsi_smooth)

oscilator_low := f_fisher(low_src, rsi_smooth)

oscilator_low

if method == 'CCI'

oscilator_high := ta.cci(high_src, rsi_smooth)

oscilator_low := ta.cci(low_src, rsi_smooth)


oscilator_low

if method == 'BB %B'

oscilator_high := pcBB(high_src, rsi_smooth)

oscilator_low := pcBB(low_src, rsi_smooth)

oscilator_low

if method == 'Ideal RSI'

oscilator_high := idealRSI(high_src)

oscilator_low := idealRSI(low_src)

oscilator_low

if method == 'Elders Force Index'

oscilator_high := forceIndex(high_src, rsi_smooth)

oscilator_low := forceIndex(low_src, rsi_smooth)

oscilator_low

if method == 'Trend Acc Volume'

oscilator_high := TVA(high_src, rsi_smooth)

oscilator_low := TVA(low_src, rsi_smooth)

oscilator_low

if method == 'ROC'

oscilator_high := ta.roc(high_src, rsi_smooth)

oscilator_low := ta.roc(low_src, rsi_smooth)


oscilator_low

if method == 'MFI'

oscilator_high := ta.mfi(high_src, rsi_smooth)

oscilator_low := ta.mfi(low_src, rsi_smooth)

oscilator_low

if method == 'SMI'

oscilator_high := SMI(high_src, rsi_smooth)

oscilator_low := SMI(low_src, rsi_smooth)

oscilator_low

if method == 'Chande composite Momentum Index'

oscilator_high := chande(close, rsi_smooth)

oscilator_low := chande(close, rsi_smooth)

oscilator_low

if method == 'Linear regression slope'

oscilator_high := lrs(close, rsi_smooth)

oscilator_low := lrs(close, rsi_smooth)

oscilator_low

//
plFound = na(ta.pivotlow(oscilator_low, lbL, lbR)) ? false : true

phFound = na(ta.pivothigh(oscilator_high, lbL, lbR)) ? false : true

_inRange(cond) =>

bars = ta.barssince(cond == true)

rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------

// Regular Bullish

// Osc: Higher Low

oscHL = oscilator_low[lbR] > ta.valuewhen(plFound, oscilator_low[lbR], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)

bullCond = uRegb and priceLL and oscHL and plFound

//------------------------------------------------------------------------------
// Hidden Bullish

// Osc: Lower Low

oscLL = oscilator_low[lbR] < ta.valuewhen(plFound, oscilator_low[lbR], 1) and _inRange(plFound[1])

// Price: Higher Low

priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)

hiddenBullCond = uHidb and priceHL and oscLL and plFound

//------------------------------------------------------------------------------

// Regular Bearish

// Osc: Lower High

oscLH = oscilator_high[lbR] < ta.valuewhen(phFound, oscilator_high[lbR], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)


bearCond = uRegs and priceHH and oscLH and phFound

//------------------------------------------------------------------------------

// Hidden Bearish

// Osc: Higher High

oscHH = oscilator_high[lbR] > ta.valuewhen(phFound, oscilator_high[lbR], 1) and _inRange(phFound[1])

// Price: Lower High

priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)

hiddenBearCond = uHids and priceLH and oscHH and phFound

Divbuy = bullCond or hiddenBullCond

Divsell = bearCond or hiddenBearCond

//Improovements
i_MinPrMov = input.float(title="Min Price Movement", defval=0.3, step = 0.01, group = "Improvements")

i_MinPrMovHid = input.float(title="Min Price Hidden Movement", defval=0.3, step = 0.01, group = "Improvements")

i_MinOscMov = input.float(title="Min Oscilator Movement", defval=0.5, step = 0.05, group = "Improvements")

i_MinOscMovHid = input.float(title="Min Oscilator Hidden Movement", defval=0.5, step = 0.05, group = "Improvements")

i_MinOscPull = input.float(title="Min Oscilator Pullback", defval=2, step = 0.05, group = "Improvements")

low_prev = ta.valuewhen(plFound, oscilator_low, 1)

high_prev = ta.valuewhen(phFound, oscilator_high, 1)

low_price = ta.valuewhen(plFound, close, 1)

high_price = ta.valuewhen(phFound, close, 1)

barsSince1 = ta.barssince(high_prev)

barsSince2 = ta.barssince(low_prev)

// Проверяваме дали barsSinceDivrsi1 е валидно

validBars = na(barsSince1) ? rangeUpper : math.min(math.max(barsSince1, rangeLower), rangeUpper)


// Изчисляваме най-ниската стойност

phlow = ta.lowest(oscilator_high, validBars)

// Проверяваме дали barsSinceDivrsi1 е валидно

validBars2 = na(barsSince2) ? rangeUpper : math.min(math.max(barsSince2, rangeLower), rangeUpper)

plhigh = ta.highest(oscilator_low, validBars2)

Imprbuy = (plhigh-oscilator_low[lbR])> i_MinOscPull and (uRegb and (((oscilator_low[lbR]-low_prev)/low_prev*100) >= i_MinOscMov) and (((low_price-
low[lbR])/low[lbR]*100)>=i_MinPrMov)) or (uHidb and ((((low_prev-oscilator_low[lbR])/oscilator_low[lbR]*100) >= i_MinOscMovHid)) and (((low[lbR] -
low_price)/low_price*100)>=i_MinPrMovHid))

Imprsell = (oscilator_high[lbR] - phlow)> i_MinOscPull and (uRegs and (((high_prev - oscilator_high[lbR])/oscilator_high[lbR]*100) >= i_MinOscMov) and
(((high[lbR] - high_price)/high_price*100)>=i_MinPrMov)) or (uHids and ((((oscilator_high[lbR] - high_prev)/high_prev*100) >= i_MinOscMovHid)) and
(((high_price - high[lbR])/high[lbR]*100)>=i_MinPrMovHid))
// Stochastic Momentum Index Filter

TF = input.timeframe(title='Timeframe', defval='', group="SMI filter")

GetData(timeframe, data) => request.security(syminfo.tickerid, timeframe, data)

DClose = GetData(TF, close)

lengK = input.int(50, "%K Length SMI", minval = 1, maxval = 15000, group="SMI filter")

lengD = input.int(3, "%D Length SMI", minval = 1, maxval = 4999, group="SMI filter")

lengEMA = input.int(3, "EMA Length", minval = 1, maxval = 49, group="SMI filter")

SMIreverse = input.bool(false, "Reverse to trend", group="SMI filter")

overbought = input.float(40, "Overbought / Trending Up level", group="SMI filter")

oversold = input.float(-40, "Oversold / Trending Down level", group="SMI filter")

highlight = input(title='Show SMI zones', defval=false, group="SMI filter")

higheHigh = ta.highest(lengK)

loweLow = ta.lowest(lengK)
higheLoweRange = higheHigh - loweLow

relatiRange = DClose - (higheHigh + loweLow) / 2

smiBi = 200 * (emaEma(relatiRange, lengD) / emaEma(higheLoweRange, lengD))

smibibi = ta.ema(smiBi, lengEMA)

smibull = SMIreverse? smiBi<=overbought and smiBi>smibibi : smiBi>=oversold and smiBi>smibibi

smibear = SMIreverse? smiBi>=oversold and smiBi<smibibi: smiBi<=overbought and smiBi<smibibi

//Antirepainting step for HTF

Bullbias2 = smibull[1]

Bearbias2 = smibear[1]

bgColor = smibear ? color.rgb(253, 51, 193, 86) : smibull ? #27f3c023 : na

bgcolor((enableBias2long or enableBias2short) and highlight ? bgColor: na)


ma_src = input(close, title='Source for Fast MA', group="MAs")

ma_src2 = input(close, title='Source for Slow MA', group="MAs")

fastType = input.string(defval='EMA', title='Fast Ribbon MA Type: ', options=['SMA', 'EMA', 'WMA', 'VWMA', 'SMMA', 'DEMA', 'TEMA', 'HullMA', 'ZEMA',
'TMA', 'SSMA', 'T3'], group="MAs")

fastLen_ = input.int(defval=50, title='Fast Ribbon MA Length:', minval=1, group="MAs")

slowType = input.string(defval='EMA', title='Slow Ribbon MA Type: ', options=['SMA', 'EMA', 'WMA', 'VWMA', 'SMMA', 'DEMA', 'TEMA', 'HullMA', 'ZEMA',
'TMA', 'SSMA', 'T3'], group="MAs")

slowLen_ = input.int(defval=200, title='Slow Ribbon MA Length:', minval=1, group="MAs")

// SuperSmoother filter

// © 2013 John F. Ehlers

variant_supersmoother(src, len) =>

a1 = math.exp(-1.414 * 3.14159 / len)

b1 = 2 * a1 * math.cos(1.414 * 3.14159 / len)

c2 = b1

c3 = -a1 * a1

c1 = 1 - c2 - c3

v9 = 0.0

v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])


v9

variant_smoothed(src, len) =>

v5 = 0.0

sma_1 = ta.sma(src, len)

v5 := na(v5[1]) ? sma_1 : (v5[1] * (len - 1) + src) / len

v5

variant_zerolagema(src, len) =>

ema1 = ta.ema(src, len)

ema2 = ta.ema(ema1, len)

v10 = ema1 + ema1 - ema2

v10

variant_doubleema(src, len) =>

v2 = ta.ema(src, len)

v6 = 2 * v2 - ta.ema(v2, len)

v6

variant_tripleema(src, len) =>


v2 = ta.ema(src, len)

v7 = 3 * (v2 - ta.ema(v2, len)) + ta.ema(ta.ema(v2, len), len) // Triple Exponential

v7

variant_zlsma(src, len) =>

lsma1 = ta.linreg(src, len, 0)

lsma21 = ta.linreg(lsma1, len, 0)

eq1 = lsma1 - lsma21

zlsma1 = lsma1 + eq1

zlsma1

gdT3(DClose, lengthT3) =>

ta.ema(DClose, lengthT3) * 1.7 - ta.ema(ta.ema(DClose, lengthT3), lengthT3) * 0.7

// return variant, defaults to SMA

variant(type, src, len) =>

ema_1 = ta.ema(src, len)

wma_1 = ta.wma(src, len)

vwma_1 = ta.vwma(src, len)

variant_smoothed__1 = variant_smoothed(src, len)

variant_doubleema__1 = variant_doubleema(src, len)


variant_tripleema__1 = variant_tripleema(src, len)

wma_2 = ta.wma(src, len / 2)

wma_3 = ta.wma(src, len)

wma_4 = ta.wma(2 * wma_2 - wma_3, math.round(math.sqrt(len)))

variant_supersmoother__1 = variant_supersmoother(src, len)

variant_zerolagema__1 = variant_zerolagema(src, len)

sma_1 = ta.sma(src, len)

sma_2 = ta.sma(sma_1, len)

T33 = gdT3(gdT3(gdT3(src, len), len), len)

zlsma1 = variant_zlsma(src, len)

type == 'EMA' ? ema_1 : type == 'WMA' ? wma_1 : type == 'ZLSMA' ? zlsma1 : type == 'VWMA' ? vwma_1 : type == 'SMMA' ? variant_smoothed__1 : type
== 'DEMA' ? variant_doubleema__1 : type == 'TEMA' ? variant_tripleema__1 : type == 'HullMA' ? wma_4 : type == 'SSMA' ? variant_supersmoother__1 :
type == 'ZEMA' ? variant_zerolagema__1 : type == 'TMA' ? sma_2 : type == 'T3' ? T33 : sma_1

// - /variant

// Get the two MAs

fastMA = variant(fastType, ma_src, fastLen_)

slowMA = variant(slowType, ma_src2, slowLen_)


MAbuy = fastMA>=slowMA

MAsell = fastMA<=slowMA

enablePlot=input.bool(false,"Plot", group="MAs")

plot(enablePlot and (enableMAlong or enableMAshort)? fastMA: na, color=#83fd89ff, style=plot.style_line, linewidth=2, title='Fast')

plot(enablePlot and (enableMAshort or enableMAlong)? slowMA: na, color=#ff2efce6, style=plot.style_line, linewidth=2, title='Slow')

// TRADING TIME

limit_day1 = input.bool(true, title="", group="Trading Time Limiter", inline="day1")

days_to_trade_on1 = input.string("1234567", title="(1) Valid Trading Days", inline="day1", tooltip="Values represent days: \nSunday (1), Monday (2), ...,
Friday (6), Saturday(7)\n\nScript will trade on days that are present in this field. Please make sure that this field and also (1) Valid Trading Hours Between is
checked.", group="Trading Time Limiter")

valid_hours1 = input.bool(true, title="", inline="inline1", group="Trading Time Limiter", tooltip="Hours between which the trades can happen. The time is
always in the exchange's timezone.")

hours_to_trade_on1 = input.session("0000-1400", title="(1) Valid Trading Hours Between", inline="inline1", group="Trading Time Limiter")

limit_day2 = input.bool(true, title="", group="Trading Time Limiter", inline="day2")


days_to_trade_on2 = input.string("1234567", title="(2) Valid Trading Days", inline="day2", tooltip="Values represent days: \nSunday (1), Monday (2), ...,
Friday (6), Saturday(7)\n\nScript will trade on days that are present in this field. Please make sure that this field and also (2) Valid Trading Hours Between is
checked.", group="Trading Time Limiter")

valid_hours2 = input.bool(true, title="", inline="inline2", group="Trading Time Limiter", tooltip="Hours between which the trades can happen. The time is
always in the exchange's timezone.")

hours_to_trade_on2 = input.session("1400-0000", title="(2) Valid Trading Hours Between", inline="inline2", group="Trading Time Limiter")

check_valid_time() =>

t7 = valid_hours1 and limit_day1 == true ? time(timeframe.period, hours_to_trade_on1) : na

t8 = valid_hours2 and limit_day2 == true ? time(timeframe.period, hours_to_trade_on2) : na

t1 = valid_hours1 and limit_day1 ? time(timeframe.period, hours_to_trade_on1 + ':' + days_to_trade_on1) : na

t2 = valid_hours2 and limit_day2 ? time(timeframe.period, hours_to_trade_on2 + ':' + days_to_trade_on2) : na

na(t1) and na(t2) ? false : true

TB = check_valid_time()

TS = check_valid_time()
//

enableTPSL=input.bool(false,"Enable/Disable TP/SL ", group="EXIT OPTIONS")

longposonly=input.bool(true,"Long Positions ", group="POSITIONS")

shortposonly=input.bool(true,"Short Positions ", group="POSITIONS")

leverage= input.int(1, title='Leverage', minval=1, maxval=100,group="STRATEGY")

shareofport = input.float(100, title= 'Share of portfolio %', minval=0, maxval=100, step=1,group="STRATEGY")/100

stoplossfixed = input.float(2.5, title='Stop loss Percentage', minval=0, step=0.1, group='Fixed Stop Loss and Take Profit') / 100

takeprofitfixed = input.float(2.5, title='Take profit percentage', minval=0, step=0.1, group='Fixed Stop Loss and Take Profit') / 100

longStopPort = strategy.position_avg_price * (1 - stoplossfixed)

shortStopPort = strategy.position_avg_price * (1 + stoplossfixed)

shortTakePort = strategy.position_avg_price * (1 - takeprofitfixed)

longTakePort = strategy.position_avg_price * (1 + takeprofitfixed)

bool longcond=true
bool shortcond=true

//

longcond:=enableDivbuy?longcond and Divbuy:longcond

longcond:=enableImprBull?longcond and Imprbuy:longcond

longcond:=enableBias2long?longcond and Bullbias2:longcond

longcond:=enableMAlong?longcond and MAbuy:longcond

longcond:=enableTlong?longcond and TB:longcond

shortcond:=enableDivsell?shortcond and Divsell:shortcond

shortcond:=enableImprBear?shortcond and Imprsell:shortcond

shortcond:=enableBias2short?shortcond and Bearbias2:shortcond

shortcond:=enableMAshort?shortcond and MAsell:shortcond

shortcond:=enableTshort?shortcond and TS:shortcond


plot(UseInd and plFound ? low[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond ? bullColor : noneColor)

plotshape(UseInd and longcond and bullCond ? low[lbR] : na, offset=-lbR, title='Regular Bullish Label', text=' Bull ', style=shape.labelup,
location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0))

plot(UseInd and plFound ? low[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond ? hiddenBullColor : noneColor)

plotshape(UseInd and longcond and hiddenBullCond ? low[lbR] : na, offset=-lbR, title='Hidden Bullish Label', text=' H Bull ', style=shape.labelup,
location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0))

plot(UseInd and phFound ? high[lbR] : na, offset=-lbR, title='Regular Bearish', linewidth=2, color=bearCond ? bearColor : noneColor)

plotshape(UseInd and shortcond and bearCond ? high[lbR] : na, offset=-lbR, title='Regular Bearish Label', text=' Bear ', style=shape.labeldown,
location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0))

plot(UseInd and phFound ? high[lbR] : na, offset=-lbR, title='Hidden Bearish', linewidth=2, color=hiddenBearCond ? hiddenBearColor : noneColor)

plotshape(UseInd and shortcond and hiddenBearCond ? high[lbR] : na, offset=-lbR, title='Hidden Bearish Label', text=' H Bear ', style=shape.labeldown,
location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0))

//Stochastic Momentum Exit

ExType = input.string(defval='None', title='Exit', options=['StochMom', 'Stant. dev', "None"], group="Exit")


lengthK = input.int(10, "%K Length", minval = 1, maxval = 150, group="Stoch Mom Exit")

lengthD = input.int(3, "%D Length", minval = 1, maxval = 49, group="Stoch Mom Exit")

lengthEMA = input.int(3, "EMA Length", minval = 1, maxval = 49, group="Stoch Mom Exit")

underbuy = input.float (-50, "Short Exit Under", group="Stoch Mom Exit")

abovesell = input.float (50, "Long Exit Above", group="Stoch Mom Exit")

highestHigh = ta.highest(lengthK)

lowestLow = ta.lowest(lengthK)

highestLowestRange = highestHigh - lowestLow

relativeRange = close - (highestHigh + lowestLow) / 2

smi = 200 * (emaEma(relativeRange, lengthD) / emaEma(highestLowestRange, lengthD))

smiP = ta.ema(smi, lengthEMA)

//Standart deviation

atrlen = input(14, 'Standart Deviation Period', group="StDev Exit")

mult = input.float(1, 'Multiplier', step=0.1, group="StDev Exit")

Ratio = input.float(2, "Reward TP / Risk SL", step=0.1, group="StDev Exit")


var float atr_slen1 = na

var float close1 = na

if (longcond or shortcond)

close1 := close

staDe = ta.stdev(close, atrlen)

upper_band1 = staDe * mult + close1

lower_band1 = close1 - staDe * mult

stopbuy1=ta.valuewhen(longcond, lower_band1, 0)

stopsell1=ta.valuewhen(shortcond, upper_band1, 0)

gobuy1=ta.valuewhen(longcond, (upper_band1 + ((upper_band1 - close1) * Ratio)), 0)

gosell1=ta.valuewhen(shortcond, (lower_band1 - ((close1 - lower_band1)*Ratio)), 0)


// Define exit conditions

exitsell = (ExType == 'StochMom' ? smi>=smiP and smi < underbuy : ExType == 'Stant. dev' ? ta.crossover(close, stopsell1) or ta.crossunder(close, gosell1) :
false)

exitbuy = (ExType == 'StochMom' ? smi<=smiP and smi > abovesell : ExType == 'Stant. dev' ? ta.crossover(close, gobuy1) or ta.crossunder(close, stopbuy1) :
false)

custom_exit_mode = input.string(title='Custom Exit Type Selection', defval='None', options=['None', 'Number of bars', 'Reversed Candle After Number of
Bars'], group='Custom Exit')

i_custom_exit_nb_bars = input.int(5, title = "Bars to exit", group = "Custom Exit", tooltip = "Exit the trade(s) after X bars have closed since the trade open")

custom_exit_VWAP = input.bool(false, title='VWAP Exit', group='Custom Exit')

OPEN2 = ta.valuewhen(longcond, open, 0)

Low23 = ta.lowest(low, 5)

High23 = ta.highest(high, 5)
Lowest23 = ta.valuewhen(longcond, Low23, 0)-((high-low)/33)

Highest23 = ta.valuewhen(shortcond, High23, 0)+((high-low)/33)

custom_exit_bull = (custom_exit_mode == "Number of bars" and ta.barssince(longcond) >= i_custom_exit_nb_bars) or (custom_exit_mode == "Reversed
Candle After Number of Bars" and ta.barssince(longcond) >= i_custom_exit_nb_bars and close<open) or (custom_exit_VWAP and ((ta.vwap[3] < close[3] and
ta.vwap[7] < close[7] and ta.vwap >close) or (ta.vwap[3] > close[3] and ta.vwap[7] > close[7] and ta.vwap> close and ta.vwap<high)))

custom_exit_bear = (custom_exit_mode == "Number of bars" and ta.barssince(shortcond) >= i_custom_exit_nb_bars) or (custom_exit_mode == "Reversed
Candle After Number of Bars" and ta.barssince(shortcond) >= i_custom_exit_nb_bars and close>open) or (custom_exit_VWAP and ((ta.vwap[3] < close[3]
and ta.vwap[7] < close[7] and ta.vwap < close and ta.vwap > low ) or (ta.vwap[3] > close[3] and ta.vwap[7] > close[7] and ta.vwap> close)))

// Close conditions using strategy.close

closeLongCondition = exitbuy and strategy.position_size > 0

closeShortCondition = exitsell and strategy.position_size < 0

// Execute strategy close

strategy.close("Long", when=closeLongCondition)

strategy.close("Short", when=closeShortCondition)
if strategy.position_size > 0 and custom_exit_bull

strategy.close(id='Long', comment='Custom Long Close Signal')

if strategy.position_size < 0 and custom_exit_bear

strategy.close(id='Short', comment='Custom Short Close')

var profit = 9999999999.0

var loss = 9999999999.0

var box box1 = na

var box box2 = na

longStopPort2 = close * (1 - stoplossfixed)

shortStopPort2 = close * (1 + stoplossfixed)

shortTakePort2 = close * (1 - takeprofitfixed)

longTakePort2= close * (1 + takeprofitfixed)

orderSize = (shareofport * strategy.equity / close * leverage)


if enableTPSL and longposonly and shortposonly

strategy.exit('Long Exit ', "Long", comment='Exit Long ', stop=longStopPort, limit=longTakePort,comment_profit = "Take Profit ",comment_loss = "LOSS")

strategy.exit('Exit Short', "Short", comment='Exit Short ', stop=shortStopPort, limit=shortTakePort,comment_loss = "LOSS",comment_profit = "Take Profit")

if enableTPSL and not shortposonly and longposonly

strategy.exit('Long Exit ', "Long", stop=longStopPort, limit=longTakePort,comment_profit = "Take Profit ",comment_loss = "LOSS")

if enableTPSL and shortposonly and not longposonly

strategy.exit('Exit Short', "Short", stop=shortStopPort, limit=shortTakePort,comment_loss = "LOSS",comment_profit = "Take Profit")

if UseStr and longcond and longposonly and shortposonly

strategy.entry('Long', strategy.long,comment = "Long Signal ",qty=orderSize)

if UseStr and shortcond and longposonly and shortposonly

strategy.entry('Short', strategy.short,comment="Short Signal",qty=orderSize)

if shortcond and longposonly and not shortposonly

strategy.close("Long",comment="Short Signal")

if UseStr and longcond and strategy.position_size==0 and not shortposonly and longposonly

strategy.entry("Long", strategy.long,comment = "Long ",qty=orderSize)


if UseStr and shortcond and strategy.position_size==0 and shortposonly and not longposonly

strategy.entry("Short", strategy.short ,comment="Short Signal",qty=orderSize)

if longcond and shortposonly and not longposonly

strategy.close("Short" ,comment = "Long Signal")

//@version=6

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// © SeerQuant

indicator(

title = "Triple MA For Loop [SeerQuant]",


shorttitle = "TMA FL",

overlay = false

// INPUTS

// @param: Moving Average Settings

maLen = input.int(45, title = "MA Length", group = "======= 𝗠𝗔 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

src = input.source(close, title = "MA Source", group = "======= 𝗠𝗔 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

maType = input.string("EMA", title = "MA Type",

options = ["SMA", "EMA", "SMMA", "WMA", "VWMA",

"LSMA", "HMA", "ALMA"], group = "======= 𝗠𝗔 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

// @param: Global Settings

sl = input.int(5, title = "Loop Start", inline = "Global", group = "======= 𝗙𝗢𝗥 𝗟𝗢𝗢𝗣 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

el = input.int(55, title = "Loop End", inline = "Global", group = "======= 𝗙𝗢𝗥 𝗟𝗢𝗢𝗣 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

thrUp = input.float(45, title = "Threshold Uptrend", inline = "Global", group = "======= 𝗙𝗢𝗥 𝗟𝗢𝗢𝗣 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

thrDown = input.float(0, title = "Threshold Downtrend", inline = "Global", group = "======= 𝗙𝗢𝗥 𝗟𝗢𝗢𝗣 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")
// @param: Style Settings

paint = input.bool(false, title = "Colour Candles?", group = "======= 𝗦𝗧𝗬𝗟𝗘 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

// @param: Colour Scheme

colScheme = input.string("Default", "Color Scheme",

options = ["Default", "Modern", "Cool",

"Alternate", "Bright"], group = "======= 𝗦𝗧𝗬𝗟𝗘 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")

// COLORS

// @function: Color Scheme Logic

[bull, bear, neutral] = switch colScheme

"Default" => [#00ff73, #ff0040, #606060]

"Modern" => [#23d7e4, #e11179, #707070]

"Cool" => [#00ffcc, #1600db, #505050]

"Alternate" => [#00ff80, #ff6600, #505050]

"Bright" => [#e8ec00, #f200fa, #505050]


// FUNCTIONS

// @function: Custom Moving Averages

ma(source, length, type) =>

switch type

"SMA" => ta.sma(source, length)

"EMA" => ta.ema(source, length)

"SMMA" => ta.rma(source, length)

"WMA" => ta.wma(source, length)

"VWMA" => ta.vwma(source, length)

"LSMA" => ta.linreg(source, length, 0)

"HMA" =>

wma1 = ta.wma(source, math.floor(length / 2))

wma2 = ta.wma(source, length)

ta.wma(2 * wma1 - wma2, math.floor(math.sqrt(length)))

"ALMA" => ta.alma(source, length, 0.85, 6)


// @function: For Loop Function

fl(s, e, val) =>

sum = 0

for i = s to e by 1

sum += (src > val[i] ? 1 : -1)

sum

// INDICATOR CALCULATION

// @description: Calculate Triple MA and Loop Sum

ma1 = ma(src, maLen, maType)

ma2 = ma(ma1, maLen, maType)

ma3 = ma(ma2, maLen, maType)

tma = 3 * (ma1 - ma2) + ma3

fl = fl(sl, el, tma)


// PLOTTING

// @description: Visualization of Indicator Outputs

var color col = na

if fl > thrUp

col := bull

if fl < thrDown

col := bear

// @description: Histogram Plot with Gradient

plot(fl, style = plot.style_line, color = col, linewidth = 3, title = "FL Histogram")

// @description: Threshold Bands

plot(thrUp, title = "Threshold Uptrend", color = color.new(bull, 50), linewidth = 2, style = plot.style_line)

plot(thrDown, title = "Threshold Downtrend", color = color.new(bear, 50), linewidth = 2, style = plot.style_line)

// @description: Candle Coloring

barcolor(paint ? col : na)


// @description: Dummy EMA for easy signal following

sma = ta.sma(close, 14)

a = plot(sma, color = col, linewidth = 2, force_overlay = true)

b = plot(sma[2], color = col, linewidth = 2, force_overlay = true)

fill(a, b, color.new(col, 70))

// @description: Initialize variables for state tracking

var int prevTrendState = 0

var int currentTrendState = 0

// @description: Determine current trend state

if fl > thrUp

currentTrendState := 1

else if fl < thrDown

currentTrendState := -1

else

currentTrendState := 0

// @description: Check for valid state transitions


bullishTransition = (prevTrendState != 1 and currentTrendState == 1)

bearishTransition = (prevTrendState != -1 and currentTrendState == -1)

// @description: Update previous trend state only after a valid transition

if bullishTransition or bearishTransition

prevTrendState := currentTrendState

// @description: Plot shapes only for valid state transitions

plotshape(bullishTransition ? sma - (sma * 0.075) : na,

title = "Bullish Trend",

style = shape.labelup,

location = location.absolute,

color = bull,

text = "▲",

textcolor = #000000,

size = size.small,

force_overlay = true)

plotshape(bearishTransition ? sma + (sma * 0.075) : na,

title = "Bearish Trend",


style = shape.labeldown,

location = location.absolute,

color = bear,

text = "▼",

textcolor = #000000,

size = size.small,

force_overlay = true)

// ================================================================================================================ //

// //

// ▄████████ ▄████████ ▄████████ ▄████████ ████████▄ ███ █▄ ▄████████ ███▄▄▄▄ ███ //

// ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███▀▀▀██▄ ▀█████████▄ //

// ███ █▀ ███ █▀ ███ █▀ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀███▀▀██ //

// ███ ▄███▄▄▄ ▄███▄▄▄ ▄███▄▄▄▄██▀ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀ //

// ▀███████████ ▀▀███▀▀▀ ▀▀███▀▀▀ ▀▀███▀▀▀▀▀ ███ ███ ███ ███ ▀███████████ ███ ███ ███ //

// ███ ███ █▄ ███ █▄ ▀███████████ ███ ███ ███ ███ ███ ███ ███ ███ ███ //

// ▄█ ███ ███ ███ ███ ███ ███ ███ ███ ▀ ███ ███ ███ ███ ███ ███ ███ ███ //

// ▄████████▀ ██████████ ██████████ ███ ███ ▀██████▀▄█ ████████▀ ███ █▀ ▀█ █▀ ▄████▀ //

// //

// ================================================================================================================ //
//@version=6

indicator("Parabolic SAR y ADX Strategy", overlay=true)

// Parámetros del Parabolic SAR

psar_start = input.float(0.02, title="PSAR Factor Inicial", step=0.01)

psar_increment = input.float(0.02, title="PSAR Incremento", step=0.01)

psar_max = input.float(0.2, title="PSAR Máximo", step=0.01)

// Parámetros del ADX

adx_length = input.int(14, title="Período ADX")

adx_smoothing = input.int(14, title="Suavización ADX", minval=1)

adx_threshold = input.float(20, title="Nivel de referencia ADX", step=1)

// Cálculo del Parabolic SAR

psar = ta.sar(psar_start, psar_increment, psar_max)

// Cálculo del ADX y direcciones (+DI y -DI)

[plus_di, minus_di, adx] = ta.dmi(adx_length, adxSmoothing=adx_smoothing)


// Condiciones de Compra y Venta

long_condition = (adx > adx_threshold) and (close > psar)

short_condition = (adx > adx_threshold) and (close < psar)

// Dibujar señales en el gráfico

plotshape(series=long_condition, title="Compra", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")

plotshape(series=short_condition, title="Venta", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

// Mostrar PSAR en el gráfico

plot(psar, color=color.blue, title="Parabolic SAR")

// Если вам нужен индивидуальный индикатор или робот для торговли, обращайтесь в Телеграм @ibobro.

// Agar sizga maxsus ko'rsatkich yoki savdo roboti kerak bo'lsa, Telegram @ibobro orqali murojaat qiling.

// If you need a custom indicator or trading robot, feel free to contact me on Telegram @ibobro.

// Wenn Sie einen individuellen Indikator oder Handelsroboter benötigen, wenden Sie sich bitte über Telegram an @ibobro.

// カスタムインジケーターやトレーディングロボットが必要な場合は、Telegram @ibobro にご連絡ください。

// 如果您需要定制的指标或交易机器人,请通过 Telegram @ibobro 联系我。


// If you need a custom indicator or trading robot, feel free to contact me on Telegram @ibobro.

// If you need a custom indicator or trading robot, feel free to contact me on Telegram @ibobro.

// 맞춤형 지표나 트레이딩 로봇이 필요하면 텔레그램 @ibobro 에 문의하세요.

//Se você precisar de um indicador personalizado ou robô de negociação, entre em contato comigo no Telegram @ibobro.

//@version=5

indicator("SCALP LINES | IBOBRO", "SCALP LINES | IBOBRO", overlay = true)

//------------------------------------------------------------------------------

//Settings

//-----------------------------------------------------------------------------{

length = input.int(14, 'Swing Detection Lookback')

mult = input.float(1., 'Slope', minval = 0, step = .1)

calcMethod = input.string('Atr', 'Slope Calculation Method', options = ['Atr','Stdev','Linreg'])

backpaint = input(true, tooltip = 'Backpainting offset displayed elements in the past. Disable backpainting to see real time information returned by the
indicator.')

//Style

upCss = input.color(color.teal, 'Up Trendline Color', group = 'Style')

dnCss = input.color(color.red, 'Down Trendline Color', group = 'Style')


showExt = input(true, 'Show Extended Lines')

//-----------------------------------------------------------------------------}

//Calculations

//-----------------------------------------------------------------------------{

var upper = 0.

var lower = 0.

var slope_ph = 0.

var slope_pl = 0.

var offset = backpaint ? length : 0

n = bar_index

src = close

ph = ta.pivothigh(length, length)

pl = ta.pivotlow(length, length)

//Slope Calculation Method

slope = switch calcMethod


'Atr' => ta.atr(length) / length * mult

'Stdev' => ta.stdev(src,length) / length * mult

'Linreg' => math.abs(ta.sma(src * n, length) - ta.sma(src, length) * ta.sma(n, length)) / ta.variance(n, length) / 2 * mult

//Get slopes and calculate trendlines

slope_ph := ph ? slope : slope_ph

slope_pl := pl ? slope : slope_pl

upper := ph ? ph : upper - slope_ph

lower := pl ? pl : lower + slope_pl

var upos = 0

var dnos = 0

upos := ph ? 0 : close > upper - slope_ph * length ? 1 : upos

dnos := pl ? 0 : close < lower + slope_pl * length ? 1 : dnos

//-----------------------------------------------------------------------------}

//Extended Lines

//-----------------------------------------------------------------------------{

var uptl = line.new(na,na,na,na, color = upCss, style = line.style_dashed, extend = extend.right)


var dntl = line.new(na,na,na,na, color = dnCss, style = line.style_dashed, extend = extend.right)

if ph and showExt

uptl.set_xy1(n-offset, backpaint ? ph : upper - slope_ph * length)

uptl.set_xy2(n-offset+1, backpaint ? ph - slope : upper - slope_ph * (length+1))

if pl and showExt

dntl.set_xy1(n-offset, backpaint ? pl : lower + slope_pl * length)

dntl.set_xy2(n-offset+1, backpaint ? pl + slope : lower + slope_pl * (length+1))

//-----------------------------------------------------------------------------}

//Plots

//-----------------------------------------------------------------------------{

plot(backpaint ? upper : upper - slope_ph * length, 'Upper', color = ph ? na : upCss, offset = -offset)

plot(backpaint ? lower : lower + slope_pl * length, 'Lower', color = pl ? na : dnCss, offset = -offset)

//Breakouts

plotshape(upos > upos[1] ? low : na, "Upper Break"

, shape.labelup

, location.absolute
, upCss

, text = "Buy"

, textcolor = color.white

, size = size.tiny)

plotshape(dnos > dnos[1] ? high : na, "Lower Break"

, shape.labeldown

, location.absolute

, dnCss

, text = "Sell"

, textcolor = color.white

, size = size.tiny)

//-----------------------------------------------------------------------------}

//Alerts

//-----------------------------------------------------------------------------{

alertcondition(upos > upos[1], 'Upward Breakout', 'Price broke the down-trendline upward')

alertcondition(dnos > dnos[1], 'Downward Breakout', 'Price broke the up-trendline downward')

//-----------------------------------------------------------------------------}
//@version=5

indicator('Supertrend х3', overlay=true, format=format.price, precision=2, timeframe='')

// Функция для расчета Supertrend

f_supertrend(_src, _atrPeriod, _multiplier) =>

atr = ta.atr(_atrPeriod)

up = _src - _multiplier * atr

up1 = nz(up[1], up)

up := close[1] > up1 ? math.max(up, up1) : up

dn = _src + _multiplier * atr

dn1 = nz(dn[1], dn)

dn := close[1] < dn1 ? math.min(dn, dn1) : dn

trend = 1

trend := nz(trend[1], trend)

trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend

[up, dn, trend]

// Настройки для трех Supertrend индикаторов


Periods1 = input(12, title='ATR Period 1')

Multiplier1 = input(3.0, title='ATR Multiplier 1')

Periods2 = input(11, title='ATR Period 2')

Multiplier2 = input(2.0, title='ATR Multiplier 2')

Periods3 = input(10, title='ATR Period 3')

Multiplier3 = input(1.0, title='ATR Multiplier 3')

[up1, dn1, trend1] = f_supertrend(hl2, Periods1, Multiplier1)

[up2, dn2, trend2] = f_supertrend(hl2, Periods2, Multiplier2)

[up3, dn3, trend3] = f_supertrend(hl2, Periods3, Multiplier3)

// Условия для покупки и продажи

longCondition = trend1 == 1 and trend2 == 1 and trend3 == 1

shortCondition = trend1 == -1 and trend2 == -1 and trend3 == -1

// Отображение линий Supertrend

plot(trend1 == 1 ? up1 : dn1, color=trend1 == 1 ? color.green : color.red, title='Supertrend 1', linewidth=2)

plot(trend2 == 1 ? up2 : dn2, color=trend2 == 1 ? color.blue : color.orange, title='Supertrend 2', linewidth=2)

plot(trend3 == 1 ? up3 : dn3, color=trend3 == 1 ? color.purple : color.yellow, title='Supertrend 3', linewidth=2)


// Сигналы на покупку и продажу

bgcolor(longCondition ? color.new(color.green, 90) : shortCondition ? color.new(color.red, 90) : na, title='Background', transp=90)

plotshape(series=longCondition, title='Buy Signal', location=location.belowbar, color=color.new(color.green, 0), style=shape.labelup, text='BUY')

plotshape(series=shortCondition, title='Sell Signal', location=location.abovebar, color=color.new(color.red, 0), style=shape.labeldown, text='SELL')

// Оповещения

alertcondition(longCondition, title='Buy Alert', message='All Supertrends indicate a BUY')

alertcondition(shortCondition, title='Sell Alert', message='All Supertrends indicate a SELL')

//@version=5

indicator('REVERSÃO POR ZONA DE RSI- INICIA CRYPTO ', overlay=false)

//functions

xrf(values, length) =>

r_val = float(na)

if length >= 1
for i = 0 to length by 1

if na(r_val) or not na(values[i])

r_val := values[i]

r_val

r_val

xsa(src, len, wei) =>

sumf = 0.0

ma = 0.0

out = 0.0

sumf := nz(sumf[1]) - nz(src[len]) + src

ma := na(src[len]) ? na : sumf / len

out := na(out[1]) ? ma : (src * wei + out[1] * (len - wei)) / len

out

// inputs

n1 = input.int(30, title='n1', minval=1)

//threshold lines

h1 = hline(50, color=color.red, linestyle=hline.style_dotted)


h2 = hline(50, color=color.green, linestyle=hline.style_dotted)

h3 = hline(10, color=color.lime, linestyle=hline.style_dotted)

h4 = hline(90, color=color.red, linestyle=hline.style_dotted)

fill(h2, h3, color=color.new(color.green, 70))

fill(h1, h4, color=color.new(color.red, 70))

//KDJ indicator

rsv = (close - ta.lowest(low, n1)) / (ta.highest(high, n1) - ta.lowest(low, n1)) * 100

k = xsa(rsv, 3, 1)

d = xsa(k, 3, 1)

crossover_1 = ta.crossover(k, d)

buysig = d < 25 and crossover_1 ? 30 : 0

crossunder_1 = ta.crossunder(d, k)

selsig = d > 75 and crossunder_1 ? 70 : 100

//plot buy and sell signal

ple = plot(buysig, color=color.new(color.green, 0), linewidth=1, style=plot.style_area)

pse = plot(selsig, color=color.new(color.red, 0), linewidth=2, style=plot.style_line)

//plot KD candles
plotcandle(k, d, k, d, color=k >= d ? color.green : na)

plotcandle(k, d, k, d, color=d > k ? color.red : na)

// KDJ leading line

var1 = (close - ta.sma(close, 13)) / ta.sma(close, 13) * 100

var2 = (close - ta.sma(close, 26)) / ta.sma(close, 21) * 100

var3 = (close - ta.sma(close, 90)) / ta.sma(close, 34) * 100

var4 = (var1 + 3 * var2 + 9 * var3) / 13

var5 = 100 - math.abs(var4)

var10 = ta.lowest(low, 10)

var13 = ta.highest(high, 25)

leadingline = ta.ema((close - var10) / (var13 - var10) * 4, 4) * 25

pbias = plot(leadingline, color=k >= d ? color.green : color.red, linewidth=4, style=plot.style_line, transp=10)

//@version=6

indicator(title="Customizable MTF Multiple Moving Averages with Cross-Timeframe Colors", shorttitle="Custom MAs+", overlay=true)
// Input per configurazione MA 1

ma1Length = input.int(title="MA 1 Length", defval=50, minval=2, group="MA 1")

ma1Source = input.source(title="MA 1 Source", defval=close, group="MA 1")

ma1Type = input.string(title="MA 1 Type", defval="EMA", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], group="MA 1")

ma1Timeframe = input.timeframe(title="MA 1 Timeframe", defval="", group="MA 1")

ma1ColorUp = input.color(title="MA 1 Rising Color", defval=color.green, group="MA 1")

ma1ColorDown = input.color(title="MA 1 Falling Color", defval=color.red, group="MA 1")

// Input per configurazione MA 2

ma2Length = input.int(title="MA 2 Length", defval=100, minval=2, group="MA 2")

ma2Source = input.source(title="MA 2 Source", defval=close, group="MA 2")

ma2Type = input.string(title="MA 2 Type", defval="EMA", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], group="MA 2")

ma2Timeframe = input.timeframe(title="MA 2 Timeframe", defval="", group="MA 2")

ma2ColorUp = input.color(title="MA 2 Rising Color", defval=color.blue, group="MA 2")

ma2ColorDown = input.color(title="MA 2 Falling Color", defval=color.orange, group="MA 2")

// Input per configurazione MA 3

ma3Length = input.int(title="MA 3 Length", defval=200, minval=2, group="MA 3")

ma3Source = input.source(title="MA 3 Source", defval=close, group="MA 3")

ma3Type = input.string(title="MA 3 Type", defval="EMA", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], group="MA 3")
ma3Timeframe = input.timeframe(title="MA 3 Timeframe", defval="", group="MA 3")

ma3ColorUp = input.color(title="MA 3 Rising Color", defval=color.purple, group="MA 3")

ma3ColorDown = input.color(title="MA 3 Falling Color", defval=color.yellow, group="MA 3")

// Funzione per calcolare il tipo di media mobile

f_moving_average(type, source, length) =>

switch type

"SMA" => ta.sma(source, length)

"EMA" => ta.ema(source, length)

"WMA" => ta.wma(source, length)

"VWMA" => ta.vwma(source, length)

"SMMA" =>

var float smma = na // Dichiarazione iniziale di SMMA

smma := na(smma) ? ta.sma(source, length) : (smma * (length - 1) + source) / length

smma

// Calcolo delle medie mobili con tipi configurabili

ma1 = request.security(syminfo.tickerid, ma1Timeframe, f_moving_average(ma1Type, ma1Source, ma1Length), gaps=barmerge.gaps_on)

ma1Prev = request.security(syminfo.tickerid, ma1Timeframe, f_moving_average(ma1Type, ma1Source, ma1Length)[1], gaps=barmerge.gaps_on)


ma2 = request.security(syminfo.tickerid, ma2Timeframe, f_moving_average(ma2Type, ma2Source, ma2Length), gaps=barmerge.gaps_on)

ma2Prev = request.security(syminfo.tickerid, ma2Timeframe, f_moving_average(ma2Type, ma2Source, ma2Length)[1], gaps=barmerge.gaps_on)

ma3 = request.security(syminfo.tickerid, ma3Timeframe, f_moving_average(ma3Type, ma3Source, ma3Length), gaps=barmerge.gaps_on)

ma3Prev = request.security(syminfo.tickerid, ma3Timeframe, f_moving_average(ma3Type, ma3Source, ma3Length)[1], gaps=barmerge.gaps_on)

// Colore dinamico per ciascuna media mobile

ma1Color = ma1 > ma1Prev ? ma1ColorUp : ma1ColorDown

ma2Color = ma2 > ma2Prev ? ma2ColorUp : ma2ColorDown

ma3Color = ma3 > ma3Prev ? ma3ColorUp : ma3ColorDown

// Disegno delle medie mobili

plot(ma1, color=ma1Color, linewidth=2, title="MA 1")

plot(ma2, color=ma2Color, linewidth=2, title="MA 2")

plot(ma3, color=ma3Color, linewidth=2, title="MA 3")

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// ©jdehorty
// @version=5

indicator('Machine Learning: Lorentzian Classification', 'Lorentzian Classification', true, precision=4, max_labels_count=500)

import jdehorty/MLExtensions/2 as ml

import jdehorty/KernelFunctions/2 as kernels

// ====================

// ==== Background ====

// ====================

// When using Machine Learning algorithms like K-Nearest Neighbors, choosing an

// appropriate distance metric is essential. Euclidean Distance is often used as

// the default distance metric, but it may not always be the best choice. This is

// because market data is often significantly impacted by proximity to significant

// world events such as FOMC Meetings and Black Swan events. These major economic

// events can contribute to a warping effect analogous a massive object's

// gravitational warping of Space-Time. In financial markets, this warping effect

// operates on a continuum, which can analogously be referred to as "Price-Time".

// To help to better account for this warping effect, Lorentzian Distance can be
// used as an alternative distance metric to Euclidean Distance. The geometry of

// Lorentzian Space can be difficult to visualize at first, and one of the best

// ways to intuitively understand it is through an example involving 2 feature

// dimensions (z=2). For purposes of this example, let's assume these two features

// are Relative Strength Index (RSI) and the Average Directional Index (ADX). In

// reality, the optimal number of features is in the range of 3-8, but for the sake

// of simplicity, we will use only 2 features in this example.

// Fundamental Assumptions:

// (1) We can calculate RSI and ADX for a given chart.

// (2) For simplicity, values for RSI and ADX are assumed to adhere to a Gaussian

// distribution in the range of 0 to 100.

// (3) The most recent RSI and ADX value can be considered the origin of a coordinate

// system with ADX on the x-axis and RSI on the y-axis.

// Distances in Euclidean Space:

// Measuring the Euclidean Distances of historical values with the most recent point

// at the origin will yield a distribution that resembles Figure 1 (below).

// [RSI]
// |

// |

// |

// ...:::....

// .:.:::••••••:::•::..

// .:•:.:•••::::••::••....::.

// ....:••••:••••••••::••:...:•.

// ...:.::::::•••:::•••:•••::.:•..

// ::•:.:•:•••••••:.:•::::::...:..

// |--------.:•••..•••••••:••:...:::•:•:..:..----------[ADX]

// 0 :•:....:•••••::.:::•••::••:.....

// ::....:.:••••••••:•••::••::..:.

// .:...:••:::••••••••::•••....:

// ::....:.....:•::•••:::::..

// ..:..::••..::::..:•:..

// .::..:::.....:

// |

// |

// |

// |
// _|_ 0

//

// Figure 1: Neighborhood in Euclidean Space

// Distances in Lorentzian Space:

// However, the same set of historical values measured using Lorentzian Distance will

// yield a different distribution that resembles Figure 2 (below).

//

// [RSI]

// ::.. | ..:::

// ..... | ......

// .••••::. | :••••••.

// .:•••••:. | :::••••••.

// .•••••:... | .::.••••••.

// .::•••••::.. | :..••••••..

// .:•••••••::.........::••••••:..

// ..::::••••.•••••••.•••••••:.

// ...:•••••••.•••••••••::.

// .:..••.••••••.••••..
// |---------------.:•••••••••••••••••.---------------[ADX]

// 0 .:•:•••.••••••.•••••••.

// .••••••••••••••••••••••••:.

// .:••••••••••::..::.::••••••••:.

// .::••••••::. | .::•••:::.

// .:••••••.. | :••••••••.

// .:••••:... | ..•••••••:.

// ..:••::.. | :.•••••••.

// .:•.... | ...::.:••.

// ...:.. | :...:••.

// :::. | ..::

// _|_ 0

//

// Figure 2: Neighborhood in Lorentzian Space

// Observations:

// (1) In Lorentzian Space, the shortest distance between two points is not

// necessarily a straight line, but rather, a geodesic curve.

// (2) The warping effect of Lorentzian distance reduces the overall influence
// of outliers and noise.

// (3) Lorentzian Distance becomes increasingly different from Euclidean Distance

// as the number of nearest neighbors used for comparison increases.

// ======================

// ==== Custom Types ====

// ======================

// This section uses PineScript's new Type syntax to define important data structures

// used throughout the script.

type Settings

float source

int neighborsCount

int maxBarsBack

int featureCount

int colorCompression

bool showExits

bool useDynamicExits
type Label

int long

int short

int neutral

type FeatureArrays

array<float> f1

array<float> f2

array<float> f3

array<float> f4

array<float> f5

type FeatureSeries

float f1

float f2

float f3

float f4

float f5

type MLModel
int firstBarIndex

array<int> trainingLabels

int loopSize

float lastDistance

array<float> distancesArray

array<int> predictionsArray

int prediction

type FilterSettings

bool useVolatilityFilter

bool useRegimeFilter

bool useAdxFilter

float regimeThreshold

int adxThreshold

type Filter

bool volatility

bool regime

bool adx
// ==========================

// ==== Helper Functions ====

// ==========================

series_from(feature_string, _close, _high, _low, _hlc3, f_paramA, f_paramB) =>

switch feature_string

"RSI" => ml.n_rsi(_close, f_paramA, f_paramB)

"WT" => ml.n_wt(_hlc3, f_paramA, f_paramB)

"CCI" => ml.n_cci(_close, f_paramA, f_paramB)

"ADX" => ml.n_adx(_high, _low, _close, f_paramA)

get_lorentzian_distance(int i, int featureCount, FeatureSeries featureSeries, FeatureArrays featureArrays) =>

switch featureCount

5 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +

math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +

math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +

math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i))) +

math.log(1+math.abs(featureSeries.f5 - array.get(featureArrays.f5, i)))

4 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +

math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +


math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +

math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i)))

3 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +

math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +

math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i)))

2 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +

math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i)))

// ================

// ==== Inputs ====

// ================

// Settings Object: General User-Defined Inputs

Settings settings =

Settings.new(

input.source(title='Source', defval=close, group="General Settings", tooltip="Source of the input data"),

input.int(title='Neighbors Count', defval=8, group="General Settings", minval=1, maxval=100, step=1, tooltip="Number of neighbors to consider"),

input.int(title="Max Bars Back", defval=2000, group="General Settings"),

input.int(title="Feature Count", defval=5, group="Feature Engineering", minval=2, maxval=5, tooltip="Number of features to use for ML predictions."),
input.int(title="Color Compression", defval=1, group="General Settings", minval=1, maxval=10, tooltip="Compression factor for adjusting the intensity of
the color scale."),

input.bool(title="Show Default Exits", defval=false, group="General Settings", tooltip="Default exits occur exactly 4 bars after an entry signal. This
corresponds to the predefined length of a trade during the model's training process.", inline="exits"),

input.bool(title="Use Dynamic Exits", defval=false, group="General Settings", tooltip="Dynamic exits attempt to let profits ride by dynamically adjusting
the exit threshold based on kernel regression logic.", inline="exits")

// Trade Stats Settings

// Note: The trade stats section is NOT intended to be used as a replacement for proper backtesting. It is intended to be used for calibration purposes only.

showTradeStats = input.bool(true, 'Show Trade Stats', tooltip='Displays the trade stats for a given configuration. Useful for optimizing the settings in the
Feature Engineering section. This should NOT replace backtesting and should be used for calibration purposes only. Early Signal Flips represent instances
where the model changes signals before 4 bars elapses; high values can indicate choppy (ranging) market conditions.', group="General Settings")

useWorstCase = input.bool(false, "Use Worst Case Estimates", tooltip="Whether to use the worst case scenario for backtesting. This option can be useful for
creating a conservative estimate that is based on close prices only, thus avoiding the effects of intrabar repainting. This option assumes that the user does
not enter when the signal first appears and instead waits for the bar to close as confirmation. On larger timeframes, this can mean entering after a large
move has already occurred. Leaving this option disabled is generally better for those that use this indicator as a source of confluence and prefer estimates
that demonstrate discretionary mid-bar entries. Leaving this option enabled may be more consistent with traditional backtesting results.", group="General
Settings")

// Settings object for user-defined settings

FilterSettings filterSettings =

FilterSettings.new(

input.bool(title="Use Volatility Filter", defval=true, tooltip="Whether to use the volatility filter.", group="Filters"),
input.bool(title="Use Regime Filter", defval=true, group="Filters", inline="regime"),

input.bool(title="Use ADX Filter", defval=false, group="Filters", inline="adx"),

input.float(title="Threshold", defval=-0.1, minval=-10, maxval=10, step=0.1, tooltip="Whether to use the trend detection filter. Threshold for detecting
Trending/Ranging markets.", group="Filters", inline="regime"),

input.int(title="Threshold", defval=20, minval=0, maxval=100, step=1, tooltip="Whether to use the ADX filter. Threshold for detecting Trending/Ranging
markets.", group="Filters", inline="adx")

// Filter object for filtering the ML predictions

Filter filter =

Filter.new(

ml.filter_volatility(1, 10, filterSettings.useVolatilityFilter),

ml.regime_filter(ohlc4, filterSettings.regimeThreshold, filterSettings.useRegimeFilter),

ml.filter_adx(settings.source, 14, filterSettings.adxThreshold, filterSettings.useAdxFilter)

// Feature Variables: User-Defined Inputs for calculating Feature Series.

f1_string = input.string(title="Feature 1", options=["RSI", "WT", "CCI", "ADX"], defval="RSI", inline = "01", tooltip="The first feature to use for ML
predictions.", group="Feature Engineering")

f1_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 1.", defval=14, inline = "02", group="Feature Engineering")
f1_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 2 (if applicable).", defval=1, inline = "02", group="Feature
Engineering")

f2_string = input.string(title="Feature 2", options=["RSI", "WT", "CCI", "ADX"], defval="WT", inline = "03", tooltip="The second feature to use for ML
predictions.", group="Feature Engineering")

f2_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 2.", defval=10, inline = "04", group="Feature Engineering")

f2_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 2 (if applicable).", defval=11, inline = "04", group="Feature
Engineering")

f3_string = input.string(title="Feature 3", options=["RSI", "WT", "CCI", "ADX"], defval="CCI", inline = "05", tooltip="The third feature to use for ML
predictions.", group="Feature Engineering")

f3_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 3.", defval=20, inline = "06", group="Feature Engineering")

f3_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 3 (if applicable).", defval=1, inline = "06", group="Feature
Engineering")

f4_string = input.string(title="Feature 4", options=["RSI", "WT", "CCI", "ADX"], defval="ADX", inline = "07", tooltip="The fourth feature to use for ML
predictions.", group="Feature Engineering")

f4_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 4.", defval=20, inline = "08", group="Feature Engineering")

f4_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 4 (if applicable).", defval=2, inline = "08", group="Feature
Engineering")

f5_string = input.string(title="Feature 5", options=["RSI", "WT", "CCI", "ADX"], defval="RSI", inline = "09", tooltip="The fifth feature to use for ML
predictions.", group="Feature Engineering")

f5_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 5.", defval=9, inline = "10", group="Feature Engineering")

f5_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 5 (if applicable).", defval=1, inline = "10", group="Feature
Engineering")
// FeatureSeries Object: Calculated Feature Series based on Feature Variables

featureSeries =

FeatureSeries.new(

series_from(f1_string, close, high, low, hlc3, f1_paramA, f1_paramB), // f1

series_from(f2_string, close, high, low, hlc3, f2_paramA, f2_paramB), // f2

series_from(f3_string, close, high, low, hlc3, f3_paramA, f3_paramB), // f3

series_from(f4_string, close, high, low, hlc3, f4_paramA, f4_paramB), // f4

series_from(f5_string, close, high, low, hlc3, f5_paramA, f5_paramB) // f5

// FeatureArrays Variables: Storage of Feature Series as Feature Arrays Optimized for ML

// Note: These arrays cannot be dynamically created within the FeatureArrays Object Initialization and thus must be set-up in advance.

var f1Array = array.new_float()

var f2Array = array.new_float()

var f3Array = array.new_float()

var f4Array = array.new_float()

var f5Array = array.new_float()

array.push(f1Array, featureSeries.f1)

array.push(f2Array, featureSeries.f2)

array.push(f3Array, featureSeries.f3)
array.push(f4Array, featureSeries.f4)

array.push(f5Array, featureSeries.f5)

// FeatureArrays Object: Storage of the calculated FeatureArrays into a single object

featureArrays =

FeatureArrays.new(

f1Array, // f1

f2Array, // f2

f3Array, // f3

f4Array, // f4

f5Array // f5

// Label Object: Used for classifying historical data as training data for the ML Model

Label direction =

Label.new(

long=1,

short=-1,

neutral=0

)
// Derived from General Settings

maxBarsBackIndex = last_bar_index >= settings.maxBarsBack ? last_bar_index - settings.maxBarsBack : 0

// EMA Settings

useEmaFilter = input.bool(title="Use EMA Filter", defval=false, group="Filters", inline="ema")

emaPeriod = input.int(title="Period", defval=200, minval=1, step=1, group="Filters", inline="ema", tooltip="The period of the EMA used for the EMA Filter.")

isEmaUptrend = useEmaFilter ? close > ta.ema(close, emaPeriod) : true

isEmaDowntrend = useEmaFilter ? close < ta.ema(close, emaPeriod) : true

useSmaFilter = input.bool(title="Use SMA Filter", defval=false, group="Filters", inline="sma")

smaPeriod = input.int(title="Period", defval=200, minval=1, step=1, group="Filters", inline="sma", tooltip="The period of the SMA used for the SMA Filter.")

isSmaUptrend = useSmaFilter ? close > ta.sma(close, smaPeriod) : true

isSmaDowntrend = useSmaFilter ? close < ta.sma(close, smaPeriod) : true

// Nadaraya-Watson Kernel Regression Settings

useKernelFilter = input.bool(true, "Trade with Kernel", group="Kernel Settings", inline="kernel")

showKernelEstimate = input.bool(true, "Show Kernel Estimate", group="Kernel Settings", inline="kernel")

useKernelSmoothing = input.bool(false, "Enhance Kernel Smoothing", tooltip="Uses a crossover based mechanism to smoothen kernel color changes. This
often results in less color transitions overall and may result in more ML entry signals being generated.", inline='1', group='Kernel Settings')

h = input.int(8, 'Lookback Window', minval=3, tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent
historical bars. Recommended range: 3-50', group="Kernel Settings", inline="kernel")
r = input.float(8., 'Relative Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert
more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian
kernel. Recommended range: 0.25-25', group="Kernel Settings", inline="kernel")

x = input.int(25, "Regression Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values
are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Settings", inline="kernel")

lag = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='1', group='Kernel
Settings')

// Display Settings

showBarColors = input.bool(true, "Show Bar Colors", tooltip="Whether to show the bar colors.", group="Display Settings")

showBarPredictions = input.bool(defval = true, title = "Show Bar Prediction Values", tooltip = "Will show the ML model's evaluation of each bar as an
integer.", group="Display Settings")

useAtrOffset = input.bool(defval = false, title = "Use ATR Offset", tooltip = "Will use the ATR offset instead of the bar prediction offset.", group="Display
Settings")

barPredictionsOffset = input.float(0, "Bar Prediction Offset", minval=0, tooltip="The offset of the bar predictions as a percentage from the bar high or
close.", group="Display Settings")

// =================================

// ==== Next Bar Classification ====

// =================================

// This model specializes specifically in predicting the direction of price action over the course of the next 4 bars.
// To avoid complications with the ML model, this value is hardcoded to 4 bars but support for other training lengths may be added in the future.

src = settings.source

y_train_series = src[4] < src[0] ? direction.short : src[4] > src[0] ? direction.long : direction.neutral

var y_train_array = array.new_int(0)

// Variables used for ML Logic

var predictions = array.new_float(0)

var prediction = 0.

var signal = direction.neutral

var distances = array.new_float(0)

array.push(y_train_array, y_train_series)

// =========================

// ==== Core ML Logic ====

// =========================

// Approximate Nearest Neighbors Search with Lorentzian Distance:

// A novel variation of the Nearest Neighbors (NN) search algorithm that ensures a chronologically uniform distribution of neighbors.
// In a traditional KNN-based approach, we would iterate through the entire dataset and calculate the distance between the current bar

// and every other bar in the dataset and then sort the distances in ascending order. We would then take the first k bars and use their

// labels to determine the label of the current bar.

// There are several problems with this traditional KNN approach in the context of real-time calculations involving time series data:

// - It is computationally expensive to iterate through the entire dataset and calculate the distance between every historical bar and

// the current bar.

// - Market time series data is often non-stationary, meaning that the statistical properties of the data change slightly over time.

// - It is possible that the nearest neighbors are not the most informative ones, and the KNN algorithm may return poor results if the

// nearest neighbors are not representative of the majority of the data.

// Previously, the user @capissimo attempted to address some of these issues in several of his PineScript-based KNN implementations by:

// - Using a modified KNN algorithm based on consecutive furthest neighbors to find a set of approximate "nearest" neighbors.

// - Using a sliding window approach to only calculate the distance between the current bar and the most recent n bars in the dataset.

// Of these two approaches, the latter is inherently limited by the fact that it only considers the most recent bars in the overall dataset.

// The former approach has more potential to leverage historical price action, but is limited by:

// - The possibility of a sudden "max" value throwing off the estimation

// - The possibility of selecting a set of approximate neighbors that are not representative of the majority of the data by oversampling
// values that are not chronologically distinct enough from one another

// - The possibility of selecting too many "far" neighbors, which may result in a poor estimation of price action

// To address these issues, a novel Approximate Nearest Neighbors (ANN) algorithm is used in this indicator.

// In the below ANN algorithm:

// 1. The algorithm iterates through the dataset in chronological order, using the modulo operator to only perform calculations every 4 bars.

// This serves the dual purpose of reducing the computational overhead of the algorithm and ensuring a minimum chronological spacing

// between the neighbors of at least 4 bars.

// 2. A list of the k-similar neighbors is simultaneously maintained in both a predictions array and corresponding distances array.

// 3. When the size of the predictions array exceeds the desired number of nearest neighbors specified in settings.neighborsCount,

// the algorithm removes the first neighbor from the predictions array and the corresponding distance array.

// 4. The lastDistance variable is overriden to be a distance in the lower 25% of the array. This step helps to boost overall accuracy

// by ensuring subsequent newly added distance values increase at a slower rate.

// 5. Lorentzian distance is used as a distance metric in order to minimize the effect of outliers and take into account the warping of

// "price-time" due to proximity to significant economic events.

lastDistance = -1.0

size = math.min(settings.maxBarsBack-1, array.size(y_train_array)-1)

sizeLoop = math.min(settings.maxBarsBack-1, size)


if bar_index >= maxBarsBackIndex //{

for i = 0 to sizeLoop //{

d = get_lorentzian_distance(i, settings.featureCount, featureSeries, featureArrays)

if d >= lastDistance and i%4 //{

lastDistance := d

array.push(distances, d)

array.push(predictions, math.round(array.get(y_train_array, i)))

if array.size(predictions) > settings.neighborsCount //{

lastDistance := array.get(distances, math.round(settings.neighborsCount*3/4))

array.shift(distances)

array.shift(predictions)

//}

//}

//}

prediction := array.sum(predictions)

//}

// ============================

// ==== Prediction Filters ====


// ============================

// User Defined Filters: Used for adjusting the frequency of the ML Model's predictions

filter_all = filter.volatility and filter.regime and filter.adx

// Filtered Signal: The model's prediction of future price movement direction with user-defined filters applied

signal := prediction > 0 and filter_all ? direction.long : prediction < 0 and filter_all ? direction.short : nz(signal[1])

// Bar-Count Filters: Represents strict filters based on a pre-defined holding period of 4 bars

var int barsHeld = 0

barsHeld := ta.change(signal) ? 0 : barsHeld + 1

isHeldFourBars = barsHeld == 4

isHeldLessThanFourBars = 0 < barsHeld and barsHeld < 4

// Fractal Filters: Derived from relative appearances of signals in a given time series fractal/segment with a default length of 4 bars

isDifferentSignalType = ta.change(signal)

isEarlySignalFlip = ta.change(signal) and (ta.change(signal[1]) or ta.change(signal[2]) or ta.change(signal[3]))

isBuySignal = signal == direction.long and isEmaUptrend and isSmaUptrend

isSellSignal = signal == direction.short and isEmaDowntrend and isSmaDowntrend

isLastSignalBuy = signal[4] == direction.long and isEmaUptrend[4] and isSmaUptrend[4]


isLastSignalSell = signal[4] == direction.short and isEmaDowntrend[4] and isSmaDowntrend[4]

isNewBuySignal = isBuySignal and isDifferentSignalType

isNewSellSignal = isSellSignal and isDifferentSignalType

// Kernel Regression Filters: Filters based on Nadaraya-Watson Kernel Regression using the Rational Quadratic Kernel

// For more information on this technique refer to my other open source indicator located here:

// https://www.tradingview.com/script/AWNvbPRM-Nadaraya-Watson-Rational-Quadratic-Kernel-Non-Repainting/

c_green = color.new(#009988, 20)

c_red = color.new(#CC3311, 20)

transparent = color.new(#000000, 100)

yhat1 = kernels.rationalQuadratic(settings.source, h, r, x)

yhat2 = kernels.gaussian(settings.source, h-lag, x)

kernelEstimate = yhat1

// Kernel Rates of Change

bool wasBearishRate = yhat1[2] > yhat1[1]

bool wasBullishRate = yhat1[2] < yhat1[1]

bool isBearishRate = yhat1[1] > yhat1

bool isBullishRate = yhat1[1] < yhat1

isBearishChange = isBearishRate and wasBullishRate

isBullishChange = isBullishRate and wasBearishRate


// Kernel Crossovers

bool isBullishCrossAlert = ta.crossover(yhat2, yhat1)

bool isBearishCrossAlert = ta.crossunder(yhat2, yhat1)

bool isBullishSmooth = yhat2 >= yhat1

bool isBearishSmooth = yhat2 <= yhat1

// Kernel Colors

color colorByCross = isBullishSmooth ? c_green : c_red

color colorByRate = isBullishRate ? c_green : c_red

color plotColor = showKernelEstimate ? (useKernelSmoothing ? colorByCross : colorByRate) : transparent

plot(kernelEstimate, color=plotColor, linewidth=2, title="Kernel Regression Estimate")

// Alert Variables

bool alertBullish = useKernelSmoothing ? isBullishCrossAlert : isBullishChange

bool alertBearish = useKernelSmoothing ? isBearishCrossAlert : isBearishChange

// Bullish and Bearish Filters based on Kernel

isBullish = useKernelFilter ? (useKernelSmoothing ? isBullishSmooth : isBullishRate) : true

isBearish = useKernelFilter ? (useKernelSmoothing ? isBearishSmooth : isBearishRate) : true

// ===========================

// ==== Entries and Exits ====

// ===========================
// Entry Conditions: Booleans for ML Model Position Entries

startLongTrade = isNewBuySignal and isBullish and isEmaUptrend and isSmaUptrend

startShortTrade = isNewSellSignal and isBearish and isEmaDowntrend and isSmaDowntrend

// Dynamic Exit Conditions: Booleans for ML Model Position Exits based on Fractal Filters and Kernel Regression Filters

lastSignalWasBullish = ta.barssince(startLongTrade) < ta.barssince(startShortTrade)

lastSignalWasBearish = ta.barssince(startShortTrade) < ta.barssince(startLongTrade)

barsSinceRedEntry = ta.barssince(startShortTrade)

barsSinceRedExit = ta.barssince(alertBullish)

barsSinceGreenEntry = ta.barssince(startLongTrade)

barsSinceGreenExit = ta.barssince(alertBearish)

isValidShortExit = barsSinceRedExit > barsSinceRedEntry

isValidLongExit = barsSinceGreenExit > barsSinceGreenEntry

endLongTradeDynamic = (isBearishChange and isValidLongExit[1])

endShortTradeDynamic = (isBullishChange and isValidShortExit[1])

// Fixed Exit Conditions: Booleans for ML Model Position Exits based on a Bar-Count Filters

endLongTradeStrict = ((isHeldFourBars and isLastSignalBuy) or (isHeldLessThanFourBars and isNewSellSignal and isLastSignalBuy)) and startLongTrade[4]

endShortTradeStrict = ((isHeldFourBars and isLastSignalSell) or (isHeldLessThanFourBars and isNewBuySignal and isLastSignalSell)) and startShortTrade[4]
isDynamicExitValid = not useEmaFilter and not useSmaFilter and not useKernelSmoothing

endLongTrade = settings.useDynamicExits and isDynamicExitValid ? endLongTradeDynamic : endLongTradeStrict

endShortTrade = settings.useDynamicExits and isDynamicExitValid ? endShortTradeDynamic : endShortTradeStrict

// =========================

// ==== Plotting Labels ====

// =========================

// Note: These will not repaint once the most recent bar has fully closed. By default, signals appear over the last closed bar; to override this behavior set
offset=0.

plotshape(startLongTrade ? low : na, 'Buy', shape.labelup, location.belowbar, color=ml.color_green(prediction), size=size.small, offset=0)

plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, ml.color_red(-prediction), size=size.small, offset=0)

plotshape(endLongTrade and settings.showExits ? high : na, 'StopBuy', shape.xcross, location.absolute, color=#3AFF17, size=size.tiny, offset=0)

plotshape(endShortTrade and settings.showExits ? low : na, 'StopSell', shape.xcross, location.absolute, color=#FD1707, size=size.tiny, offset=0)

// ================

// ==== Alerts ====

// ================

// Separate Alerts for Entries and Exits


alertcondition(startLongTrade, title='Open Long ▲', message='LDC Open Long ▲ | {{ticker}}@{{close}} | ({{interval}})')

alertcondition(endLongTrade, title='Close Long ▲', message='LDC Close Long ▲ | {{ticker}}@{{close}} | ({{interval}})')

alertcondition(startShortTrade, title='Open Short ▼', message='LDC Open Short | {{ticker}}@{{close}} | ({{interval}})')

alertcondition(endShortTrade, title='Close Short ▼', message='LDC Close Short ▼ | {{ticker}}@{{close}} | ({{interval}})')

// Combined Alerts for Entries and Exits

alertcondition(startShortTrade or startLongTrade, title='Open Position ▲▼', message='LDC Open Position ▲▼ | {{ticker}}@{{close}} | ({{interval}})')

alertcondition(endShortTrade or endLongTrade, title='Close Position ▲▼', message='LDC Close Position ▲▼ | {{ticker}}@[{{close}}] | ({{interval}})')

// Kernel Estimate Alerts

alertcondition(condition=alertBullish, title='Kernel Bullish Color Change', message='LDC Kernel Bullish ▲ | {{ticker}}@{{close}} | ({{interval}})')

alertcondition(condition=alertBearish, title='Kernel Bearish Color Change', message='LDC Kernel Bearish ▼ | {{ticker}}@{{close}} | ({{interval}})')

// =========================

// ==== Display Signals ====

// =========================

atrSpaced = useAtrOffset ? ta.atr(1) : na

compressionFactor = settings.neighborsCount / settings.colorCompression


c_pred = prediction > 0 ? color.from_gradient(prediction, 0, compressionFactor, #787b86, #009988) : prediction <= 0 ? color.from_gradient(prediction, -
compressionFactor, 0, #CC3311, #787b86) : na

c_label = showBarPredictions ? c_pred : na

c_bars = showBarColors ? color.new(c_pred, 50) : na

x_val = bar_index

y_val = useAtrOffset ? prediction > 0 ? high + atrSpaced: low - atrSpaced : prediction > 0 ? high + hl2*barPredictionsOffset/20 : low -
hl2*barPredictionsOffset/30

label.new(x_val, y_val, str.tostring(prediction), xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_up, c_label, size.normal,
text.align_left)

barcolor(showBarColors ? color.new(c_pred, 50) : na)

// =====================

// ==== Backtesting ====

// =====================

// The following can be used to stream signals to a backtest adapter

backTestStream = switch

startLongTrade => 1

endLongTrade => 2

startShortTrade => -1

endShortTrade => -2
plot(backTestStream, "Backtest Stream", display=display.none)

// The following can be used to display real-time trade stats. This can be a useful mechanism for obtaining real-time feedback during Feature Engineering.
This does NOT replace the need to properly backtest.

// Note: In this context, a "Stop-Loss" is defined instances where the ML Signal prematurely flips directions before an exit signal can be generated.

[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader, winLossRatio, winRate] = ml.backtest(high, low, open, startLongTrade,
endLongTrade, startShortTrade, endShortTrade, isEarlySignalFlip, maxBarsBackIndex, bar_index, settings.source, useWorstCase)

init_table() =>

c_transparent = color.new(color.black, 100)

table.new(position.top_right, columns=2, rows=7, frame_color=color.new(color.black, 100), frame_width=1, border_width=1,


border_color=c_transparent)

update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winRate, stopLosses) =>

c_transparent = color.new(color.black, 100)

table.cell(tbl, 0, 0, tradeStatsHeader, text_halign=text.align_center, text_color=color.gray, text_size=size.normal)

table.cell(tbl, 0, 1, 'Winrate', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)

table.cell(tbl, 1, 1, str.tostring(totalWins / totalTrades, '#.#%'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray,


text_size=size.normal)

table.cell(tbl, 0, 2, 'Trades', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)

table.cell(tbl, 1, 2, str.tostring(totalTrades, '#') + ' (' + str.tostring(totalWins, '#') + '|' + str.tostring(totalLosses, '#') + ')', text_halign=text.align_center,
bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 5, 'WL Ratio', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)

table.cell(tbl, 1, 5, str.tostring(totalWins / totalLosses, '0.00'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray,


text_size=size.normal)

table.cell(tbl, 0, 6, 'Early Signal Flips', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)

table.cell(tbl, 1, 6, str.tostring(totalEarlySignalFlips, '#'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)

if showTradeStats

var tbl = ml.init_table()

if barstate.islast

update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winRate, totalEarlySignalFlips)

//@version=5

indicator("Options Levels Support and Resistance", "✨Support and Resistance Options Levels✨ by Mars", overlay=true)

// Level data strings:

var string level_data1 =


"NDX:18500,19500,21275,22000,19130.0,22384.8,20700,22000,20740,19,0.8,6.5,1,20600,22000;RUT:2000,2110,2250,2400,2056.5,2381.9,2170,2300,2210
,24,0.6,-2.1,2,2185,2300;SPX:5000,4000,6000,5950,5551.9,6134.0,5825,6050,5835,15,0.6,-0.4,4,5825,6050;VIX:17,15,20,30,11.5,26.0,18,19,17,108,2.6,-
5,4,18,19;DJT:2.5,1,50,70,23.5,55.2,25,40,0,139,1.5,-4.8,4,35.5,39.5;PTON:3,2,10,9,6.2,11.3,7,9,0,97,2.3,-
5.3,4,8.5,9;IONQ:10,20,30,50,17.2,41.9,20,30,0,145,1.1,0,3,27,30;NRG:20,45,100,105,86.7,112.8,95,105,0,45,0.8,5,3,95,105;ALGT:100,40,105,110,85.2,116.
7,100,105,0,54,1.2,5,1,100,105;ATOM:7.5,5,20,15,4.9,13.7,7.5,10,0,153,3.1,-20,3,0,10;BMA:80,45,125,120,95.6,133.5,110,115,0,55,2.6,-
4.2,1,110,115;GGAL:38,40,75,80,59.6,81.2,65,75,0,53,1.1,-6.2,2,65,75;INTA:35,45,75,70,54.9,76.6,65,70,0,55,1.5,-
6.7,0,65,70;MRVL:72.5,70,120,125,98.9,131.5,110,120,0,48,1.0,4.3,4,109,116;MVST:2,1.5,3,2.5,1,3.1,1.5,2.5,0,180,2.9,25,4,2,0;RCAT:7,9,15,12,5.6,13.1,9,10
,0,137,2.0,-9.1,3,9,10;UNFI:28,14,30,31,23.9,32.1,26,29,0,49,4.2,3.6,2,26,29;WRBY:12.5,20,25,30,20.8,28.4,22.5,25,0,53,0.7,-
16.7,3,22.5,25;MMM:130,120,140,150,121.2,153.2,135,140,0,39,2.1,2.2,3,135,140;GEO:22,20,40,35,24.9,38.4,30,32,0,70,1.8,3.2,4,29,32;HIMS:20,25,35,30
,19.6,32.8,23,28,0,86,1.0,7.7,4,24,26.5;MS:80,85,135,130,110.9,138.3,115,135,0,38,0.8,3.8,4,115,131;SN:75,100,110,115,88.6,122.9,100,110,0,53,0.9,4.8,2,
100,110;BX:160,155,195,185,150,188.6,160,180,0,38,0.9,5.9,3,165,175;FVRR:30,25,35,34,25.9,36.7,30,32,0,59,3.1,3.2,2,30,32;BE:5,15,30,25,17.5,27.1,21,2
5,0,73,1.6,4.2,3,21.5,23.5;GEV:330,280,390,400,320.2,444.3,350,390,0,57,1.3,-
2.5,2,360,390;CRDO:65,25,80,75,53.1,85.7,65,75,0,80,1.6,7.1,3,65,75;OXY:50,45,55,60,47.6,56.6,50,55,0,29,2.4,5.8,4,52,53;BROS:45,55,60,70,50.2,67.9,55,
60,0,51,1.4,-4,2,57.5,60;RKLB:20,5,30,26,17.4,30.9,20,26,0,95,1.7,4,4,22,24.5;QCOM:105,140,170,165,140.7,178.4,155,160,0,40,1.0,-
5.9,4,155,165;ENVX:10,7.5,20,40,8.2,12.9,9,11,0,75,3.0,-8.3,4,10,11;FTAI:120,130,180,170,120.6,186,150,160,0,74,0.6,-
3.0,2,150,160;PAY:30,26,35,33,23.3,37.5,29,33,0,78,4.5,3.1,1,29,33;FTI:29,28,35,33,29.0,35.9,32,33,0,36,3.2,-
2.9,2,32,33;OWL:22,15,23,26,20.0,25.1,22,23,0,39,0.9,-
4.2,3,22,23;ERJ:35,17.5,40,45,31.3,44.2,35,40,0,51,1.3,0,3,35,40;VST:145,120,200,180,138.9,202.2,155,175,0,63,1.3,2.9,3,155,172.5;A:140,115,145,150,129
.1,157.8,140,145,0,33,1.2,-3.3,1,140,145;AA:35,25,50,40,31.2,42.6,35,37,0,54,1.5,-
9.8,3,35,37;AAL:10,12,20,25,15.6,20.9,18,19,0,49,0.6,5.6,4,18,18.5;AAOI:25,12.5,40,50,19.4,36.2,25,30,0,102,2.2,-
14.3,4,0,30;AAPL:200,220,250,255,215.9,250.6,230,240,0,25,1.2,-2.0,4,230,240;AAT:20,22.5,25,30,20.1,29.3,22.5,25,0,53,2.4,-16.7,1,22.5,25;"

var string level_data2 = "ABNB:120,115,150,140,114.4,140.8,125,130,0,35,1.0,-7.1,3,125,130;ACIC:11.5,12,13.5,15,10.3,14.3,12,13,0,56,1.3,-


7.1,1,12,13;ACRS:2,1,4,3,0,5.8,2,3,0,339,3.4,-
25,2,0,0;ADBE:400,410,500,450,380.1,445.3,410,420,0,27,1.3,1.2,2,410,420;AEHR:10,5,15,17.5,9.0,14.3,10,12.5,0,78,1.7,-
28.6,3,0,12.5;AEM:70,75,90,85,75.3,92.6,80,85,0,35,1.9,-
15,3,80,85;AFRM:35,32.5,75,60,42.2,68.5,45,60,0,81,1.2,9.1,4,50,56;AGX:140,35,170,175,134.2,201.9,160,170,0,65,1.0,-
2.9,1,160,170;AHR:22.5,25,30,35,18.6,36.1,17.5,30,0,101,18.7,0,1,25,30;AIRG:2.5,5,7.5,12.5,2.8,9.8,5,7.5,0,170,1.1,0,1,0,0;ALAB:125,30,150,145,96.1,160.8
,125,135,0,85,1,3.8,2,125,135;ALK:57.5,35,70,80,58.6,76.3,65,67.5,0,43,2,-
3.6,3,65,67.5;ALL:135,170,200,210,168.1,205.6,185,195,0,34,0.6,2.6,2,185,195;ALSN:105,115,125,120,101.5,130.5,115,120,0,42,3.0,4.3,0,115,120;AMAT:15
0,160,180,200,150.1,197.2,170,180,0,44,0.9,2.9,3,170,180;AMD:110,115,150,130,99.7,132.5,115,120,0,48,1.6,4.3,4,114,119;AMSC:23,24,45,30,19.4,33.3,2
6,27,0,88,2.1,3.8,2,26,27;AMZN:180,160,230,225,199.1,236.4,215,225,0,29,1.3,-
2.2,4,215,225;ANET:90,95,120,115,100.3,129.5,110,120,0,43,0.9,4.3,3,114,120;ANF:120,115,162.5,160,110.0,152.8,115,140,0,56,0.5,-
9.7,2,125,140;AOUT:12.5,10,15,17.5,11.9,17.6,12.5,15,0,59,14.3,-14.3,1,0,15;APAM:40,35,55,45,37.1,45.5,40,45,0,35,13.3,-
10,1,40,45;APEI:15,20,22.5,35,12.9,27.9,20,22.5,0,107,15.5,-
10,0,0,0;APH:70,65,75,80,62.3,78.3,37.5,75,0,39,1.1,7.1,2,70,75;APLD:7,8,10,9,4.7,12.4,6,9,0,157,2.0,-
10,4,8,9;APO:150,155,180,175,141.1,177.5,155,165,0,38,1.8,6.5,3,155,165;APOG:50,45,60,80,42.9,63.1,50,55,0,55,3.3,-
8.3,1,50,55;APP:300,120,400,350,253.1,389.1,290,330,0,72,1.3,-
5.7,2,295,322.5;ARGT:80,84,89,90,75.3,99.8,80,89,0,45,0.6,1.1,0,80,89;ARM:120,110,270,150,115.5,164.6,125,145,0,60,0.9,3.6,3,127,141;AROC:25,22.5,30,
35,18.7,38.5,17.5,30,0,83,6.8,20,1,0,30;AS:25,22.5,30,35,24.5,33.3,25,30,0,53,0.7,-14.3,2,0,30;ASAN:10,12.5,30,20,15.6,21.8,18,20,0,56,2.9,-
9.1,2,18,20;ASML:700,630,800,900,635.8,836.8,700,770,0,46,1.1,6.2,2,700,755;ASTS:20,5,30,35,15.2,25.8,20,22,0,88,2.3,-
12,4,19,21;ATAT:22.5,25,30,35,19.7,30.7,25,30,0,74,1.6,20,2,25,0;ATEN:15,17.5,20,22.5,15.0,21.4,17.5,20,0,58,8.8,-
11.1,1,17.5,20;AVGO:150,200,250,240,195.0,254.4,220,235,0,44,1,2.2,3,220,235;AVO:10,7.5,15,12.5,9.9,14.7,10,12.5,0,62,6.8,-
16.7,1,0,12.5;AVPT:9,15,19,20,13.6,19.5,9,17,0,51,2.1,-5.6,2,16,17;AXON:560,450,670,650,506.5,653.1,360,580,0,44,1.3,-
4.9,1,570,580;BABA:80,75,100,90,73.0,90.3,80,85,0,36,2.8,4.9,4,80,82;BAC:30,25,48,50,41.4,50.2,45,47,0,32,0.9,-
6,4,45,48;BANF:100,110,125,120,87.0,144.8,115,135,0,75,1.6,12.5,0,115,0;BB:2.5,3,5,4.5,3.2,4.8,3.5,4.5,0,69,4.3,12.5,4,0,0;"

var string level_data3 = "BBWI:22.5,32.5,40,37.5,32.2,41.3,36,38,0,42,0.7,-5,3,36,37;BFLY:1,2,5,7.5,2.2,4.6,2.5,3.5,0,117,5.6,-


12.5,3,0,3.5;BGC:9,8,10,12,7.9,10.6,9,10,0,48,5.4,-
9.1,2,9,10;BHB:25,30,35,40,10.2,50.8,30,35,0,163,11.0,16.7,0,30,0;BILL:42.5,37.5,100,85,69.2,95.4,75,85,0,54,2.0,-
5.6,2,81,84;BITX:40,35,80,60,37.0,71.5,40,55,0,106,2.1,-3.5,2,53,55;BL:35,57.5,65,62.5,45.3,71.1,57.5,60,0,67,0.1,-
4,1,57.5,60;BLK:960,920,1000,1100,860.2,1066.1,940,1020,0,35,0.8,2,1,940,1010;BMI:185,200,210,250,179.6,239.9,195,210,0,46,1.3,-
4.5,0,195,210;BOOT:145,125,170,160,124.9,175.3,135,155,0,58,1.2,-3.1,1,140,155;BR:210,220,240,260,207.5,246.7,220,230,0,27,3.4,-
4.2,0,220,230;BRC:65,70,75,80,60.0,85.3,70,75,0,55,7,-
6.2,0,70,75;BRFS:2.5,3.7,5,7.5,2.7,5.2,2.5,5,0,99,5.6,0,2,0,0;BRKL:10,7.5,12.5,15,7.3,16.1,10,12.5,0,104,1.5,0,0,0,12.5;BRO:100,95,105,110,93.3,113.9,100,1
05,0,34,10.5,-4.5,1,100,110;BURL:260,175,300,320,254.6,312.3,260,300,0,34,0.6,-
1.6,2,275,295;BWXT:100,115,120,125,100.7,133.5,110,120,0,41,2.5,4.3,1,115,120;BYRN:25,17.5,30,35,20.4,33.8,25,30,0,78,2.4,-
14.3,2,25,0;CAAP:12.5,15,22.5,20,14.3,23.9,17.5,22.5,0,75,19.4,12.5,1,17.5,20;CAC:35,40,45,50,32.0,54.8,40,45,0,71,1.1,-
10,1,40,0;CALM:95,100,110,115,98.4,121.5,105,110,0,36,1.1,-
4.3,1,105,110;CART:15,40,47,50,38.4,54.5,45,47,0,55,1.3,4.4,2,43,47;CAVA:50,105,120,150,95.8,129.0,105,115,0,51,1.1,2.7,2,107,115;CCL:5,2.5,25,26,21.5,
27.5,24,26,0,41,0.7,4,4,24,25.5;CDE:5,3.5,7.5,10,4.5,8.2,3.5,7.5,0,75,3.5,0,4,0,0;CEIX:60,90,100,110,82.4,116.9,90,105,0,57,0.9,5,2,90,105;CENX:3,16,30,25,
15.9,24.0,18,20,0,68,1.9,-4.8,2,19,20;CF:70,60,105,95,86.2,103.7,90,95,0,31,0.6,-
1.0,2,91,95;CFB:10,13.9,17.5,20,11.7,17.5,10,17.5,0,63,1.9,16.7,0,0,0;CFLT:25,15,35,30,22.1,32.4,26,28,0,64,2.7,-
6.7,3,26,28;CIVB:2.5,10,22.5,22.1,2.7,37.4,0,22.5,0,184,23.6,0,0,0,0;CLBT:17.5,20,22.5,25,18.2,26.4,20,22.5,0,58,2.4,-
10,2,0,22.5;CLH:200,210,240,260,209.8,260,230,240,0,34,1.6,-7.7,1,230,240;CLOV:3,3.5,4,7,2.9,4.6,3.5,4,0,75,4.8,-
11.1,4,3.5,4;CLS:70,62.5,105,115,82.1,124.1,100,110,0,66,1.6,4.8,2,99,110;CMG:14,55,94,60,50.4,62.4,56,58,0,35,0.8,-
3.3,3,56,58;CEG:210,200,290,300,248.8,328.9,270,290,0,47,0.7,-3.3,3,275,295;COCO:30,25,40,35,28.7,39.5,30,35,0,50,0.9,-
12.5,1,0,35;COF:170,165,195,190,161.9,207.5,175,185,0,41,1.3,-
2.6,3,182.5,185;COHR:90,55,100,105,78.8,107.2,85,100,0,53,1.5,4.2,2,90,96;COIN:200,220,320,300,202.8,307.9,230,260,0,70,1.6,-
3.7,4,230,260;COOP:25,40,100,110,84.7,108.3,92.5,100,0,38,0.8,2.6,1,92.5,100;CORT:43,50,60,65,40.3,63.0,36,55,0,77,0.9,10,2,48,55;CPRT:50,52.5,65,62.5
,51.4,61.1,55,62.5,0,28,1.6,8.7,2,55,57.5;CRM:320,300,370,360,295.6,351.5,320,340,0,29,1.0,3.0,3,320,335;"

var string level_data4 = "CRMD:8,9,12,13,8.4,14.0,10,12,0,87,4.2,-7.7,2,11,12;CRNT:4,3,6,5,3.6,5.8,4,5,0,77,17,-


16.7,3,0,5;CROX:100,105,115,130,89.9,120.3,100,110,0,50,1.4,2.8,2,103,108;CRS:155,165,260,200,167.6,224.6,185,200,0,49,1.6,-
4.8,2,185,200;CRWD:300,340,400,370,306.3,389.8,330,350,0,41,0.9,-
2.8,3,340,350;CSTL:22.5,25,35,30,19.7,31.2,25,30,0,72,4.0,20,1,25,0;CSV:30,25,40,45,33.2,46.2,35,40,0,57,8.3,-
11.1,1,0,40;CTAS:185,180,220,200,177.3,207.3,187.5,195,0,25,1.1,-
2.5,1,187.5,195;CTBI:50,40,55,60,42.0,63.6,40,60,0,68,2.0,0,0,0,0;CVCO:440,410,490,460,361.1,543.9,410,470,0,55,7.2,2.2,0,410,470;CVGW:20,22.5,30,25,
16.2,32.1,20,25,0,112,0.5,-
16.7,2,22.5,25;CVNA:25,125,200,215,158.6,231.8,180,200,0,64,0.6,2.6,3,190,200;CYBR:330,310,350,360,302.7,380.3,340,350,0,39,1.3,-
2.8,1,340,350;DAL:50,40,70,80,58.4,74.2,65,70,0,38,1.4,7.7,4,66,69;DASH:155,80,175,185,149.8,188.8,160,175,0,39,2.0,2.9,3,167.5,175;DAVE:80,75,105,95
,60.0,104.1,75,85,0,91,4.2,-10.5,1,75,85;DDL:2.5,3.1,5,7.5,0.8,5.8,2.5,0,0,230,13.1,-100,2,0,0;DDOG:135,130,150,140,124.0,154.3,135,140,0,38,0.9,-
0.7,3,135,140;DE:380,300,450,470,397.4,467.2,420,440,0,27,0.9,2.3,2,420,440;DECK:165,145,210,225,180.5,231.7,200,220,0,41,1.0,2.3,1,200,210;DLNG:5,
2.5,7.5,5.8,4,6.6,5,0,0,83,24.6,-
100,1,5,0;DLO:10,8,25,12.5,9.4,13.3,11,12.5,0,58,4.6,13.6,2,11,0;DOCS:45,30,60,55,41.8,59.8,50,52.5,0,59,1.3,5,2,50,52.5;DORM:100,110,150,160,102.2,14
9.7,125,140,0,54,8.9,12,0,125,130;DRS:25,27,40,35,29.8,39.2,20,35,0,47,3.1,-
2.8,1,34,35;DSP:17.5,12.5,20,22.5,13.8,21.3,17.5,20,0,72,1.3,14.3,1,17.5,0;DUOL:310,145,390,350,262.9,362.2,300,320,0,54,0.9,-
3.0,1,300,320;DX:10,11.7,12.5,15,10.7,13.8,10,12.5,0,31,2.7,-
16.7,2,0,12.5;EAT:70,60,145,155,120.9,165.4,135,145,0,53,0.6,3.6,1,135,145;EBS:7,6,12.5,10,6.6,12.1,9,12,0,99,3.7,20,2,9,10;EE:28,30,32,31,24.1,37.8,30,3
2,0,63,5.2,-
3.0,0,30,33;EFXT:10,5,12.5,11.3,8.4,12.1,10,12.5,0,61,7.9,25,0,10,0;ELF:95,115,140,150,106.4,156.6,120,140,0,66,1.0,7.7,2,126,133;EME:370,400,510,520,4
36.4,549.4,370,520,0,38,1.5,2.0,0,490,520;ENVA:70,85,105,115,74.1,128.8,90,105,0,72,2.8,5,0,95,105;EOSE:1,2,5,10,3.2,6.0,4,5,0,97,3.6,-
9.1,4,4.5,5;EXK:3,3.5,5,5.5,2.9,4.3,3.5,4,0,64,5.0,14.3,4,3.5,0;FAF:55,50,65,60,44.9,74.1,55,65,0,73,1.1,8.3,0,55,65;FBK:50,40,60,55,42.3,60.4,35,55,0,56,2.4,
10,0,50,55;FCX:35,23,50,60,33.8,45.2,39,40,0,44,1.5,2.6,4,37,40;FINV:5,6.6,7.5,10,5.2,8.8,5,7.5,0,72,163.7,0,2,0,7.5;FIX:400,430,470,480,393.1,539.8,240,5
00,0,55,0.9,6.4,0,460,500;FNKO:7.5,10,15,17.5,10,16.6,12.5,15,0,85,6.6,20,3,12.5,0;FOA:25,22.5,30,35,18.2,35.2,20,30,0,89,4.4,-
14.3,1,25,0;FOLD:9,8,10,11,7.4,11.0,9,10,0,64,3.3,11.1,2,9,10;"

var string level_data5 = "FOUR:95,97.5,110,120,87.9,116.4,100,105,0,47,0.7,-


4.5,2,100,105;FOXA:44,34,50,55,43.4,54.2,46,50,0,32,2.5,3.1,1,46,50;FSM:4.5,3.5,7,5.5,3.6,5.5,4.5,5,0,64,4.0,11.1,4,4.5,5;FSS:90,85,115,105,78.8,115.4,90,
100,0,55,3.9,5.3,0,90,100;FTDR:45,55,60,65,47.6,65.2,35,60,0,52,7.1,9.1,1,55,60;FTK:8,6,10,11,6.7,10.7,8,9,0,72,1.9,-
10,1,8,9;FTNT:50,45,100,95,80.9,104.1,90,95,0,43,0.9,1.1,3,89,93;FUTU:58.0,60,148.1,150,65.3,90.0,70,80,0,55,1.5,6.7,2,70,80;FWONA:75,80.4,90,85,66.2,
102.9,75,95,0,71,7.8,11.8,0,0,85;G:40,35,50,45,40.3,48.1,40,45,0,29,2.0,0,2,40,45;GAP:15,22,26,25,19.5,25.8,22,23,0,45,0.9,-
4.2,3,22.5,24;GBX:42.5,57.5,75,70,59.7,72.4,65,67.5,0,33,1.2,3.8,1,65,67.5;GCT:17.5,15,30,25,15.0,22.9,17.5,20,0,70,2.1,-
11.1,3,17.5,20;GDYN:20,17.5,25,22.5,16.7,24.2,20,22.5,0,61,3.2,12.5,1,20,0;GLOB:200,185,230,220,177.6,237.6,200,220,0,49,1.8,4.8,0,200,220;GLUE:5,2.5,
10,7.5,3.7,7.4,5,0,0,115,18.9,-
100,2,0,0;GM:33,30,57.5,55,44.7,57.2,50,55,0,41,1.0,5.8,4,50,52;GOOG:160,145,200,210,172.2,209.9,190,200,0,33,1.4,2.6,4,190,195;GRMN:200,190,220,2
30,192.3,232.3,210,220,0,32,0.8,4.8,1,210,220;GRND:15,13,18,17,14.3,19,16,17,0,47,2.8,-5.6,1,16,17;GRNY:19,18,22,21,17.2,22.5,19,21,0,40,4.8,-
4.5,1,19,20;GROY:1,1.2,2.5,1.5,0,2.5,1,1.5,0,288,22.6,-25,2,0,0;GSBC:45,40,65,75,50.3,68.7,50,65,0,33,8.6,-
7.1,0,0,65;GWRE:155,165,180,190,156.2,187.8,170,175,0,30,1.7,2.9,1,170,175;HAFC:17.5,20,22.5,25,0,47.3,17.5,25,0,264,34.9,0,1,0,22.5;HBCP:35,40,50,45
,28.3,60.8,40,45,0,64,5.3,-10,0,0,45;HITI:2.5,2.9,5,7.5,1.6,4.6,2.5,0,0,150,2.5,-
100,3,0,0;HLNE:120,110,160,150,75.0,207.3,120,150,0,104,2.0,3.4,0,0,145;HNST:5,2.5,7.5,10,4.0,8.2,5,7.5,0,110,5.4,0,3,0,0;HOOD:36,10,45,50,33.2,50.3,38
,42,0,69,1.9,-6.7,4,39.5,42;HQY:95,80,105,110,87,120.2,100,105,0,48,5.9,-
4.5,1,100,105;HURN:85,80,150,130,107.5,146.1,120,135,0,52,1.7,8,0,120,0;HWKN:110,100,200,195,72.3,151.6,100,115,0,90,3.9,-
8,0,110,115;HWM:110,105,125,130,106.0,132.4,60,125,0,37,3.3,4.2,2,115,125;IBIT:54,51,55,60,46.0,63.6,53,55,0,54,1.6,-
1.8,4,54,55;IBKR:180,175,185,190,160.6,204.7,175,185,0,39,1.3,-
2.6,2,175,185;IDCC:165,170,210,200,148.0,207.1,160,185,0,52,1.2,2.8,1,175,185;IMAX:21,20,25,28,19.7,26.4,23,24,0,47,1,4.3,2,23,24;IMCR:25,17.5,35,80,
15.4,41.7,25,30,0,151,1.8,-
14.3,0,0,30;INGR:130,120,135,145,107.1,158.5,115,140,0,59,0.8,3.7,0,130,140;INOD:25,33,40,50,24.3,43.6,25,35,0,93,1.5,2.9,2,31,35;INSG:9,10,12,14,8.1,1
3.1,10,11,0,80,0.7,-8.3,1,10,11;INSP:165,160,210,240,137.9,202.1,130,180,0,65,0.9,-2.7,1,155,180;IRDM:22.5,25,35,40,20.2,34.2,25,30,0,72,2.7,-
14.3,2,25,0;ISRG:500,530,600,540,473.5,604.3,520,540,0,42,0.9,-0.9,2,520,565;"

var string level_data6 = "IT:470,460,540,530,453,546.6,490,500,0,30,1.4,-


5.7,0,490,500;ITRN:30,22.5,35,40,27.5,37.6,30,35,0,49,8.7,16.7,0,30,35;IWM:210,200,240,230,202.6,236.8,219,230,0,24,0.6,1.3,4,219,230;JD:30,25,40,36,3
0.3,39.2,33,35,0,44,3.1,-2.8,4,33,35;JEF:67.5,65,72.5,75,64.0,79.1,70,72.5,0,34,2.0,-3.3,2,70,72.5;JHG:35,40,45,50,34.1,47.8,40,45,0,56,14.9,-
10,0,0,45;JPM:225,130,250,255,220.2,274.7,240,250,0,38,1.1,-
5.7,4,245,260;KEX:105,95,130,135,90.0,121.9,105,110,0,49,8.9,4.8,0,105,110;KGC:5.5,5,11,15,9.0,12.2,10,11,0,49,1.7,4.8,4,10.5,11;KGS:25,42.5,47.5,50,38,
52.8,40,47.5,0,51,1.9,5.6,1,0,47.5;KINS:10,12.5,15,17.5,10.4,18.3,7.5,15,0,80,25.4,-14.3,2,0,15;KNSL:380,420,500,440,362.1,497.5,360,430,0,52,0.7,-
2.3,0,420,440;KNTK:45,50,65,70,51.5,72.4,60,65,0,50,5.3,8.3,1,60,65;KR:55,57,60,65,55.5,64.3,59,60,0,24,2.6,-
1.6,3,59,61;KVYO:32.5,27.5,40,42.5,33.2,45.9,37.5,40,0,52,3.0,-
5.9,2,37.5,40;LAB:2,1.5,2.5,5,1.4,2.6,2,2.5,0,93,4.0,25,1,2,0;LC:13,14,20,25,12.6,18.2,15,16,0,62,2.1,-
5.9,2,15,16;LDOS:150,135,165,160,137.3,168.3,145,155,0,34,1.9,-
8.8,2,145,155;LMB:75,100,125,110,82.2,118.4,55,105,0,61,6.2,5,1,100,105;LMND:20,30,35,50,23.3,39.2,25,35,0,85,1.1,9.4,2,30,32.5;LNG:200,140,250,260,
222.5,263.6,230,250,0,29,1.1,4.2,2,240,250;LOCO:11,10,14,20,9.7,13.5,11,12,0,56,6.8,-
7.7,1,11,12;LRN:65,80,110,115,93.3,125.3,105,115,0,50,0.9,4.5,1,105,115;LULU:240,290,400,410,349.1,428.4,370,400,0,34,1.0,2.6,2,370,395;LUMN:1,2,7,1
0,4.0,6.6,3.5,5.5,0,83,1.4,-8.3,4,5,5.5;LUNR:16,11,25,20,11.1,22.5,13,17,0,119,2.8,-
5.6,3,15.5,18;LUV:22.5,25,35,37.5,29.4,36.9,32,35,0,37,0.9,6.1,4,33,34;LX:5,2.5,7.5,6.9,1.8,10.8,5,7.5,0,175,4.8,0,3,0,0;LZB:40,35,45,50,35.4,52.5,25,45,0,52
,1.5,-18.2,1,40,45;MANH:260,270,290,310,233,309,260,280,0,44,1.7,3.7,0,270,280;MASI:160,165,175,190,140.1,192.1,160,175,0,53,1.9,-
10.3,0,160,175;MATX:130,125,145,150,119.6,165.2,135,155,0,55,2.4,6.9,0,140,155;MAX:10,2.5,12.5,15,8.4,14.0,10,12.5,0,83,4,0,1,0,0;MCS:15,10,20,22.5,1
2.9,27,12.5,20,0,88,5.0,-11.1,0,0,20;MCY:40,45,70,55,34.8,63.1,40,55,0,98,0.3,-
8.3,2,45,50;MD:12.5,10,15,17.5,6.7,20.6,12.5,15,0,125,0.7,20,1,12.5,15;MDB:240,220,300,280,204.9,279.9,240,250,0,50,1.3,4.2,2,225,250;MELI:1600,1700
,2000,1900,1570.5,1936.8,1750,1760,0,35,1.0,-7.4,1,1710,1810;META:550,500,650,700,518.1,670.4,570,600,0,43,1.4,-
3.2,4,570,595;MFC:26,27,30,35,27.6,32.0,29,30,0,26,2.9,-
3.2,2,29,30;MFG:2.5,4.7,5,7.5,3.6,6.2,2.5,5,0,76,80.2,0,2,0,5;MNDY:160,220,280,290,183.7,256.6,145,230,0,56,2.1,4.5,2,220,230;MODG:7.5,5,10,20,6.1,10.
2,7.5,10,0,76,1.1,0,3,7.5,0;MOFG:25,27.4,30,31.7,16.8,40.8,25,30,0,120,3.9,0,0,0,30;MRX:30,25,35,35.8,25.3,39.8,30,35,0,76,1.2,0,0,30,35;"

var string level_data7 = "MSFT:400,410,470,450,383.2,448.2,415,430,0,26,1.2,-


1.1,4,415,425;MSGE:35,30,40,45,30.3,39.9,35,40,0,46,9.4,14.3,2,35,0;MSTR:0.5,315,460,370,252.3,432.1,180,350,0,90,0.9,2.9,3,310,345;MTCH:30,27.5,35,
37.5,27.5,35.9,30,32,0,42,2.9,-
3.0,3,30,32;MTZ:125,130,155,160,131.7,169.6,90,155,0,43,1.9,3.3,1,140,155;MU:90,80,105,110,83.8,110.9,90,100,0,48,1.5,5.3,4,93,98;MUFG:10,2.5,12.5,1
5,8.3,15.3,10,12.5,0,71,0.4,0,1,0,12.5;NBBK:12.5,16.6,20,17.5,10.5,24.4,12.5,17.5,0,92,49.0,-
12.5,2,0,17.5;NBTB:45,30,50,55,36.8,57.3,35,60,0,57,9.0,20,1,0,50;NCLH:7.5,5,29,30,22.3,29.7,24,27,0,46,1.0,3.8,4,24,27;NECB:19.9,22.5,30,29.9,18.8,29.4,
20,25,0,61,9.3,-16.7,1,0,25;NEO:12.5,10,20,17.5,5.6,22,12.5,15,0,152,2.0,7.1,2,0,15;NFLX:500,800,900,1000,715.2,941.6,800,845,0,46,0.8,-
1.7,3,825,845;NGVC:20,22.5,45,50,31.3,46.7,35,40,0,64,1.9,-
11.1,0,0,40;NIC:100,70,120,125,88.2,122.0,105,120,0,55,2.1,14.3,0,105,0;NKE:70,65,80,90,65.6,76.8,70,75,0,27,1.4,4.2,4,70,73;NNE:20,15,30,40,12.4,30.3,
20,25,0,124,2.1,25,2,20,22;NOW:800,940,1120,1260,911.9,1150.7,1020,1060,0,39,0.9,3.9,1,1020,1060;NREF:15,12.5,17.5,20,12.2,18.1,15,17.5,0,58,1.7,16.
7,0,0,0;NTCT:20,15,22.5,25,15.4,28.4,20,25,0,78,2.5,11.1,0,0,22.5;NTGR:17,25,32,33,20.7,31.9,25,27,0,66,4.7,-
3.6,2,26,27;NTRS:90,97.5,110,105,91.9,111.3,100,105,0,32,0.9,5,1,100,105;NU:10,8,14,12,9.4,12.4,10,11,0,47,2.4,-
8.3,4,10.5,11;NVDA:130,120,140,150,113.8,149.7,130,132,0,46,1.1,-4.3,4,131,135;NVO:80,77,110,125,70.9,91.5,80,85,0,43,1.3,-
2.3,3,79,84;NWG:7.5,9.1,10,12.5,7.4,11.8,7.5,10,0,62,4.4,-
20,1,0,10;NWPX:30,35,50,55,24.1,70.7,35,50,0,121,3.9,11.1,0,45,50;OKLO:20,15,25,30,16.1,29.5,21,24,0,100,1.8,-
7.7,3,21,23;OLLI:82.5,72.5,115,125,88.3,111.0,97.5,100,0,38,0.7,-
4.8,1,97.5,100;OLO:5,2.5,10,7.5,6.1,8.9,5,7.5,0,63,4.4,0,2,0,7.5;OMCL:40,35,50,45,26.3,58.4,40,45,0,106,3.1,-
10,1,40,45;ONIT:28,21,33,31,11.3,49.8,29,31,0,139,2.7,-3.1,0,29,31;ONON:42.5,50,60,55,47.2,61.8,50,55,0,44,1.8,-
8.3,3,53,55;OPFI:5,10,12.5,15,6.5,14.8,7.5,12.5,0,113,5.6,25,3,10,0;OPK:1,0.5,1.5,2,1.1,1.8,1,1.5,0,76,1.7,0,4,0,1.5;OPRA:10,15,20,22.5,14.5,21.1,17.5,20,0,
60,1.4,14.3,2,17.5,0;ORRF:15,30,40,38.6,1.1,69.1,30,40,0,228,27,14.3,0,0,0;OSPN:15,17.5,20,25,15.9,21.7,17.5,20,0,54,1.1,0,1,17.5,20;PAHC:20,15,22.5,25,
16.1,24.4,20,22.5,0,64,0.0,-10,1,0,0;PANW:140,75,190,200,152.4,188.8,170,175,0,36,0.9,2.9,3,170,175;PAYO:3,7,11,10,8.2,11.7,9,10,0,57,3.1,-
9.1,2,9,10;PBPB:9,8,11,13,8.4,12.5,10,11,0,67,14.9,10,1,10,11;PETS:2.5,4.6,7.5,5,3.8,5.9,2.5,5,0,72,0.5,0,3,0,5;PFSI:25,100,120,115,89.9,112.9,100,105,0,36,
1.2,5,2,100,105;PGC:20,25,35,34.6,17.9,45.0,30,35,0,135,0.4,16.7,0,30,0;"

var string level_data8 =


"PGR:230,155,260,250,217.0,262.5,235,250,0,31,4.2,2.0,2,235,250;PI:130,125,200,180,109.1,189.5,135,155,0,89,1.5,3.3,1,135,155;PKG:200,230,240,250,2
11.0,254.3,230,240,0,29,0.9,4.3,1,230,240;PLTR:60,50,80,70,53.0,78.8,50,70,0,67,1.1,7.7,4,61,66;PLUG:2,2.5,3,3.5,1.6,3.7,1.5,3,0,132,3.4,-
14.3,4,2.5,0;PLXS:140,160,195,170,109.6,221.9,140,170,0,77,50.8,3.0,0,165,170;PNC:180,190,210,200,175.4,216.0,185,210,0,33,2.7,7.7,2,185,205;PODD:2
50,175,280,270,225.6,308.4,260,280,0,52,0.9,3.7,1,260,280;PR:13,15,20,16,13.6,17.4,15,16,0,40,3.3,6.7,3,15,16;PRDO:25,22.5,30,35,20.2,33.3,25,30,0,70,0
.4,0,0,25,0;PRGS:55,57.5,67.5,70,54.9,70.1,60,65,0,30,0.1,-13.3,2,60,65;PRTH:0,1,12.5,10,7.2,11.9,0,10,0,72,2.2,-
20,0,0,10;PSN:90,70,105,130,84.5,104.4,90,95,0,36,3.5,-5,1,90,95;PSTG:60,35,70,65,54.9,71.6,50,65,0,46,1.4,-
7.1,3,60,65;PYPL:80,70,140,145,77.1,97.2,85,90,0,39,2.3,5.9,4,86,88;QCRH:60,74.7,80,85,67.0,90.2,60,80,0,44,11.0,-
11.1,0,0,80;QFIN:25,22.5,40,45,30.5,42.8,35,40,0,58,1.7,-11.1,2,35,40;QTWO:65,55,110,105,44.0,140.8,90,95,0,116,2.8,-
5,1,90,95;QUBT:5,2.5,25,20,2.5,12.4,5,8,0,223,1.5,-
11.1,3,7,7.5;RBLX:60,50,70,65,52.9,71.6,60,65,0,51,1.6,6.6,4,61,63;RBRK:60,65,80,70,53.6,76.6,65,70,0,57,2.0,3.7,2,65,70;RCL:22.5,25,240,242.5,200.4,259.
0,220,240,0,43,0.6,-4,2,225,235;RDDT:160,150,170,200,129.5,200.2,135,165,0,75,0.9,-
2.9,2,149,165;RDW:9,12,18,25,8.9,18.7,12,15,0,118,4.4,7.1,2,13,15;RDWR:20,21,22,24,16.9,25.4,21,22,0,69,2.2,-
4.3,0,21,22;RGTI:6,5,15,10,3.0,14.9,5,9,0,232,1.7,12.5,4,8.5,9;RIVN:10,12.5,15,16,10.6,16.0,11,14,0,67,1.4,3.7,4,12.5,13.5;RNG:25,20,40,35,27.6,38.1,30,35,
0,51,3.4,6.1,1,30,35;ROOT:70,75,90,100,58.1,111.5,80,85,0,110,1.7,-5.6,2,80,85;RSI:7.5,10,15,17.5,11.3,18.3,12.5,15,0,67,11.5,-
14.3,2,0,15;RUM:10,5,20,15,7.4,13.0,9,11,0,95,2.7,-
4.3,3,9.5,10.5;RUSHA:55,50,60,65,36.4,79.9,50,60,0,128,0.7,9.1,1,55,60;RWT:4,6,8,7,5.4,7.2,6,7,0,48,0.8,-
22.2,2,6,0;RYAAY:40,35,50,45,31.6,53.6,40,45,0,66,1.7,-
10,1,40,45;SAP:220,200,270,260,225.3,281.7,250,270,0,35,0.7,3.8,1,250,270;SE:55,75,120,130,96.2,124.7,100,115,0,43,1.4,4.5,3,108,114;SEI:12.5,22.5,30,3
5,22.0,36.6,22.5,30,0,84,17.3,-
14.3,2,0,30;SEIC:80,75,85,90,65.5,96.1,80,85,0,55,2.3,6.2,0,80,85;SFBS:60,55,100,95,57.1,115.2,50,95,0,94,32.2,11.8,0,0,0;SFM:75,70,140,180,120.2,156.0,
135,140,0,44,0.8,-3.4,2,135,140;SHOP:50,65,120,115,87.3,115.9,95,105,0,48,1.0,2.9,4,100,103;SKWD:35,40,50,45,35.8,53.0,35,45,0,63,12.2,-
10,0,40,45;SKX:70,55,72.5,75,62.5,80.1,70,72.5,0,39,1.1,-
3.3,2,70,72.5;SKY:85,90,110,105,77.6,103.1,90,95,0,47,1.4,5.6,1,90,95;SKYW:95,92.5,110,115,94.9,123.1,82.5,115,0,41,1.4,4.5,1,105,115;"

var string level_data9 = "SMH:240,200,275,270,220.0,270.9,245,250,0,35,0.8,-3.8,3,245,252.5;SMTC:50,55,75,65,53.4,75.6,60,65,0,60,1,-


7.1,1,60,65;SMWB:12.5,15,17.5,16.6,12.2,18,15,17.5,0,61,13.5,16.7,2,15,0;SNA:340,250,370,350,315.0,365.7,330,350,0,26,1.3,2.9,0,330,350;SND:0,1,2.5,5,
1.5,3.1,0,2.5,0,112,269.9,0,2,0,2.5;SNOW:100,160,170,200,142.8,184,155,165,0,42,1.8,-
2.9,4,160,165;SOFI:14,5,15,16,11.5,17.5,13,15,0,73,1.4,7.1,4,13.5,15;SOUN:10,5,20,15,8.0,17.6,10,13,0,127,1.5,-
7.1,4,12,13;SPMO:90,86,101,98,84.1,106.9,95,100,0,41,1.3,3.1,0,95,97;SPOT:40,100,500,470,412.0,515.2,460,490,0,38,0.7,5.4,2,455,470;SPSC:170,175,210
,195,162.0,202.6,155,195,0,19,0.5,5.4,0,175,195;SPY:450,500,600,585,551.8,612.6,580,600,0,16,0.6,0.8,4,582,600;SQ:80,70,100,120,69.7,95.1,80,85,0,52,1
.6,3.7,4,78,83;SRDX:35,30,40,45,19.8,51.3,35,40,0,140,1.7,-
11.1,1,35,0;SRTS:5,4,8,7,3.4,9.9,5,8,0,132,17.0,14.3,1,6,7;STN:75,73.6,90,80,51.8,103.2,75,80,0,75,9.8,-5.9,0,0,80;STNE:8,3,15,20,6.5,10,8,8.5,0,74,4.2,-
5.6,3,8,8.5;STNG:47,45,70,65,47.1,65.6,55,57.5,0,52,4.1,4.5,3,55,57.5;STT:95,65,105,97.5,80.7,110.2,57.5,97.5,0,47,1.1,-
2.5,2,95,97.5;SUPV:7.5,5,20,25,15.3,23.0,17.5,20,0,69,3.0,14.3,2,17.5,20;SYF:15,65,75,70,57.9,74.2,65,70,0,41,1.6,7.7,3,65,70;SYK:340,360,370,380,332.2,3
93.4,310,420,0,27,0.9,10.5,1,360,370;T:15,17,25,24,20.1,23.5,21.5,22,0,26,1.5,-
2.2,4,21.5,22;TAL:8,6,15,20,8,11.3,9,10,0,58,0.6,5.3,4,9,10;TALK:0.5,2,3,5,2.1,3.6,2,3,0,82,3.0,0,2,0,3;TBI:5,7.1,7.5,17.5,6.2,8.7,5,7.5,0,29,4.8,0,0,0,0;TCBI:40
,75,80,100,64.3,89.2,75,85,0,54,0.2,6.2,0,75,80;TEAM:240,100,280,290,215.9,276.9,240,250,0,43,1.2,-
3.8,2,240,255;TEVA:18,17,22,23,18.3,23.7,20,22,0,42,1.9,4.8,4,20,21.5;THC:120,125,170,200,109.1,146.1,72.5,135,0,46,1.7,3.8,2,125,135;TILE:17.5,10,25,3
0,15.8,30.9,20,25,0,111,0.8,-
16.7,0,22.5,25;TKO:120,135,145,160,127.7,158.5,120,150,0,36,0.2,3.4,3,141.1,150;TLN:190,180,230,270,184.7,255.8,195,230,0,55,1.6,4.5,2,220,230;TM:18
0,170,200,195,170.7,200.1,185,190,0,27,1.1,2.7,1,185,190;TMDX:60,50,75,70,49,76.1,60,65,0,75,1.8,-
7.1,2,60,65;TMHC:60,50,70,100,54.2,72.4,60,65,0,48,1.7,-7.1,1,60,65;TMUS:150,145,230,220,197.2,231.2,210,220,0,26,0.9,-
1.1,3,210,220;TOST:12.5,15,46,40,30.3,42.2,35,37,0,53,1.6,2.8,3,35,37;TOUR:0,1,2.5,5,0,2.5,0,0,0,533,21.1,0,1,0,0;TPR:52.5,40,70,72.5,59.2,76.1,65,70,0,39
,0.4,4.5,3,66,71;TQQQ:70,65,90,80,62.0,89.5,75,83,0,62,1.6,-3.5,4,75,82;TRDA:7.5,10,17.5,35,0,32.3,10,15,0,432,3.0,-
14.3,0,0,0;TSLA:30,300,500,450,327.3,465.4,355,400,0,60,1.1,-
5.9,4,365,400;TSM:160,35,220,210,162.5,240.4,170,210,0,66,0.8,5,4,185,205;TSSI:10,7.5,15,12.5,7.9,13.9,10,12.5,0,92,4.3,-16.7,2,10,0;"

var string level_data10 =


"TTMI:25,17.5,30,35,20,30.4,25,30,0,65,1.6,20,0,25,0;TUYA:1.5,1.6,2.5,2,0.5,2.9,1.5,2,0,234,161.8,0,1,0,0;TWLO:50,40,110,115,92.2,125.2,100,115,0,52,1.5
,2.7,2,106,113;TZOO:15,17.5,20,22.5,11.7,26.8,17.5,20,0,115,3.9,-20,0,17.5,20;UAL:85,35,110,130,89.0,126.4,105,110,0,59,1.1,-
4.3,4,102,110;UBER:55,60,80,70,56.2,73.5,60,65,0,43,1.5,-
7.1,4,64,66;UNM:52.5,32.5,75,80,66.7,79.2,72.5,75,0,28,1.0,3.4,2,72.5,75;UNTY:30,15,0,1,26.7,59.9,40,0,0,98,0.7,-
100,0,40,0;UTI:25,22.5,30,27.5,22,29.6,25,27.5,0,50,0.9,10,1,25,27.5;V:285,250,315,310,288.3,329.9,305,315,0,22,1.1,1.6,3,305,315;VCTR:35,50,70,75,50.8
,74.4,35,65,0,64,5.3,-7.1,0,0,65;VCYT:40,35,50,45,30.8,51.3,40,45,0,80,7.3,-
10,1,40,45;VEON:40,30,50,50.7,37.0,55.2,40,50,0,60,0.5,11.1,0,0,50;VIRT:34,15,37,36,30.4,40.5,34,37,0,46,1.4,2.8,2,34,37;VIST:45,40,65,60,49.5,68.0,55,60
,0,54,0.5,-
7.7,2,55,60;VITL:35,30,45,50,35.4,48.7,40,45,0,54,6.5,12.5,2,40,45;VLRS:5,7.5,10,12.5,5.2,11.8,7.5,10,0,118,1.3,33.3,1,0,0;VMEO:5,5.5,7.5,10,4.4,7.8,5.5,7.5
,0,89,12.8,0,1,5.5,0;VRT:115,110,140,155,109.1,148.8,120,130,0,53,1.2,-
3.7,3,119,130;VZ:38,33,42,40,35.3,41.2,38,39,0,27,1.8,2.6,4,38,39;WASH:25,30,40,35,24.2,38.6,25,35,0,75,2.7,16.7,0,30,0;WD:85,70,110,140,68.4,108.8,85
,100,0,67,3.2,-
4.8,0,85,0;WDAY:220,245,300,260,220.5,271.6,240,260,0,34,0.9,4,2,240,260;WFC:45,40,75,80,63.2,79.2,65,75,0,39,1.1,7.1,4,65,72;WGS:70,55,92.5,80,48.9,
95.1,55,80,0,105,2.6,6.7,1,70,72.5;WHR:100,110,130,135,112.2,139.9,125,130,0,37,1.2,-
7.1,2,125,130;WMT:85,50,100,95,84.8,96.8,90,95,0,21,1.2,1.1,4,90,93;WT:7.5,2.5,12.5,15,7.7,11.1,7.5,10,0,58,2.7,-
20,2,0,10;WTBA:17.5,20,22.5,23.0,0,51.9,17.5,22.5,0,490,0.7,0,0,20,22.5;WW:1,0.5,7.5,5,0.2,2.2,1,1.5,0,231,4.3,-
25,4,0,0;WWW:22.5,20,25,30,16.9,28.9,20,25,0,81,2.9,11.1,2,22.5,25;X:30,25,55,45,30.2,42.8,35,40,0,59,1.2,8.1,4,35,37;XOM:100,80,110,120,102.3,117.1,
105,110,0,23,1.8,-4.3,4,105,111;YELP:25,15,40,47,34.6,43.1,38,40,0,36,1.5,2.6,1,38,40;ZBRA:360,380,440,410,350.0,438.8,390,400,0,38,2.0,-
2.4,0,390,400;ZIM:12.5,11.7,45,29.2,13.3,22.9,9.2,19,0,89,0.9,-5,4,17,19;"

var string last_update = "Jan 14, 6:44p"

process_level_data(level_data, symbol_data) =>

float[] result = array.new_float(0)

int start = str.pos(level_data, symbol_data)

if start >= 0 and (start == 0 or str.substring(level_data, math.max(0, start - 1), start) == ";")

int data_start = start + str.length(symbol_data)

string remaining_data = str.substring(level_data, data_start)

int data_end = str.pos(remaining_data, ";")

string values = data_end >= 0 ? str.substring(remaining_data, 0, data_end) : remaining_data


string[] value_array = str.split(values, ",")

for value in value_array

array.push(result, str.tonumber(value))

result

get_symbol_data(string symbol) =>

string symbol_data = symbol + ":"

float[] result = process_level_data(level_data1, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data2, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data3, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data4, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data5, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data6, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data7, symbol_data)


if array.size(result) == 0

result := process_level_data(level_data8, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data9, symbol_data)

if array.size(result) == 0

result := process_level_data(level_data10, symbol_data)

result

show_short_term = input.bool(true, "Show Short-term (st) Walls")

extend_st = input.bool(false, "Extend st levels to the left", inline="st")

label_size = input.string("small", "Label Size", options=["tiny", "small", "normal", "large"], group="Style", display=display.none)

line_style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group="Style",display=display.none)

line_transparency = input.int(40, "Lines Transparency", minval=0, maxval=100, group="Style", display=display.none)

support_color = color.lime

resist_color = color.red

put_wall_color = #00FF00

call_wall_color = #FF0000

gamma_flip_color = color.white
var float s1_sorted = na

var float s2_sorted = na

var float r1_sorted = na

var float r2_sorted = na

var float lower_end = na

var float upper_end = na

var float gamma_support = na

var float gamma_resistance = na

var float gamma_flip = na

var float iv = na

var float cp_ratio = na

var float trend = na

var label[] labels = array.new_label()

draw_line_and_label(price, color, name, is_gamma = false) =>

if not na(price) and price != 0

line_style_used = line_style == "Solid" ? line.style_solid :

line_style == "Dashed" ? line.style_dashed :

line.style_dotted
bool is_short_term = str.startswith(name, "st")

bool is_gamma = name == "PW" or name == "CW" or name == "st PW" or name == "st CW"

int transparency = is_gamma ? (is_short_term ? 60 : 0) : line_transparency

int start_x = is_short_term and extend_st ? bar_index - 52 : bar_index

int end_x = bar_index + 10

line_id = line.new(x1=start_x, y1=price, x2=end_x, y2=price,

color=color.new(color, transparency), width=2,

style=line_style_used)

int label_x = is_short_term ? start_x + math.round((end_x - start_x) / 2) : bar_index + (is_gamma ? 15 : 11)

label_style = is_short_term ? label.style_none : label.style_label_left

label_id = label.new(

x=label_x,

y=price,

text=name + ": " + str.tostring(price, "#.##"),

color=color.new(color.black, 100),
textcolor=color,

style=label_style,

size=label_size == "tiny" ? size.tiny :

label_size == "small" ? size.small :

label_size == "normal" ? size.normal : size.large)

array.push(labels, label_id)

line_id

clear_labels() =>

for lbl in labels

label.delete(lbl)

array.clear(labels)

sort_levels(s1, s2, r1, r2) =>

levels = array.from(s1, s2, r1, r2)

array.sort(levels, order.ascending)

[array.get(levels, 0), array.get(levels, 1), array.get(levels, 2), array.get(levels, 3)]

current_levels = get_symbol_data(syminfo.ticker)
var line s2_line = na

var line s1_line = na

var line r1_line = na

var line r2_line = na

if array.size(current_levels) >= 4

clear_labels()

float s1_input = array.get(current_levels, 0)

float s2_input = array.get(current_levels, 1)

float r1_input = array.get(current_levels, 2)

float r2_input = array.get(current_levels, 3)

[s2_sorted, s1_sorted, r1_sorted, r2_sorted] = sort_levels(s1_input, s2_input, r1_input, r2_input)

line.delete(s2_line)

line.delete(s1_line)

line.delete(r1_line)

line.delete(r2_line)
s2_line := draw_line_and_label(s2_sorted, support_color, "S2")

s1_line := draw_line_and_label(s1_sorted, support_color, "S1")

r1_line := draw_line_and_label(r1_sorted, resist_color, "R1")

r2_line := draw_line_and_label(r2_sorted, resist_color, "R2")

var box implied_move_box = na

if array.size(current_levels) >= 11

lower_end := array.get(current_levels, 4)

upper_end := array.get(current_levels, 5)

iv := array.get(current_levels, 9)

cp_ratio := array.get(current_levels, 10)

if not na(lower_end) and not na(upper_end) and lower_end != 0 and upper_end != 0

box.delete(implied_move_box)

implied_move_box := box.new(

left=bar_index,

top=upper_end,

right=bar_index + 10,

bottom=lower_end,

bgcolor=color.new(color.gray, 87),

border_color=color.new(color.gray, 50)
)

float upper_pct = (upper_end - close) / close * 100

float lower_pct = (lower_end - close) / close * 100

array.push(labels, label.new(x=bar_index + 12, y=upper_end, text="↑+" + str.tostring(upper_pct, "#") + "%", color=color.new(color.gray, 100),
textcolor=color.white, style=label.style_label_right, size=size.tiny))

array.push(labels, label.new(x=bar_index + 12, y=lower_end, text="↓" + str.tostring(lower_pct, "#") + "%", color=color.new(color.gray, 100),
textcolor=color.white, style=label.style_label_right, size=size.tiny))

var line gamma_support_line = na

var line gamma_resistance_line = na

var box gamma_area_box_red = na

var box gamma_area_box_lime = na

var box gamma_area_box_green = na

if array.size(current_levels) >= 15

gamma_support := array.get(current_levels, 6)

gamma_resistance := array.get(current_levels, 7)

gamma_flip := array.get(current_levels, 8)

line.delete(gamma_support_line)

line.delete(gamma_resistance_line)
box.delete(gamma_area_box_red)

box.delete(gamma_area_box_lime)

box.delete(gamma_area_box_green)

gamma_support_line := draw_line_and_label(gamma_support, put_wall_color, "PW", true)

gamma_resistance_line := draw_line_and_label(gamma_resistance, call_wall_color, "CW", true)

var line st_gamma_support_line = na

var line st_gamma_resistance_line = na

if array.size(current_levels) >= 15

float st_gamma_support = array.get(current_levels, 13)

float st_gamma_resistance = array.get(current_levels, 14)

line.delete(st_gamma_support_line)

line.delete(st_gamma_resistance_line)

if show_short_term

st_gamma_support_line := draw_line_and_label(st_gamma_support, put_wall_color, "st PW", true)

st_gamma_resistance_line := draw_line_and_label(st_gamma_resistance, call_wall_color, "st CW", true)


float upper_limit = upper_end

float lower_limit = lower_end

if gamma_resistance < upper_limit

gamma_area_box_green := box.new(

left=bar_index + 10,

top=math.min(gamma_resistance * 1.2, upper_limit),

right=bar_index + 11,

bottom=gamma_resistance,

bgcolor=color.new(#00FF00, 75),

border_color=color.new(#00FF00, 100))

gamma_area_box_lime := box.new(

left=bar_index + 10,

top=math.min(gamma_resistance, upper_limit),

right=bar_index + 11,

bottom=math.max(gamma_support, lower_limit),

bgcolor=color.new(color.lime, 85),

border_color=color.new(color.lime, 100))
if gamma_support > lower_limit

gamma_area_box_red := box.new(

left=bar_index + 10,

top=gamma_support,

right=bar_index + 11,

bottom=math.max(gamma_support * 0.8, lower_limit),

bgcolor=color.new(color.red, 85),

border_color=color.new(color.red, 100))

var line gamma_flip_line = na

if array.size(current_levels) >= 9

float gamma_flip = array.get(current_levels, 8)

if not na(gamma_flip) and gamma_flip != 0

line.delete(gamma_flip_line)

gamma_flip_line := draw_line_and_label(gamma_flip, gamma_flip_color, "Flip", true)

var table info_table = table.new(position.top_center, columns=8, rows=3, bgcolor=color.new(color.black, 90), border_width=1)

get_activity_text(level) =>
switch level

0 => "Very Low"

1 => "Low"

2 => "Medium"

3 => "High"

4 => "Very High"

=> "Unknown"

if barstate.islast and array.size(current_levels) >= 15

for i = 0 to 7

table.cell(info_table, i, 0, "", bgcolor=color.new(color.black, 100), text_size=label_size == "tiny" ? size.tiny : label_size == "small" ? size.small : label_size
== "normal" ? size.normal : size.large)

string[] headers = array.from("Call/Put Ratio", "IV", "Call Wall", "Put Wall", "CW Trend", "Imp. Move", "Op Activity", "Last Updated")

for i = 0 to 7 // Changed from 6 to 7

table.cell(info_table, i, 1, headers.get(i), bgcolor=color.new(color.black, 90), text_color=color.white, text_size=label_size == "tiny" ? size.tiny : label_size


== "small" ? size.small : label_size == "normal" ? size.normal : size.large)

float cp_ratio = array.get(current_levels, 10)

float iv = array.get(current_levels, 9)

float call_wall = array.get(current_levels, 7)


float put_wall = array.get(current_levels, 6)

trend := array.get(current_levels, 11)

float activity_level = array.get(current_levels, 12)

float im_value = (((upper_end - lower_end) / close) * 100) / 2

color iv_color = iv <= 30 ? color.green : iv >= 70 ? color.red : color.yellow

color last_lines_bg_color = color.new(color.gray, 70)

var text_size = label_size == "tiny" ? size.tiny : label_size == "small" ? size.small : label_size == "normal" ? size.normal : size.large

table.cell(info_table, 0, 2, str.tostring(cp_ratio, "#.##"), text_color=cp_ratio >= 1 ? color.green : color.red, text_size=text_size, bgcolor=last_lines_bg_color)

table.cell(info_table, 1, 2, str.tostring(iv, "#.##") + "%", text_color=iv_color, text_size=text_size, bgcolor=last_lines_bg_color)

float call_wall_pct = call_wall != 0 ? ((close - call_wall) / call_wall) * 100 : na

float put_wall_pct = put_wall != 0 ? ((close - put_wall) / put_wall) * 100 : na

color call_wall_color = call_wall_pct > 0 ? color.green : call_wall_pct < 0 ? #FF0000 : #FF0000

color put_wall_color = put_wall_pct > 0 ? color.green : put_wall_pct < 0 ? #00FF00 : #00FF00

table.cell(info_table, 2, 2, not na(call_wall_pct) ? (call_wall_pct > 0 ? "+" : "") + str.tostring(call_wall_pct, "#.##") + "%" : "N/A",
text_color=not na(call_wall_pct) ? call_wall_color : color.white, text_size=text_size, bgcolor=last_lines_bg_color)

table.cell(info_table, 3, 2, not na(put_wall_pct) ? (put_wall_pct > 0 ? "+" : "") + str.tostring(put_wall_pct, "#.##") + "%" : "N/A",

text_color=not na(put_wall_pct) ? put_wall_color : color.white, text_size=text_size, bgcolor=last_lines_bg_color)

table.cell(info_table, 4, 2, (trend >= 0 ? "+" : "") + str.tostring(trend, "#.##") + "%", text_color=trend >= 0 ? color.green : color.red, text_size=text_size,
bgcolor=last_lines_bg_color)

table.cell(info_table, 5, 2, str.tostring(im_value, "±#.##") + "%", text_color=color.white, text_size=text_size, bgcolor=last_lines_bg_color)

table.cell(info_table, 6, 2, get_activity_text(activity_level),

text_color=activity_level >= 3 ? color.green : activity_level >= 2 ? color.yellow : color.red,

text_size=text_size,

bgcolor=last_lines_bg_color)

table.cell(info_table, 7, 2, last_update, text_color=color.gray, text_size=text_size)

var float bounce_threshold_percent = 0.15

var float min_bounce_percent = 0.5

var bool broke_call_wall = false

var bool broke_put_wall = false

var float covered_calls_iv_threshold = 65.0

var float leaps_iv_threshold = 35.0

var float call_wall_bounce_threshold = 0.15


var float call_wall_min_rejection = 0.5

var bool near_call_wall = false

var float bounce_reference_high = na

var bool near_put_wall = false

var float bounce_reference_low = na

if not na(gamma_support) and gamma_support != 0

float distance_to_put_wall = math.abs(low - gamma_support) / gamma_support * 100

if distance_to_put_wall <= bounce_threshold_percent

if not near_put_wall

near_put_wall := true

bounce_reference_low := low

else if near_put_wall and high > bounce_reference_low

float bounce_percent = (high - bounce_reference_low) / bounce_reference_low * 100

if bounce_percent >= min_bounce_percent

near_put_wall := false

if not na(gamma_resistance) and gamma_resistance != 0


float distance_to_call_wall = math.abs(high - gamma_resistance) / gamma_resistance * 100

if distance_to_call_wall <= call_wall_bounce_threshold

if not near_call_wall

near_call_wall := true

bounce_reference_high := high

else if near_call_wall and low < bounce_reference_high

float rejection_percent = (bounce_reference_high - low) / bounce_reference_high * 100

if rejection_percent >= call_wall_min_rejection

near_call_wall := false

broke_call_wall := close > gamma_resistance and gamma_resistance != 0

broke_put_wall := close < gamma_support and gamma_support != 0

alertcondition(not na(gamma_support) and gamma_support != 0 and math.abs(close - gamma_support) / gamma_support * 100 <= 0.3, "At Put Wall",
"Price is at Put Wall level (within 0.3%)")

alertcondition(not na(gamma_resistance) and gamma_resistance != 0 and math.abs(close - gamma_resistance) / gamma_resistance * 100 <= 0.3, "At Call
Wall", "Price is at Call Wall level (within 0.3%)")

alertcondition(ta.cross(close, gamma_flip) and gamma_flip != 0, "Gamma Flip Cross", "Price crossed Gamma Flip level")

alertcondition(near_put_wall and close > bounce_reference_low and ((close - bounce_reference_low) / bounce_reference_low * 100) >=
min_bounce_percent, "Put Wall Bounce", "Price bounced off Put Wall (Gamma Support)")
alertcondition(near_call_wall and low < bounce_reference_high and ((bounce_reference_high - low) / bounce_reference_high * 100) >=
call_wall_min_rejection,"Call Wall Rejection","Price rejected from Call Wall (Gamma Resistance)")

alertcondition(trend > 1, "Call Wall Moved Up", "Call Wall Trend moved up more than 1%")

alertcondition(trend < -1, "Call Wall Moved Down", "Call Wall Trend moved down more than 1%")

alertcondition(broke_put_wall and not broke_put_wall[1], "Broke Put Wall (Gamma Support)", "Price closed below Put Wall (Gamma Support)")

alertcondition(broke_call_wall and not broke_call_wall[1], "Broke Call Wall (Gamma Resistance)", "Price closed above Call Wall (Gamma Resistance)")

alertcondition(iv >= covered_calls_iv_threshold, "Covered Calls Candidates", "High IV Environment (>65%) - Consider Covered Calls Strategy")

alertcondition(iv <= leaps_iv_threshold, "LEAPS Candidates", "Low IV Environment (<35%) - Consider LEAPS Strategy")

var table not_supported_table = table.new(position.bottom_center, columns=1, rows=1, bgcolor=color.new(color.black, 0), border_width=1)

if array.size(current_levels) == 0

var table no_data = table.new(position.bottom_center, 1, 1)

table.cell(no_data, 0, 0, text="⚠️No options data available for " + syminfo.ticker,

bgcolor=color.new(color.red, 90),

text_color=color.white)

//@version=6

indicator("Variações Diárias", overlay=true)


// Variáveis para cálculo do ajuste e armazenamento do ajuste diário

var float sum_prices = 0.0

var float sum_weights = 0.0

var float adjustment = na

var int adjustment_bar_index = na

// Acumular os preços ponderados entre 17:55 e 18:10

if (hour == 17 and minute >= 55) or (hour == 18 and minute <= 10)

sum_prices := sum_prices + close * volume

sum_weights := sum_weights + volume

// Quando o intervalo de 17:55-18:10 termina, calcula o ajuste

if (hour == 18 and minute == 10 and sum_weights > 0)

adjustment := sum_prices / sum_weights

adjustment_bar_index := bar_index

sum_prices := 0.0

sum_weights := 0.0

// Desenhar a linha do ajuste do dia mais atual

if not na(adjustment) and not na(adjustment_bar_index)


line.new(x1=adjustment_bar_index, y1=adjustment, x2=bar_index, y2=adjustment, color=color.blue, width=2, style=line.style_solid)

label.new(x=bar_index, y=adjustment, text="Ajuste: " + str.tostring(adjustment, "#.##"), color=color.blue, style=label.style_label_left, yloc=yloc.price,


size=size.small)

// Calcular as variações com base no ajuste (0,5%, 1,0%, 1,5% para cima e para baixo)

variation_0_5_up = adjustment * (1 + 0.005) // 0,5% positivo

variation_1_0_up = adjustment * (1 + 0.010) // 1,0% positivo

variation_1_5_up = adjustment * (1 + 0.015) // 1,5% positivo

variation_0_5_down = adjustment * (1 - 0.005) // 0,5% negativo

variation_1_0_down = adjustment * (1 - 0.010) // 1,0% negativo

variation_1_5_down = adjustment * (1 - 0.015) // 1,5% negativo

// Desenhando as linhas de variação no gráfico

line1 = line.new(x1=adjustment_bar_index, y1=variation_0_5_up, x2=bar_index, y2=variation_0_5_up, color=color.green, width=2, style=line.style_solid)

line2 = line.new(x1=adjustment_bar_index, y1=variation_1_0_up, x2=bar_index, y2=variation_1_0_up, color=color.green, width=2, style=line.style_solid)

line3 = line.new(x1=adjustment_bar_index, y1=variation_1_5_up, x2=bar_index, y2=variation_1_5_up, color=color.green, width=2, style=line.style_solid)

line4 = line.new(x1=adjustment_bar_index, y1=variation_0_5_down, x2=bar_index, y2=variation_0_5_down, color=color.red, width=2,


style=line.style_solid)

line5 = line.new(x1=adjustment_bar_index, y1=variation_1_0_down, x2=bar_index, y2=variation_1_0_down, color=color.red, width=2,


style=line.style_solid)
line6 = line.new(x1=adjustment_bar_index, y1=variation_1_5_down, x2=bar_index, y2=variation_1_5_down, color=color.red, width=2,
style=line.style_solid)

// Adicionando os preços nas linhas existentes

label.new(x=bar_index, y=variation_0_5_up, text="+0,5%: " + str.tostring(variation_0_5_up, "#.##"), color=color.green, style=label.style_label_left,


yloc=yloc.price, size=size.small)

label.new(x=bar_index, y=variation_1_0_up, text="+1,0%: " + str.tostring(variation_1_0_up, "#.##"), color=color.green, style=label.style_label_left,


yloc=yloc.price, size=size.small)

label.new(x=bar_index, y=variation_1_5_up, text="+1,5%: " + str.tostring(variation_1_5_up, "#.##"), color=color.green, style=label.style_label_left,


yloc=yloc.price, size=size.small)

label.new(x=bar_index, y=variation_0_5_down, text="-0,5%: " + str.tostring(variation_0_5_down, "#.##"), color=color.red, style=label.style_label_left,


yloc=yloc.price, size=size.small)

label.new(x=bar_index, y=variation_1_0_down, text="-1,0%: " + str.tostring(variation_1_0_down, "#.##"), color=color.red, style=label.style_label_left,


yloc=yloc.price, size=size.small)

label.new(x=bar_index, y=variation_1_5_down, text="-1,5%: " + str.tostring(variation_1_5_down, "#.##"), color=color.red, style=label.style_label_left,


yloc=yloc.price, size=size.small)

//@version=6

indicator("EMA Crossover Signal", overlay=true)


// Input for EMAs

ema9_length = input.int(9, title="9 EMA Length")

ema21_length = input.int(21, title="21 EMA Length")

// Calculate EMAs

ema9 = ta.ema(close, ema9_length)

ema21 = ta.ema(close, ema21_length)

// Crossover and Crossunder Conditions

bullish_cross = ta.crossover(ema9, ema21)

bearish_cross = ta.crossunder(ema9, ema21)

// Plot EMAs

plot(ema9, color=color.green, title="9 EMA")

plot(ema21, color=color.red, title="21 EMA")

// Highlight crossover signals

bgcolor(bullish_cross ? color.new(color.green, 90) : na, title="Bullish Cross")

bgcolor(bearish_cross ? color.new(color.red, 90) : na, title="Bearish Cross")


// Plot buy/sell signals

plotshape(bullish_cross, style=shape.labelup, location=location.belowbar, color=color.green, size=size.small, title="Buy Signal")

plotshape(bearish_cross, style=shape.labeldown, location=location.abovebar, color=color.red, size=size.small, title="Sell Signal")

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// © TwistedChef

//@version=6

plot(close)

//@version=5

indicator("0x - v83 MA Ribbon", shorttitle="v83 MA Ribbon", overlay=true, timeframe="", timeframe_gaps=true)

ma(source, length, type) =>

type == "SMA" ? ta.sma(source, length) :

type == "EMA" ? ta.ema(source, length) :

type == "SMMA (RMA)" ? ta.rma(source, length) :

type == "WMA" ? ta.wma(source, length) :

type == "VWMA" ? ta.vwma(source, length) :

na
show_ma1 = input(true , "MA №1", inline="MA #1", display = display.data_window)

ma1_type = input.string("SMA" , "" , inline="MA #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])

ma1_source = input(close , "" , inline="MA #1", display = display.data_window)

ma1_length = input.int(5 , "" , inline="MA #1", minval=1)

show_ma2 = input(true , "MA №2", inline="MA #2", display = display.data_window)

ma2_type = input.string("SMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])

ma2_source = input(close , "" , inline="MA #2", display = display.data_window)

ma2_length = input.int(10 , "" , inline="MA #2", minval=1)

show_ma3 = input(true , "MA №3", inline="MA #3", display = display.data_window)

ma3_type = input.string("SMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])

ma3_source = input(close , "" , inline="MA #3", display = display.data_window)

ma3_length = input.int(20 , "" , inline="MA #3", minval=1)

show_ma4 = input(true , "MA №4", inline="MA #4", display = display.data_window)


ma4_type = input.string("SMA" , "" , inline="MA #4", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])

ma4_source = input(close , "" , inline="MA #4", display = display.data_window)

ma4_length = input.int(30 , "" , inline="MA #4", minval=1)

show_ma5 = input(true , "MA №5", inline="MA #5", display = display.data_window)

ma5_type = input.string("SMA" , "" , inline="MA #5", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])

ma5_source = input(close , "" , inline="MA #5", display = display.data_window)

ma5_length = input.int(60 , "" , inline="MA #5", minval=1)

show_ma6 = input(true , "MA №6", inline="MA #6", display = display.data_window)

ma6_type = input.string("SMA" , "" , inline="MA #6", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])

ma6_source = input(close , "" , inline="MA #6", display = display.data_window)

ma6_length = input.int(120 , "" , inline="MA #6", minval=1)

lookback = input.int(1440, title='Stdev Rank Lookback', group='Ranking')


ma1 = ma(ma1_source, ma1_length, ma1_type)

ma2 = ma(ma2_source, ma2_length, ma2_type)

ma3 = ma(ma3_source, ma3_length, ma3_type)

ma4 = ma(ma4_source, ma4_length, ma4_type)

ma5 = ma(ma5_source, ma5_length, ma5_type)

ma6 = ma(ma6_source, ma6_length, ma6_type)

ma1_color = ma1>ma2 ? color.new(color.green, 0) : color.new(color.red, 0)

ma2_color = ma2>ma3 ? color.new(color.green, 20) : color.new(color.red, 20)

ma3_color = ma3>ma4 ? color.new(color.green, 40) : color.new(color.red, 40)

ma4_color = ma4>ma5 ? color.new(color.green, 60) : color.new(color.red, 60)

ma5_color = ma5>ma6 ? color.new(color.green, 80) : color.new(color.red, 80)

ma6_color = close>ma6 ? color.new(color.green, 80) : color.new(color.red, 80)

plot(show_ma1 ? ma1 : na, color = ma1_color, title="MA №1", linewidth=1)

plot(show_ma2 ? ma2 : na, color = ma2_color, title="MA №2", linewidth=2)

plot(show_ma3 ? ma3 : na, color = ma3_color, title="MA №3", linewidth=3)


plot(show_ma4 ? ma4 : na, color = ma4_color, title="MA №4", linewidth=4)

plot(show_ma5 ? ma5 : na, color = ma5_color, title="MA №5", linewidth=5)

plot(show_ma6 ? ma6 : na, color = ma6_color, title="MA №6", linewidth=6)

r1 = ta.roc(ma1,1)

r2 = ta.roc(ma2,1)

r3 = ta.roc(ma3,1)

r4 = ta.roc(ma4,1)

r5 = ta.roc(ma5,1)

r6 = ta.roc(ma6,1)

mma = (ma1+ma2+ma3+ma4+ma5+ma6+close)/7

std = math.sqrt( ((ma1-mma)*(ma1-mma) + (ma2-mma)*(ma2-mma) + (ma3-mma)*(ma3-mma) + (ma4-mma)*(ma4-mma) + (ma5-mma)*(ma5-mma) +


(ma6-mma)*(ma6-mma) + (close-mma)*(close-mma))/7)
var stdevArray = array.new_float(lookback,0.0)

array.push(stdevArray, std)

if array.size(stdevArray)>=lookback

array.remove(stdevArray, 0)

rank = array.percentrank(stdevArray, lookback-1)

r_score1 = (r1>0 ? 1 : 0) + (r2>0 ? 1 : 0) + (r3>0 ? 1 : 0) + (r4 > 0 ? 1 : 0) + (r5 > 0 ? 1 : 0) + (r6 > 0 ? 1 : 0)

r_score2 = (r1<0 ? 1 : 0) + (r2<0 ? 1 : 0) + (r3<0 ? 1 : 0) + (r4 < 0 ? 1 : 0) + (r5 < 0 ? 1 : 0) + (r6 < 0 ? 1 : 0)

ma_score1 = (ma1>ma2 ? 1 : 0) + (ma2>ma3 ? 1 : 0) + (ma3>ma4 ? 1 : 0) + (ma4 > ma5 ? 1 : 0) + (ma5 > ma6 ? 1 : 0) + (close>ma6 ? 1 : 0) +(close>ma1 ? 1 :
0) +(close>ma2 ? 1 : 0) + (close>ma3 ? 1 : 0) +(close>ma4 ? 1 : 0) +(close>ma5 ? 1 : 0)

ma_score2 = (ma1<ma2 ? 1 : 0) + (ma2<ma3 ? 1 : 0) + (ma3<ma4 ? 1 : 0) + (ma4 < ma5 ? 1 : 0) + (ma5 < ma6 ? 1 : 0) + (close<ma6 ? 1 : 0) +(close<ma1 ? 1 :
0) +(close<ma2 ? 1 : 0) + (close<ma3 ? 1 : 0) +(close<ma4 ? 1 : 0) +(close<ma5 ? 1 : 0)

plotchar(ma_score1==6 , title="Condition", location=location.bottom, color=color.new(color.green, 50), text="1", size=size.tiny)

plotchar(ma_score1==7 , title="Condition", location=location.bottom, color=color.new(color.green, 50), text="2", size=size.tiny)


plotchar(ma_score1==8 , title="Condition", location=location.bottom, color=color.new(color.green, 75), text="3", size=size.tiny)

plotchar(ma_score1==9 , title="Condition", location=location.bottom, color=color.new(color.green, 75), text="4", size=size.tiny)

plotchar(ma_score1==10 , title="Condition", location=location.bottom, color=color.new(color.green, 0), text="5", size=size.tiny)

plotchar(ma_score1==11 , title="Condition", location=location.bottom, color=color.new(color.green, 0), text="6", size=size.tiny)

plotchar(ma_score2==6 , title="Condition", location=location.bottom, color=color.new(color.red, 50), text="1", size=size.tiny)

plotchar(ma_score2==7 , title="Condition", location=location.bottom, color=color.new(color.red, 50), text="2", size=size.tiny)

plotchar(ma_score2==8 , title="Condition", location=location.bottom, color=color.new(color.red, 75), text="3", size=size.tiny)

plotchar(ma_score2==9 , title="Condition", location=location.bottom, color=color.new(color.red, 75), text="4", size=size.tiny)

plotchar(ma_score2==10 , title="Condition", location=location.bottom, color=color.new(color.red, 0), text="5", size=size.tiny)

plotchar(ma_score2==11 , title="Condition", location=location.bottom, color=color.new(color.red, 0), text="6", size=size.tiny)

plotchar(r_score1==4 , title="Condition", location=location.bottom, color=color.new(color.green, 0), text="4", size=size.tiny)

plotchar(r_score1==5 , title="Condition", location=location.bottom, color=color.new(color.green, 20), text="5", size=size.tiny)

plotchar(r_score1==6 , title="Condition", location=location.bottom, color=color.new(color.green, 40), text="6", size=size.tiny)

plotchar(r_score2==4, title="Condition", location=location.bottom, color=color.new(color.red, 0), text="4", size=size.tiny)

plotchar(r_score2==5, title="Condition", location=location.bottom, color=color.new(color.red, 20), text="5", size=size.tiny)

plotchar(r_score2==6, title="Condition", location=location.bottom, color=color.new(color.red, 40), text="6", size=size.tiny)


var stdevArray2 = array.new_float(lookback,0.0)

df=ta.highest(high,90) - ta.lowest(low,90)

array.push(stdevArray2, df)

if array.size(stdevArray2)>=lookback

array.remove(stdevArray2, 0)

rank2 = array.percentrank(stdevArray2, lookback-1)

plotshape(rank > 50, color=color.new(color.yellow, 75), location=location.top, style=shape.circle, size=size.tiny, title='MV Variance')

plotshape(rank < 15, color=color.new(color.red, 75), location=location.top, style=shape.circle, size=size.tiny, title='MV Variance 1')

plotshape(rank2 > 50, color=color.new(color.yellow, 75), location=location.top, style=shape.circle, size=size.tiny, title='Fib Variance')

plotshape(rank2 < 15, color=color.new(color.red, 75), location=location.top, style=shape.circle, size=size.tiny, title='Fib Variance 1')
period=20

mult=2

tf1="5"

tf2="15"

[basis0, upper0, lower0] = request.security(syminfo.tickerid, "1", ta.bb(close, period, mult), lookahead=barmerge.lookahead_on)

[basis1, upper1, lower1] = request.security(syminfo.tickerid, tf1, ta.bb(close, period, mult), lookahead=barmerge.lookahead_on)

[basis2, upper2, lower2] = request.security(syminfo.tickerid, tf2, ta.bb(close, period, mult), lookahead=barmerge.lookahead_on)

g1 = upper0 - lower0

g2 = upper1 - lower1

g3 = upper2 - lower2

plotchar(g1 > g2 , title="Condition", location=location.top, color=color.orange, text="B")

plotchar(g2 > g3, title="Condition", location=location.top, color=color.red, text="B")

//@version=5

indicator("Compare Symbol [LuxmiAI]", overlay=false)


// Input for selecting the symbol

symbolInput = input.symbol("", "Select Symbol")

// Input for selecting the timeframe

timeframeInput = input.timeframe("", "Select Timeframe")

// Option to choose the candle style

candleStyle = input.string("Candles", "Candle Style", options=["Candles", "Bars", "Heikin-Ashi"])

// Input for Moving Average type and length

maType = input.string("EMA", "MA Type", options=["EMA", "SMA", "WMA", "VWMA"])

maLength = input.int(14, "MA Length", minval=1)

// Fetching OHLC data of the selected symbol and timeframe

openPrice = request.security(symbolInput, timeframeInput, open)

highPrice = request.security(symbolInput, timeframeInput, high)

lowPrice = request.security(symbolInput, timeframeInput, low)

closePrice = request.security(symbolInput, timeframeInput, close)


// Placeholder for Heikin-Ashi open price

var float haOpen = na

// Calculating Heikin-Ashi OHLC if selected

haClose = (openPrice + highPrice + lowPrice + closePrice) / 4

haOpen := na(haOpen[1]) ? (openPrice + closePrice) / 2 : (nz(haOpen[1]) + haClose) / 2

haHigh = math.max(highPrice, math.max(haOpen, haClose))

haLow = math.min(lowPrice, math.min(haOpen, haClose))

// Determine which OHLC values to plot based on style selection

o = candleStyle == "Heikin-Ashi" ? haOpen : openPrice

h = candleStyle == "Heikin-Ashi" ? haHigh : highPrice

l = candleStyle == "Heikin-Ashi" ? haLow : lowPrice

c = candleStyle == "Heikin-Ashi" ? haClose : closePrice

// Color for candles

candleColor = (c >= o ? color.lime : color.red)

// Control visibility

isCandle = candleStyle == "Candles" or candleStyle == "Heikin-Ashi"


isBar = candleStyle == "Bars"

// Calculating the selected moving average

ma = switch maType

"EMA" => ta.ema(c, maLength)

"SMA" => ta.sma(c, maLength)

"WMA" => ta.wma(c, maLength)

"VWMA" => ta.vwma(c, maLength)

// Plotting candles (Candles or Heikin-Ashi)

plotcandle(isCandle ? o : na, isCandle ? h : na, isCandle ? l : na, isCandle ? c : na,

color=isCandle ? candleColor : na, bordercolor=isCandle ? candleColor : na, wickcolor=isCandle ? candleColor : na, title="Candles/Heikin-Ashi")

// Plotting bars

plotbar(isBar ? o : na, isBar ? h : na, isBar ? l : na, isBar ? c : na, color=isBar ? candleColor : na, title="Bars")

// Plotting the moving average

plot(ma, color=color.rgb(57, 57, 61), linewidth=2, title="Moving Average")

// Watermark setup using a table


var table watermark = table.new(position.top_right, 1, 1)

if barstate.islast

// Display selected symbol and timeframe in watermark

watermarkText = "Symbol: " + symbolInput + "\n" + "Timeframe: " + timeframeInput

table.cell(watermark, 0, 0, text=watermarkText, text_color=color.white, text_size=size.normal, bgcolor=color.rgb(41, 148, 236))

///////

mC = closePrice

actualClose = mC

// Plot current price line dynamically

var line currentPriceLine = na

if (na(currentPriceLine))

currentPriceLine := line.new(x1=bar_index, y1=actualClose, x2=bar_index + 1, y2=actualClose, color=color.gray, width=1, extend = extend.both)

// Set the line style to dotted

line.set_style(currentPriceLine, line.style_dashed)

else
line.set_xy1(currentPriceLine, x=bar_index, y=actualClose)

line.set_xy2(currentPriceLine, x=bar_index + 1, y=actualClose)

//Liquidity ignoring price location

//@version=6

strategy("Liquidity Weighted Moving Averages [AlgoAlpha]", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1,


slippage=3)

// Inputs

outlierThreshold = input.int(10, "Outlier Threshold Length")

fastMovingAverageLength = input.int(50, "Fast MA Length")

slowMovingAverageLength = input.int(100, "Slow MA Length")

start_date = input.time(timestamp("2018-01-01 00:00"), title="Start Date")

end_date = input.time(timestamp("2069-12-31 23:59"), title="End Date")

// Define liquidity based on volume and price movement

priceMovementLiquidity = volume / math.abs(close - open)


// Calculate the boundary for liquidity to identify outliers

liquidityBoundary = ta.ema(priceMovementLiquidity, outlierThreshold) + ta.stdev(priceMovementLiquidity, outlierThreshold)

// Initialize an array to store liquidity values when they cross the boundary

var liquidityValues = array.new_float(5)

// Check if the liquidity crosses above the boundary and update the array

if ta.crossover(priceMovementLiquidity, liquidityBoundary)

array.insert(liquidityValues, 0, close)

if array.size(liquidityValues) > 5

array.pop(liquidityValues)

// Calculate the Exponential Moving Averages for the close price at the last liquidity crossover

fastEMA = ta.ema(array.size(liquidityValues) > 0 ? array.get(liquidityValues, 0) : na, fastMovingAverageLength)

slowEMA = ta.ema(array.size(liquidityValues) > 0 ? array.get(liquidityValues, 0) : na, slowMovingAverageLength)

// Trading Logic

in_date_range = (time >= start_date and time <= end_date)

buy_signal = ta.crossover(fastEMA, slowEMA) and in_date_range

sell_signal = ta.crossunder(fastEMA, slowEMA) and in_date_range


// Strategy Entry and Exit

if (buy_signal)

strategy.entry("Buy", strategy.long)

if (sell_signal)

strategy.close("Buy")

// Plotting

fastPlot = plot(fastEMA, color=fastEMA > slowEMA ? color.new(#00ffbb, 50) : color.new(#ff1100, 50), title="Fast EMA")

slowPlot = plot(slowEMA, color=fastEMA > slowEMA ? color.new(#00ffbb, 50) : color.new(#ff1100, 50), title="Slow EMA")

// Create a fill between the fast and slow EMA plots with appropriate color based on crossover

fill(fastPlot, slowPlot, fastEMA > slowEMA ? color.new(#00ffbb, 50) : color.new(#ff1100, 50))

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// © saipopzeinzs

//@version=6

indicator("Comprehensive Trading Indicator", overlay=true)


// === Inputs ===

showSupportResistance = input.bool(true, "Show Support/Resistance Levels")

showCandlestickPatterns = input.bool(true, "Show Candlestick Patterns")

showMovingAverages = input.bool(true, "Show Moving Averages")

maLength1 = input.int(50, "MA 1 Length")

maLength2 = input.int(200, "MA 2 Length")

showVolumeAnalysis = input.bool(true, "Show Volume Analysis")

volumeThreshold = input.float(1.5, "Volume Spike Multiplier")

// === Moving Averages ===

ma1 = ta.sma(close, maLength1)

ma2 = ta.sma(close, maLength2)

// Plot Moving Averages (handled dynamically)

plot(showMovingAverages ? ma1 : na, color=color.blue, linewidth=2, title="MA 1")

plot(showMovingAverages ? ma2 : na, color=color.red, linewidth=2, title="MA 2")

// === Support and Resistance ===

support = ta.lowest(close, 20)


resistance = ta.highest(close, 20)

// Draw Support and Resistance Levels

if showSupportResistance

line.new(bar_index - 1, support, bar_index, support, color=color.green, width=1, style=line.style_dotted)

line.new(bar_index - 1, resistance, bar_index, resistance, color=color.red, width=1, style=line.style_dotted)

// === Candlestick Patterns ===

bullishEngulfing = ta.crossover(close, open[1]) and close > open

bearishEngulfing = ta.crossunder(close, open[1]) and close < open

// Label Candlestick Patterns

if showCandlestickPatterns

if bullishEngulfing

label.new(bar_index, high, "Bullish Engulfing", color=color.new(color.green, 0), style=label.style_label_down)

if bearishEngulfing

label.new(bar_index, low, "Bearish Engulfing", color=color.new(color.red, 0), style=label.style_label_up)

// === Volume Analysis ===

avgVolume = ta.sma(volume, 50)


volumeSpike = volume > avgVolume * volumeThreshold

// Highlight Volume Spikes (handled dynamically)

bgcolor(showVolumeAnalysis and volumeSpike ? color.new(color.blue, 90) : na, title="Volume Spike")

// === Alerts ===

alertcondition(volumeSpike, title="Volume Spike Alert", message="High volume spike detected!")

alertcondition(bullishEngulfing, title="Bullish Pattern Alert", message="Bullish Engulfing pattern detected!")

alertcondition(bearishEngulfing, title="Bearish Pattern Alert", message="Bearish Engulfing pattern detected!")

// === Chart Annotations ===

var string titleText = "Comprehensive Trading Indicator\n- Moving Averages (50, 200)\n- Support/Resistance Levels\n- Candlestick Patterns\n- Volume
Analysis"

//@version=5

indicator("Optimized ICT Buy and Sell Signals", overlay=true)

// --- Input Parameters ---

emaLength = input.int(9, title="EMA Length")


fvgLookback = input.int(10, title="Fair Value Gap Lookback Period")

orderBlockLookback = input.int(30, title="Order Block Lookback Period")

minGapSize = input.float(0.5, title="Min Gap Size (FVG)") // Minimum gap size for FVG detection

// --- EMA 9 (for trend direction) ---

ema9 = ta.ema(close, emaLength)

plot(ema9, title="EMA 9", color=color.blue, linewidth=2)

// --- Market Structure (ICT) ---

// Identify Higher Highs (HH) and Higher Lows (HL) for Bullish Market Structure

hhCondition = high > ta.highest(high, orderBlockLookback)[1] // Higher High

hlCondition = low > ta.lowest(low, orderBlockLookback)[1] // Higher Low

isBullishStructure = hhCondition and hlCondition // Bullish Market Structure condition

// Identify Lower Highs (LH) and Lower Lows (LL) for Bearish Market Structure

lhCondition = high < ta.highest(high, orderBlockLookback)[1] // Lower High

llCondition = low < ta.lowest(low, orderBlockLookback)[1] // Lower Low

isBearishStructure = lhCondition and llCondition // Bearish Market Structure condition

// --- Order Blocks (ICT) ---


// Bullish Order Block (consolidation before upmove)

var float bullishOrderBlock = na

if isBullishStructure

bullishOrderBlock := ta.valuewhen(low == ta.lowest(low, orderBlockLookback), low, 0)

// Bearish Order Block (consolidation before downmove)

var float bearishOrderBlock = na

if isBearishStructure

bearishOrderBlock := ta.valuewhen(high == ta.highest(high, orderBlockLookback), high, 0)

// --- Fair Value Gap (FVG) ---

// Bullish Fair Value Gap (FVG): Gap between a down-close followed by an up-close

fvgBullish = (low[fvgLookback] < high[1]) and (high[1] - low[fvgLookback] > minGapSize) // Bullish FVG condition with gap size filter

// Bearish Fair Value Gap (FVG): Gap between an up-close followed by a down-close

fvgBearish = (high[fvgLookback] > low[1]) and (high[fvgLookback] - low[1] > minGapSize) // Bearish FVG condition with gap size filter

// --- Entry Conditions ---

// Buy Condition: Bullish Market Structure and Price touching a Bullish Order Block or FVG, and above EMA

longCondition = isBullishStructure and (close <= bullishOrderBlock or fvgBullish) and close > ema9
// Sell Condition: Bearish Market Structure and Price touching a Bearish Order Block or FVG, and below EMA

shortCondition = isBearishStructure and (close >= bearishOrderBlock or fvgBearish) and close < ema9

// --- Plot Buy and Sell Signals on the Chart ---

plotshape(series=longCondition, location=location.belowbar, color=color.green, style=shape.labelup, title="Buy Signal", text="BUY", size=size.small)

plotshape(series=shortCondition, location=location.abovebar, color=color.red, style=shape.labeldown, title="Sell Signal", text="SELL", size=size.small)

// --- Highlight Order Blocks ---

plot(bullishOrderBlock, color=color.green, linewidth=1, title="Bullish Order Block", style=plot.style_circles)

plot(bearishOrderBlock, color=color.red, linewidth=1, title="Bearish Order Block", style=plot.style_circles)

// --- Highlight Fair Value Gaps (FVG) ---

bgcolor(fvgBullish ? color.new(color.green, 90) : na, title="Bullish FVG", transp=90)

bgcolor(fvgBearish ? color.new(color.red, 90) : na, title="Bearish FVG", transp=90)

// --- Alerts ---

// Alert for Buy Signals

alertcondition(longCondition, title="Long Signal", message="Optimized ICT Buy Signal: Bullish structure, price touching bullish order block or FVG, and above
EMA.")
// Alert for Sell Signals

alertcondition(shortCondition, title="Short Signal", message="Optimized ICT Sell Signal: Bearish structure, price touching bearish order block or FVG, and
below EMA.")

//@version=5

indicator("Market Direction and Next Pivot", overlay=true)

// Inputs for trend and pivot calculation

sma_length = input.int(50, title="SMA Length", minval=1) // Length for trend detection (Simple Moving Average)

pivot_lookback = input.int(1, title="Pivot Lookback", minval=1) // Lookback period for calculating pivot levels

// Calculate the Simple Moving Average (SMA) for trend detection

sma = ta.sma(close, sma_length)

// Calculate the pivot points (Support and Resistance)

pivot_high = ta.highest(high, pivot_lookback)

pivot_low = ta.lowest(low, pivot_lookback)

pivot_close = (pivot_high + pivot_low + close) / 3 // Standard Pivot Point


// Predict next support and resistance levels

next_resistance = pivot_close + (pivot_high - pivot_low) // Next Resistance Level

next_support = pivot_close - (pivot_high - pivot_low) // Next Support Level

// Determine market direction (trend)

uptrend = close > sma

downtrend = close < sma

// Plot market direction (SMA and trend labels)

plot(sma, color=color.purple, linewidth=2, title="Simple Moving Average (SMA)")

bgcolor(uptrend ? color.new(color.green, 90) : downtrend ? color.new(color.red, 90) : na, title="Trend Background")

// Display trend direction labels

label.new(bar_index, high, text=uptrend ? "Uptrend" : downtrend ? "Downtrend" : "Neutral", color=uptrend ? color.green : downtrend ? color.red :
color.gray, style=label.style_label_down, size=size.small, textcolor=color.white)

// Plot the next pivot points (support and resistance)

plot(next_resistance, color=color.red, linewidth=2, title="Next Resistance")

plot(next_support, color=color.green, linewidth=2, title="Next Support")


//@version=5

indicator("RSI Crossover Signals", overlay=true)

// RSI parameters

rsiPeriod = 14

rsi = ta.rsi(close, rsiPeriod)

// Thresholds for RSI

rsiUpper = 60

rsiLower = 40

// Conditions for buy (RSI crossing above 60) and sell (RSI crossing below 40)

buyCondition = ta.crossover(rsi, rsiUpper)

sellCondition = ta.crossunder(rsi, rsiLower)

// Plot buy and sell signals on the chart

plotshape(series=buyCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")

plotshape(series=sellCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")


// Plot the RSI on a separate chart

plot(rsi, "RSI", color=color.blue)

hline(rsiUpper, "RSI 60", color=color.green)

hline(rsiLower, "RSI 40", color=color.red)

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// © fabbriliar9192@gmail.com by Franco Fabbri.

//@version=6

indicator('SUPRA BERSERKER CAPITAL CA & NFL', overlay = true)

// Parámetros para las EMAs

ema1_length = input.int(100, title = 'EMA 1 Length', minval = 1)

ema2_length = input.int(200, title = 'EMA 2 Length', minval = 1)

ema_source = input.source(close, title = 'EMA Source')

ema1_color = input.color(color.white, title = 'EMA 1 Color')

ema2_color = input.color(color.purple, title = 'EMA 2 Color')


// Parámetros para la VWMA

vwma_length = input.int(250, title = 'VWMA Length', minval = 1)

vwma_source = input.source(close, title = 'VWMA Source')

vwma_color = input.color(color.red, title = 'VWMA Color')

vwma_offset = input.int(0, title = 'VWMA Offset', minval = -500, maxval = 500)

// Cálculo de las EMAs

ema1 = ta.ema(ema_source, ema1_length)

ema2 = ta.ema(ema_source, ema2_length)

// Cálculo de la VWMA

vwma = ta.vwma(vwma_source, vwma_length)

// Mostrar las EMAs

plot(ema1, color = ema1_color, title = 'EMA 1', linewidth = 2)

plot(ema2, color = ema2_color, title = 'EMA 2', linewidth = 2)

// Mostrar la VWMA

plot(vwma, color = vwma_color, title = 'VWMA', offset = vwma_offset, linewidth = 2)


// Código de importado del Gaussian

import loxx/loxxexpandedsourcetypes/4

// Ehlers 2-pole super smoother

_twopoless(float src, int len)=>

a1 = 0., b1 = 0.

coef1 = 0., coef2 = 0., coef3 = 0.

filt = 0., trig = 0.

a1 := math.exp(-1.414 * math.pi / len)

b1 := 2 * a1 * math.cos(1.414 * math.pi / len)

coef2 := b1

coef3 := -a1 * a1

coef1 := 1 - coef2 - coef3

filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])

filt := bar_index < 3 ? src : filt

filt

// Gaussian

_gaussian(size, x)=>
out = (math.exp(-x * x * 9 / ((size + 1) * (size + 1))))

out

// Fibonacci

_fiblevels(len)=>

arr_levels = array.new_float(len, 0.)

t1 = 0, t2 = 1

nxt = t1 + t2

for i = 0 to len - 1

array.set(arr_levels, i, nxt)

t1 := t2

t2 := nxt

nxt := t1 + t2

arr_levels

// Salida de calculos Gaussian

_gaussout(levels)=>

perin = array.size(levels)

arr_gauss = matrix.new<float>(perin, perin, 0.)

for k = 0 to array.size(levels) - 1
sum = 0.

for i = 0 to perin - 1

if (i >= array.get(levels, k))

break

matrix.set(arr_gauss, i, k, _gaussian(array.get(levels, k), i))

sum += matrix.get(arr_gauss, i, k)

for i = 0 to perin - 1

if (i >= array.get(levels, k))

break

temp = matrix.get(arr_gauss, i, k) / sum

matrix.set(arr_gauss, i, k, temp)

arr_gauss

// Smooth moving average

_smthMA(level, src, per)=>

sum = 0.

lvltemp = _fiblevels(per)

gtemp = _gaussout(lvltemp)

for i = 0 to matrix.rows(gtemp) - 1

sum += matrix.get(gtemp, i, level) * nz(src[i])


sum

// Entradas para filtrar Gaussian

gaussian_length = input.int(72, "Gaussian Length", maxval=200, group="Gaussian Settings")

gaussian_source = input.source(close, title = "Gaussian Source", group="Gaussian Settings")

smthper = input.int(9, "Gaussian Levels Depth", maxval=100, group="Gaussian Settings")

extrasmthper = input.int(9, "Extra Smoothing (2-Pole Ehlers Super Smoother) Period", group="Gaussian Settings")

atrper = input.int(21, "ATR Period", group="Gaussian Settings")

mult = input.float(3, "ATR Multiplier", group="Gaussian Settings")

// Datos de calculo

src = gaussian_source

lmax = smthper + 1

out1 = _smthMA(smthper, src, lmax)

out = _twopoless(out1, gaussian_length)

atr = ta.atr(atrper)

smax = out + atr * mult

smin = out - atr * mult


// Cambiar el color de la GMA dependiendo de la relación con el precio de cierre

color_gma = close > out ? color.yellow : color.red

// Mostrar Gaussian Filter con la GMA cambiando de color

plot(smax, color=color.red, linewidth=2)

plot(smin, color=color.yellow, linewidth=2)

plot(out, "GMA", color=color_gma, linewidth=4)

//@version=6

indicator("SMA+BB+PSAR+GOLDEN AND DEATH CROSS", overlay=true)

activeSMA = input.bool(true, title="activeSMA")

sma_1 = ta.sma(close, 5)

plot(activeSMA ? sma_1 : na, color=color.yellow, linewidth=1, title="5")

sma_2 = ta.sma(close, 8)

plot(activeSMA ? sma_2 : na, color=color.red, linewidth=1, title="8")

sma_3 = ta.sma(close, 13)

plot(activeSMA ? sma_3 : na, color=color.rgb(9, 198, 236), linewidth=1, title="13")

sma_4 = ta.sma(close, 21)


plot(activeSMA ? sma_4 : na, color=color.rgb(10, 72, 244), linewidth=1, title="21")

sma_5 = ta.sma(close, 34)

plot(activeSMA ? sma_5 : na, color=color.rgb(84, 4, 4), linewidth=1, title="34")

sma_6 = ta.sma(close, 55)

plot(activeSMA ? sma_6 : na, color=color.rgb(82, 255, 134), linewidth=1, title="55")

sma_7 = ta.sma(close, 89)

plot(activeSMA ? sma_7 : na, color=color.rgb(243, 33, 212), linewidth=1, title="89")

sma_8 = ta.sma(close, 144)

plot(activeSMA ? sma_8 : na, color=color.rgb(232, 157, 141), linewidth=2, title="144")

sma_9 = ta.sma(close, 233)

plot(activeSMA ? sma_9 : na, color=color.rgb(22, 22, 22), linewidth=2, title="233")

sma_10 = ta.sma(close, 377)

plot(activeSMA ? sma_10 : na, color=color.rgb(189, 185, 185), linewidth=1, title="377")

sma_11 = ta.sma(close, 610)

plot(activeSMA ? sma_11 : na, color=color.rgb(118, 180, 227), linewidth=1, title="610")

activeBB = input.bool(false, title="activeBB")

source = input(close, title="BBSource")

length = input.int(20, title="BBLength")

mult = input.float(2.0, title="BBMultiply")


dev = ta.stdev(source, length) * mult

base = ta.sma(source, length)

upper = base + dev

lower = base - dev

u = plot(activeBB ? upper : na, color=color.red, title="Upper Band")

plot(activeBB ? base : na, color=color.black, title="Base Line")

l = plot(activeBB ? lower : na, color=color.green, title="Lower Band")

fill(u, l, title="Bollinger Band")

activeSAR = input.bool(true, title="activePSAR")

start = input.float(title="Start", step=0.001, defval=0.02)

increment = input.float(title="Increment", step=0.001, defval=0.02)

maximum = input.float(title="Maximum", step=0.01, defval=0.2)

width = input.int(title="Point Width", minval=1, defval=2)

highlightStartPoints = input.bool(title="Highlight Start Points ?", defval=true)

psar = ta.sar(start, increment, maximum)


dir = psar < close ? 1 : -1

psarColor = psar < close ? #3388bb : #fdcc02

plot(activeSAR ? psar : na, title="PSAR", style=plot.style_circles, linewidth=width, color=psarColor)

plotshape(dir == 1 and dir[1] == -1 and highlightStartPoints ? psar : na, title="Long Stop Start", location=location.absolute, style=shape.circle, size=size.tiny,
color=color.green)

plotshape(dir == -1 and dir[1] == 1 and highlightStartPoints ? psar : na, title="Short Stop Start", location=location.absolute, style=shape.circle, size=size.tiny,
color=color.red)

changeCond = dir != dir[1]

alertcondition(changeCond, title="Alert on Parabolic SAR Direction Change", message="Parabolic SAR has changed direction!")

fast_period = input.int(50, minval=1, title="fast sma-period")

slow_period = input.int(200, minval=1, title="slow sma-period")

fastMA = ta.sma(close, fast_period)

slowMA = ta.sma(close, slow_period)

golden_cross = ta.cross(slowMA, fastMA) and fastMA[1] <= slowMA[1]

death_cross = ta.cross(slowMA, fastMA) and slowMA[1] <= fastMA[1]


plot(fastMA, color=color.red)

plot(slowMA, color=color.blue)

plot(ta.cross(fastMA, slowMA) ? fastMA : na, color=slowMA - fastMA > 0 ? color.red : color.lime, style=plot.style_circles, linewidth=4)

plotshape(death_cross ? fastMA : na, color=color.red, text="DeathCross", textcolor=color.black, style=shape.labeldown, location=location.absolute)

plotshape(golden_cross ? fastMA : na, color=color.lime, text="GoldenCross", textcolor=color.black, style=shape.labelup, location=location.absolute)

plotshape(golden_cross, style=shape.labelup, location=location.belowbar, color=color.lime)

plotshape(death_cross, style=shape.labeldown, location=location.abovebar, color=color.red)

//@version=5

indicator('Fibonacci Retracment & Pivot Points by Amarpatil04', 'FIBs ʙʏ Amarpatil04', true, max_lines_count = 500, max_labels_count = 500)

//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //

//

// Fibonacci Retracement / Extention / Pivot Points and Zig Zag

//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
// ---------------------------------------------------------------------------------------------- //

// -Inputs -------------------------------------------------------------------------------------- //

tooltip_threshold = 'Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new
pivot' +

'\n\nDepth affects the minimum number of bars that will be taken into account when building'

tooltip_pivot_point = 'A pivot point is a technical analysis indicator used to determine the overall trend of the market over different time frames'

tooltip_zigzag = 'The Zig Zag indicator is used to identify price trends then connected by straight lines that help the trader visual the price action' +

'This indicator works to eliminate confusion over small price changes or fluctuations and aims to project trend changes overtime'

// ---------------------------------------------------------------------------------------------- //

group_pick = 'Pick a Fibonacci Tool'

i_isFib = input.bool (true, 'Pick a Fibonacci Tool', inline='FIB', group=group_pick)

i_fibTool = input.string('Pivot Points', ' ',

options=['Pivot Points', 'Retracements', 'Retracements + Pivot Points', 'Extentions', 'Extentions + Pivot Points'], inline='FIB',
group=group_pick)
i_fibTime = input.bool (true, 'Fib Time Zones', inline='TZ', group=group_pick)

i_tzColor = input.color(#2196f3, '' , inline='TZ', group=group_pick)

// ---------------------------------------------------------------------------------------------- //

group_pivot = 'Fibonacci Pivot Points Settings'

i_htf_mode = input.string('Auto', 'Pivot Points TimeFrame', options=['Auto', 'User Defined'], inline='HTF', group=group_pivot, tooltip=tooltip_pivot_point)

i_htf_user_ = input.string('Weekly', ' or User Defined',

options=['15 Min', '1 Hour', '4 Hour', 'Daily', 'Weekly', 'Monthly', 'Quarterly', 'Yearly'], inline='HTF1', group=group_pivot)

i_htf_user = i_htf_user_ == '15 Min' ? '15' :

i_htf_user_ == '1 Hour' ? '60' :

i_htf_user_ == '4 Hour' ? '240' :

i_htf_user_ == 'Daily' ? 'D' :

i_htf_user_ == 'Weekly' ? 'W' :

i_htf_user_ == 'Monthly' ? 'M' :

i_htf_user_ == 'Quarterly' ? '3M' : '12M'

i_levelsPvt = input.string('Levels', 'Level Labels', options=['Levels', 'Prices', 'Levels + Prices', 'None'], inline='pvt', group=group_pivot)

i_levelsPvtP = input.string('Pivot End', '', options=['Last Bar', 'Pivot End'], inline='pvt', group=group_pivot)
i_levelsPvtS = input.string('Small', '', options=['Small', 'Normal'], inline='pvt', group=group_pivot)

i_relevant = input.bool(false, 'Only Relevant Pivot Point Levels', group=group_pivot)

i_histPP = input.bool(false, 'Historical Pivot Points', group=group_pivot)

i_extend = input.bool(false, 'Extend Pivot Point Lines', inline='fLines', group=group_pivot)

i_extendL = input.string('Dashed', '', options=['Dashed', 'Dotted', 'Solid'], inline='fLines', group=group_pivot)

// ---------------------------------------------------------------------------------------------- //

group_fib_tool = 'Fibonacci Extention / Retracement / TimeZone Settings'

i_dev_thresh = ta.atr(10) / close * 100 * input.float(3, 'Deviation', minval=0, inline='Pivots', group=group_fib_tool, tooltip=tooltip_threshold)

i_depth = input.int(11, ' Depth', minval=1, inline='Pivots', group=group_fib_tool)

i_levels = input.string('Levels', 'Level Labels', options=['Levels', 'Prices', 'Levels + Prices', 'None'], inline='fLines', group=group_fib_tool)

i_levelsP = input.string('Pivot Start', '', options=['Last Bar', 'Pivot Start'], inline='fLines', group=group_fib_tool)

i_levelsS = input.string('Small', '', options=['Small', 'Normal'], inline='fLines', group=group_fib_tool)

i_reverse = input.bool(false, 'Reverse Extention / Retracement Levels', group=group_fib_tool)

i_extendER = input.bool(false, 'Extend Extention / Retracement Lines', inline='fLine', group=group_fib_tool)


i_histPivot = input.int (0, 'Historical Extention / Retracement Levels', minval=0, group=group_fib_tool)

i_histPivot2 = input.int(0, 'Historical Time Zones', minval=0, group=group_fib_tool)

i_fib_tzl = input.bool(true, 'Time Zone Lables', inline='tz poz', group=group_fib_tool)

i_fib_tzlp = input.string('Left', '', options=['Right', 'Left'], inline='tz poz', group=group_fib_tool)

fib_tzlp = i_fib_tzlp == 'Left' ? label.style_label_left : label.style_label_right

i_fib_tzlp2 = input.string('Bottom', '', options=['Bottom', 'Top'], inline='tz poz', group=group_fib_tool)

// ---------------------------------------------------------------------------------------------- //

group_zigzag = 'ZigZag Settings'

i_zigZag = input.bool(false, 'Zig Zag ', inline='ZZ', group=group_zigzag, tooltip=tooltip_zigzag)

i_zzColor = input.color(#c77a08, '', inline='ZZ', group=group_zigzag)

i_zzStyle = input.string('Solid', '', options=['Dashed', 'Dotted', 'Solid'], inline='ZZ', group=group_zigzag)

i_zzWidth = input.int(1, '', minval=1, inline='ZZ', group=group_zigzag)

// ---------------------------------------------------------------------------------------------- //
// -Calculations -------------------------------------------------------------------------------- //

var line lineLast = na

var int iLast = 0

var int iPrev = 0

var float pLast = 0

var isHighLast = false // otherwise the last pivot is a low pivot

var iPrevPivot = 0

var pPrevPivot = 0.

var iLastPivot = 0

var pLastPivot = 0.

pivots(src, length, isHigh) =>

l2 = length * 2

c = nz(src[length])

ok = true

for i = 0 to l2 by 1

if isHigh and src[i] > c


ok := false

ok

if not isHigh and src[i] < c

ok := false

ok

if ok

[bar_index[length], c]

else

[int(na), float(na)]

[iH, pH] = pivots(high, i_depth / 2, true)

[iL, pL] = pivots(low, i_depth / 2, false)

calc_dev(base_price, price) =>

100 * (price - base_price) / price

pivotFound(dev, isHigh, index, price) =>

if isHighLast == isHigh and not na(lineLast)

// same direction
if isHighLast ? price > pLast : price < pLast

line.set_xy2(lineLast, index, price)

[lineLast, isHighLast]

else

[line(na), bool(na)]

else

// reverse the direction (or create the very first line)

if math.abs(dev) > i_dev_thresh

// price move is significant

// ---------------------------------------------------------------------------------------- //

[zzCol, zzWid, zzSty] = if not i_zigZag

[na, 1, line.style_dashed]

else

[i_zzColor, i_zzWidth, i_zzStyle == 'Solid' ? line.style_solid : i_zzStyle == 'Dotted' ? line.style_dotted : line.style_dashed]

// ---------------------------------------------------------------------------------------- //

id = line.new(iLast, pLast, index, price, color=zzCol, width=zzWid, style=zzSty)

[id, isHigh]

else
[line(na), bool(na)]

if not na(iH)

dev = calc_dev(pLast, pH)

[id, isHigh] = pivotFound(dev, true, iH, pH)

if not na(id)

if id != lineLast

// ---------------------------------------------------------------------------------------- //

iPrevPivot := line.get_x1(lineLast)

pPrevPivot := line.get_y1(lineLast)

iLastPivot := line.get_x2(lineLast)

pLastPivot := line.get_y2(lineLast)

if not i_zigZag

// ---------------------------------------------------------------------------------------- //

line.delete(lineLast)

lineLast := id
isHighLast := isHigh

iPrev := iLast

iLast := iH

pLast := pH

pLast

else

if not na(iL)

dev = calc_dev(pLast, pL)

[id, isHigh] = pivotFound(dev, false, iL, pL)

if not na(id)

if id != lineLast

// ---------------------------------------------------------------------------------------- //

iPrevPivot := line.get_x1(lineLast)

pPrevPivot := line.get_y1(lineLast)

iLastPivot := line.get_x2(lineLast)

pLastPivot := line.get_y2(lineLast)

if not i_zigZag

// ---------------------------------------------------------------------------------------- //
line.delete(lineLast)

lineLast := id

isHighLast := isHigh

iPrev := iLast

iLast := iL

pLast := pL

pLast

iStartBase = i_histPivot > 0 ? ta.valuewhen(ta.change(iPrevPivot), iPrevPivot, i_histPivot) : ta.valuewhen(ta.change(iPrevPivot), iPrevPivot, 0)

pStartBase = i_histPivot > 0 ? ta.valuewhen(ta.change(pPrevPivot), pPrevPivot, i_histPivot) : ta.valuewhen(ta.change(pPrevPivot), pPrevPivot, 0)

iEndBase = i_histPivot > 0 ? ta.valuewhen(ta.change(iLastPivot), iLastPivot, i_histPivot - 1) : line.get_x2(lineLast)

pEndBase = i_histPivot > 0 ? ta.valuewhen(ta.change(pLastPivot), pLastPivot, i_histPivot - 1) : line.get_y2(lineLast)

iMidPivot = i_histPivot > 0 ? ta.valuewhen(ta.change(iPrevPivot), iPrevPivot, i_histPivot - 1) : line.get_x1(lineLast)

pMidPivot = i_histPivot > 0 ? ta.valuewhen(ta.change(pPrevPivot), pPrevPivot, i_histPivot - 1) : line.get_y1(lineLast)

iEndBase2 = i_histPivot2 > 0 ? ta.valuewhen(ta.change(iLastPivot), iLastPivot, i_histPivot2 - 1) : line.get_x2(lineLast)

pEndBase2 = i_histPivot2 > 0 ? ta.valuewhen(ta.change(pLastPivot), pLastPivot, i_histPivot2 - 1) : line.get_y2(lineLast)

iMidPivot2 = i_histPivot2 > 0 ? ta.valuewhen(ta.change(iPrevPivot), iPrevPivot, i_histPivot2 - 1) : line.get_x1(lineLast)


pMidPivot2 = i_histPivot2 > 0 ? ta.valuewhen(ta.change(pPrevPivot), pPrevPivot, i_histPivot2 - 1) : line.get_y1(lineLast)

//------------------------------------------------------------------------------

// auto higher time frame code snippet from pine wizard LonesomeTheBlue

htf_auto = timeframe.period == '1' ? '240' :

timeframe.period == '3' ? '240' :

timeframe.period == '5' ? '240' :

timeframe.period == '15' ? 'D' :

timeframe.period == '30' ? 'D' :

timeframe.period == '45' ? 'D' :

timeframe.period == '60' ? 'W' :

timeframe.period == '120' ? 'W' :

timeframe.period == '180' ? 'W' :

timeframe.period == '240' ? 'W' :

timeframe.period == 'D' ? 'M' :

timeframe.period == 'W' ? '3M' : '12M'

htf = i_htf_mode == 'Auto' ? htf_auto : i_htf_user


//------------------------------------------------------------------------------

// security function free price calculations

f_htf_ohlc(_htf) =>

var htf_o = 0.

var htf_h = 0.

var htf_l = 0.

htf_c = close

var htf_ox = 0.

var htf_hx = 0.

var htf_lx = 0.

var htf_cx = 0.

if ta.change(time(_htf))

htf_ox := htf_o

htf_o := open

htf_hx := htf_h

htf_h := high
htf_lx := htf_l

htf_l := low

htf_cx := htf_c[1]

htf_cx

else

htf_h := math.max(high, htf_h)

htf_l := math.min(low , htf_l)

htf_l

[htf_ox, htf_hx, htf_lx, htf_cx, htf_o, htf_h, htf_l, htf_c]

[_, htf_h1, htf_l1, htf_c1, _, _, _, _] = f_htf_ohlc(htf)

// ---------------------------------------------------------------------------------------------- //

// -Plotting ------------------------------------------------------------------------------------ //

time_x10 = ta.valuewhen(ta.change(time(htf)), time, 1)

time_x11 = ta.valuewhen(ta.change(time(htf)), time, 0)


time_x21 = 2 * time_x11 - time_x10

f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>

var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)

if _y1 > 0 and _y2 > 0

line.set_xy1(id, _x1, _y1)

line.set_xy2(id, _x2, _y2)

line.set_color(id, _color)

else

line.set_xy1(id, _x1, close)

line.set_xy2(id, _x2, close)

line.set_color(id, #00000000)

f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>

var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)

label.set_text(id, i_extend or i_extendER or i_levelsP == 'Last Bar' ? _text + '\n\n' : _text)

label.set_tooltip(id, _tooltip)

if _y > 0
label.set_xy(id, _x, _y)

label.set_textcolor(id, _textcolor)

else

label.set_xy(id, _x, close)

label.set_textcolor(id, #00000000)

f_crossingLevel(_curret, _level) =>

_level > _curret and _level < _curret[1] or _level < _curret and _level > _curret[1]

var ln = array.new_line()

var lb = array.new_label()

if ta.change(time) and array.size(ln) > 0

for i = 1 to array.size(ln) by 1

line.delete(array.shift(ln))

if ta.change(time) and array.size(lb) > 0

for i = 1 to array.size(lb) by 1

label.delete(array.shift(lb))
f_drawLineTZ(_x1, _y1, _x2, _y2, _xloc, _extend, _c, _s, _w) =>

if _x1 - bar_index < 500

array.push(ln, line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _c, _s, _w))

f_drawLabelTZ(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>

if _x - bar_index < 500

array.push(lb, label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip))

f_drawLinePVT(_x1, _y1, _x2, _y2, _xloc, _extend, _c, _s, _w) =>

if _y1 > 0

array.push(ln, line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _c, _s, _w))

f_drawLabelPVT(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>

if _y > 0

array.push(lb, label.new(_x, _y, i_extend or i_levelsPvtP == "Last Bar" ? _text + '\n\n' : _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign,
_tooltip))

if i_fibTime

referance = math.round(iEndBase2 - iMidPivot2)


f_drawLineTZ(iMidPivot2 - referance , pEndBase2, iMidPivot2 - referance , pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid, 1)

f_drawLineTZ(iMidPivot2 , pEndBase2, iMidPivot2 , pMidPivot2, xloc.bar_index, extend.both, color.gray, line.style_solid, 1)

f_drawLineTZ(iMidPivot2 + referance , pEndBase2, iMidPivot2 + referance , pMidPivot2, xloc.bar_index, extend.both, color.gray, line.style_solid, 1)

f_drawLineTZ(iMidPivot2 + referance * 2 , pEndBase2, iMidPivot2 + referance * 2 , pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid, 1)

f_drawLineTZ(iMidPivot2 + referance * 3 , pEndBase2, iMidPivot2 + referance * 3 , pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid, 1)

f_drawLineTZ(iMidPivot2 + referance * 5 , pEndBase2, iMidPivot2 + referance * 5 , pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid, 1)

f_drawLineTZ(iMidPivot2 + referance * 8 , pEndBase2, iMidPivot2 + referance * 8 , pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid, 1)

f_drawLineTZ(iMidPivot2 + referance * 13 , pEndBase2, iMidPivot2 + referance * 13, pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid,
1)

f_drawLineTZ(iMidPivot2 + referance * 21 , pEndBase2, iMidPivot2 + referance * 21, pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid,
1)

f_drawLineTZ(iMidPivot2 + referance * 34 , pEndBase2, iMidPivot2 + referance * 34, pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid,
1)

f_drawLineTZ(iMidPivot2 + referance * 55 , pEndBase2, iMidPivot2 + referance * 55, pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid,
1)

f_drawLineTZ(iMidPivot2 + referance * 89 , pEndBase2, iMidPivot2 + referance * 89, pMidPivot2, xloc.bar_index, extend.both, i_tzColor , line.style_solid,
1)

if i_fib_tzl

f_drawLabelTZ(iMidPivot2 + referance * -1, i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '-1',
xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')
f_drawLabelTZ(iMidPivot2 + referance * 0 , i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '0' ,
xloc.bar_index, yloc.price, #00000000, fib_tzlp, color.gray, size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 1 , i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '1' ,


xloc.bar_index, yloc.price, #00000000, fib_tzlp, color.gray, size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 2 , i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '2' ,


xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 3 , i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '3' ,


xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 5 , i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '5' ,


xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 8 , i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '8' ,


xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 13, i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '13',
xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 21, i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '21',
xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 34, i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '34',
xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 55, i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '55',
xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_drawLabelTZ(iMidPivot2 + referance * 89, i_fib_tzlp2 == 'Bottom' ? math.min(pEndBase2, pMidPivot2) : math.max(pEndBase2, pMidPivot2), '89',
xloc.bar_index, yloc.price, #00000000, fib_tzlp, i_tzColor , size.normal, text.align_center, '')

f_processLevelX(_show, _level, _color) =>


if i_isFib

pPivotDiff = math.abs(pMidPivot - pEndBase)

price = 0.

if i_fibTool == 'Extentions' or i_fibTool == 'Extentions + Pivot Points'

f_drawLineX(iStartBase, pStartBase, iMidPivot, pMidPivot, xloc.bar_index, extend.none, color.gray, line.style_dashed, 1)

f_drawLineX(iMidPivot , pMidPivot , iEndBase , pEndBase , xloc.bar_index, extend.none, color.gray, line.style_dashed, 1)

offset = math.abs(pMidPivot - pStartBase)

price := pEndBase < pMidPivot ? pMidPivot - pPivotDiff + (i_reverse ? -1 : 1) * offset * _level : pMidPivot + pPivotDiff - (i_reverse ? -1 : 1) * offset *
_level

if _show

f_drawLineX(iMidPivot, price, bar_index, price, xloc.bar_index, i_extendER ? extend.both : extend.right, _color, line.style_solid, 1)

if i_levels != 'None'

bar = i_levelsP == "Last Bar" ? bar_index : iMidPivot

style = i_levelsP == "Last Bar" ? label.style_label_left : label.style_label_right

size = i_levelsS == 'Small' ? size.small : size.normal

f_drawLabelX(bar, price, (i_levels == 'Prices' ? '' : 'EXT ' + str.tostring(_level)) + (i_levels == 'Levels + Prices' or i_levels == 'Prices' ? ' (' +
str.tostring(price, format.mintick) + ')' : ''), xloc.bar_index, yloc.price, #00000000, style, _color, size, text.align_left, str.tostring(price, format.mintick))
if f_crossingLevel(close, price)

alert('AutoFib Extention : ' + syminfo.ticker + ' crossing level ' + str.tostring(_level))

if i_fibTool == 'Retracements' or i_fibTool == 'Retracements + Pivot Points'

f_drawLineX(iMidPivot, pMidPivot, iEndBase, pEndBase, xloc.bar_index, extend.none, color.gray, line.style_dashed, 1)

price := pEndBase < pMidPivot ? (i_reverse ? pEndBase : pMidPivot) - (i_reverse ? -1 : 1) * pPivotDiff * _level : (i_reverse ? pEndBase : pMidPivot) +
(i_reverse ? -1 : 1) * pPivotDiff * _level

if _show

f_drawLineX(iMidPivot, price, bar_index, price, xloc.bar_index, i_extendER ? extend.both : extend.right, _color, line.style_solid, 1)

if i_levels != 'None'

bar = i_levelsP == "Last Bar" ? bar_index : iMidPivot

style = i_levelsP == "Last Bar" ? label.style_label_left : label.style_label_right

size = i_levelsS == 'Small' ? size.small : size.normal

f_drawLabelX(bar, price, (i_levels == 'Prices' ? '' : 'RET ' + str.tostring(_level)) + (i_levels == 'Levels + Prices' or i_levels == 'Prices' ? ' (' +
str.tostring(price, format.mintick) + ')' : ''), xloc.bar_index, yloc.price, #00000000, style, _color, size, text.align_left, str.tostring(price, format.mintick))

if f_crossingLevel(close, price)
alert('AutoFib Retracment : ' + syminfo.ticker + ' crossing level ' + str.tostring(_level))

if i_fibTool == 'Pivot Points' or i_fibTool == 'Extentions + Pivot Points' or i_fibTool == 'Retracements + Pivot Points'

pivot = math.avg(htf_h1, htf_l1, htf_c1)

range_2 = htf_h1 - htf_l1

if not i_histPP

f_drawLinePVT(time_x10, pivot, time_x21, pivot, xloc.bar_time, extend.none, color.gray, line.style_dashed, 1)

if _show and _level >= 0

pvtPoints = _level == 0 or _level == 0.382 or _level == 0.618 or _level == 1

f_drawLinePVT(time_x11, pivot - range_2 * _level, time_x21, pivot - range_2 * _level, xloc.bar_time, extend.none, i_relevant ? close < pivot ?
_color : na : _color, pvtPoints ? line.style_solid : line.style_dashed, pvtPoints ? 2 : 1)

f_drawLinePVT(time_x11, pivot + range_2 * _level, time_x21, pivot + range_2 * _level, xloc.bar_time, extend.none, i_relevant ? close > pivot ?
_color : na : _color, pvtPoints ? line.style_solid : line.style_dashed, pvtPoints ? 2 : 1)

if i_extend

style = i_extendL == 'Solid' ? line.style_solid : i_extendL == 'Dotted' ? line.style_dotted : line.style_dashed

f_drawLinePVT(time_x11, pivot - range_2 * _level, time_x21, pivot - range_2 * _level, xloc.bar_time, extend.both, i_relevant ? close < pivot ?
_color : na : _color, style, 1)
f_drawLinePVT(time_x11, pivot + range_2 * _level, time_x21, pivot + range_2 * _level, xloc.bar_time, extend.both, i_relevant ? close > pivot ?
_color : na : _color, style, 1)

if i_levelsPvt != 'None'

time_xx = i_levelsPvtP == "Last Bar" ? timenow : time_x21

size = i_levelsPvtS == 'Small' ? size.small : size.normal

if pvtPoints

if _level == 0

f_drawLabelPVT(time_xx, pivot, (i_levelsPvt == 'Prices' ? '' : 'PP') + (i_levelsPvt == 'Levels + Prices' or i_levelsPvt == 'Prices' ? ' (' +
str.tostring(pivot, format.mintick) + ')' : ''), xloc.bar_time, yloc.price, #00000000, label.style_label_left, _color, size, text.align_left, str.tostring(pivot,
format.mintick))

else

f_drawLabelPVT(time_xx, pivot - range_2 * _level, (i_levelsPvt == 'Prices' ? '' : (_level == 0.382 ? 'S1 PP ' : _level == 0.618 ? 'S2 PP ' : 'S3 PP ') +
str.tostring(_level)) + (i_levelsPvt == 'Levels + Prices' or i_levelsPvt == 'Prices' ? ' (' + str.tostring(pivot - range_2 * _level, format.mintick) + ')' : ''),
xloc.bar_time, yloc.price, #00000000, label.style_label_left, i_relevant ? close < pivot ? _color : na : _color, size, text.align_left, str.tostring(pivot - range_2 *
_level, format.mintick))

f_drawLabelPVT(time_xx, pivot + range_2 * _level, (i_levelsPvt == 'Prices' ? '' : (_level == 0.382 ? 'R1 PP ' : _level == 0.618 ? 'R2 PP ' : 'R3 PP ')
+ str.tostring(_level)) + (i_levelsPvt == 'Levels + Prices' or i_levelsPvt == 'Prices' ? ' (' + str.tostring(pivot + range_2 * _level, format.mintick) + ')' : ''),
xloc.bar_time, yloc.price, #00000000, label.style_label_left, i_relevant ? close > pivot ? _color : na : _color, size, text.align_left, str.tostring(pivot + range_2 *
_level, format.mintick))

else

f_drawLabelPVT(time_xx, pivot - range_2 * _level, (i_levelsPvt == 'Prices' ? '' : ' PP ' + str.tostring(_level)) + (i_levelsPvt == 'Levels + Prices' or
i_levelsPvt == 'Prices' ? ' (' + str.tostring(pivot - range_2 * _level, format.mintick) + ')' : ''), xloc.bar_time, yloc.price, #00000000, label.style_label_left,
i_relevant ? close < pivot ? _color : na : _color, size, text.align_left, str.tostring(pivot - range_2 * _level, format.mintick))
f_drawLabelPVT(time_xx, pivot + range_2 * _level, (i_levelsPvt == 'Prices' ? '' : ' PP ' + str.tostring(_level)) + (i_levelsPvt == 'Levels + Prices' or
i_levelsPvt == 'Prices' ? ' (' + str.tostring(pivot + range_2 * _level, format.mintick) + ')' : ''), xloc.bar_time, yloc.price, #00000000, label.style_label_left,
i_relevant ? close > pivot ? _color : na : _color, size, text.align_left, str.tostring(pivot + range_2 * _level, format.mintick))

if f_crossingLevel(close, pivot - range_2 * _level)

alert('AutoFib PivotPoints : ' + syminfo.ticker + ' crossing support level ' + str.tostring(_level))

if f_crossingLevel(close, pivot + range_2 * _level)

alert('AutoFib PivotPoints : ' + syminfo.ticker + ' crossing resistance level ' + str.tostring(_level))

group_fib_levels = 'Fibonacci Levels'

show_0 = input.bool(true, '', inline='Level0', group=group_fib_levels)

value_0 = input.float(0., '', inline='Level0', group=group_fib_levels)

color_0 = input.color(#787b86, '', inline='Level0', group=group_fib_levels)

f_processLevelX(show_0, value_0, color_0)

show_0_236 = input.bool(true, '', inline='Level0', group=group_fib_levels)

value_0_236 = input.float(0.236, '', inline='Level0', group=group_fib_levels)

color_0_236 = input.color(#f44336, '', inline='Level0', group=group_fib_levels)

f_processLevelX(show_0_236, value_0_236, color_0_236)


show_0_382 = input.bool(true, '', inline='Level1', group=group_fib_levels)

value_0_382 = input.float(0.382, '', inline='Level1', group=group_fib_levels)

color_0_382 = input.color(#81c784, '', inline='Level1', group=group_fib_levels)

f_processLevelX(show_0_382, value_0_382, color_0_382)

show_0_5 = input.bool(true, '', inline='Level1', group=group_fib_levels)

value_0_5 = input.float(0.5, '', inline='Level1', group=group_fib_levels)

color_0_5 = input.color(#4caf50, '', inline='Level1', group=group_fib_levels)

f_processLevelX(show_0_5, value_0_5, color_0_5)

show_0_618 = input.bool(true, '', inline='Level2', group=group_fib_levels)

value_0_618 = input.float(0.618, '', inline='Level2', group=group_fib_levels)

color_0_618 = input.color(#009688, '', inline='Level2', group=group_fib_levels)

f_processLevelX(show_0_618, value_0_618, color_0_618)

show_0_65 = input.bool(false, '', inline='Level2', group=group_fib_levels)

value_0_65 = input.float(0.65, '', inline='Level2', group=group_fib_levels)

color_0_65 = input.color(#009688, '', inline='Level2', group=group_fib_levels)

f_processLevelX(show_0_65, value_0_65, color_0_65)


show_0_786 = input.bool(true, '', inline='Level3', group=group_fib_levels)

value_0_786 = input.float(0.786, '', inline='Level3', group=group_fib_levels)

color_0_786 = input.color(#64b5f6, '', inline='Level3', group=group_fib_levels)

f_processLevelX(show_0_786, value_0_786, color_0_786)

show_1 = input.bool(true, '', inline='Level3', group=group_fib_levels)

value_1 = input.float(1., '', inline='Level3', group=group_fib_levels)

color_1 = input.color(#787b86, '', inline='Level3', group=group_fib_levels)

f_processLevelX(show_1, value_1, color_1)

show_1_272 = input.bool(false, '', inline='Level4', group=group_fib_levels)

value_1_272 = input.float(1.272, '', inline='Level4', group=group_fib_levels)

color_1_272 = input.color(#81c784, '', inline='Level4', group=group_fib_levels)

f_processLevelX(show_1_272, value_1_272, color_1_272)

show_1_414 = input.bool(false, '', inline='Level4', group=group_fib_levels)

value_1_414 = input.float(1.414, '', inline='Level4', group=group_fib_levels)

color_1_414 = input.color(#f44336, '', inline='Level4', group=group_fib_levels)

f_processLevelX(show_1_414, value_1_414, color_1_414)


show_1_618 = input.bool(true, '', inline='Level5', group=group_fib_levels)

value_1_618 = input.float(1.618, '', inline='Level5', group=group_fib_levels)

color_1_618 = input.color(#2196f3, '', inline='Level5', group=group_fib_levels)

f_processLevelX(show_1_618, value_1_618, color_1_618)

show_1_65 = input.bool(false, '', inline='Level5', group=group_fib_levels)

value_1_65 = input.float(1.65, '', inline='Level5', group=group_fib_levels)

color_1_65 = input.color(#2196f3, '', inline='Level5', group=group_fib_levels)

f_processLevelX(show_1_65, value_1_65, color_1_65)

show_2_618 = input.bool(false, '', inline='Level6', group=group_fib_levels)

value_2_618 = input.float(2.618, '', inline='Level6', group=group_fib_levels)

color_2_618 = input.color(#f44336, '', inline='Level6', group=group_fib_levels)

f_processLevelX(show_2_618, value_2_618, color_2_618)

show_2_65 = input.bool(false, '', inline='Level6', group=group_fib_levels)

value_2_65 = input.float(2.65, '', inline='Level6', group=group_fib_levels)

color_2_65 = input.color(#f44336, '', inline='Level6', group=group_fib_levels)

f_processLevelX(show_2_65, value_2_65, color_2_65)


show_3_618 = input.bool(false, '', inline='Level7', group=group_fib_levels)

value_3_618 = input.float(3.618, '', inline='Level7', group=group_fib_levels)

color_3_618 = input.color(#9c27b0, '', inline='Level7', group=group_fib_levels)

f_processLevelX(show_3_618, value_3_618, color_3_618)

show_3_65 = input.bool(false, '', inline='Level7', group=group_fib_levels)

value_3_65 = input.float(3.65, '', inline='Level7', group=group_fib_levels)

color_3_65 = input.color(#9c27b0, '', inline='Level7', group=group_fib_levels)

f_processLevelX(show_3_65, value_3_65, color_3_65)

show_4_236 = input.bool(false, '', inline='Level8', group=group_fib_levels)

value_4_236 = input.float(4.236, '', inline='Level8', group=group_fib_levels)

color_4_236 = input.color(#e91e63, '', inline='Level8', group=group_fib_levels)

f_processLevelX(show_4_236, value_4_236, color_4_236)

show_4_618 = input.bool(false, '', inline='Level8', group=group_fib_levels)

value_4_618 = input.float(4.618, '', inline='Level8', group=group_fib_levels)

color_4_618 = input.color(#81c784, '', inline='Level8', group=group_fib_levels)

f_processLevelX(show_4_618, value_4_618, color_4_618)


show_neg_0_236 = input.bool(false, '', inline='Level9', group=group_fib_levels)

value_neg_0_236 = input.float(-0.236, '', inline='Level9', group=group_fib_levels)

color_neg_0_236 = input.color(#f44336, '', inline='Level9', group=group_fib_levels)

f_processLevelX(show_neg_0_236, value_neg_0_236, color_neg_0_236)

show_neg_0_382 = input.bool(false, '', inline='Level9', group=group_fib_levels)

value_neg_0_382 = input.float(-0.382, '', inline='Level9', group=group_fib_levels)

color_neg_0_382 = input.color(#81c784, '', inline='Level9', group=group_fib_levels)

f_processLevelX(show_neg_0_382, value_neg_0_382, color_neg_0_382)

show_neg_0_618 = input.bool(true, '', inline='Level10', group=group_fib_levels)

value_neg_0_618 = input.float(-0.618, '', inline='Level10', group=group_fib_levels)

color_neg_0_618 = input.color(#009688, '', inline='Level10', group=group_fib_levels)

f_processLevelX(show_neg_0_618, value_neg_0_618, color_neg_0_618)

show_neg_0_65 = input.bool(false, '', inline='Level10', group=group_fib_levels)

value_neg_0_65 = input.float(-0.65, '', inline='Level10', group=group_fib_levels)

color_neg_0_65 = input.color(#009688, '', inline='Level10', group=group_fib_levels)

f_processLevelX(show_neg_0_65, value_neg_0_65, color_neg_0_65)


i_histPP := i_histPP and (i_fibTool == 'Pivot Points' or i_fibTool == 'Extentions + Pivot Points' or i_fibTool == 'Retracements + Pivot Points')

plot(i_histPP and show_0 ? math.avg(htf_h1, htf_l1, htf_c1) : na, 'PP' , ta.change(time(htf)) ? na : color_0)

plot(i_histPP and show_0_236 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_0_236 : na, 'PP 0_236', ta.change(time(htf)) ? na : color_0_236, 1,
plot.style_cross)

plot(i_histPP and show_0_236 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_0_236 : na, 'PP 0_236', ta.change(time(htf)) ? na : color_0_236,
1, plot.style_cross)

plot(i_histPP and show_0_382 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_0_382 : na, 'PP 0_382', ta.change(time(htf)) ? na : color_0_382)

plot(i_histPP and show_0_382 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_0_382 : na, 'PP 0_382', ta.change(time(htf)) ? na : color_0_382)

plot(i_histPP and show_0_5 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_0_5 : na, 'PP 0_5 ', ta.change(time(htf)) ? na : color_0_5 , 1,
plot.style_cross)

plot(i_histPP and show_0_5 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_0_5 : na, 'PP 0_5 ', ta.change(time(htf)) ? na : color_0_5 , 1,
plot.style_cross)

plot(i_histPP and show_0_618 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_0_618 : na, 'PP 0_618', ta.change(time(htf)) ? na : color_0_618)

plot(i_histPP and show_0_618 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_0_618 : na, 'PP 0_618', ta.change(time(htf)) ? na : color_0_618)

plot(i_histPP and show_0_65 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_0_65 : na, 'PP 0_65 ', ta.change(time(htf)) ? na : color_0_65 , 1,
plot.style_cross)

plot(i_histPP and show_0_65 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_0_65 : na, 'PP 0_65 ', ta.change(time(htf)) ? na : color_0_65 , 1,
plot.style_cross)

plot(i_histPP and show_0_786 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_0_786 : na, 'PP 0_786', ta.change(time(htf)) ? na : color_0_786, 1,
plot.style_cross)
plot(i_histPP and show_0_786 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_0_786 : na, 'PP 0_786', ta.change(time(htf)) ? na : color_0_786,
1, plot.style_cross)

plot(i_histPP and show_1 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_1 : na, 'PP 1 ', ta.change(time(htf)) ? na : color_1)

plot(i_histPP and show_1 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_1 : na, 'PP 1 ', ta.change(time(htf)) ? na : color_1)

plot(i_histPP and show_1_272 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_1_272 : na, 'PP 1_272', ta.change(time(htf)) ? na : color_1_272, 1,
plot.style_cross)

plot(i_histPP and show_1_272 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_1_272 : na, 'PP 1_272', ta.change(time(htf)) ? na : color_1_272,
1, plot.style_cross)

plot(i_histPP and show_1_414 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_1_414 : na, 'PP 1_414', ta.change(time(htf)) ? na : color_1_414, 1,
plot.style_cross)

plot(i_histPP and show_1_414 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_1_414 : na, 'PP 1_414', ta.change(time(htf)) ? na : color_1_414,
1, plot.style_cross)

plot(i_histPP and show_1_618 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_1_618 : na, 'PP 1_618', ta.change(time(htf)) ? na : color_1_618, 1,
plot.style_cross)

plot(i_histPP and show_1_618 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_1_618 : na, 'PP 1_618', ta.change(time(htf)) ? na : color_1_618,
1, plot.style_cross)

plot(i_histPP and show_1_65 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_1_65 : na, 'PP 1_65 ', ta.change(time(htf)) ? na : color_1_65 , 1,
plot.style_cross)

plot(i_histPP and show_1_65 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_1_65 : na, 'PP 1_65 ', ta.change(time(htf)) ? na : color_1_65 , 1,
plot.style_cross)

plot(i_histPP and show_2_618 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_2_618 : na, 'PP 2_618', ta.change(time(htf)) ? na : color_2_618, 1,
plot.style_cross)

plot(i_histPP and show_2_618 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_2_618 : na, 'PP 2_618', ta.change(time(htf)) ? na : color_2_618,
1, plot.style_cross)
plot(i_histPP and show_2_65 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_2_65 : na, 'PP 2_65 ', ta.change(time(htf)) ? na : color_2_65 , 1,
plot.style_cross)

plot(i_histPP and show_2_65 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_2_65 : na, 'PP 2_65 ', ta.change(time(htf)) ? na : color_2_65 , 1,
plot.style_cross)

plot(i_histPP and show_3_618 ? math.avg(htf_h1, htf_l1, htf_c1) - (htf_h1 - htf_l1) * value_3_618 : na, 'PP 3_618', ta.change(time(htf)) ? na : color_3_618, 1,
plot.style_cross)

plot(i_histPP and show_3_618 ? math.avg(htf_h1, htf_l1, htf_c1) + (htf_h1 - htf_l1) * value_3_618 : na, 'PP 3_618', ta.change(time(htf)) ? na : color_3_618,
1, plot.style_cross)

// Fibonacci Retracement / Extention / Pivot Points and Zig Zag

//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //

//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //

//

// Volume / Volatility AddOns

//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //

// ---------------------------------------------------------------------------------------------- //
// -Inputs -------------------------------------------------------------------------------------- //

group_vol_vol = 'Volume / Volatility AddOns'

tooltip_volume_spike_sign_of_exhaustion = 'Moments where\n' + 'huge volume detected : current volume is grater than the product of the theshold value
and volume moving average'

tooltip_high_volatility = 'Moments where\n' + 'price range of the current bar is grater than the product of the theshold value and average true range value
of defined period'

tooltip_volume_weighted_colored_bars = 'Volume Weighted Colored Bars\nColors bars based on the bar\'s volume relative to volume moving average'

// ---------------------------------------------------------------------------------------------- //

// High Volatility ------------------------------------------------------------------------------ //

i_hATRLb = input.bool(true, '⚡', inline='ATR', group=group_vol_vol, tooltip=tooltip_high_volatility)

i_weightedATR = ta.atr(input.int(13, 'ATR : Length', inline='ATR', group=group_vol_vol)) * input.float(2.718, 'Mult', minval=.1, step=.1, inline='ATR',
group=group_vol_vol)

// ---------------------------------------------------------------------------------------------- //

// Volume Moving Average : Base ----------------------------------------------------------------- //


i_vSMA = ta.sma(nz(volume), input.int(89, 'Volume Moving Average Length', group=group_vol_vol))

// ---------------------------------------------------------------------------------------------- //

// Volume Spike - Sign of Exhaustion ------------------------------------------------------------ //

i_vSpikeLb = input.bool(true, '🚦', inline='SRS1', group=group_vol_vol, tooltip=tooltip_volume_spike_sign_of_exhaustion)

i_vSpikeThresh = input.float(4.669, 'Volume Spike Theshold ', minval=.1, step=.1, inline='SRS1', group=group_vol_vol)

// ---------------------------------------------------------------------------------------------- //

// Volume Weighted Colored Bars ----------------------------------------------------------------- //

i_vwcb = input.bool(true, '', inline='VWC', group=group_vol_vol, tooltip=tooltip_volume_weighted_colored_bars)

i_vwcbHighThresh = input.float(1.618, 'VWCB : High ', minval=1., step=.1, inline='VWC', group=group_vol_vol)

i_vwcbLowThresh = input.float(0.618, ' Low', minval=.1, step=.1, inline='VWC', group=group_vol_vol)

// ---------------------------------------------------------------------------------------------- //

// -Calculations and Plotting ------------------------------------------------------------------- //

nzVolume = nz(volume)
bullCandle = close > open

bearCandle = close < open

range_1 = math.abs(high - low)

// ---------------------------------------------------------------------------------------------- //

// Volume Spike - Sign of Exhaustion ------------------------------------------------------------ //

exhaustVol = nzVolume > i_vSpikeThresh * i_vSMA

plotchar(i_vSpikeLb and nzVolume ? exhaustVol : na, 'Exhaustion Bar', '🚦', location.abovebar, size=size.tiny)

alertcondition(ta.crossover(nzVolume, i_vSMA * i_vSpikeThresh), 'Volume Spikes', 'sign of exhaustion, huge volume increase detected\n{{exchange}}:
{{ticker}}->\nOpen = {{open}}, Current = {{close}},\nTime = {{time}}')

// ---------------------------------------------------------------------------------------------- //

// High Volatility ------------------------------------------------------------------------------ //

highVolatility = range_1 > i_weightedATR

plotchar(i_hATRLb ? highVolatility : na, 'High Volatile Bar', '⚡', location.belowbar, size=size.tiny)

alertcondition(ta.crossover(range_1, i_weightedATR), 'High Volatility', 'high volatility detected\n{{exchange}}:{{ticker}}->\nOpen = {{open}}, Current =


{{close}},\nTime = {{time}}')

// ---------------------------------------------------------------------------------------------- //
// Volume Weighted Colored Bars by Kıvanç Özbilgiç ---------------------------------------------- //

vwcbCol = nzVolume > i_vSMA * i_vwcbHighThresh ? bullCandle ? #006400 : #910000 : nzVolume < i_vSMA * i_vwcbLowThresh ? bearCandle ? #FF9800 :
#7FFFD4 : na

barcolor(i_vwcb and nzVolume ? vwcbCol : na, title='Volume Weighted Colored Bars')

// Voloume / Volatility AddOns

//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //

var table logo = table.new(position.bottom_right, 1, 1)

table.cell(logo, 0, 0, '☼☾ ', text_size=size.normal, text_color=color.teal)

//@version=5

indicator("Thrax - Pullback based short side scalping", overlay=true)

// User Inputs
zoneTopPercent = input.float(0.4, "Zone TOP Size %", minval=0, step=0.001)

zoneBtmPercent = input.float(0.2, "Zone Bottom Size %", minval=0, step=0.001)

minPullback = input.float(2.0, "Minimum Pullback %", minval=0, step=0.01)

lookback = input.int(50, "Lookback Period", minval=10)

var color zoneColor = color.rgb(230, 184, 212, 90)

var color borderColor = color.rgb(57, 7, 61)

var color signalColor = #FF4136

var color pullbackColor = #ac2ecc

// Initialize Variables

var bool R1 = true

var bool R2 = false

var bool R3 = false

var float RCL1 = high

var float RCL2 = 0.0

var float RCL3 = 0.0

var float lowestSinceRCL1 = high

var float lowestSinceRCL2 = high

var int RCL1Bar = bar_index

var bool r1plot = true

var bool r2plot = false


var bool r3plot = false

var bool shortplot = false

var box currentZone = na

// Zone Calculation

float zoneTop = RCL1 * (1 + zoneTopPercent/100)

float zoneBottom = RCL1 * (1 - zoneBtmPercent/100)

bool inZone = high >= zoneBottom and high <= zoneTop

bool breakZone = high > zoneTop

barsSinceRCL1 = bar_index - RCL1Bar

// Track lowest prices for pullback calculation

lowestSinceRCL1 := math.min(lowestSinceRCL1, low)

lowestSinceRCL2 := math.min(lowestSinceRCL2, low)

// Calculate pullbacks

float pullbackFromRCL1 = ((RCL1 - lowestSinceRCL1) / RCL1) * 100


float pullbackFromRCL2 = ((RCL2 - lowestSinceRCL2) / RCL2) * 100

// Update zone visualization

if R1

if not na(currentZone)

box.delete(currentZone)

currentZone := box.new(bar_index[barsSinceRCL1], zoneTop, bar_index , zoneBottom, bgcolor=zoneColor, border_color=borderColor)

// Debug Info (optional)

var label debugLabel = na

label.delete(debugLabel)

bool pullback1Valid = pullbackFromRCL1 >= minPullback

bool pullback2Valid = pullbackFromRCL2 >= minPullback

//debugLabel := label.new(bar_index, low, text="R1=" + str.tostring(R1) + "\nR2=" + str.tostring(R2) + "\nR3=" + str.tostring(R3) + "\nRCL1=" +
str.tostring(RCL1) + "\nRCL2=" + str.tostring(RCL2) + "\nRCL3=" + str.tostring(RCL3) + "\nr1plot =" + str.tostring(r1plot) + "\nr2plot =" + str.tostring(r2plot) + "\
nr3plot=" + str.tostring(r3plot) + "\nshortplot =" + str.tostring(shortplot) + "\nZone Top=" + str.tostring(zoneTop) + "\nZone Bottom=" +
str.tostring(zoneBottom) + "\nPullback1=" + str.tostring(pullbackFromRCL1) + " (" + str.tostring(pullbackFromRCL1 >= minPullback) + ")\nPullback2=" +
str.tostring(pullbackFromRCL2) + " (" + str.tostring(pullbackFromRCL2 >= minPullback) + ")\nBars=" + str.tostring(bar_index - RCL1Bar) + "/" +
str.tostring(lookback), color=color.blue, style=label.style_label_up, textcolor=color.white, size=size.small)

// Reset on zone break


if breakZone

if not na(currentZone)

box.delete(currentZone)

R1 := true

R2 := false

R3 := false

RCL1 := high

RCL2 := 0.0

RCL3 := 0.0

RCL1Bar := bar_index

lowestSinceRCL1 := high

lowestSinceRCL2 := high

r1plot := true

r2plot := false

r3plot := false

shortplot := false

// Reset on lookback period exceeded

if bar_index - RCL1Bar > lookback

if not na(currentZone)
box.delete(currentZone)

R1 := true

R2 := false

R3 := false

RCL1 := high

RCL2 := 0.0

RCL3 := 0.0

RCL1Bar := bar_index

lowestSinceRCL1 := high

lowestSinceRCL2 := high

r1plot := true

r2plot := true

r3plot := true

shortplot := false

// Check for R2 condition

if inZone and not R2 and pullbackFromRCL1 >= minPullback

R2 := true

RCL2 := high

lowestSinceRCL2 := high
r2plot := true

// Check for R3 condition

if inZone and R2 and not R3 and pullbackFromRCL2 >= minPullback

R3 := true

RCL3 := high

r3plot := true

shortplot := true

// Plot rejection points

if R1 and r1plot

//label.new(bar_index, RCL1, text="R1", style=label.style_label_down, color=color.new(pullbackColor, 20), textcolor=color.white, size=size.small)

r1plot := false

if R2 and r2plot

label.new(bar_index, RCL2, text="⚠ Possible Pullback incoming", style=label.style_label_down, color=color.new(pullbackColor, 20), textcolor=color.white,
size=size.small)

r2plot := false

if R3 and r3plot

r3plot := false
// Plot Short Signal

if R1 and R2 and R3 and shortplot

shortplot := false

RCL2 := high

pullbackFromRCL2:= 0

lowestSinceRCL2 := high

//label.new(bar_index, RCL3, text="Short", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.large)

label.new(bar_index, RCL2, text="⚠ Possible Pullback incoming", style=label.style_label_down, color=color.new(pullbackColor, 20), textcolor=color.white,
size=size.small)

R3 := false // Reset R3 after signal

// Plot zone levels

plot(R1 ? zoneTop : na, "Zone Top", color=color.red, style=plot.style_circles)

plot(R1 ? zoneBottom : na, "Zone Bottom", color=color.red, style=plot.style_circles)

//@version=5

indicator("EMA Candlestick + Volume-Based Trend/Sentiment Indicator with Supertrend", overlay=true)

// Define EMA lengths


ema4 = ta.ema(close, 4)

ema9 = ta.ema(close, 9)

ema13 = ta.ema(close, 13)

ema20 = ta.ema(close, 20)

ema50 = ta.ema(close, 50)

ema200 = ta.ema(close, 200)

// Plot the EMAs with thick white lines

plot(ema4, color=color.new(color.white, 0), title="EMA 4", linewidth=2)

plot(ema9, color=color.new(color.white, 0), title="EMA 9", linewidth=2)

plot(ema13, color=color.new(color.white, 0), title="EMA 13", linewidth=2)

plot(ema20, color=color.new(color.white, 0), title="EMA 20", linewidth=2)

plot(ema50, color=color.new(color.white, 0), title="EMA 50", linewidth=2)

plot(ema200, color=color.new(color.white, 0), title="EMA 200", linewidth=2)

// --- Supertrend Parameters ---

atrPeriod = 10

factor = 3.0

[supertrend, direction] = ta.supertrend(factor, atrPeriod)


// Buy and Sell Signals

buySignal = ta.crossover(close, supertrend)

sellSignal = ta.crossunder(close, supertrend)

// Plot Supertrend

plot(supertrend, color=direction ? color.green : color.red, title="Supertrend", linewidth=2)

// Plot Buy and Sell Signals with white text

plotshape(series=buySignal, location=location.belowbar, color=color.green, style=shape.labelup, title="Buy Signal", text="BUY", textcolor=color.white)

plotshape(series=sellSignal, location=location.abovebar, color=color.red, style=shape.labeldown, title="Sell Signal", text="SELL", textcolor=color.white)

// --- Trend and Sentiment Analysis based on Volume Moving Averages (VMAs) ---

vma1m = request.security(syminfo.tickerid, "1", ta.sma(volume, 14), lookahead=barmerge.lookahead_on)

vma5m = request.security(syminfo.tickerid, "5", ta.sma(volume, 14), lookahead=barmerge.lookahead_on)

vma30m = request.security(syminfo.tickerid, "30", ta.sma(volume, 14), lookahead=barmerge.lookahead_on)

vma1h = request.security(syminfo.tickerid, "60", ta.sma(volume, 14), lookahead=barmerge.lookahead_on)

vma4h = request.security(syminfo.tickerid, "240", ta.sma(volume, 14), lookahead=barmerge.lookahead_on)

vma1d = request.security(syminfo.tickerid, "D", ta.sma(volume, 14), lookahead=barmerge.lookahead_on)


// Function to analyze volume trend

analyzeVolumeTrend(currentVolume, previousVolume) =>

trend = "Stable"

sentiment = "Neutral"

if (currentVolume > previousVolume) // If current volume is greater than previous volume

trend := "Increasing"

sentiment := "Bullish"

else if (currentVolume < previousVolume) // If current volume is less than previous volume

trend := "Decreasing"

sentiment := "Bearish"

[trend, sentiment]

// Store trend and sentiment data for each timeframe

[trend_1m, sentiment_1m] = analyzeVolumeTrend(vma1m, vma1m[1])

[trend_5m, sentiment_5m] = analyzeVolumeTrend(vma5m, vma5m[1])

[trend_30m, sentiment_30m] = analyzeVolumeTrend(vma30m, vma30m[1])

[trend_1h, sentiment_1h] = analyzeVolumeTrend(vma1h, vma1h[1])

[trend_4h, sentiment_4h] = analyzeVolumeTrend(vma4h, vma4h[1])


[trend_1d, sentiment_1d] = analyzeVolumeTrend(vma1d, vma1d[1])

// --- Display Data in Table ---

var table trendSentimentTable = table.new(position.bottom_right, 3, 7, bgcolor=color.new(color.black, 90))

if (bar_index == 0)

// Create table headers

table.cell(trendSentimentTable, 0, 0, "Timeframe", text_color=color.white, bgcolor=color.gray)

table.cell(trendSentimentTable, 1, 0, "Trend", text_color=color.white, bgcolor=color.gray)

table.cell(trendSentimentTable, 2, 0, "Sentiment", text_color=color.white, bgcolor=color.gray)

// Update table with trend and sentiment data for each timeframe

table.cell(trendSentimentTable, 0, 1, "1 Minute", text_color=color.white)

table.cell(trendSentimentTable, 1, 1, trend_1m, text_color=(trend_1m == "Increasing" ? color.green : trend_1m == "Decreasing" ? color.red : color.yellow))

table.cell(trendSentimentTable, 2, 1, sentiment_1m, text_color=(sentiment_1m == "Bullish" ? color.green : sentiment_1m == "Bearish" ? color.red :


color.white))

table.cell(trendSentimentTable, 0, 2, "5 Minutes", text_color=color.white)

table.cell(trendSentimentTable, 1, 2, trend_5m, text_color=(trend_5m == "Increasing" ? color.green : trend_5m == "Decreasing" ? color.red : color.yellow))

table.cell(trendSentimentTable, 2, 2, sentiment_5m, text_color=(sentiment_5m == "Bullish" ? color.green : sentiment_5m == "Bearish" ? color.red :


color.white))
table.cell(trendSentimentTable, 0, 3, "30 Minutes", text_color=color.white)

table.cell(trendSentimentTable, 1, 3, trend_30m, text_color=(trend_30m == "Increasing" ? color.green : trend_30m == "Decreasing" ? color.red :


color.yellow))

table.cell(trendSentimentTable, 2, 3, sentiment_30m, text_color=(sentiment_30m == "Bullish" ? color.green : sentiment_30m == "Bearish" ? color.red :


color.white))

table.cell(trendSentimentTable, 0, 4, "1 Hour", text_color=color.white)

table.cell(trendSentimentTable, 1, 4, trend_1h, text_color=(trend_1h == "Increasing" ? color.green : trend_1h == "Decreasing" ? color.red : color.yellow))

table.cell(trendSentimentTable, 2, 4, sentiment_1h, text_color=(sentiment_1h == "Bullish" ? color.green : sentiment_1h == "Bearish" ? color.red :


color.white))

table.cell(trendSentimentTable, 0, 5, "4 Hours", text_color=color.white)

table.cell(trendSentimentTable, 1, 5, trend_4h, text_color=(trend_4h == "Increasing" ? color.green : trend_4h == "Decreasing" ? color.red : color.yellow))

table.cell(trendSentimentTable, 2, 5, sentiment_4h, text_color=(sentiment_4h == "Bullish" ? color.green : sentiment_4h == "Bearish" ? color.red :


color.white))

table.cell(trendSentimentTable, 0, 6, "1 Day", text_color=color.white)

table.cell(trendSentimentTable, 1, 6, trend_1d, text_color=(trend_1d == "Increasing" ? color.green : trend_1d == "Decreasing" ? color.red : color.yellow))

table.cell(trendSentimentTable, 2, 6, sentiment_1d, text_color=(sentiment_1d == "Bullish" ? color.green : sentiment_1d == "Bearish" ? color.red :


color.white))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy