15th Jan 25
15th Jan 25
////////////////////////////////////////////////////////////
// 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
//
// WARNING:
////////////////////////////////////////////////////////////
xPP = (xHigh+xLow+(xClose*2)) / 4
// © LuxAlgo
//@version=5
, overlay = true
, max_labels_count = 500
, max_lines_count = 500
, max_boxes_count = 500
, max_bars_back = 500)
//-----------------------------------------------------------------------------{
//Constants
//-----------------------------------------------------------------------------{
//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_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 EXTEND_FVG = 'Determine how many bars to extend the Fair Value Gap boxes on chart'
//Settings
//-----------------------------------------------------------------------------{
//General
//----------------------------------------{
mode = input.string('Historical'
, tooltip = MODE_TOOLTIP)
style = input.string('Colored'
, tooltip = STYLE_TOOLTIP)
, tooltip = COLOR_CANDLES_TOOLTIP)
//----------------------------------------}
//Internal Structure
//----------------------------------------{
, tooltip = SHOW_INTERNAL)
, inline = 'ibull'
, inline = 'ibull'
//Bear Structure
, inline = 'ibear'
, inline = 'ibear'
, tooltip = CONFLUENCE_FILTER)
//----------------------------------------}
//Swing Structure
//----------------------------------------{
, tooltip = SHOW_SWING)
//Bull Structure
, inline = 'bull'
, inline = 'bull'
//Bear Structure
, inline = 'bear'
, inline = 'bear'
//Swings
, inline = 'swings'
, tooltip = SHOW_SWING_POINTS)
, minval = 10
, inline = 'swings'
, tooltip = SHOW_SWHL_POINTS)
//----------------------------------------}
//Order Blocks
//----------------------------------------{
, inline = 'iob'
, tooltip = INTERNAL_OB)
, minval = 1
, inline = 'iob'
, inline = 'ob'
, tooltip = SWING_OB)
, minval = 1
, inline = 'ob'
, group = 'Order Blocks')
, tooltip = FILTER_OB)
//----------------------------------------}
//EQH/EQL
//----------------------------------------{
, group = 'EQH/EQL'
, tooltip = SHOW_EQHL)
, minval = 1
, group = 'EQH/EQL'
, tooltip = EQHL_BARS)
, minval = 0
, maxval = 0.5
, step = 0.1
, group = 'EQH/EQL'
, tooltip = EQHL_THRESHOLD)
//----------------------------------------}
//----------------------------------------{
, tooltip = SHOW_FVG)
, tooltip = AUTO_FVG)
, tooltip = FVG_TF)
, minval = 0
, tooltip = EXTEND_FVG)
//----------------------------------------}
//----------------------------------------{
//Daily
, inline = 'daily'
, inline = 'daily'
, inline = 'daily'
//Weekly
, inline = 'weekly'
, inline = 'weekly'
, inline = 'weekly'
//Monthly
show_pmhl = input(false, 'Monthly'
, inline = 'monthly'
, inline = 'monthly'
, inline = 'monthly'
//----------------------------------------}
//Premium/Discount zones
//----------------------------------------{
, tooltip = PED_ZONES)
premium_css = input.color(#f23645, 'Premium Zone'
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
atr = ta.atr(200)
structure_line = line.new(x, y, n, y
, color = css
, color = TRANSP_CSS
, textcolor = css
, 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)
[top, btm]
min = 99999999.
max = 0.
idx = 1
if use_max
for i = 1 to (n - loc)-1
else
for i = 1 to (n - loc)-1
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
get_box = array.get(boxes, i)
box.set_extend(get_box, extend.right)
color css = na
if swing
if style == 'Monochrome'
box.set_border_color(get_box, border_css)
else
box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)
else
if style == 'Monochrome'
else
box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)
get_line_style(style) =>
, color = css
, style = get_line_style(pdhl_style))
, xloc = xloc.bar_time
, color = TRANSP_CSS
, textcolor = css
, size = size.small
, style = label.style_label_left)
, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))
, xloc = xloc.bar_time
, textcolor = css
, size = size.small
, style = label.style_label_left)
hy = ta.valuewhen(h != h[1], h, 1)
ly = ta.valuewhen(l != l[1], l, 1)
if barstate.islast
//High
//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
//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
: swing_bull_css
: swing_bear_css
: swing_ibull_css
: swing_ibear_css
//Labels size
? size.tiny
: internal_structure_size == 'Small'
? size.small
: size.normal
? size.tiny
: swing_structure_size == 'Small'
? size.small
: size.normal
? size.tiny
: eq_size == 'Small'
? size.small
: size.normal
//Swings
[top, btm] = swings(length)
//-----------------------------------------------------------------------------}
//Pivot High
//-----------------------------------------------------------------------------{
, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = size.tiny)
if top
top_cross := true
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])
line.delete(extend_top[1])
, 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
label.set_x(extend_top_lbl, n + 20)
label.set_y(extend_top_lbl, trail_up)
//-----------------------------------------------------------------------------}
//Pivot Low
//-----------------------------------------------------------------------------{
, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = size.tiny)
if btm
btm_cross := true
if show_swings
, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = swing_structure_lbl_size)
if mode == 'Present'
label.delete(btm_lbl[1])
line.delete(extend_btm[1])
, 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
label.set_x(extend_btm_lbl, n + 20)
label.set_y(extend_btm_lbl, trail_dn)
//-----------------------------------------------------------------------------}
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------}
//-----------------------------------------------------------------------------{
//Filtering
if ifilter_confluence
bool choch = na
if itrend < 0
choch := true
bull_ichoch_alert := true
else
bull_ibos_alert := true
if show_internals
if show_ibull == 'All' or (show_ibull == 'BOS' and not choch) or (show_ibull == 'CHoCH' and choch)
itop_cross := false
itrend := 1
if show_iob
bool choch = na
if trend < 0
choch := true
bull_choch_alert := true
else
bull_bos_alert := true
if show_Structure
if show_bull == 'All' or (show_bull == 'BOS' and not choch) or (show_bull == 'CHoCH' and choch)
//Order Block
if show_ob
top_cross := false
trend := 1
//-----------------------------------------------------------------------------}
//-----------------------------------------------------------------------------{
if ifilter_confluence
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)
ibtm_cross := false
itrend := -1
if show_iob
bool choch = na
if trend > 0
choch := true
bear_choch_alert := true
else
bear_bos_alert := true
if show_Structure
if show_bear == 'All' or (show_bear == 'BOS' and not choch) or (show_bear == 'CHoCH' and choch)
//Order Block
if show_ob
btm_cross := false
trend := -1
//-----------------------------------------------------------------------------}
//Order Blocks
//-----------------------------------------------------------------------------{
array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bull_iob_break := true
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
array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bull_ob_break := true
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
if show_ob
for i = 0 to ob_showlast-1
if iob_size > 0
if barstate.islast
if ob_size > 0
if barstate.islast
//-----------------------------------------------------------------------------}
//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
if 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
, color = bull_css
, style = line.style_dotted)
, 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
//-----------------------------------------------------------------------------{
float bullish_fvg_avg = na
float bearish_fvg_avg = na
bullish_fvg_cnd = false
bearish_fvg_cnd = false
if show_fvg
:0
//FVG conditions
and change_tf
and change_tf
//FVG Areas
if bullish_fvg_cnd
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))
if bearish_fvg_cnd
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))
for bx in bullish_fvg_min
box.delete(bx)
box.delete(bx)
//-----------------------------------------------------------------------------}
//-----------------------------------------------------------------------------{
//Daily high/low
, lookahead = barmerge.lookahead_on)
//Weekly high/low
, lookahead = barmerge.lookahead_on)
//Monthly high/low
, lookahead = barmerge.lookahead_on)
//Display Daily
if show_pdhl
//Display Weekly
if show_pwhl
//Display Monthly
if show_pmhl
//-----------------------------------------------------------------------------}
//Premium/Discount/Equilibrium zones
//-----------------------------------------------------------------------------{
, border_color = na)
, color = TRANSP_CSS
, textcolor = premium_css
, style = label.style_label_down
, size = size.small)
, border_color = na)
, text = 'Equilibrium'
, color = TRANSP_CSS
, textcolor = eq_css
, style = label.style_label_left
, size = size.small)
, 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)
box.set_rightbottom(discount, n, trail_dn)
//-----------------------------------------------------------------------------}
//Trend
//-----------------------------------------------------------------------------{
if show_trend
if style == 'Colored'
, color = trend_css
, wickcolor = trend_css
, bordercolor = trend_css
, editable = false)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
//Internal Structure
//Swing Structure
//EQH/EQL
//FVG
//-----------------------------------------------------------------------------}
//@version=5
// === 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")
// || RSI / STOCH / VOLUME / ACC/DIST/ FISHER/ CCI/ BB %B Input/ Elders Force Index/ ROC/ MFI/ Chande composite MI:
bearColor = color.red
bullColor = color.green
textColor = color.white
// MACD Input:
r=ta.rsi(close, rsi_smooth)
rsidelta = ta.mom(r, 9)
rsisma = ta.sma(r, 3)
s=rsidelta+rsisma
// MACD FUNCTION
_hist
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
_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
irma(p, l) =>
irma = 0.0
irma := (nz(irma[1]) * (l - 1) + p) / l
irma
irsi(p, l) =>
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
I1 = nz(dDeTrend[3])
I2_ = I1 - jQ
Q2_ = Q1 + jI
II = nz(Period[1])
idealRSI
pcBB(p, l) =>
basis = ta.sma(p, l)
pcBB
forceIndex(p, l) =>
f = (p - p[1]) * volume
TVA(p, l) =>
rising_1 = ta.rising(ma1, 3)
falling_1 = ta.falling(ma1, 3)
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)
smiPP = ta.ema(smi, 3)
smiPP
e1 = ta.ema(src, length)
e2 = ta.ema(e1, length)
2 * e1 - e2
chande(p, l) =>
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
oscilator_high = float(na)
oscilator_low = float(na)
if method == 'RSI'
oscilator_low
oscilator_high := s
oscilator_low := s
oscilator_low
if method == 'MACD'
oscilator_low
if method == 'Stochastic'
if method == 'Volume'
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
oscilator_low
if method == 'CCI'
oscilator_low
oscilator_high := idealRSI(high_src)
oscilator_low := idealRSI(low_src)
oscilator_low
oscilator_low
oscilator_low
if method == 'ROC'
if method == 'MFI'
oscilator_low
if method == 'SMI'
oscilator_low
oscilator_low
oscilator_low
//
plFound = na(ta.pivotlow(oscilator_low, lbL, lbR)) ? false : true
_inRange(cond) =>
//------------------------------------------------------------------------------
// Regular Bullish
//------------------------------------------------------------------------------
// Hidden Bullish
//------------------------------------------------------------------------------
// Regular Bearish
//------------------------------------------------------------------------------
// Hidden Bearish
//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_MinOscMovHid = input.float(title="Min Oscilator Hidden Movement", defval=0.5, step = 0.05, group = "Improvements")
barsSince1 = ta.barssince(high_prev)
barsSince2 = ta.barssince(low_prev)
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
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")
higheHigh = ta.highest(lengK)
loweLow = ta.lowest(lengK)
higheLoweRange = higheHigh - loweLow
Bullbias2 = smibull[1]
Bearbias2 = smibear[1]
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")
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")
// SuperSmoother filter
c2 = b1
c3 = -a1 * a1
c1 = 1 - c2 - c3
v9 = 0.0
v5 = 0.0
v5
v10
v2 = ta.ema(src, len)
v6 = 2 * v2 - ta.ema(v2, len)
v6
v7
zlsma1
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
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
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")
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() =>
TB = check_valid_time()
TS = check_valid_time()
//
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
bool longcond=true
bool shortcond=true
//
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))
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")
highestHigh = ta.highest(lengthK)
lowestLow = ta.lowest(lengthK)
//Standart deviation
if (longcond or shortcond)
close1 := close
stopbuy1=ta.valuewhen(longcond, lower_band1, 0)
stopsell1=ta.valuewhen(shortcond, upper_band1, 0)
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")
Low23 = ta.lowest(low, 5)
High23 = ta.highest(high, 5)
Lowest23 = ta.valuewhen(longcond, Low23, 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)))
strategy.close("Long", when=closeLongCondition)
strategy.close("Short", when=closeShortCondition)
if strategy.position_size > 0 and custom_exit_bull
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")
strategy.exit('Long Exit ', "Long", stop=longStopPort, limit=longTakePort,comment_profit = "Take Profit ",comment_loss = "LOSS")
strategy.close("Long",comment="Short Signal")
if UseStr and longcond and strategy.position_size==0 and not shortposonly and longposonly
//@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(
overlay = false
// INPUTS
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 = "======= 𝗦𝗧𝗬𝗟𝗘 𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦 =======")
// COLORS
switch type
"HMA" =>
sum = 0
for i = s to e by 1
sum
// INDICATOR CALCULATION
if fl > thrUp
col := bull
if fl < thrDown
col := bear
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)
if fl > thrUp
currentTrendState := 1
currentTrendState := -1
else
currentTrendState := 0
if bullishTransition or bearishTransition
prevTrendState := currentTrendState
style = shape.labelup,
location = location.absolute,
color = bull,
text = "▲",
textcolor = #000000,
size = size.small,
force_overlay = true)
location = location.absolute,
color = bear,
text = "▼",
textcolor = #000000,
size = size.small,
force_overlay = true)
// ================================================================================================================ //
// //
// ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███▀▀▀██▄ ▀█████████▄ //
// ███ █▀ ███ █▀ ███ █▀ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀███▀▀██ //
// ███ ▄███▄▄▄ ▄███▄▄▄ ▄███▄▄▄▄██▀ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀ //
// ▀███████████ ▀▀███▀▀▀ ▀▀███▀▀▀ ▀▀███▀▀▀▀▀ ███ ███ ███ ███ ▀███████████ ███ ███ ███ //
// ███ ███ █▄ ███ █▄ ▀███████████ ███ ███ ███ ███ ███ ███ ███ ███ ███ //
// ▄█ ███ ███ ███ ███ ███ ███ ███ ███ ▀ ███ ███ ███ ███ ███ ███ ███ ███ //
// //
// ================================================================================================================ //
//@version=6
// Если вам нужен индивидуальный индикатор или робот для торговли, обращайтесь в Телеграм @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.
// If you need a custom indicator or trading robot, feel free to contact me on Telegram @ibobro.
//Se você precisar de um indicador personalizado ou robô de negociação, entre em contato comigo no Telegram @ibobro.
//@version=5
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
backpaint = input(true, tooltip = 'Backpainting offset displayed elements in the past. Disable backpainting to see real time information returned by the
indicator.')
//Style
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
var upper = 0.
var lower = 0.
var slope_ph = 0.
var slope_pl = 0.
n = bar_index
src = close
ph = ta.pivothigh(length, length)
pl = ta.pivotlow(length, length)
'Linreg' => math.abs(ta.sma(src * n, length) - ta.sma(src, length) * ta.sma(n, length)) / ta.variance(n, length) / 2 * mult
var upos = 0
var dnos = 0
//-----------------------------------------------------------------------------}
//Extended Lines
//-----------------------------------------------------------------------------{
if ph and showExt
if pl and showExt
//-----------------------------------------------------------------------------}
//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
, shape.labelup
, location.absolute
, upCss
, text = "Buy"
, textcolor = color.white
, size = size.tiny)
, 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
atr = ta.atr(_atrPeriod)
trend = 1
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
// Оповещения
//@version=5
//functions
r_val = float(na)
if length >= 1
for i = 0 to length by 1
r_val := values[i]
r_val
r_val
sumf = 0.0
ma = 0.0
out = 0.0
out
// inputs
//threshold lines
//KDJ indicator
k = xsa(rsv, 3, 1)
d = xsa(k, 3, 1)
crossover_1 = ta.crossover(k, d)
crossunder_1 = ta.crossunder(d, k)
//plot KD candles
plotcandle(k, d, k, d, color=k >= d ? color.green : na)
//@version=6
indicator(title="Customizable MTF Multiple Moving Averages with Cross-Timeframe Colors", shorttitle="Custom MAs+", overlay=true)
// Input per configurazione MA 1
ma1Type = input.string(title="MA 1 Type", defval="EMA", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], group="MA 1")
ma2Type = input.string(title="MA 2 Type", defval="EMA", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], group="MA 2")
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")
switch type
"SMMA" =>
smma
// 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
import jdehorty/MLExtensions/2 as ml
// ====================
// ====================
// the default distance metric, but it may not always be the best choice. This is
// world events such as FOMC Meetings and Black Swan events. These major economic
// 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
// 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
// Fundamental Assumptions:
// (2) For simplicity, values for RSI and ADX are assumed to adhere to a Gaussian
// (3) The most recent RSI and ADX value can be considered the origin of a coordinate
// Measuring the Euclidean Distances of historical values with the most recent point
// [RSI]
// |
// |
// |
// ...:::....
// .:.:::••••••:::•::..
// .:•:.:•••::::••::••....::.
// ....:••••:••••••••::••:...:•.
// ...:.::::::•••:::•••:•••::.:•..
// ::•:.:•:•••••••:.:•::::::...:..
// |--------.:•••..•••••••:••:...:::•:•:..:..----------[ADX]
// 0 :•:....:•••••::.:::•••::••:.....
// ::....:.:••••••••:•••::••::..:.
// .:...:••:::••••••••::•••....:
// ::....:.....:•::•••:::::..
// ..:..::••..::::..:•:..
// .::..:::.....:
// |
// |
// |
// |
// _|_ 0
//
// However, the same set of historical values measured using Lorentzian Distance will
//
// [RSI]
// ::.. | ..:::
// ..... | ......
// .••••::. | :••••••.
// .:•••••:. | :::••••••.
// .•••••:... | .::.••••••.
// .::•••••::.. | :..••••••..
// .:•••••••::.........::••••••:..
// ..::::••••.•••••••.•••••••:.
// ...:•••••••.•••••••••::.
// .:..••.••••••.••••..
// |---------------.:•••••••••••••••••.---------------[ADX]
// 0 .:•:•••.••••••.•••••••.
// .••••••••••••••••••••••••:.
// .:••••••••••::..::.::••••••••:.
// .::••••••::. | .::•••:::.
// .:••••••.. | :••••••••.
// .:••••:... | ..•••••••:.
// ..:••::.. | :.•••••••.
// .:•.... | ...::.:••.
// ...:.. | :...:••.
// :::. | ..::
// _|_ 0
//
// Observations:
// (1) In Lorentzian Space, the shortest distance between two points is not
// (2) The warping effect of Lorentzian distance reduces the overall influence
// of outliers and noise.
// ======================
// ======================
// This section uses PineScript's new Type syntax to define important data structures
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
// ==========================
// ==========================
switch feature_string
switch featureCount
// ================
// ================
Settings settings =
Settings.new(
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="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")
// 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")
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.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 filter =
Filter.new(
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(
// Note: These arrays cannot be dynamically created within the FeatureArrays Object Initialization and thus must be set-up in advance.
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 =
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
// EMA Settings
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.")
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.")
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")
// =================================
// =================================
// 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 prediction = 0.
array.push(y_train_array, y_train_series)
// =========================
// =========================
// 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
// 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
// - 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
// 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 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.
// 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
// 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
// 5. Lorentzian distance is used as a distance metric in order to minimize the effect of outliers and take into account the warping of
lastDistance = -1.0
lastDistance := d
array.push(distances, d)
array.shift(distances)
array.shift(predictions)
//}
//}
//}
prediction := array.sum(predictions)
//}
// ============================
// User Defined Filters: Used for adjusting the frequency of the ML Model's predictions
// 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
isHeldFourBars = 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)
// 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/
yhat1 = kernels.rationalQuadratic(settings.source, h, r, x)
kernelEstimate = yhat1
// Kernel Colors
// Alert Variables
// ===========================
// ===========================
// Entry Conditions: Booleans for ML Model Position Entries
// Dynamic Exit Conditions: Booleans for ML Model Position Exits based on Fractal Filters and Kernel Regression Filters
barsSinceRedEntry = ta.barssince(startShortTrade)
barsSinceRedExit = ta.barssince(alertBullish)
barsSinceGreenEntry = ta.barssince(startLongTrade)
barsSinceGreenExit = ta.barssince(alertBearish)
// 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
// =========================
// =========================
// 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(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)
// ================
// ================
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}})')
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}})')
// =========================
// =========================
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)
// =====================
// =====================
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() =>
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)
if showTradeStats
if barstate.islast
//@version=5
indicator("Options Levels Support and Resistance", "✨Support and Resistance Options Levels✨ by Mars", overlay=true)
if start >= 0 and (start == 0 or str.substring(level_data, math.max(0, start - 1), start) == ";")
array.push(result, str.tonumber(value))
result
if array.size(result) == 0
if array.size(result) == 0
if array.size(result) == 0
if array.size(result) == 0
if array.size(result) == 0
if array.size(result) == 0
if array.size(result) == 0
if array.size(result) == 0
result
label_size = input.string("small", "Label Size", options=["tiny", "small", "normal", "large"], 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 iv = na
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"
style=line_style_used)
label_id = label.new(
x=label_x,
y=price,
color=color.new(color.black, 100),
textcolor=color,
style=label_style,
array.push(labels, label_id)
line_id
clear_labels() =>
label.delete(lbl)
array.clear(labels)
array.sort(levels, order.ascending)
current_levels = get_symbol_data(syminfo.ticker)
var line s2_line = na
if array.size(current_levels) >= 4
clear_labels()
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")
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)
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)
)
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))
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)
if array.size(current_levels) >= 15
line.delete(st_gamma_support_line)
line.delete(st_gamma_resistance_line)
if show_short_term
gamma_area_box_green := box.new(
left=bar_index + 10,
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,
bgcolor=color.new(color.red, 85),
border_color=color.new(color.red, 100))
if array.size(current_levels) >= 9
line.delete(gamma_flip_line)
get_activity_text(level) =>
switch level
1 => "Low"
2 => "Medium"
3 => "High"
=> "Unknown"
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")
float iv = array.get(current_levels, 9)
var text_size = label_size == "tiny" ? size.tiny : label_size == "small" ? size.small : label_size == "normal" ? size.normal : size.large
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",
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, 6, 2, get_activity_text(activity_level),
text_size=text_size,
bgcolor=last_lines_bg_color)
if not near_put_wall
near_put_wall := true
bounce_reference_low := low
near_put_wall := false
if not near_call_wall
near_call_wall := true
bounce_reference_high := high
near_call_wall := false
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")
if array.size(current_levels) == 0
bgcolor=color.new(color.red, 90),
text_color=color.white)
//@version=6
if (hour == 17 and minute >= 55) or (hour == 18 and minute <= 10)
adjustment_bar_index := bar_index
sum_prices := 0.0
sum_weights := 0.0
// Calcular as variações com base no ajuste (0,5%, 1,0%, 1,5% para cima e para baixo)
//@version=6
// Calculate EMAs
// Plot EMAs
// 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
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"])
ma2_type = input.string("SMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma3_type = input.string("SMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma5_type = input.string("SMA" , "" , inline="MA #5", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma6_type = input.string("SMA" , "" , inline="MA #6", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
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
array.push(stdevArray, std)
if array.size(stdevArray)>=lookback
array.remove(stdevArray, 0)
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)
df=ta.highest(high,90) - ta.lowest(low,90)
array.push(stdevArray2, df)
if array.size(stdevArray2)>=lookback
array.remove(stdevArray2, 0)
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"
g1 = upper0 - lower0
g2 = upper1 - lower1
g3 = upper2 - lower2
//@version=5
// Control visibility
ma = switch maType
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")
if barstate.islast
///////
mC = closePrice
actualClose = mC
if (na(currentPriceLine))
line.set_style(currentPriceLine, line.style_dashed)
else
line.set_xy1(currentPriceLine, x=bar_index, y=actualClose)
//@version=6
// Inputs
// Initialize an array to store liquidity values when they cross the boundary
// 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
// Trading Logic
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
// 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
if showSupportResistance
if showCandlestickPatterns
if bullishEngulfing
if bearishEngulfing
var string titleText = "Comprehensive Trading Indicator\n- Moving Averages (50, 200)\n- Support/Resistance Levels\n- Candlestick Patterns\n- Volume
Analysis"
//@version=5
minGapSize = input.float(0.5, title="Min Gap Size (FVG)") // Minimum gap size for FVG detection
// Identify Higher Highs (HH) and Higher Lows (HL) for Bullish Market Structure
// Identify Lower Highs (LH) and Lower Lows (LL) for Bearish Market Structure
if isBullishStructure
if isBearishStructure
// 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
// 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
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
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
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)
// RSI parameters
rsiPeriod = 14
rsiUpper = 60
rsiLower = 40
// Conditions for buy (RSI crossing above 60) and sell (RSI crossing below 40)
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
// Cálculo de la VWMA
// Mostrar la VWMA
import loxx/loxxexpandedsourcetypes/4
a1 = 0., b1 = 0.
coef2 := b1
coef3 := -a1 * a1
filt
// Gaussian
_gaussian(size, x)=>
out = (math.exp(-x * x * 9 / ((size + 1) * (size + 1))))
out
// Fibonacci
_fiblevels(len)=>
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
_gaussout(levels)=>
perin = array.size(levels)
for k = 0 to array.size(levels) - 1
sum = 0.
for i = 0 to perin - 1
break
sum += matrix.get(arr_gauss, i, k)
for i = 0 to perin - 1
break
matrix.set(arr_gauss, i, k, temp)
arr_gauss
sum = 0.
lvltemp = _fiblevels(per)
gtemp = _gaussout(lvltemp)
for i = 0 to matrix.rows(gtemp) - 1
extrasmthper = input.int(9, "Extra Smoothing (2-Pole Ehlers Super Smoother) Period", group="Gaussian Settings")
// Datos de calculo
src = gaussian_source
lmax = smthper + 1
atr = ta.atr(atrper)
//@version=6
sma_1 = ta.sma(close, 5)
sma_2 = ta.sma(close, 8)
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)
alertcondition(changeCond, title="Alert on Parabolic SAR Direction Change", message="Parabolic SAR has changed direction!")
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)
//@version=5
indicator('Fibonacci Retracment & Pivot Points by Amarpatil04', 'FIBs ʙʏ Amarpatil04', true, max_lines_count = 500, max_labels_count = 500)
//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
//
//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
// ---------------------------------------------------------------------------------------------- //
// -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'
// ---------------------------------------------------------------------------------------------- //
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_htf_mode = input.string('Auto', 'Pivot Points TimeFrame', options=['Auto', 'User Defined'], inline='HTF', group=group_pivot, tooltip=tooltip_pivot_point)
options=['15 Min', '1 Hour', '4 Hour', 'Daily', 'Weekly', 'Monthly', 'Quarterly', 'Yearly'], inline='HTF1', group=group_pivot)
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_dev_thresh = ta.atr(10) / close * 100 * input.float(3, 'Deviation', minval=0, inline='Pivots', group=group_fib_tool, tooltip=tooltip_threshold)
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)
// ---------------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //
// -Calculations -------------------------------------------------------------------------------- //
var iPrevPivot = 0
var pPrevPivot = 0.
var iLastPivot = 0
var pLastPivot = 0.
l2 = length * 2
c = nz(src[length])
ok = true
for i = 0 to l2 by 1
ok
ok := false
ok
if ok
[bar_index[length], c]
else
[int(na), float(na)]
// same direction
if isHighLast ? price > pLast : price < pLast
[lineLast, isHighLast]
else
[line(na), bool(na)]
else
// ---------------------------------------------------------------------------------------- //
[na, 1, line.style_dashed]
else
// ---------------------------------------------------------------------------------------- //
[id, isHigh]
else
[line(na), bool(na)]
if not na(iH)
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)
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
//------------------------------------------------------------------------------
// auto higher time frame code snippet from pine wizard LonesomeTheBlue
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_l
// ---------------------------------------------------------------------------------------------- //
// -Plotting ------------------------------------------------------------------------------------ //
f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
line.set_color(id, _color)
else
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_tooltip(id, _tooltip)
if _y > 0
label.set_xy(id, _x, _y)
label.set_textcolor(id, _textcolor)
else
label.set_textcolor(id, #00000000)
_level > _curret and _level < _curret[1] or _level < _curret and _level > _curret[1]
var ln = array.new_line()
var lb = array.new_label()
for i = 1 to array.size(ln) by 1
line.delete(array.shift(ln))
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) =>
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) =>
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
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 * 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, '')
price = 0.
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'
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)
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'
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'
if not i_histPP
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
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'
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))
alert('AutoFib PivotPoints : ' + syminfo.ticker + ' crossing support level ' + str.tostring(_level))
alert('AutoFib PivotPoints : ' + syminfo.ticker + ' crossing resistance level ' + str.tostring(_level))
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)
//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
//
//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
// ---------------------------------------------------------------------------------------------- //
// -Inputs -------------------------------------------------------------------------------------- //
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'
// ---------------------------------------------------------------------------------------------- //
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)
// ---------------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //
i_vSpikeThresh = input.float(4.669, 'Volume Spike Theshold ', minval=.1, step=.1, inline='SRS1', group=group_vol_vol)
// ---------------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //
nzVolume = nz(volume)
bullCandle = close > open
// ---------------------------------------------------------------------------------------------- //
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}}')
// ---------------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //
// 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
//
═════════════════════════════════════════════════════════════════════════════════════════
═════════ //
//@version=5
// User Inputs
zoneTopPercent = input.float(0.4, "Zone TOP Size %", minval=0, step=0.001)
// Initialize Variables
// Zone Calculation
// Calculate pullbacks
if R1
if not na(currentZone)
box.delete(currentZone)
label.delete(debugLabel)
//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)
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
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
R2 := true
RCL2 := high
lowestSinceRCL2 := high
r2plot := true
R3 := true
RCL3 := high
r3plot := true
shortplot := true
if R1 and r1plot
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
shortplot := false
RCL2 := high
pullbackFromRCL2:= 0
lowestSinceRCL2 := high
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)
//@version=5
ema9 = ta.ema(close, 9)
atrPeriod = 10
factor = 3.0
// Plot Supertrend
// --- Trend and Sentiment Analysis based on Volume Moving Averages (VMAs) ---
trend = "Stable"
sentiment = "Neutral"
trend := "Increasing"
sentiment := "Bullish"
else if (currentVolume < previousVolume) // If current volume is less than previous volume
trend := "Decreasing"
sentiment := "Bearish"
[trend, sentiment]
if (bar_index == 0)
// Update table with trend and sentiment data for each timeframe