name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Weight Gain 4000 - (Adjustable Volume Weighted MA) - [mutantdog] | https://www.tradingview.com/script/h7GWumy5-Weight-Gain-4000-Adjustable-Volume-Weighted-MA-mutantdog/ | mutantdog | https://www.tradingview.com/u/mutantdog/ | 227 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mutantdog
//@version=5
indicator ('Weight Gain 4000 v2', 'Weight Gain 4k', true, explicit_plot_zorder=true)
// v2.1
// | |
string S01 = 'open'
string S02 = 'high'
string S03 = 'low'
string S04 = 'close'
string S11 = 'hl2'
string S12 = 'hlc3'
string S13 = 'ohlc4'
string S14 = 'hlcc4'
string S51 = 'oc2'
string S52 = 'hlc2-o2'
string S53 = 'hl-oc2'
string S54 = 'cc-ohlc4'
string M01 = 'SMA'
string M02 = 'EMA'
string M03 = 'WMA'
string M04 = 'RMA'
string M61 = 'hSMA'
string M62 = 'DEMA'
string M63 = 'TEMA'
string M64 = 'VIDYA'
string M65 = 'HMA'
string M66 = 'sEMA'
string M67 = 'DRMA'
// ---------
// INPUTS
// ---------
auxSource = input.source (close, 'Aux In')
trackerSource = input.string ('hlc2-o2', 'Price Tracker', [S01, S02, S03, S04, S11, S12, S13, S14, S51, S52, S53, S54, '* AUX', '* DISABLE'])
maActive_1 = input.bool (true, 'Active', inline='10', group='MA 1: Fast')
volFilter_1 = input.bool (true, 'Volume Filter', inline='10', group='MA 1: Fast')
maSource_1 = input.string ('hlcc4', 'Source', [S01, S02, S03, S04, S11, S12, S13, S14, S51, S52, S53, S54, '* AUX'], inline='11', group='MA 1: Fast')
volPower_1 = input.float (0.5, 'Volume', minval=0, maxval=1, step=0.05, inline='11', group='MA 1: Fast')
maMode_1 = input.string ('EMA', 'Mode ', [M01, M02, M03, M04, M61, M62, M63, M64, M65, M66, M67], inline='12', group='MA 1: Fast')
maLength_1 = input.int (8, 'Length', minval=1, inline='12', group='MA 1: Fast')
maActive_2 = input.bool (true, 'Active', inline='20', group='MA 2: Slow')
volFilter_2 = input.bool (true, 'Volume Filter', inline='20', group='MA 2: Slow')
bandActive_2 = input.bool (false, 'Dev Bands', inline='20', group='MA 2: Slow')
maSource_2 = input.string ('hlcc4', 'Source', [S01, S02, S03, S04, S11, S12, S13, S14, S51, S52, S53, S54, '* AUX', '* MA 1'], inline='21', group='MA 2: Slow')
volPower_2 = input.float (0.5, 'Volume', minval=0, maxval=1, step=0.05, inline='21', group='MA 2: Slow')
maMode_2 = input.string ('EMA', 'Mode ', [M01, M02, M03, M04, M61, M62, M63, M64, M65, M66, M67], inline='22', group='MA 2: Slow')
maLength_2 = input.int (21, 'Length', minval=1, inline='22', group='MA 2: Slow')
bandMult_2 = input.float (2, 'Bands ', minval=0, step=0.1, inline='23', group='MA 2: Slow')
bullHue = input.color (#22B747, '', inline='55', group='Visual')
bearHue = input.color (#B7143C, '', inline='55', group='Visual')
bandHue = input.color (#336680, '', inline='55', group='Visual')
neutralHue = input.color (#808080, '', inline='55', group='Visual')
mainOpacP = input.int (100, 'Main ', minval=0, maxval=100, step=5, inline='61', group='Visual')
mainOpacF = input.int (40, 'Fill', minval=0, maxval=100, step=5, inline='61', group='Visual')
bandOpacP = input.int (80, 'Bands ', minval=0, maxval=100, step=5, inline='62', group='Visual')
bandOpacF = input.int (10, 'Fill', minval=0, maxval=100, step=5, inline='62', group='Visual')
trackOpacP = input.int (50, 'Tracker', minval=0, maxval=100, step=5, inline='63', group='Visual')
showMax_12 = input.bool (false, 'MA1 x MA2 ', inline='81', group='Visual')
showMax_t2 = input.bool (false, 'Price x MA2', inline='81', group='Visual')
showBx_in = input.bool (false, 'Price x Inside Bands', inline='82', group='Visual')
showBx_out = input.bool (false, 'Price x Outside Bands', inline='82', group='Visual')
// ---------
// FUNCTIONS
// ---------
source_switch (src, aux) =>
source = switch src
'open' => open
'high' => high
'low' => low
'close' => close
'hl2' => hl2
'hlc3' => hlc3
'ohlc4' => ohlc4
'hlcc4' => hlcc4
'oc2' => (open + close) / 2
'hlc2-o2' => (high + low + close - open) / 2
'hl-oc2' => (high + low) - (open + close) / 2
'cc-ohlc4' => 2 * close - ohlc4
'* AUX' => aux
//
// --- MAs
weightgain_sma (src, len, vol) => ta.sma (src * vol, len) / ta.sma (vol, len)
weightgain_hsma (src, len, vol) => ta.sma (vol, len) / ta.sma (vol / src, len)
weightgain_wma (src, len, vol) => ta.wma (src * vol, len) / ta.wma (vol, len)
weightgain_sema (src, len, vol) => ta.ema (src * vol, len) / ta.ema (vol, len)
weightgain_elastic (src, alpha, mode) =>
var float e0 = na
var float e1 = na
var float e2 = na
e0 := alpha * src + (1 - alpha) * nz(e0[1], src[1])
e1 := alpha * e0 + (1 - alpha) * nz(e1[1], e0[1])
e2 := alpha * e1 + (1 - alpha) * nz(e2[1], e1[1])
ed = 2 * e0 - e1
et = (3 * e0 - 3 * e1) + e2
output = switch mode
1 => e0
2 => ed
3 => et
//
weightgain_hma (src, len, vol) =>
halfLen = math.max (int (len / 2), 2)
rootLen = int (math.sqrt (len))
wmaBasic = ta.wma (src * vol, len) / ta.wma (vol, len)
wmaHalf = ta.wma (src * vol, halfLen) / ta.wma (vol, halfLen)
hmaComp = 2 * wmaHalf - wmaBasic
hmaFinal = ta.wma (hmaComp * vol, rootLen) / ta.wma (vol, rootLen)
//
weightgain_vidya_vx (src, len, vol) =>
variSum = 0.0
volSum = 0.0
smaBasic = ta.sma (src * vol, len) / ta.sma (vol, len)
for i = 0 to len - 1
variSum := variSum + vol[i] * math.pow (smaBasic - src[i], 2)
volSum := volSum + vol[i]
devSigma = math.sqrt (variSum / volSum)
smaSigma = ta.sma (devSigma * vol, len) / ta.sma (vol, len)
vxSigma = devSigma / smaSigma
//
// --- Deviations
weightgain_sigma_standard (src, len, vol, lwt, ref) =>
variSum = 0.0
weightSum = 0.0
for i = 0 to len - 1
volWeight = vol[i]
linWeight = lwt ? len - i : 0
sumWeight = nz (linWeight + volWeight, 1)
variSum := variSum + sumWeight * math.pow (ref - src[i], 2)
weightSum := weightSum + sumWeight
sigmaDev = math.sqrt (variSum / weightSum)
//
weightgain_sigma_elastic (src, alpha, ref) =>
var float vari = na
vari := (1 - alpha) * ((alpha * math.pow (src - ref[1], 2)) + nz(vari[1]))
dev = math.sqrt (vari)
//
weightgain_sigma_sema (src, len, vol) =>
emaSrcsq = ta.ema (src * src * vol, len) / ta.ema (vol, len)
emasqSrc = math.pow (ta.ema (src * vol, len) / ta.ema (vol, len), 2)
semaDev = math.sqrt (emaSrcsq - emasqSrc)
//
// Main Process
weightgain_main_process (src, len, mult, filt, mode) =>
fixVolume = volume > 1 ? math.pow (volume, mult) : 1
wmaOmega = filt ? ta.wma (fixVolume, 4) : fixVolume
rmaOmega = filt ? ta.rma (fixVolume, 2) : fixVolume
emaAlpha = 2 * rmaOmega / (math.sum (rmaOmega, len) + rmaOmega)
rmaAlpha = rmaOmega / math.sum (rmaOmega, len)
vidyaAlpha = mode == 'VIDYA' ? weightgain_vidya_vx (src, len, rmaOmega) * rmaAlpha : na
vwmaSwitch = switch mode
'SMA' => weightgain_sma (src, len, wmaOmega)
'EMA' => weightgain_elastic (src, emaAlpha, 1)
'WMA' => weightgain_wma (src, len, wmaOmega)
'RMA' => weightgain_elastic (src, rmaAlpha, 1)
'hSMA' => weightgain_hsma (src, len, wmaOmega)
'DEMA' => weightgain_elastic (src, emaAlpha, 2)
'TEMA' => weightgain_elastic (src, emaAlpha, 3)
'VIDYA' => weightgain_elastic (src, vidyaAlpha, 1)
'HMA' => weightgain_hma (src, len, wmaOmega)
'sEMA' => weightgain_sema (src, len, wmaOmega)
'DRMA' => weightgain_elastic (src, rmaAlpha, 2)
sigmaSwitch = switch mode
'SMA' => weightgain_sigma_standard (src, len, wmaOmega, false, vwmaSwitch)
'EMA' => weightgain_sigma_elastic (src, emaAlpha, vwmaSwitch)
'WMA' => weightgain_sigma_standard (src, len, wmaOmega, true, vwmaSwitch)
'RMA' => weightgain_sigma_elastic (src, rmaAlpha, vwmaSwitch)
'hSMA' => weightgain_sigma_standard (src, len, wmaOmega, false, vwmaSwitch)
'DEMA' => weightgain_sigma_elastic (src, emaAlpha, vwmaSwitch)
'TEMA' => weightgain_sigma_elastic (src, emaAlpha, vwmaSwitch)
'VIDYA' => weightgain_sigma_elastic (src, vidyaAlpha, vwmaSwitch)
'HMA' => weightgain_sigma_standard (src, len, wmaOmega, true, vwmaSwitch)
'sEMA' => weightgain_sigma_sema (src, len, rmaOmega)
'DRMA' => weightgain_sigma_elastic (src, rmaAlpha, vwmaSwitch)
[vwmaSwitch, sigmaSwitch]
//
// -------
// PROCESS
// -------
tracker = source_switch (trackerSource, auxSource)
source_1 = maActive_1 ? source_switch (maSource_1, auxSource) : na
[maProcess_1, sigmaProcess_1] = weightgain_main_process (source_1, maLength_1, volPower_1, volFilter_1, maMode_1)
source_2 = maActive_2 ? maSource_2 == '* MA 1' ? maProcess_1 : source_switch (maSource_2, auxSource) : na
[maProcess_2, sigmaProcess_2] = weightgain_main_process (source_2, maLength_2, volPower_2, volFilter_2, maMode_2)
hiBand_2 = bandActive_2 ? maProcess_2 + bandMult_2 * sigmaProcess_2 : na
loBand_2 = bandActive_2 ? maProcess_2 - bandMult_2 * sigmaProcess_2 : na
// ----------------
// VISUALS & ALERTS
// ----------------
// - Colours
weightgain_gradient (ma1, ma2, dev, bear, bull, mid, mult) =>
bearstrong = color.new (bear, 100 - mult)
bearweak = color.new (bear, 100 - mult / 10)
bullstrong = color.new (bull, 100 - mult)
bullweak = color.new (bull, 100 - mult / 10)
base = color.new (mid, 100 - mult / 10)
beargrad = dev != 0 ? color.from_gradient (ma1, ma2 - dev, ma2, bearstrong, bearweak) : bearstrong
bullgrad = dev != 0 ? color.from_gradient (ma1, ma2, ma2 + dev, bullweak, bullstrong) : bullstrong
color colourgrad = ma1 < ma2 ? beargrad : ma1 > ma2 ? bullgrad : base
//
bullColour = color.new (bullHue, 100 - mainOpacP)
bearColour = color.new (bearHue, 100 - mainOpacP)
neutColour = color.new (neutralHue, 100 - mainOpacP / 2)
bandColour = color.new (bandHue, 100 - bandOpacP)
bandFill = color.new (bandHue, 100 - bandOpacF)
trackColour = color.new (neutralHue, 100 - trackOpacP)
maColour = maProcess_1 > maProcess_2 ? bullColour : maProcess_1 < maProcess_2 ? bearColour : neutColour
fillGrad = (sigmaProcess_1 + sigmaProcess_2)
fillColour = weightgain_gradient (maProcess_1, maProcess_2, fillGrad, bearHue, bullHue, neutralHue, mainOpacF)
// - Plots
hibandPlot = plot (hiBand_2, 'Hi Band', bandColour, 1)
lobandPlot = plot (loBand_2, 'Lo Band', bandColour, 1)
fill (hibandPlot, lobandPlot, bandFill, 'Band Area Fill')
trackerPlot = plot (tracker, 'Price Tracker', trackColour, 1, plot.style_stepline)
maPlot_1 = plot (maProcess_1, 'MA 1 Plot', maColour, 2)
maPlot_2 = plot (maProcess_2, 'MA 2 Plot', maColour, 2)
fill (maPlot_1, maPlot_2, fillColour, 'MA Area Fill')
// - Alerts
maxo_12 = ta.crossover (maProcess_1, maProcess_2)
maxu_12 = ta.crossunder (maProcess_1, maProcess_2)
maxo_t2 = ta.crossover (tracker, maProcess_2)
maxu_t2 = ta.crossunder (tracker, maProcess_2)
tbxo_lo = bandActive_2 ? ta.crossover (tracker, loBand_2) : na
tbxu_lo = bandActive_2 ? ta.crossunder (tracker, loBand_2) : na
tbxo_hi = bandActive_2 ? ta.crossover (tracker, hiBand_2) : na
tbxu_hi = bandActive_2 ? ta.crossunder (tracker, hiBand_2) : na
plotatr = ta.atr (4)
plotshape (maxo_12 and showMax_12 ? maProcess_2 - plotatr : na, 'MA Cross: Bull', shape.triangleup, location.absolute, maColour, size=size.tiny, display=display.pane)
plotshape (maxu_12 and showMax_12 ? maProcess_2 + plotatr : na, 'MA Cross: Bear', shape.triangledown, location.absolute, maColour, size=size.tiny, display=display.pane)
plotshape (tbxo_lo and showBx_in ? loBand_2 : na, 'Inside Lo Band', shape.triangleup, location.belowbar, bandColour, size=size.tiny, display=display.pane)
plotshape (tbxu_hi and showBx_in ? hiBand_2 : na, 'Inside Hi Band', shape.triangledown, location.abovebar, bandColour, size=size.tiny, display=display.pane)
plotshape (tbxu_lo and showBx_out ? loBand_2 : na, 'Outside Lo Band', shape.triangledown, location.belowbar, bandColour, size=size.tiny, display=display.pane)
plotshape (tbxo_hi and showBx_out ? hiBand_2 : na, 'Outside Hi Band', shape.triangleup, location.abovebar, bandColour, size=size.tiny, display=display.pane)
plotshape (maxo_t2 and showMax_t2 ? maProcess_2 - plotatr : na, 'Price x-over MA2', shape.triangleup, location.absolute, trackColour, size=size.tiny, display=display.pane)
plotshape (maxu_t2 and showMax_t2 ? maProcess_2 + plotatr : na, 'Price x-under MA2', shape.triangledown, location.absolute, trackColour, size=size.tiny, display=display.pane)
alertcondition (maxo_12, '00: MA1 Above MA2', 'BUY ALERT: MA1 Crossed Above MA2')
alertcondition (maxu_12, '00: MA1 Below MA2', 'SELL ALERT: MA1 Crossed Below MA2')
alertcondition (maxo_12 or maxu_12, '00: MA1 Crossed MA2', 'MIXED ALERT: MA1 Crossed Above or Below MA2')
alertcondition (tbxo_lo, '01: Price Inside LoBand', 'DIP ALERT: Price Tracker Crossed Inside Lo Band')
alertcondition (tbxu_lo, '01: Price Outside LoBand', 'DIP ALERT: Price Tracker Crossed Outside Lo Band')
alertcondition (tbxu_hi, '02: Price Inside HiBand', 'RIP ALERT: Price Tracker Crossed Inside Hi Band')
alertcondition (tbxo_hi, '02: Price Outside HiBand', 'RIP ALERT: Price Tracker Crossed Outside Hi Band')
alertcondition (maxo_t2, '03: Price Above MA2', 'BUY ALERT: Price Tracker Crossed Above MA2')
alertcondition (maxu_t2, '03: Price Below MA2', 'SELL ALERT: Price Tracker Crossed Below MA2')
|
SD Levels | https://www.tradingview.com/script/kZ1FSD6R-SD-Levels/ | NeonMoney | https://www.tradingview.com/u/NeonMoney/ | 209 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NeonMoney
//@version=5
indicator(title='', shorttitle='SD Levels', overlay=true)
//Inputs
src = input(ohlc4, title='Levels source')
stddev1 = input(true, title='Standard Deviation Levels')
sHiLo = input(false, title='Previous Day\'s High Low Levels')
sHiLoNow = input(false, title='Current Day\'s Running High Low Levels')
m=color.gray
n=66
//Emas
out0 = ta.ema(close, 25 )
out1 = ta.ema(close, 100 )
out2 = ta.ema(close, 400 )
plot(out0, color=m, transp=n)
plot(out1, color=m, transp=n)
plot(out2, color=m, transp=n)
//VWAP
timeflag = timeframe.period == '15S' or timeframe.period == '1' or timeframe.period == '3' or timeframe.period == '5' or timeframe.period == '15' or timeframe.period == '60' or timeframe.period == '240' or timeframe.period == 'D' ? true : false
src1 = hlc3
t = time('D')
start0 = na(t[1]) or t > t[1]
sumSrc = src1 * volume
sumVol = volume
sumSrc := start0 ? sumSrc : sumSrc + sumSrc[1]
sumVol := start0 ? sumVol : sumVol + sumVol[1]
Value = timeflag ? sumSrc / sumVol : na
plot(Value, title="Vwap", style=plot.style_circles, linewidth=1, color=m, transp=n)
//SD Levels
sLength = timeframe.isintraday ? 1 : 1
nstart = request.security(syminfo.tickerid, 'D', bar_index, barmerge.gaps_off, barmerge.lookahead_on)
start = request.security(syminfo.tickerid, 'D', time, barmerge.gaps_off, barmerge.lookahead_on)
first = request.security(syminfo.tickerid, 'D', ta.valuewhen(barstate.islast, time, 0), barmerge.gaps_off, barmerge.lookahead_on)
nohist = nstart <= math.max(sLength, 20) + 1
change_1 = ta.change(start)
newDay = nohist ? false : timeframe.isintraday ? change_1 : dayofmonth(time) < dayofmonth(time[1])
//Annualised Volatility
hv = 0.0
stdev_1 = ta.stdev(math.log(src / src[1]), 20)
security_1 = request.security(syminfo.tickerid, 'D', stdev_1 * math.sqrt(250), barmerge.gaps_off, barmerge.lookahead_on)
stdev_2 = ta.stdev(math.log(src / src[1]), 20)
hv_ = true ? security_1 : stdev_2 * math.sqrt(250)
hv := newDay ? hv_ : nz(hv[1], hv_)
hinow = high
hinow := newDay ? high : high > hinow[1] ? high : hinow[1]
lonow = low
lonow := newDay ? low : low < lonow[1] ? low : lonow[1]
prevhi = ta.valuewhen(newDay, hinow[1], 0)
prevlo = ta.valuewhen(newDay, lonow[1], 0)
//Daily Settlement
valuewhen_1 = ta.valuewhen(start[1] <= time, src, 0)
vwma_1 = ta.vwma(src[1], sLength)
settlement = sLength == 1 ? valuewhen_1 : vwma_1
settlement := newDay ? settlement : nz(settlement[1], open[1])
firstDay = dayofmonth(start) == dayofmonth(first) and month(start) == month(first) and year(start) == year(first)
stdhv = 0.0
DaystoExpire = 0 == 0 ? timeframe.isintraday ? true ? 1 : math.min(250, 1440 / timeframe.multiplier) : 20 : 0
stdhv := newDay ? settlement * hv * math.sqrt(DaystoExpire / 250) : nz(stdhv[1])
// SD Ratios.
stdhv05 = stdhv * 0.33
stdhv07 = stdhv * 0.66
stdhv1 = stdhv
// Plot
SettleM = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement : na, color=color.new(color.gray, 40), title='Settlement', linewidth=2, style=plot.style_linebr)
Stdhv05u = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement + stdhv05 : na, color=color.new(color.red, 20), title='+0.33 SD', linewidth=1, style=plot.style_linebr)
Stdhv05d = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement - stdhv05 : na, color=color.new(color.red, 20), title='-0.33 SD', linewidth=1, style=plot.style_linebr)
Stdhv07u = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement + stdhv07 : na, color=color.new(color.lime, 20), title='+0.66 SD', linewidth=1, style=plot.style_linebr)
Stdhv07d = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement - stdhv07 : na, color=color.new(color.lime, 20), title='-0.66 SD', linewidth=1, style=plot.style_linebr)
Stdhv1u = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement + stdhv1 : na, color=color.new(color.orange, 20), title='+1 SD', linewidth=1, style=plot.style_linebr)
Stdhv1d = plot(not nohist and stddev1 and (not false or firstDay) and not newDay ? settlement - stdhv1 : na, color=color.new(color.orange, 20), title='-1 SD', linewidth=1, style=plot.style_linebr)
//
plot((not false or firstDay) and not nohist and sHiLo and not newDay ? prevhi : na, color=color.new(color.teal, 20), title='PREV HI', linewidth=1, style=plot.style_cross, join=false)
plot((not false or firstDay) and not nohist and sHiLo and not newDay ? prevlo : na, color=color.new(color.teal, 20), title='PREV LO', linewidth=1, style=plot.style_cross, join=false)
plot((not false or firstDay) and not nohist and sHiLoNow and not newDay ? lonow : na, color=color.new(color.blue, 20), title='D Lo', linewidth=1, trackprice=false, offset=0, style=plot.style_circles, join=false)
plot((not false or firstDay) and not nohist and sHiLoNow and not newDay ? hinow : na, color=color.new(color.blue, 20), title='D Hi', linewidth=1, trackprice=false, offset=0, style=plot.style_circles, join=false)
|
Koalafied Risk Management | https://www.tradingview.com/script/kfH7yAaW-Koalafied-Risk-Management/ | Koalafied_3 | https://www.tradingview.com/u/Koalafied_3/ | 221 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Koalafied_3
//@version=5
indicator("Koalafied Risk Management", overlay = true)
// ---------- INPUTS ---------- //
var GRP1 = "PORTFOLIO INPUTS"
portfolio_size = input.float(1000.00, "Portfolio Size", group = GRP1)
risk_sel = input.float(1, "Percentage Risk", minval = 0.1, maxval = 100, step = 0.1, group = GRP1)
var GRP2 = "TRADE INPUTS"
entry_price = input.float(0, "Entry Price", minval = 0, group = GRP2)
stop_price = input.float(0, "Stop Price", minval = 0, group = GRP2)
exit_price = input.float(0, "Exit Price", minval = 0, group = GRP2)
var GRP3 = "PLOT SELECTION"
show_table = input(true, "Show Table", group = GRP3)
show_labels = input(true, title='Show Trade Labels', group = GRP3)
_offset = input(15, "Line offset", group = GRP3)
transp_label = input.int(0, "Label Transparency", minval = 0, maxval = 100, group = GRP3)
// ---------- CALCS ---------- //
current_price = close
long = entry_price > stop_price
risk_amount = portfolio_size * (risk_sel/100) // Risk amount
stop_per = long ? 100 - ((stop_price / entry_price) * 100) : (100 - ((stop_price / entry_price) * 100)) * -1
position_size = risk_amount / (stop_per / 100)
asset_quantity = position_size / entry_price
risk = (entry_price - stop_price) / entry_price
reward = ((exit_price - entry_price) / entry_price)
rr = math.round(reward / risk, 2)
// ---------- PLOTS ---------- //
// Plot Lines
_offsettime = timenow + math.round(ta.change(time)*_offset)
if show_labels and entry_price > 0
_entry = label.new(_offsettime, entry_price,"___Entry", xloc = xloc.bar_time, textcolor = color.new(color.white, transp_label), style = label.style_none, size = size.small)
_stop = label.new(_offsettime, stop_price, "___Stop", xloc = xloc.bar_time, textcolor = color.new(color.red, transp_label), style = label.style_none, size = size.small)
_exit = label.new(_offsettime, exit_price, "___Exit", xloc = xloc.bar_time, textcolor = color.new(color.green, transp_label), style = label.style_none, size = size.small)
label.delete(_entry[1])
label.delete(_stop[1])
label.delete(_exit[1])
// Plot Table
text_col = color.white
b_col = color.black
col_trade = color.new(color.green, 70)
col_risk = color.new(color.red, 70)
col_position = color.new(color.orange, 70)
var table RiskTable = table.new(position.bottom_right, 2, 12, frame_color=color.new(color.white, 50), frame_width=1, border_width=1, border_color=color.new(color.white, 50))
if barstate.islast
// Headings
if show_table
table.cell(RiskTable, 0, 0, 'INFO', text_color = color.white, text_size = size.small, bgcolor = color.new(color.olive,75))
table.cell(RiskTable, 1, 0, 'VALUE', text_color = color.white, text_size = size.small, bgcolor = color.new(color.olive,75))
if (show_table)
table.cell(RiskTable, 0, 1, "Current Price", text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 1, 1, '$' + str.tostring(math.round(current_price, 2)), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 2, "Portfolio Size", text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 1, 2, '$' + str.tostring(portfolio_size), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 3, "Risk Percent", text_color = text_col, text_size = size.small, bgcolor = col_risk)
table.cell(RiskTable, 1, 3, str.tostring(risk_sel) + '%', text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 4, "Risk Amount", text_color = text_col, text_size = size.small, bgcolor = col_risk)
table.cell(RiskTable, 1, 4, '$' + str.tostring(math.round(risk_amount, 2)), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 5, "Entry Price", text_color = text_col, text_size = size.small, bgcolor = col_trade)
table.cell(RiskTable, 1, 5, str.tostring(math.round(entry_price, 2)), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 6, "Stop Price", text_color = text_col, text_size = size.small, bgcolor = col_trade)
table.cell(RiskTable, 1, 6, str.tostring(math.round(stop_price, 2)), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 7, "Exit Price", text_color = text_col, text_size = size.small, bgcolor = col_trade)
table.cell(RiskTable, 1, 7, str.tostring(math.round(exit_price, 2)), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 8, "Stop Percent", text_color = text_col, text_size = size.small, bgcolor = col_risk)
table.cell(RiskTable, 1, 8, str.tostring(math.round(stop_per, 2)) + '%', text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 9, "Risk / Reward", text_color = text_col, text_size = size.small, bgcolor = col_risk)
table.cell(RiskTable, 1, 9, str.tostring(rr), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 10, "Position Size", text_color = text_col, text_size = size.small, bgcolor = col_position)
table.cell(RiskTable, 1, 10, '$' + str.tostring(math.round(position_size, 2)), text_color = text_col, text_size = size.small, bgcolor = b_col)
table.cell(RiskTable, 0, 11, "Asset Quantity", text_color = text_col, text_size = size.small, bgcolor = col_position)
table.cell(RiskTable, 1, 11, str.tostring(math.round(asset_quantity, 5)), text_color = text_col, text_size = size.small, bgcolor = b_col)
|
MPF EMA Cross Strategy (8~13~21) by Market Pip Factory | https://www.tradingview.com/script/copnq3lr-MPF-EMA-Cross-Strategy-8-13-21-by-Market-Pip-Factory/ | Market-Pip-Factory | https://www.tradingview.com/u/Market-Pip-Factory/ | 332 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Market-Pip-Factory
//@version=4
study("MPF EMA Cross Strategy (8~13~21) by Market Pip Factory", shorttitle = "MPF EMA Cross Strategy", overlay=true)
// Draw 3x EMAs
// Provide editable parameters
ema1 = input(8)
ema2 = input(13)
ema3 = input(21)
// Set EMA type
ema1_ = ema(close, ema1)
ema2_ = ema(close, ema2)
ema3_ = ema(close, ema3)
// Draw EMAs on chart
plot(ema1_, color=color.red, linewidth=2, title="EMA 1")
plot(ema2_, color=color.blue, linewidth=2, title="EMA 2")
plot(ema3_, color=color.orange, linewidth=2, title="EMA 3")
// Set Parameters for Alerts and Draw Bullish & Bearish Shapes
Bullish = crossover(ema1_,ema3_)
plotshape(Bullish, style=shape.triangleup, color=color.green, location=location.belowbar, size=size.small, text="EMA\n CROSS", title="Bullish Trend EMA Cross")
Bearish = crossunder(ema1_,ema3_)
plotshape(Bearish, style=shape.triangledown, color=color.red, location=location.abovebar, size=size.small, text="EMA\n CROSS", title="Bearish Trend EMA Cross")
// ema color
ema0_ = ema1_ > ema3_ ? color.new(color.green,0) : color.new(color.red,0)
// Color Asignment for Trends
colorTrend = ema1_ > ema3_ ? color.new(color.green,0) : ema1_ < ema3_ ? color.new(color.red,0) : color.new(color.gray,0)
// Trend Calc
trendCalcBull = ema1_ > ema3_
trendCalcBear = ema3_ > ema1_
//Bullish Trend = EMA8 > EMA21 = crossover
//Bearish Trend = EMA21 > EMA8 = crossunder
//Check on DAILY and 4HOURLY for confirmations
PrepCandleL = ema1_ > ema3_
PrepCandleS = ema3_ > ema1_
//-------------------------------------------------------------------------------------
// Market Session Parameters (Set for ICT London ~ New York ONLY)
// Comment out if you want 24 hours active
// Get user input
session = input(title="Time session", type=input.session, defval="0930-2330")
// Create function for detecting if current bar falls within specified time period
InSession(sess) => na(time(timeframe.period, sess)) == false
// Check if the current bar falls within pre-determined market session
isInSession = InSession(session)
// Change bar color if bar falls within after hours time
barcolor(isInSession ? color.orange : na)
// Trigger alert only if bar is outside of after hours time
alertTrigger = close >= open
alertcondition(alertTrigger and isInSession, title="Alert title", message="Alert message")
//-------------------------------------------------------------------------------------
// Strategy notes for feature additions:
// SHORTS
// If PrepCandle = EMA21 > EMA8 and CandlePrice > EMA8 then draw red X (Preparatory Candle)
//plotshape(PrepCandleS, style=shape.xcross, color=color.red, location=location.abovebar, size=size.tiny, text="SHORT-PREP", title="Short Preparatory Candle")
// LONGS
// If PrepCandle = EMA8 > EMA21 and CandlePrice < EMA8 then draw green x (Preparatory Candle)
//plotshape(PrepCandleL, style=shape.xcross, color=color.green, location=location.belowbar, size=size.tiny, text="LONG-PREP", title="Long Preparatory Candle")
//-------------------------------------------------------------------------------------
// FOREX STUFF
// Trancate Math Function
truncate(_number, _decimalPlaces) =>
_factor = pow(10, _decimalPlaces)
int(_number * _factor) / _factor
// Forex ONLY converter from pips into whole numbers math
atr = atr(14)
toWhole(number) =>
if syminfo.type == "forex" // ONLY for forex
return = atr < 1.0 ? (number / syminfo.mintick) / 10 : number
return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return
else
number
//-------------------------------------------------------------------------------------
// MultiTimeframes Section
// Set Timeframe Parameters
res_d = input(title="EMA Cross Daily TF", type=input.resolution, defval="1440")
res_4h = input(title="EMA Cross 4H TF", type=input.resolution, defval="240")
res_1h = input(title="EMA Cross 1H TF", type=input.resolution, defval="60")
//smooth = input(title="Smooth", type=input.bool, defval=true)
// MultiTimeFrame Data
ema_d_smooth_l = security(syminfo.tickerid, res_d, trendCalcBull, barmerge.gaps_off, barmerge.lookahead_off)
ema_4h_smooth_l = security(syminfo.tickerid, res_4h, trendCalcBull, barmerge.gaps_off, barmerge.lookahead_off)
ema_1h_smooth_l = security(syminfo.tickerid, res_1h, trendCalcBull, barmerge.gaps_on, barmerge.lookahead_off)
ema_d_smooth_s = security(syminfo.tickerid, res_d, trendCalcBear, barmerge.gaps_off, barmerge.lookahead_off)
ema_4h_smooth_s = security(syminfo.tickerid, res_4h, trendCalcBear, barmerge.gaps_off, barmerge.lookahead_off)
ema_1h_smooth_s = security(syminfo.tickerid, res_1h, trendCalcBear, barmerge.gaps_on, barmerge.lookahead_off)
candleOnEma_1h_l = 0
candleOnEma_1h_s = 1
setup_prep_l = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l
setup_prep_s = ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s
setup_l = setup_prep_l and candleOnEma_1h_l
setup_s = setup_prep_s and candleOnEma_1h_s
priceOn21ema = 3
// Color Data
color_filter_daily = ema_d_smooth_l ? color.new(color.green,0) : ema_d_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_4h = ema_4h_smooth_l ? color.new(color.green,0) : ema_4h_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_1h = ema_1h_smooth_l ? color.new(color.green,0) : ema_1h_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_overall = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l ? color.new(color.green,0) : ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_candleOnEma = candleOnEma_1h_l ? color.new(color.green,0) : candleOnEma_1h_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_setup = setup_l ? color.new(color.orange,0) : setup_s ? color.new(color.blue,0) : color.new(color.gray,0)
// Long & Short Labels
trendLabel_d = ema_d_smooth_l ? "LONG" : ema_d_smooth_s ? "SHORT" : "WAITING"
trendLabel_4h = ema_4h_smooth_l ? "LONG" : ema_4h_smooth_s ? "SHORT" : "WAITING"
trendLabel_1h = ema_1h_smooth_l ? "LONG" : ema_1h_smooth_s ? "SHORT" : "WAITING"
candleOnEmaLabel_1h = candleOnEma_1h_l ? "LONG SETUP" : candleOnEma_1h_s ? "SHORT SETUP" : "NO SETUP"
setupLabel_1h = setup_l ? "LONG ACTIVATED" : setup_s ? "SHORT ACTIVATED" : "NO SETUP"
// Trend Confirmation x3 Charts
trendConfirm = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l ? "LONG TREND CONFIRMED" : ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s ? "SHORT TREND CONFIRMED" : "UNCONFIRMED"
trendAlarmConfirm_Bull = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l
trendAlarmConfirm_Bear = ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s
// Draw Tables for display top right hand side of chart/screen
var table outputTable = table.new(position.top_right, 5, 2, border_width=1)
if barstate.isconfirmed
dailytxt = "DAILY TREND\n" + trendLabel_d
fourhourtxt = "4H TREND\n" + trendLabel_4h
onehourtxt = "1H TREND\n" + trendLabel_1h
slval = "STOP LOSS\n"
entryval = "ENTRY PRICE\n"
candleHitEma = "Candle On 8EMA\n" + candleOnEmaLabel_1h
setup = "SETUP\n" + setupLabel_1h
trend = "OVERALL TREND\n" + trendConfirm
table.cell(outputTable, 0, 0, text=dailytxt, bgcolor=color_filter_daily, text_color=color.white)
table.cell(outputTable, 1, 0, text=fourhourtxt, bgcolor=color_filter_4h, text_color=color.white)
table.cell(outputTable, 2, 0, text=onehourtxt, bgcolor=color_filter_1h, text_color=color.white)
table.cell(outputTable, 3, 0, text=trend, bgcolor=color_filter_overall, text_color=color.white)
table.cell(outputTable, 0, 1, text=entryval, bgcolor=color.black, text_color=color.white)
table.cell(outputTable, 1, 1, text=slval, bgcolor=color.black, text_color=color.white)
table.cell(outputTable, 2, 1, text=candleHitEma, bgcolor=color.black, text_color=color.white)
table.cell(outputTable, 3, 1, text=setup, bgcolor=color.black, text_color=color.white)
plot(close)
// Set Alerts Bullish and Bearish Trends
alertcondition(trendAlarmConfirm_Bull, title='Bullish Trend Confirmation', message='Bullish Trend Alert')
alertcondition(trendAlarmConfirm_Bear, title='Bearish Trend Confirmation', message='Bearish Trend Alert')
//-------------------------------------------------------------------------------------
// Add strategy system to activate preparatory candle on first touch of 8EMA
// This function returns true if the current bar falls within the given time session (:1234567 is to include all weekdays)
//inSession(sess) => na(time(timeframe.period, sess + ":1234567")) == false and time >= startDate and time <= endDate
//bgcolor(inSession(timeSession) and colorGB ? color.rgb(0, 0, 255, 90) : na)
// Check if new session has begun
//var withinSession = false
//if inSession(timeSession) and not inSession(timesession) [1]
// withinSession := true
// Check if session has ended
//if not inSession(timeSession) and inSession(timeSession)[1]
// withinSession := false
// Analyse Movement
// recentMovement := highestHigh - lowestLow
// totalMovement := totalMovement + recentMovement
// sessionsCounted := sessionsCounted + 1
// Reset stored high/low
// highestHigh := -1.0
// lowestLow := MAXINT
// Get highest high and lowest low of current session
//if withinSession
// if high > highestHigh
// highestHigh := high
// if low < lowestLow
// lowestLow := low
//longCondition = crossover(sma(close, 14), sma(close, 28))
//if (longCondition)
// strategy.entry("My Long Entry Id", strategy.long)
//shortCondition = crossunder(sma(close, 14), sma(close, 28))
//if (shortCondition)
// strategy.entry("My Short Entry Id", strategy.short)
// ————— Method 1: wait until bar following order and use its open.
//var float entryPrice = na
//if longCondition[1] or shortCondition[1]
// entryPrice := open
//plot(entryPrice, "Method 1", color.orange, 3, plot.style_circles)
// ————— Method 2: use built-in variable.
//plot(strategy.position_avg_price, "Method 2", color.gray, 1, plot.style_circles, transp = 0)
// Add strategy system to deactivate preparatory candle if price action touches 21EMA
// Add strategy system to activate trade (long and short) on preparatory candle rules confirmed
// Add strategy system to add trailing stop on 5th previous candle high/low +3 pips (pip value editable)
// Add strategy check to not enable more than one trade per pair at a time
// Add strategy check to not activate more than one trade per EMA cross
// Add strategy system to set stop loss at break even upon X number of pips (editable)
// Add strategy system to close trade upon opposite EMA cross
// Add strategy system to incorporate cipher twister into preparatory parameters prior to trade being executed (which will stop trades when market goes sideways) |
Kendall Rank Correlation NET on SMA [Loxx] | https://www.tradingview.com/script/neh5f526-Kendall-Rank-Correlation-NET-on-SMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 99 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Kendall Rank Correlation NET on SMA [Loxx]",
shorttitle="KRCNETSMA [Loxx]",
overlay=true,
max_bars_back = 3000)
greencolor = #2DD204
redcolor = #D2042D
src = input.source(close, "Source", group = "Basic Settings")
smaper = input.int(14, "SMA Period", group = "Basic Settings")
netper = input.int(5, "NET Period", group = "Basic Settings", minval = 1)
colorbars = input.bool(false, "Color bars?", group = "UI Options")
smaperout = math.max(smaper, 1)
netperout = math.max(netper, 2)
netd = 0.5 * netperout * (netperout - 1)
val = ta.sma(src, smaper)
netNum = 0.
for k = 0 to netperout - 1
for j = 0 to k
diff = math.sign(nz(val[k]) - nz(val[j]))
netNum -= (diff > 0) ? 1 : (diff < 0) ? -1 : 0
net = netNum / netd
valc = 0.
valc := (net > 0) ? 0 : (net < 0) ? 1 : nz(valc[1])
colorout = valc == 1 ? redcolor : valc == 0 ? greencolor : color.gray
plot(val, color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na) |
WMACD | https://www.tradingview.com/script/ZA3pbvG7-WMACD/ | RafaelZioni | https://www.tradingview.com/u/RafaelZioni/ | 367 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator(title='WMACD', overlay=true, max_bars_back=2000, max_lines_count=500)
source = close
fastLength = input.int(3, minval=1)
slowLength = input.int(8, minval=1)
fast = ta.ema(source, fastLength)
slow = ta.ema(source, slowLength)
vr = fast - slow
macd_lookback =100, oo =500,mult =50,zz = 35,ui = 1,macd_show = true
b_color = color.gray,cop = vr<= 0 ? color.red : color.lime
//
float macd_up = 0.0,int macd_upId = 0,int macd_n_b = oo,var int macd_fs = time
a1 = array.new_float(macd_n_b + 1, 0.0),b1 = array.new_float(macd_n_b, 0.0),c1 = array.new_float(macd_n_b, 0.0),d1 = array.new_int(macd_n_b, 0)
float macd_high = ta.highest(high, macd_lookback),float macd_low = ta.lowest(low, macd_lookback)
if barstate.islast
float m_hl = (macd_high - macd_low) / macd_n_b
for pp = 1 to macd_n_b + 1 by 1
array.set(a1, pp - 1, macd_low + m_hl * pp)
for i = 0 to macd_lookback + 1 by 1
int cc = 0
array.fill(c1, 0.0)
for pp = 0 to macd_n_b - 1 by 1
float tx = array.get(a1, pp)
if low[i] < tx and high[i] > tx
float trep = array.get(c1, pp)
float dtrep = trep + nz(vr[i])
array.set(c1, pp, dtrep)
cc += 2
cc
for pp = 0 to macd_n_b - 1 by 1
float jj = array.get(b1, pp)
float trep = array.get(c1, pp)
float djj = jj + (cc >= 0 ? trep / cc : 0.0)
array.set(b1, pp, djj)
macd_up := array.max(b1)
macd_upId := array.indexof(b1, macd_up)
for pp = 0 to macd_n_b - 1 by 1
float jj = array.get(b1, pp)
int tres = math.round(mult * jj / macd_up)
array.set(d1, pp, tres)
if barstate.isfirst
macd_fs := time
macd_fs
yyy = ta.change(time)
yn = timenow + math.round(yyy * zz)
f(n) =>
x1 = macd_upId == n and macd_show ? math.max(time[macd_lookback], macd_fs) : timenow + math.round(yyy * (zz - array.get(d1, n)))
ut = array.get(a1, n)
line.new(x1=x1, y1=ut, x2=yn, y2=ut, xloc=xloc.bar_time, extend=extend.none, color=macd_upId == n ? cop : b_color, style=line.style_solid, width=ui)
if barstate.islast
for i = 0 to macd_n_b - 1 by 1
f(i)
length = input(14)
overSold = input(35)
overBought = input(65)
p = close
vrsi = ta.rsi(p, length)
price = close
var bool long = na
var bool short = na
long := ta.crossover(vrsi, overSold)
short := ta.crossunder(vrsi, overBought)
var float last_open_long = na
var float last_open_short = na
last_open_long := long ? close : nz(last_open_long[1])
last_open_short := short ? close : nz(last_open_short[1])
entry_value = last_open_long
entry_value1 = last_open_short
// Rounding levels to min tick
nround(x) =>
n = math.round(x / syminfo.mintick) * syminfo.mintick
n
//
disp_panels = input(true, title='Display info panels?')
fibs_label_off = input(5, title='fibs label offset')
fibs_label_size = input.string(size.normal, options=[size.tiny, size.small, size.normal, size.large, size.huge], title='fibs label size')
r1_x = timenow + math.round(ta.change(time) * fibs_label_off)
r1_y = last_open_short
text1 = 'High : ' + str.tostring(nround(last_open_short))
s1_y = last_open_long
text3 = 'low : ' + str.tostring(nround(last_open_long))
R1_label = disp_panels ? label.new(x=r1_x, y=r1_y, text=text1, xloc=xloc.bar_time, yloc=yloc.price, color=color.orange, style=label.style_label_down, textcolor=color.black, size=fibs_label_size) : na
S1_label = disp_panels ? label.new(x=r1_x, y=s1_y, text=text3, xloc=xloc.bar_time, yloc=yloc.price, color=color.lime, style=label.style_label_up, textcolor=color.black, size=fibs_label_size) : na
label.delete(R1_label[1])
label.delete(S1_label[1])
//
|
MTF High and Low Fractions | https://www.tradingview.com/script/T0T6pR70-MTF-High-and-Low-Fractions/ | geneclash | https://www.tradingview.com/u/geneclash/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © geneclash
//
// Acknowledgement:
//
// @HeWhoMustNotBeNamed - Previous High/Low MTF
// https://www.tradingview.com/script/DNqSoMlx-Previous-High-Low-MTF/
//
//@version=5
indicator('MTF high and low fractions', overlay=true, max_lines_count=500, max_labels_count=500)
tf1 = input.timeframe(defval='D', title='Timeframe for High/Low')
type = input.string("1/4",title="Levels:",options=["1/3","1/4","1/8"])
lineCount = input.int(30,title="Total Level Count",step=2,minval=2)/2
showhist = input(defval=false, title='Show Historical Lines', group='Lines & Labels')
showlabel = input(defval=false, title='Show Price Labels', group='Lines & Labels')
offsetlabel = input.int(3,title="Label Offset", group='Lines & Labels')
linestyle2 = input.string(defval='Solid', title="Line Style",options=['Solid', 'Dotted', 'Dashed'], group='Lines & Labels')
linestyle1 = linestyle2 == 'Solid' ? line.style_solid : linestyle2 == 'Dotted' ? line.style_dotted : line.style_dashed
lwidth = input.int(defval=1, minval=1, maxval=4, title='Line Width', group='Lines & Labels')
color1 = input.color(defval=color.white, title='Color (Lines & Labels)', group='Lines & Labels')
hhigh = request.security(syminfo.ticker, tf1, high[1], lookahead=barmerge.lookahead_on)
hlow = request.security(syminfo.ticker, tf1, low[1], lookahead=barmerge.lookahead_on)
hbar = request.security(syminfo.ticker, tf1, barstate.islast)
var division = 1
if type == "1/3"
division := 3
else if type == "1/4"
division := 4
else if type == "1/8"
division := 8
range1 = (hhigh - hlow) / division
zerolevel = hlow
var line highline = na
var line lowline = na
var lines = array.new_line()
var labels = array.new_label()
x1Value = bar_index + offsetlabel
var label highlabel = label.new(x1Value, hhigh, style=label.style_none, text=str.tostring(hhigh), textcolor=color1)
var label lowlabel = label.new(x1Value, hlow, style=label.style_none, text=str.tostring(hlow), textcolor=color1)
if hhigh != hhigh[1] or hlow != hlow[1]
if not showhist
line.delete(highline)
line.delete(lowline)
label.delete(highlabel)
label.delete(lowlabel)
highline := line.new(bar_index, hhigh, bar_index + 1, hhigh, color=color1, style=linestyle1, width=lwidth)
lowline := line.new(bar_index, hlow, bar_index + 1, hlow, color=color1, style=linestyle1, width=lwidth)
if showlabel
highlabel := label.new(x1Value, hhigh, style=label.style_none, text=str.tostring(hhigh), textcolor=color1)
lowlabel := label.new(x1Value, hlow, style=label.style_none, text=str.tostring(hlow), textcolor=color1)
label.set_y(highlabel, hhigh)
label.set_y(lowlabel, hlow)
label.set_text(highlabel, str.tostring(hhigh) + '-(1.0)')
label.set_text(lowlabel, str.tostring(hlow) + '-(0.0)')
label.set_x(highlabel, x1Value)
label.set_x(lowlabel, x1Value)
line.set_x2(highline, bar_index + 1)
line.set_x2(lowline, bar_index + 1)
if not showlabel
label.delete(highlabel)
label.delete(lowlabel)
if hhigh != hhigh[1] or hlow != hlow[1]
if not showhist and array.size(lines) > 0
for i = 0 to array.size(lines) - 1 by 1
line.delete(array.get(lines, i))
label.delete(array.get(labels, i))
array.clear(lines)
array.clear(labels)
for i = 1 to lineCount by 1
shigh = zerolevel + i * range1
slow = zerolevel - i * range1
if i != division
array.push(lines, line.new(bar_index, shigh, bar_index + 1, shigh, color=color1, style=linestyle1, width=lwidth))
array.push(labels, label.new(bar_index, shigh, text=str.tostring(shigh), textcolor=showlabel ? color1 : color.new(color1, 100), style=label.style_none))
array.push(lines, line.new(bar_index, slow, bar_index + 1, slow, color=color1, style=linestyle1, width=lwidth))
array.push(labels, label.new(bar_index, slow, text=str.tostring(slow), textcolor=showlabel ? color1 : color.new(color1, 100), style=label.style_none))
if array.size(lines) > 0
for i = 0 to array.size(lines) - 1 by 1
line.set_x2(array.get(lines, i), bar_index + 1)
label.set_x(array.get(labels, i), x1Value) |
Dragon Double RSI | https://www.tradingview.com/script/o2t2eZmy-Dragon-Double-RSI/ | Dragon_trader95 | https://www.tradingview.com/u/Dragon_trader95/ | 88 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dragon_trader95
res(MAResolution) =>
if MAResolution == '00 Current'
timeframe.period
else
if MAResolution == '01 1m'
'1'
else
if MAResolution == '02 3m'
'3'
else
if MAResolution == '03 5m'
'5'
else
if MAResolution == '04 15m'
'15'
else
if MAResolution == '05 30m'
'30'
else
if MAResolution == '06 45m'
'45'
else
if MAResolution == '07 1h'
'60'
else
if MAResolution == '08 2h'
'120'
else
if MAResolution == '09 3h'
'180'
else
if MAResolution == '10 4h'
'240'
else
if MAResolution == '11 1D'
'1D'
else
if MAResolution == '12 1W'
'1W'
else
if MAResolution == '13 1M'
'1M'
//@version=5
indicator(title='Dragon Double RSI by @Dragon_Trader95', shorttitle='Doubel RSI')
ShowCrose =input(title='Show Crose', defval=true)
//RSI
ShowFastRSI =input(title='Show Regular RSI', defval=false, group="RSI Settings")
rsiSourceInput = input.source(close, 'Source', group='RSI Settings')
TimeFrame1 = input.string(title='Resolution For Fast RSI', defval='00 Current', options=['00 Current', '01 1m', '02 3m', '03 5m', '04 15m', '05 30m', '06 45m', '07 1h', '08 2h', '09 3h', '10 4h', '11 1D', '12 1W', '13 1M'], group="RSI Settings")
rsiLengthInput = input.int(14, minval=1, title='RSI Length', group='RSI Settings')
rsiOverbought = input.int(title='RSI Overbought Level', defval=70, group='RSI Settings')
rsiOversold = input.int(title='RSI Oversold Level', defval=30, group='RSI Settings')
rsi = request.security(syminfo.tickerid, res(TimeFrame1), ta.rsi(rsiSourceInput, rsiLengthInput))
rsiPlot = plot(ShowFastRSI ? rsi : na, 'Regular RSI', color=rsi<rsiOversold ? color.new(color.green, 0) : rsi>rsiOverbought ?color.new(color.red, 0) : color.new(#7E57C2, 50), linewidth=1)
rsiUpperBand = hline(rsiOverbought, "RSI Upper Band", color=#787B86)
midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(rsiOversold, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30, 0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
// rsiUpperBand = hline(70, 'RSI Upper Band', color=#787B86, display= display.none)
// hline(50, 'RSI Middle Band', color.new(color.lime, 70), linestyle=hline.style_solid, linewidth=1)
// hline(20, 'RSI Middle Band', color.new(color.lime, 90), linestyle=hline.style_solid, linewidth=1)
// hline(80, 'RSI Middle Band', color.new(color.red, 90), linestyle=hline.style_solid, linewidth=1)
// rsiLowerBand = hline(30, 'RSI Lower Band', color=#787B86, display= display.none)
// fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title='RSI Background Fill')
//Doubel RSI
ShowSlowsRSI =input(title='Show Slows RSI', defval=true, group="Doubel RSI Settings")
TimeFrame2 = input.string(title='Resolution For RSI Length 1', defval='00 Current', options=['00 Current', '01 1m', '02 3m', '03 5m', '04 15m', '05 30m', '06 45m', '07 1h', '08 2h', '09 3h', '10 4h', '11 1D', '12 1W', '13 1M'], group="Doubel RSI Settings")
TimeFrame3 = input.string(title='Resolution For RSI Length 2', defval='00 Current', options=['00 Current', '01 1m', '02 3m', '03 5m', '04 15m', '05 30m', '06 45m', '07 1h', '08 2h', '09 3h', '10 4h', '11 1D', '12 1W', '13 1M'], group="Doubel RSI Settings")
rsiLengthInput1 = input.int(100, minval=1, title='RSI Length 1', group='Doubel RSI Settings')
rsiLengthInput2 = input.int(25, minval=1, title='RSI Length 2', group='Doubel RSI Settings')
rsiSourceInputDoubel = input.source(close, 'Source', group='Doubel RSI Settings')
rsi1 = request.security(syminfo.tickerid, res(TimeFrame2), ta.rsi(rsiSourceInputDoubel, rsiLengthInput1))
rsi2 = request.security(syminfo.tickerid, res(TimeFrame3), ta.rsi(rsiSourceInputDoubel, rsiLengthInput2))
plot(ShowSlowsRSI ? rsi1 : na, 'Slowest RSI', color=rsi1<40 ? color.new(color.green, 0) : rsi1>60 ?color.new(color.red, 0) : color.new(color.orange, 0), linewidth=1)
rsi2Plot = plot(ShowSlowsRSI ? rsi2 : na, 'Slow RSI', color=#78909c, linewidth=1)
fill(rsi2Plot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(rsi2Plot, midLinePlot, 30, 0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
// rsiUpperBand1 = hline(60, 'RSI Upper Band', color=color.new(color.red, 70), display= display.none)
// rsiLowerBand1 = hline(40, 'RSI Lower Band', color=color.new(color.green, 70), display= display.none)
// rsiUpperBand1x = hline(58, 'RSI Upper Band', color=color.new(color.red, 70), display= display.none)
// rsiLowerBand1y = hline(42, 'RSI Lower Band', color=color.new(color.green, 70), display= display.none)
// fill(rsiUpperBand1, rsiUpperBand1x, color=color.new(color.red, 70), title='RSI Background Fill')
// fill(rsiLowerBand1, rsiLowerBand1y, color=color.new(color.green, 70), title='RSI Background Fill')
crossunderOB1 = barstate.isconfirmed and ta.crossover(rsi, rsiOverbought)
crossoverOS1 = barstate.isconfirmed and ta.crossunder(rsi, rsiOversold)
bool IsCrossoverForSlowsRSI = false
bool IsCrossunderForSlowsRSI = false
if ShowSlowsRSI and ShowCrose and barstate.isconfirmed and ta.crossover(rsi2,rsi1)
lun1 = label.new(bar_index, na, color=color.green, textcolor=color.green, style=label.style_xcross, size=size.auto)
label.set_y(lun1, rsi1)
IsCrossoverForSlowsRSI := true
if ShowSlowsRSI and ShowCrose and barstate.isconfirmed and ta.crossunder(rsi2,rsi1)
lun1 = label.new(bar_index, na, color=color.red, textcolor=color.red, style=label.style_xcross, size=size.auto)
label.set_y(lun1, rsi1)
IsCrossunderForSlowsRSI := true
alertcondition(IsCrossoverForSlowsRSI, title='Slow RSI Crossover Call-out', message='Crossover Call-out')
alertcondition(IsCrossunderForSlowsRSI, title='Slow RSI Crossunder Call-out', message='Crossunder Call-out')
alertcondition(IsCrossunderForSlowsRSI and IsCrossoverForSlowsRSI, title='Slow RSI Crossunder-Crossover Call-out', message='Slow RSI Crossunder-Crossover Call-out')
|
Polynomial Regression Extrapolation [LuxAlgo] | https://www.tradingview.com/script/zAkeVs4R-Polynomial-Regression-Extrapolation-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,560 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Polynomial Regression Extrapolation [LuxAlgo]"
, overlay = true
, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(100
, minval = 0)
extrapolate = input.int(10
, minval = 0)
degree = input.int(3, 'Polynomial Degree'
, minval = 0
, maxval = 8)
src = input(close)
lock = input(false, 'Lock Forecast')
//Style
up_css = input.color(#0cb51a, 'Upward Color'
, group = 'Style')
dn_css = input.color(#ff1100, 'Downward Color'
, group = 'Style')
ex_css = input.color(#ff5d00, 'Extrapolation Color'
, group = 'Style')
width = input(1, 'Width'
, group = 'Style')
//-----------------------------------------------------------------------------}
//Fill lines array
//-----------------------------------------------------------------------------{
var lines = array.new_line(0)
if barstate.isfirst
for i = -extrapolate to length-1
array.push(lines, line.new(na, na, na, na))
//-----------------------------------------------------------------------------}
//Get design matrix & partially solve system
//-----------------------------------------------------------------------------{
n = bar_index
var design = matrix.new<float>(0, 0)
var response = matrix.new<float>(0, 0)
if barstate.isfirst
for i = 0 to degree
column = array.new_float(0)
for j = 0 to length-1
array.push(column, math.pow(j,i))
matrix.add_col(design, i, column)
var a = matrix.inv(matrix.mult(matrix.transpose(design), design))
var b = matrix.mult(a, matrix.transpose(design))
//-----------------------------------------------------------------------------}
//Get response matrix and compute roling polynomial regression
//-----------------------------------------------------------------------------{
var pass = 1
var matrix<float> coefficients = na
var x = -extrapolate
var float forecast = na
if barstate.islast
if pass
prices = array.new_float(0)
for i = 0 to length-1
array.push(prices, src[i])
matrix.add_col(response, 0, prices)
coefficients := matrix.mult(b, response)
float y1 = na
idx = 0
for i = -extrapolate to length-1
y2 = 0.
for j = 0 to degree
y2 += math.pow(i, j)*matrix.get(coefficients, j, 0)
if idx == 0
forecast := y2
//------------------------------------------------------------------
//Set lines
//------------------------------------------------------------------
css = y2 < y1 ? up_css : dn_css
get_line = array.get(lines, idx)
line.set_xy1(get_line, n - i + 1, y1)
line.set_xy2(get_line, n - i, y2)
line.set_color(get_line, i <= 0 ? ex_css : css)
line.set_width(get_line, width)
y1 := y2
idx += 1
if lock
pass := 0
else
y2 = 0.
x -= 1
for j = 0 to degree
y2 += math.pow(x, j)*matrix.get(coefficients, j, 0)
forecast := y2
plot(pass == 0 ? forecast : na, 'Extrapolation'
, color = ex_css
, offset = extrapolate
, linewidth = width)
//-----------------------------------------------------------------------------}
|
DI-CD with ADX | https://www.tradingview.com/script/CMgG6P70-DI-CD-with-ADX/ | m_b_round | https://www.tradingview.com/u/m_b_round/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// original idea © BeikabuOyaji
// new display options © m_b_round
//@version=5
indicator('DI-CD with ADX')
len = input(14)
th = input(20)
TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - nz(SmoothedTrueRange[1]) / len + TrueRange
SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - nz(SmoothedDirectionalMovementPlus[1]) / len + DirectionalMovementPlus
SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - nz(SmoothedDirectionalMovementMinus[1]) / len + DirectionalMovementMinus
DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
ADX = ta.sma(DX, len)
plot(math.abs(DIPlus - DIMinus), title="DI-CD", color=DIPlus > DIMinus ? DIPlus > nz(DIPlus[1]) and DIMinus < nz(DIMinus[1]) ? color.lime : color.green : DIPlus < nz(DIPlus[1]) and DIMinus > nz(DIMinus[1]) ? color.red : color.maroon, style=plot.style_columns)
// plot(DIPlus, color=color.new(color.green, 0), title='DI+')
// plot(DIMinus, color=color.new(color.red, 0), title='DI-')
plot(ADX, color=color.new(color.yellow, 0), title='ADX')
hline(th, color=color.white)
|
Gann Levels For Nifty | https://www.tradingview.com/script/Fp04fGAc-Gann-Levels-For-Nifty/ | snchoudhary | https://www.tradingview.com/u/snchoudhary/ | 121 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © snchoudhary
//@version=4
study("Gann Levels For Nifty", shorttitle="Gann", overlay=true)
a1=(input(type=input.integer, defval= 15000))
plot(a1, linewidth=2 ,color=color.aqua, trackprice=true )
a2=(input(type=input.integer, defval= 15000))
plot(a2, linewidth=2 ,color=color.aqua, trackprice=true )
a3=(input(type=input.integer, defval= 15000))
plot(a3, linewidth=2 ,color=color.aqua, trackprice=true )
a4=(input(type=input.integer, defval= 15000))
plot(a4, linewidth=2 ,color=color.aqua, trackprice=true )
a5=(input(type=input.integer, defval= 15000))
plot(a5, linewidth=2 ,color=color.aqua, trackprice=true )
a6=(input(type=input.integer, defval= 15000))
plot(a6, linewidth=2 ,color=color.aqua, trackprice=true )
a7=(input(type=input.integer, defval= 15000))
plot(a7, linewidth=2 ,color=color.aqua, trackprice=true )
a8=(input(type=input.integer, defval= 15000))
plot(a8, linewidth=2 ,color=color.aqua, trackprice=true )
a9=(input(type=input.integer, defval= 15000))
plot(a9, linewidth=2 ,color=color.aqua, trackprice=true )
a10=(input(type=input.integer, defval= 15000))
plot(a10, linewidth=2 ,color=color.aqua, trackprice=true )
a11=(input(type=input.integer, defval= 15000))
plot(a11, linewidth=2 ,color=color.aqua, trackprice=true )
a12=(input(type=input.integer, defval= 15000))
plot(a12, linewidth=2 ,color=color.aqua, trackprice=true )
a13=(input(type=input.integer, defval= 15000))
plot(a13, linewidth=2 ,color=color.aqua, trackprice=true )
a14=(input(type=input.integer, defval= 15000))
plot(a14, linewidth=2 ,color=color.aqua, trackprice=true )
a15=(input(type=input.integer, defval= 15000))
plot(a15, linewidth=2 ,color=color.aqua, trackprice=true )
a16=(input(type=input.integer, defval= 15000))
plot(a16, linewidth=2 ,color=color.aqua, trackprice=true )
a17=(input(type=input.integer, defval= 15000))
plot(a17, linewidth=2 ,color=color.aqua, trackprice=true )
a18=(input(type=input.integer, defval= 15000))
plot(a18, linewidth=2 ,color=color.aqua, trackprice=true )
a19=(input(type=input.integer, defval= 15000))
plot(a19, linewidth=2 ,color=color.aqua, trackprice=true )
a20=(input(type=input.integer, defval= 15000))
plot(a20, linewidth=2 ,color=color.aqua, trackprice=true )
a21=(input(type=input.integer, defval= 15000))
plot(a21, linewidth=2 ,color=color.aqua, trackprice=true )
a22=(input(type=input.integer, defval= 15000))
plot(a22, linewidth=2 ,color=color.aqua, trackprice=true )
a23=(input(type=input.integer, defval= 15000))
plot(a23, linewidth=2 ,color=color.aqua, trackprice=true )
a24=(input(type=input.integer, defval= 15000))
plot(a24, linewidth=2 ,color=color.aqua, trackprice=true )
a25=(input(type=input.integer, defval= 15000))
plot(a25, linewidth=2 ,color=color.aqua, trackprice=true )
a26=(input(type=input.integer, defval= 15000))
plot(a26, linewidth=2 ,color=color.aqua, trackprice=true )
a27=(input(type=input.integer, defval= 15000))
plot(a27, linewidth=2 ,color=color.aqua, trackprice=true )
a28=(input(type=input.integer, defval= 15000))
plot(a28, linewidth=2 ,color=color.aqua, trackprice=true )
a29=(input(type=input.integer, defval= 15000))
plot(a29, linewidth=2 ,color=color.aqua, trackprice=true )
a30=(input(type=input.integer, defval= 15000))
plot(a30, linewidth=2 ,color=color.aqua, trackprice=true )
a31=(input(type=input.integer, defval= 15000))
plot(a31, linewidth=2 ,color=color.aqua, trackprice=true )
a32=(input(type=input.integer, defval= 15000))
plot(a32, linewidth=2 ,color=color.aqua, trackprice=true )
a33=(input(type=input.integer, defval= 15000))
plot(a33, linewidth=2 ,color=color.aqua, trackprice=true )
a34=(input(type=input.integer, defval= 15000))
plot(a34, linewidth=2 ,color=color.aqua, trackprice=true )
a35=(input(type=input.integer, defval= 15000))
plot(a35, linewidth=2 ,color=color.aqua, trackprice=true )
a36=(input(type=input.integer, defval= 15000))
plot(a36, linewidth=2 ,color=color.aqua, trackprice=true )
a37=(input(type=input.integer, defval= 15000))
plot(a37, linewidth=2 ,color=color.aqua, trackprice=true )
a38=(input(type=input.integer, defval= 15000))
plot(a38, linewidth=2 ,color=color.aqua, trackprice=true )
a39=(input(type=input.integer, defval= 15000))
plot(a39, linewidth=2 ,color=color.aqua, trackprice=true )
a40=(input(type=input.integer, defval= 15000))
plot(a40, linewidth=2 ,color=color.aqua, trackprice=true )
a41=(input(type=input.integer, defval= 15000))
plot(a41, linewidth=2 ,color=color.aqua, trackprice=true )
a42=(input(type=input.integer, defval= 15000))
plot(a42, linewidth=2 ,color=color.aqua, trackprice=true )
a43=(input(type=input.integer, defval= 15000))
plot(a43, linewidth=2 ,color=color.aqua, trackprice=true )
a44=(input(type=input.integer, defval= 15000))
plot(a44, linewidth=2 ,color=color.aqua, trackprice=true )
a45=(input(type=input.integer, defval= 15000))
plot(a45, linewidth=2 ,color=color.aqua, trackprice=true )
a46=(input(type=input.integer, defval= 15000))
plot(a46, linewidth=2 ,color=color.aqua, trackprice=true )
a47=(input(type=input.integer, defval= 15000))
plot(a47, linewidth=2 ,color=color.aqua, trackprice=true )
a48=(input(type=input.integer, defval= 15000))
plot(a48, linewidth=2 ,color=color.aqua, trackprice=true )
a49=(input(type=input.integer, defval= 15000))
plot(a49, linewidth=2 ,color=color.aqua, trackprice=true )
a50=(input(type=input.integer, defval= 15000))
plot(a50, linewidth=2 ,color=color.aqua, trackprice=true )
|
Candle Level of VWAP [By MUQWISHI] | https://www.tradingview.com/script/yv3YPDLU-Candle-Level-of-VWAP-By-MUQWISHI/ | MUQWISHI | https://www.tradingview.com/u/MUQWISHI/ | 194 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MUQWISHI
//@version=5
indicator("Candle Level of Volume Weighted Average Price", shorttitle = "LVWAP")
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | INPUT |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
prcSrc = input.source(close, "Price Source ", group = "VWAP Settings")
vwapSrc = input.source(hlc3, "VWAP Source ", group = "VWAP Settings")
numPerid = input.int(1, "Anchor Period ", 1, group = "VWAP Settings", inline = "1")
session = input.string("Day", "", ["Day", "Week", "Month", "Year", "Length"],
group = "VWAP Settings", inline = "1")
spkFltr = input.bool(true, "Enable Spike Filtering", group = "VWAP Settings")
smthChk = input.bool(false, "Enable Smoothing", group = "Level VWAP Smoothing")
smthLen = input.int(14, "Length", 1, group = "Level VWAP Smoothing")
smthTyp = input.string("WMA", "Type", ["RMA", "SMA", "EMA", "WMA"], group = "Level VWAP Smoothing")
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | CALCULATION |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// Smoothing Function
maType(scr) =>
switch smthTyp
"RMA" => ta.rma(scr, smthLen)
"SMA" => ta.sma(scr, smthLen)
"EMA" => ta.ema(scr, smthLen)
=> ta.wma(scr, smthLen)
// Get Session
NewSession = switch session
"Day" => str.tostring(numPerid) + "D"
"Week" => str.tostring(numPerid) + "W"
"Month" => str.tostring(numPerid) + "M"
"Year" => str.tostring(numPerid*12) + "M"
=> na
// VWAP Calculation
vwap(scr, tf) =>
var float volPrcSum = scr * volume // Sum Price * Volume
var float volSum = volume // Sum Volume
var float avgSamVarSum = math.pow(scr, 2) * volume // Sum Average Sample Variances
if session == "Length"
volPrcSum := math.sum(scr * volume, numPerid)
volSum := math.sum(volume, numPerid)
avgSamVarSum := math.sum(math.pow(scr, 2) * volume, numPerid)
else
if timeframe.change(tf)
volPrcSum := scr * volume
volSum := volume
avgSamVarSum := math.pow(scr, 2) * volume
else if bar_index > 0
volPrcSum := scr * volume + volPrcSum[1]
volSum := volume + volSum[1]
avgSamVarSum := math.pow(scr, 2) * volume + avgSamVarSum[1]
// VWAP
vwap = volPrcSum / volSum
// VWAP Standard Deviation
vwapSTD = math.sqrt( (avgSamVarSum/volSum) - math.pow(vwap, 2))
[vwap, vwapSTD]
// Get VWAP & Std Values
[vwap, vwapSTD] = vwap(vwapSrc, NewSession)
// Candle Level of VWAP
lVWAP = (prcSrc - vwap)/vwapSTD
lVWAP := spkFltr and not na(lVWAP) ? (lVWAP > 5 ? 5 : lVWAP < -5 ? -5 : lVWAP) : lVWAP
lVWAP := smthChk ? maType(lVWAP) : lVWAP
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | PLOTTING |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// VWAP Line
vwaplin = hline( 0, "VWAP", color = color.new(color.silver, 50), linewidth = 2, linestyle = hline.style_dotted)
// 1 STANDARD DEVIATION LINE
stdUp1 = hline( 1, "1σ", color = color.new(color.white, 75), linewidth = 1, linestyle = hline.style_solid)
stdDn1 = hline(-1, "-1σ", color = color.new(color.white, 75), linewidth = 1, linestyle = hline.style_solid)
fill(stdUp1, vwaplin, color = color.new(color.white, 90), title = "VWAP 1σ Fill")
fill(stdDn1, vwaplin, color = color.new(color.white, 90), title = "VWAP -1σ Fill")
// 2 STANDARD DEVIATION LINE
stdUp2 = hline( 2, "2σ", color = color.new(color.orange, 75), linewidth = 4, linestyle = hline.style_solid)
stdDn2 = hline(-2, "-2σ", color = color.new(color.orange, 75), linewidth = 4, linestyle = hline.style_solid)
fill(stdUp1, stdUp2, color = color.new(color.orange, 90), title = " 1σ 2σ Fill")
fill(stdDn1, stdDn2, color = color.new(color.orange, 90), title = "-1σ -2σ Fill")
// 3 STANDARD DEVIATION LINE
stdUp3 = hline( 3, "3σ", color = color.new(color.green, 75), linewidth = 2, linestyle = hline.style_solid)
stdDn3 = hline(-3, "-3σ", color = color.new(color.green, 75), linewidth = 2, linestyle = hline.style_solid)
fill(stdUp3, stdUp2, color = color.new(color.green, 90), title = " 2σ 3σ Fill")
fill(stdDn3, stdDn2, color = color.new(color.green, 90), title = "-2σ -3σ Fill")
// Candle Level of VWAP Indicator
plot(lVWAP, "Candle Level of VWAP", color = lVWAP > 0 ? color.green : color.red, linewidth = 2)
|
ndt Bull & Bear | https://www.tradingview.com/script/Mz3M3ocd-ndt-Bull-Bear/ | doinguoilacloi | https://www.tradingview.com/u/doinguoilacloi/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © doinguoilacloi
//@version=5
indicator(title="Indicator", shorttitle="ndt Bull & Bear", overlay=true)
ema9 = ta.ema(close, 9)
ema21 = ta.ema(close, 21)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
p1=plot(ema9, title = "HMA9", color = color.new(color.lime,0), linewidth=2)
p2=plot(ema21, title = "HMA21", color = color.new(color.orange,0), linewidth=2)
p3=plot(ema50, title = "HMA50", color = color.new(color.blue,0), linewidth=2)
p4=plot(ema200, title = "HMA200", color = color.new(color.red,0), linewidth=2)
cloudcolor9_21 = ema9 > ema21 ? color.green : color.red
cloudcolor21_50 = ema21 > ema50 ? color.white : color.maroon
fill(p1, p2, color = color.new(cloudcolor9_21, 50), title = "HMA Cloud 9&21")
fill(p3, p4, color = color.new(cloudcolor21_50, 50), title = "HMA Cloud 21&50")
//plotshape(ta.crossover(ema9,ema21), title = "Bull", style=shape.triangleup, size=size.small,location=location.belowbar, color=color.new(color.green,0), text="Mua", textcolor=color.new(color.green,0))
//plotshape(ta.crossunder(ema9,ema21), title = "Bear", style=shape.triangledown, size=size.small,location=location.abovebar, color=color.new(color.red,0), text="Bán", textcolor=color.new(color.red,0)) |
% Per Bar | https://www.tradingview.com/script/e6AOEPiq-Per-Bar/ | Sainsley2500 | https://www.tradingview.com/u/Sainsley2500/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sainsley2500
// This script compute the average price swing per bar (between High and low)
// It does not include gaps between bars in the calcul
//@version=5
indicator("% Per Bar", overlay = false)
var LabelString = ""
var Label = label.new(0, 0, "", color= color.black, textcolor=color.white, yloc=yloc.price)
HighLowPercent = math.abs((high-low)/low *100)
SMA10 = ta.sma(HighLowPercent, 10)
SMA100 = ta.sma(HighLowPercent, 100)
SMA1000 = ta.sma(HighLowPercent, 1000)
plot(HighLowPercent, title = "High - Low", color = color.black)
if barstate.islast
label.set_xy(Label, bar_index, SMA10)
LabelString := "Average on last 10 Bars: " + str.format("{0,number,#.####}", SMA10) + "%\n"
LabelString := LabelString + "Average on last 100 Bars: " + str.format("{0,number,#.####}", SMA100) + "%\n"
LabelString := LabelString + "Average on last 1000 Bars: " + str.format("{0,number,#.####}", SMA1000) + "%\n"
label.set_text(Label, LabelString)
|
NK Sir's SRT | https://www.tradingview.com/script/Dh24RBUj-NK-Sir-s-SRT/ | apurvaverma | https://www.tradingview.com/u/apurvaverma/ | 222 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © apurvaverma
//@version=5
// Thanks to Nitish Sir for teaching the concept of SRT for Investments
indicator("NK Sir's SRT", overlay = true)
isScripValid = if(syminfo.ticker == "NIFTY")
1
else
0
nifty = if(isScripValid)
close
else
na
var string GP1 = "SRT Panel"
string tableYposInput = input.string("top", "SRT Panel Position", inline = "11", options = ["top", "middle", "bottom"], group = GP1)
string tableXposInput = input.string("right", "", inline = "11", options = ["left", "center", "right"], group = GP1)
var srtTable = table.new(tableYposInput + "_" + tableXposInput, columns = 2, rows = 4, bgcolor = color.white, border_width = 1, frame_color = color.gray, frame_width = 2, border_color = color.gray)
vix = request.security("INDIAVIX", "D", close)
sma = ta.sma(close, 124)
srt = nifty/sma
table.cell(table_id = srtTable, column = 0, row = 0, text = "NIFTY 50", text_color = color.white, bgcolor = color.aqua)
table.cell(table_id = srtTable, column = 0, row = 1, text = "SMA 124", text_color = color.white, bgcolor = color.aqua)
table.cell(table_id = srtTable, column = 0, row = 2, text = "SRT Value", text_color = color.white, bgcolor = color.aqua)
table.cell(table_id = srtTable, column = 0, row = 3, text = "India VIX", text_color = color.white, bgcolor = color.aqua)
table.cell(table_id = srtTable, column = 1, row = 0, text = str.tostring(nifty))
table.cell(table_id = srtTable, column = 1, row = 1, text = str.tostring(sma,"#.##"))
table.cell(table_id = srtTable, column = 1, row = 2, text = str.tostring(srt,"#.##"))
table.cell(table_id = srtTable, column = 1, row = 3, text = str.tostring(vix,"#.##"))
|
BTC - Novel RPPI Indicator | https://www.tradingview.com/script/NHZCrddT-BTC-Novel-RPPI-Indicator/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 96 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Steversteves & Stein3d
//@version=5
indicator("BTC - RPPI Indicator", overlay=true)
// Grab data from previous daily candle
last_dclose = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on)
last_dopen = request.security(syminfo.tickerid, "D", open[1], lookahead=barmerge.lookahead_on)
last_dhigh = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
last_dlow = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)
last_dvolume = request.security(syminfo.tickerid, "D", volume[1], lookahead=barmerge.lookahead_on)
today_open = request.security(syminfo.tickerid, "D", open, lookahead=barmerge.lookahead_on)
today_low = request.security(syminfo.tickerid, "D", low, lookahead=barmerge.lookahead_on)
today_high = request.security(syminfo.tickerid, "D", high, lookahead=barmerge.lookahead_on)
// RPP Variables: Bull Target
o = today_open * 1.083
l = last_dlow * -0.193
lo = last_dopen * 0.127
lv = last_dvolume * 0.000000002958
// Daily bull targets plot
bull_green = color.new(color.green, 40)
h2 = (o + l + lo + lv) - 4.433
h3 = h2 + 508.88
plot(h2, "Bull Target 1", bull_green)
plot(h3, "Bull Target 2", bull_green)
// RPP Variables: Bear Target
o := today_open * 1.057
f = last_dhigh * -0.249
ldl = last_dlow * 0.172
// Daily bear targets plot
bear_red = color.new(color.red, 40)
l2 = (o + f + ldl) + 18.327
neutral_target = l2 + 660.28
l3 = l2 - 660.28
// plot(l1, "Math Bear Target 1", bear_red)
plot(neutral_target, "Neutral Target", color.yellow)
plot(l2, "Bear Target 1", bear_red)
plot(l3, "Bear Target 2", bear_red)
// Anticipated Close
h = today_high * 1.214
h2 := last_dhigh * -0.160
o := today_open * -0.209
l := today_low * 0.130
closeguess = (h + h2 + o + l) + 11.888
plot(closeguess, "Anticipated Close", color.purple, style=plot.style_circles)
|
MACD Potential Divergence - Fontiramisu | https://www.tradingview.com/script/7YEL8gai-MACD-Potential-Divergence-Fontiramisu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 230 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author : @Fontiramisu
// The divergence part is inspired from divergence indicator by @tradingView team.
// Indicator showing potential divergences on MACD momentum.
//@version=5
indicator(title="MACD Potential Divergence - Fontiramisu", shorttitle="Potential Div MACD - Fontiramisu", timeframe="", timeframe_gaps=true)
import Fontiramisu/fontilab/7 as fontilab
// ] ------------------ MACD ---------------- [
// Getting inputs
fast_length = input(title="Fast Length", defval=12, group="MACD 30 9")
slow_length = input(title="Slow Length", defval=26, group="MACD 30 9")
src = input(title="Source", defval=close, group="MACD 30 9")
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9, group="MACD 30 9")
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD 30 9")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD 30 9")
// Plot colors
col_macd = input(#2962FF, "MACD Line ", inline="MACD", group="MACD 30 9")
col_signal = input(#FF6D00, "Signal Line ", inline="Signal", group="MACD 30 9")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
plot(hist, title="Histogram", style=plot.style_histogram, color=color.new(color.yellow,30))
plot(hist, title="Line", color=color.aqua, linewidth=2, display=display.all)
plot(macd, title="MACD", color=col_macd, display=display.none)
plot(signal, title="Signal", color=col_signal, display=display.none)
// ] -------------- Divergence Handle -------------- [
showDiv = input.bool(title="Show Divergence", defval=true, group="div settings")
lbR = input(title="Pivot Lookback Right", defval=5, group="div settings")
lbL = input(title="Pivot Lookback Left", defval=5, group="div settings")
rangeUpper = input(title="Max of Lookback Range", defval=60, group="div settings")
rangeLower = input(title="Min of Lookback Range", defval=5, group="div settings")
plotBull = input(title="Plot Bullish", defval=true, group="div settings")
plotBullPot = input(title="Plot Bullish Potential", defval=true, group="div settings")
plotHiddenBull = input(title="Plot Hidden Bullish", defval=false, group="div settings")
plotHiddenBullPot = input(title="Plot Hidden Bullish", defval=false, group="div settings")
plotBear = input(title="Plot Bearish", defval=true, group="div settings")
plotBearPot = input(title="Plot Bearish Potential Potential", defval=true, group="div settings")
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false, group="div settings")
plotHiddenBearPot = input(title="Plot Hidden Bearish Potential", defval=false, group="div settings")
bearColor = color.red
bearPotColor = color.new(color.red, 20)
bullColor = color.green
bullPotColor = color.new(color.green, 20)
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
textColorDivPot = color.new(color.white, 20)
noneColor = color.new(color.white, 100)
float osc = hist
// Get pivots.
[plFound, phFound, plFoundPot, phFoundPot] = fontilab.getOscPivots(osc, lbL, lbR)
// Div for curent ut.
[bullDiv, bullDivPot, hiddenBullDiv, hiddenBullDivPot, bearDiv, bearDivPot, hiddenBearDiv, hiddenBearDivPot] =
fontilab.plotDivergences(osc, lbR, plFound, phFound, plFoundPot, phFoundPot, rangeLower, rangeUpper)
//------
// Regular Bullish
plot(
showDiv and plotBullPot and plFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullDiv ? bullColor : noneColor)
)
plotshape(
showDiv and plotBullPot and bullDivPot ? osc[1] : na,
offset= -1,
title="Regular Bullish Pot Label",
text="B",
style=shape.labelup,
location=location.absolute,
color=bullPotColor,
textcolor=textColorDivPot
)
plotshape(
showDiv and plotBullPot and bullDiv ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------
// Hidden Bullish
plot(
showDiv and plotHiddenBull and plFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullDiv ? hiddenBullColor : noneColor)
)
plotshape(
showDiv and plotHiddenBullPot and hiddenBullDivPot ? osc[1] : na,
offset=-1,
title="Hidden Bullish Pot Label",
text="H",
style=shape.labelup,
location=location.absolute,
color=bullPotColor,
textcolor=textColorDivPot
)
plotshape(
showDiv and plotHiddenBull and hiddenBullDiv ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text=" H Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------
// Regular Bearish
plot(
showDiv and plotBearPot and phFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearDiv ? bearColor : noneColor)
)
plotshape(
showDiv and plotBearPot and bearDivPot ? osc[1] : na,
offset=-1,
title="Regular Bearish Pot Label",
text="B",
style=shape.labeldown,
location=location.absolute,
color=bearPotColor,
textcolor=textColorDivPot
)
plotshape(
showDiv and plotBearPot and bearDiv ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
//-----
// Hidden Bearish
plot(
showDiv and plotHiddenBear and phFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearDiv ? hiddenBearColor : noneColor)
)
plotshape(
showDiv and plotHiddenBearPot and hiddenBearDivPot ? osc[1] : na,
offset=-1,
title="Hidden Bearish Pot Label",
text="H",
style=shape.labeldown,
location=location.absolute,
color=bearPotColor,
textcolor=textColorDivPot
)
plotshape(
showDiv and plotHiddenBear and hiddenBearDiv ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text=" H Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
// ]
|
SST Table New | https://www.tradingview.com/script/5tkgJ8JU-SST-Table-New/ | atulkharadi | https://www.tradingview.com/u/atulkharadi/ | 328 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// atulkharadi
//@version=5
indicator(title='SST Table New', shorttitle='SST Table New', overlay=true)
Stock = syminfo.ticker
length = input.int(20, minval=1)
profit = input.int(10, minval=1)
HIGH20 = ta.highest(length)
LOW20 = ta.lowest(length)
TARGET = HIGH20 * (100 + profit) / 100
LHIGH20 = HIGH20[1]
DIFF = (HIGH20 - close) / close * 100
//================================================================================================
//Input RS
swrs = input(true, title='RS')
source = input(title='Source', defval=close)
comparativeTickerId = input.symbol('NSE:NIFTY', title='Comparative Symbol')
RSlength = input.int(55, minval=1, title='Period')
//showZeroLine = input(defval=true, title='Show Zero Line')
toggleRSColor = input(defval=true, title='Toggle RS color on crossovers')
//Setup RS
baseSymbol = request.security(syminfo.tickerid, timeframe.period, source)
comparativeSymbol = request.security(comparativeTickerId, timeframe.period, source)
//Plot RS
//plot(showZeroLine ? 0 : na, linewidth=1, color=color.new(color.maroon, 0), title='Zero Line')
res = (baseSymbol / baseSymbol[RSlength] / (comparativeSymbol / comparativeSymbol[RSlength]) - 1) * 100
resColor = toggleRSColor ? res > 0 ? color.green : color.red : color.blue
plot(swrs ? (100+res)*close/100 : na, title='RS', linewidth=2, color=resColor)
//=============================================================================================
plot(HIGH20, 'HIGH20', color=color.new(color.blue, 0), trackprice=false, editable=true)
plot(LOW20, 'LOW20', color=color.new(color.red, 0), trackprice=false, editable=true)
plot(TARGET, 'TARGET', color=color.new(color.green, 0), trackprice=false, editable=true)
var table gttTable = table.new(position.top_right, 8, 6, bgcolor=color.white, frame_color=color.white, frame_width=2, border_width=2)
Low20D = '20D \nLOW'
table.cell(gttTable, 0, 0, text=Low20D, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
LHigh20D = 'OLD \nGTT'
table.cell(gttTable, 1, 0, text=LHigh20D, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
High20D = 'NEW \nGTT'
table.cell(gttTable, 2, 0, text=High20D, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
SST = 'STOCK NAME'
table.cell(gttTable, 3, 0, text=SST, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
CMP = 'PRICE'
table.cell(gttTable, 4, 0, text=CMP, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
Diff = 'DIFF %'
table.cell(gttTable, 5, 0, text=Diff, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
UpdateGTT = 'Update \nGTT'
table.cell(gttTable, 6, 0, text=UpdateGTT, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
RS_55 = 'RS 55'
table.cell(gttTable, 7, 0, text='RS 55', bgcolor=color.silver, text_color=color.white, text_size=size.normal)
table.cell(gttTable, 3, 1, text=Stock, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
if barstate.islast
Low20D = str.tostring(math.round(LOW20, 2))
table.cell(gttTable, 0, 1, text=Low20D, bgcolor=color.blue, text_color=color.white, text_size=size.normal)
LHigh20D = str.tostring(math.round(LHIGH20, 2))
table.cell(gttTable, 1, 1, text=LHigh20D, bgcolor=color.blue, text_color=color.white, text_size=size.normal)
High20D = str.tostring(math.round(HIGH20, 2))
table.cell(gttTable, 2, 1, text=High20D, bgcolor=color.blue, text_color=color.white, text_size=size.normal)
CMP = str.tostring(math.round(close, 2))
table.cell(gttTable, 4, 1, text=CMP, bgcolor=color.silver, text_color=color.white, text_size=size.normal)
Diff = str.tostring(math.round(DIFF, 2))
table.cell(gttTable, 5, 1, text=Diff, bgcolor=color.blue, text_color=color.white, text_size=size.normal)
RS_55 = str.tostring(math.round(res/100, 2))
table.cell(gttTable, 7, 1, text=RS_55, bgcolor=color.blue, text_color=color.white, text_size=size.normal)
UpdateGTT = if HIGH20 < HIGH20[1]
str.tostring('YES')
table.cell(gttTable, 6, 1, text=UpdateGTT, width=0, bgcolor=color.blue, text_color=color.white, text_size=size.auto)
// TriggeredGTT = if HIGH20 > HIGH20[1]
// str.tostring('TRG @ ')+str.tostring(HIGH20[1])
// table.cell(gttTable, 6, 1, text=TriggeredGTT, width=0, bgcolor=color.blue, text_color=color.white, text_size=size.auto)
// TargetGTT = if HIGH20 > HIGH20[1]
// str.tostring(math.round(TARGET[1], 2))
// table.cell(gttTable, 7, 1, text=TargetGTT, bgcolor=color.blue, text_color=color.white, text_size=size.normal)
plot(res/100, title='RS', linewidth=2, color=resColor) |
Zigzag Lines | https://www.tradingview.com/script/fN3bzwgL-Zigzag-Lines/ | mebiele1 | https://www.tradingview.com/u/mebiele1/ | 124 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @mebiele
// Thanks to @mmoiwgg, this is just a simplified and less fancy presentattion of your work
//@version=5
indicator('Zigzag Lines', overlay=true, max_lines_count=500)
//Inputs
zigperiod = input(defval=5, title='ZigZag Period', group='Zigzag')
zigsrc = input.string("close", title='Zig Zag Source',options=["close", "high/low"], group='Zigzag')
upcolor = input(defval=color.green, title='Zig Zag Up Color', group='Display')
downcolor = input(defval=color.red, title='Zig Zag Down Color', group='Display')
zigstyle = input.string(defval='Solid', title='Zig Zag Line Style', options=['Solid', 'Dotted'], group='Display')
zigwidth = input(defval=3, title='Zig zag Line Width', group='Display')
//Float
float highs = na
float lows = na
if zigsrc == "close"
highs := ta.highestbars(close, zigperiod) == 0 ? close : na
lows := ta.lowestbars(close, zigperiod) == 0 ? close : na
else
highs := ta.highestbars(high, zigperiod) == 0 ? high : na
lows := ta.lowestbars(low, zigperiod) == 0 ? low : na
//Variables
var dir1 = 0
iff_1 = lows and na(highs) ? -1 : dir1
dir1 := highs and na(lows) ? 1 : iff_1
var max_array_size = 100
var zigzagPivots = array.new_float(max_array_size)
var zigzagPivotBars = array.new_int(max_array_size)
add_to_arrays(pointer1, value, pointer2, bindex) =>
array.unshift(pointer2, bindex)
array.unshift(pointer1, value)
if array.size(pointer1) > max_array_size
array.pop(pointer1)
array.pop(pointer2)
update_arrays(pointer1, value, pointer2, bindex, dir) =>
if array.size(pointer1) == 0
add_to_arrays(pointer1, value, pointer2, bindex)
else
if dir == 1 and value > array.get(pointer1, 0) or dir == -1 and value < array.get(pointer1, 0)
array.set(pointer1, 0, value)
array.set(pointer2, 0, bindex)
0.
dir1changed = ta.change(dir1)
if highs or lows
if dir1changed
add_to_arrays(zigzagPivots, dir1 == 1 ? highs : lows, zigzagPivotBars, bar_index)
else
update_arrays(zigzagPivots, dir1 == 1 ? highs : lows, zigzagPivotBars, bar_index, dir1)
if array.size(zigzagPivots) >= 2
var line zzline1 = na
var label zzlabel1 = na
float val = array.get(zigzagPivots, 0)
int point = array.get(zigzagPivotBars, 0)
if ta.change(val) or ta.change(point)
float val1 = array.get(zigzagPivots, 1)
int point1 = array.get(zigzagPivotBars, 1)
if ta.change(val1) == 0 and ta.change(point1) == 0
line.delete(zzline1)
label.delete(zzlabel1)
// showline
zzline1 := line.new(x1=point, x2=point1, y1=val, y2=val1, color=dir1 == 1 ? upcolor : downcolor, width=zigwidth, style=zigstyle == 'Solid' ? line.style_solid : line.style_dotted)
zzline1
|
Volume Risk Avoidance Indicator | https://www.tradingview.com/script/LSWq5fBX-Volume-Risk-Avoidance-Indicator/ | accutrades_net | https://www.tradingview.com/u/accutrades_net/ | 190 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// Name: VRAI - Volume Risk Avoidance Indicator [Sherwin Shao]
// Created: 2022/01/07 - from VCO928
//@version=5
indicator(title='Volume Risk Avoidance Indicator', shorttitle='VRAI', format=format.inherit)
// Inputs
vco_short = input.int(3, title='Short Period', minval=1)
vco_long = input.int(10, title='Long Period', minval=2)
vco_showFill = input(true, title='Apply Filling')
vco_normalizeLookback = input(25, title='Normalization look-back period')
vco_reverseColor = input(false, title='Reverse Color')
kNeutralColor = color.rgb(245,220,0,0)
kBearColor = color.red
kBullColor = color.rgb(0,160,0,0) // color.green
// Functionality
isFlat(sig) =>
not(sig>0.5 or sig<-0.5 or math.abs(sig)>math.abs(sig[1])) //? color.gray : // sig == sig[1]
vco_color(sig) =>
isFlat(sig) ? color.gray : sig > 0 ? kBullColor : kBearColor
osc_color(sig) =>
sig == 0 ? kNeutralColor : sig > 0 ? kBullColor : kBearColor
momo_color(sig) =>
sig > math.max(sig[1],0) ? color.new(kBullColor,0) : sig < math.min(sig[1],0) ? color.new(kBearColor,60) : color.new(kNeutralColor,60)
smooth(sig, len) =>
ma = float(sig) // None
ma := ta.wma(sig, len)
ma
calc_vco(sig, short, long) =>
src = sig
vt = ta.cum(close == high and close == low or high == low ? 0 : (close - low / 4 - high / 4 - open / 2) / (high - low) * nz(volume, 1)) // from Accum/Dist
sh = smooth(vt, short)
lg = smooth(vt, long)
sh - lg
maxAbs(series, len) =>
max = float(0)
for i = 0 to len - 1 by 1
max := math.max(max, math.abs(series[i]))
max
max
raw_vco = calc_vco(close, vco_short, vco_long)
maxAbs_vco = maxAbs(raw_vco, vco_normalizeLookback)
range_vco = 1.0 // range to fit values into
value_vco = raw_vco / maxAbs_vco * range_vco
color_vco = vco_color(value_vco)
color_stall = vco_color(-value_vco[1])
color_osc = vco_showFill ? osc_color(value_vco) : na
fill_color = math.abs(value_vco)<0.5 and math.abs(value_vco)<math.abs(value_vco[1]) ? 85 : 75
plot_vco = plot(value_vco, title='VCO', color=momo_color(value_vco), linewidth=1, style=plot.style_histogram) // green-yellow-red
plot_fill = plot(0, color=color.new(color_osc, fill_color), editable=false)
fill(plot_vco, plot_fill, title='Oscillator Fill', color=color.new(color_vco, fill_color)) |
Gap Size Outcome Statistics [vnhilton] | https://www.tradingview.com/script/e8YolFu5-Gap-Size-Outcome-Statistics-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 21 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vnhilton
//Note: 1 LIMITATION ASSUMES THAT DAYS CLOSED AT SAME PRICE AS ITS OPEN ARE GREEN DAYS, & THAT 0% GAPS ARE GAP UPS
//@version=4
study("Gap Size Outcome Statistics [vnhilton]",shorttitle="Gap Size Outcome Statistics", overlay = true)
//Table column & row headers
var tble = table.new(position.bottom_left, 7, 3, border_width = 1)
table.cell(tble, 1, 0, "Threshold Value", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 2, 0, "Sample Size", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 3, 0, "Green Day", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 4, 0, "Red Day", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 5, 0, "Average Historical Gap", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 6, 0, "Historical Total Gap Sample Size", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 0, 0, " ", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 0, 1, ">", bgcolor=color.blue, text_size=size.normal)
table.cell(tble, 0, 2, "<", bgcolor=color.blue, text_size=size.normal)
//Gap inputs
greaterThres = input(1.00, minval=0.0, title="(GAP UP) | Input % >= 0")
lessThres = input(-1.00, minval=-100.0, maxval=-0.01, title="(GAP DOWN) | Input % < 0")
//Average gap up
avgGapUp = ((open[1] - close[2]) * 100 / close[2]) >= 0 ? 1 : 0 // Gap up
avgGapUSum = cum(avgGapUp ? ((open[1] - close[2]) * 100 / close[2]) : 0) // Update gap up summation in percent
avgGapUCounter = cum(avgGapUp ? 1 : 0) // Update gap up counter
avgGapUPercent = round(avgGapUSum / avgGapUCounter, 2) // Average gap up percent
//Average gap down
avgGapDown = ((open[1] - close[2]) * 100 / close[2]) < 0 ? 1 : 0 // Gap down
avgGapDSum = cum(avgGapDown ? ((open[1] - close[2]) * 100 / close[2]) : 0) // Update gap down summation in percent
avgGapDCounter = cum(avgGapDown ? 1 : 0) // Update gap down counter
avgGapDPercent = round(avgGapDSum / avgGapDCounter, 2) // Average gap down percent
//Average gap outputs
table.cell(tble, 5, 1, tostring(avgGapUPercent) + "%", bgcolor = color.orange, text_size = size.normal) // Place 'Average gap up' in table
table.cell(tble, 5, 2, tostring(avgGapDPercent) + "%", bgcolor = color.orange, text_size = size.normal) // Place 'Average gap down' in table
table.cell(tble, 6, 1, tostring(avgGapUCounter) + " Gap Ups", bgcolor = color.rgb(150, 75, 0), text_size = size.normal) // Place 'Average gap up counter' in table
table.cell(tble, 6, 2, tostring(avgGapDCounter) + " Gap Downs", bgcolor = color.rgb(150, 75, 0), text_size = size.normal) // Place 'Average gap down counter' in table
//Gap up
gapUpGreen = ((open[1] - close[2]) * 100 / close[2]) >= greaterThres and close[1] >= open[1] ? 1 : 0 // Gapped up & ended day in green
gapUpRed = ((open[1] - close[2]) * 100 / close[2]) >= greaterThres and close[1] < open[1] ? 1 : 0 // Gapped up & ended day in red
gUGCounter = cum(gapUpGreen ? 1 : 0) // Update gap up green day cummulative counter
gUDCounter = cum(gapUpRed ? 1 : 0) // Update gap up red day cummulative counter
gUGPercent = round(gUGCounter * 100 / (gUGCounter + gUDCounter), 2) // Gapped up & green day end percent
gUDPercent = round(gUDCounter * 100 / (gUGCounter + gUDCounter), 2) // Gapped up & red day end percent
gUSamples = gUGCounter + gUDCounter // Total gap up events
//Gap up table outputs
table.cell(tble, 1, 1, tostring(greaterThres), bgcolor = color.white, text_size = size.normal) // Place threshold value in table
table.cell(tble, 3, 1, tostring(gUGPercent) + "%", bgcolor = color.green, text_size = size.normal) // Place 'Gapped up & green day end percent' in table
table.cell(tble, 4, 1, tostring(gUDPercent) + "%", bgcolor = color.red, text_size = size.normal) // Place 'Gapped up & red day end percent' in table
table.cell(tble, 2, 1, tostring(gUSamples), bgcolor = color.gray, text_size = size.normal) // Place 'Total gap up events' in table
//Gap down
gapDownRed = ((open[1] - close[2]) * 100 / close[2]) <= lessThres and close[1] < open[1] ? 1 : 0 // Gapped down & ended day in red
gapDownGreen = ((open[1] - close[2]) * 100 / close[2]) <= lessThres and close[1] >= open[1] ? 1 : 0 // Gapped down & ended day in green
gDRCounter = cum(gapDownRed ? 1 : 0) // Update gap down red day cummulative counter
gDGCounter = cum(gapDownGreen ? 1 : 0) // Update gap down green day cummulative counter
gDRPercent = round(gDRCounter * 100 / (gDRCounter + gDGCounter), 2) // Gapped down & red day end percent
gDGPercent = round(gDGCounter * 100 / (gDRCounter + gDGCounter), 2) // Gapped down & green day end percent
gDSamples = gDRCounter + gDGCounter // Total gap down events
//Gap down table outputs
table.cell(tble, 1, 2, tostring(lessThres), bgcolor = color.white, text_size = size.normal) // Place threshold value in table
table.cell(tble, 4, 2, tostring(gDRPercent) + "%", bgcolor = color.red, text_size = size.normal) // Place 'Gapped down & red day end percent' in table
table.cell(tble, 3, 2, tostring(gDGPercent) + "%", bgcolor = color.green, text_size = size.normal) // Place 'Gapped down & green day end percent' in table
table.cell(tble, 2, 2, tostring(gDSamples), bgcolor = color.gray, text_size = size.normal) // Place 'Total gap down events' in table |
Entry OHL 5 Min | https://www.tradingview.com/script/n8OSJn1D-Entry-OHL-5-Min/ | aneeshkuruvilla | https://www.tradingview.com/u/aneeshkuruvilla/ | 21 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © maheshpatil
//////i copied the code and made it as per mine not my orignal code and rights reseved to admin@ TRADEMASTER EDUTECH
//@version=4
study(title="TRADEMASTER 2.35", shorttitle=" TRADEMASTER 2.35 ", overlay=true)
up5on = input(true, title="5 Minute Opening Range High")
down5on = input(true, title="5 Minute Opening Range Low")
is_newbar(res) => change(time(res)) != 0
adopt(r, s) => security(syminfo.tickerid, r, s)
//high_range = valuewhen(is_newbar('D'),high,0)
//low_range = valuewhen(is_newbar('D'),low,0)
high_rangeL = valuewhen(is_newbar('D'),high,0)
low_rangeL = valuewhen(is_newbar('D'),low,0)
diff = (high_rangeL-low_rangeL)/2.35
up5 = plot(up5on ? adopt('5', high_rangeL): na, color = #009900, linewidth=1,style=plot.style_line)
down5 = plot(down5on ? adopt('5', low_rangeL): na, color = #ff0000, linewidth=1,style=plot.style_line)
diffup5 = plot(up5on ? adopt('5', (high_rangeL+diff)): na, color = #009900, linewidth=1,style=plot.style_line)
diffdown5 = plot(down5on ? adopt('5', (low_rangeL-diff)): na, color = #ff0000, linewidth=1,style=plot.style_line)
|
SSR Advance Psychological Level V1 | https://www.tradingview.com/script/LRGPTyiL-SSR-Advance-Psychological-Level-V1/ | SSR_1974 | https://www.tradingview.com/u/SSR_1974/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Babuliray
//@version=5
indicator(title="SSR Advance Psychological Level for Nifty and BankNifty V1", overlay=true)
string tfInput = input.timeframe("D", "Timeframe")
// Create variables
var D_Open = 0.0
var PSY = 0.0
var HiPSY = float(na)
var LoPSY = float(na)
var hipsy_X = float(na)
var hipsy_Y = float(na)
var lopsy_X = float(na)
var lopsy_Y = float(na)
var box hipsyBox = na
var box lopsyBox = na
var line hiline = na
var line loline = na
var bool newDayStart = na
//if syminfo.type =="index"
// See if a new calendar day started on the intra-day time frame
newDayStart := dayofmonth != dayofmonth[1] and
timeframe.isintraday
// If a new day starts, set the set the Psychological labels from opening price.
if newDayStart
D_Open := open
PSY := math.round(D_Open/1000)*1000
if (PSY > D_Open)
HiPSY := PSY
LoPSY := PSY - 500
else
HiPSY := PSY +500
LoPSY := PSY
hipsy_X := HiPSY + 50
hipsy_Y := HiPSY - 50
lopsy_X := LoPSY + 50
lopsy_Y := LoPSY - 50
else
// if level breaks either color change for violation for psychocological levels
if close > hipsy_X or close < lopsy_Y
if close > hipsy_X
box.set_bgcolor(hipsyBox, color.new(color.orange, 50))
box.set_bgcolor(lopsyBox, color.new(color.lime, 50))
if close < lopsy_Y
box.set_bgcolor(lopsyBox, color.new(color.lime, 50))
box.set_bgcolor(hipsyBox, color.new(color.orange, 50))
PSY := math.round(close/1000)*1000
if PSY > close
HiPSY := PSY
LoPSY := PSY - 500
else
HiPSY := PSY +500
LoPSY := PSY
hipsy_X := HiPSY + 50
hipsy_Y := HiPSY - 50
lopsy_X := LoPSY + 50
lopsy_Y := LoPSY - 50
hipsyBox := box.new(bar_index - 1, hipsy_X, bar_index, hipsy_Y, border_color = color.new(color.red,85), bgcolor = color.new(color.red, 25 ))
lopsyBox := box.new(bar_index - 1, lopsy_X, bar_index, lopsy_Y, border_color = color.new(color.green,85), bgcolor = color.new(color.green,25))
//hiline := line.new(bar_index , D_Open, bar_index, D_Open, color = color.new(color.green, 30), width = 10)
//loline := line.new(bar_index , BoxLev, bar_index, BoxLev, color = color.new(color.green, 30), width = Lwidth)
// color changing during price enter/reverse into/from Psychlogical level
if close > hipsy_Y and close < HiPSY
box.set_bgcolor(hipsyBox, color.new(color.red, math.round(close)- hipsy_Y +25))
if close < hipsy_X and close > HiPSY
box.set_bgcolor(hipsyBox, color.new(color.green, hipsy_X - math.round(close)+25))
if close < lopsy_X and close > LoPSY
box.set_bgcolor(lopsyBox, color.new(color.green, lopsy_X - math.round(close) +25 ))
if close > lopsy_Y and close < LoPSY
box.set_bgcolor(lopsyBox, color.new(color.red, math.round(close) - lopsy_Y +25))
if close < hipsy_Y
box.set_bgcolor(hipsyBox, color.new(color.red, 25 ))
if close > lopsy_X
box.set_bgcolor(lopsyBox, color.new(color.green,25))
// When a new day start, create both phychological levels.
// Else, during the day, update that day's box.
bool newTF = ta.change(time(tfInput))
if newTF
if newDayStart
hipsyBox := box.new(bar_index - 1, hipsy_X, bar_index, hipsy_Y, border_color = color.new(color.red, 85) , bgcolor = color.new(color.red, 25 ))
lopsyBox := box.new(bar_index - 1, lopsy_X, bar_index, lopsy_Y, border_color = color.new(color.green, 85), bgcolor = color.new(color.green,25))
//hiline := line.new(bar_index , D_Open, bar_index, D_Open, color = color.new(color.green, 30), width = 10)
else
box.set_right(hipsyBox, bar_index)
box.set_right(lopsyBox, bar_index)
//line.set_x2(hiline, bar_index)
//label.new(bar_index, low, "OK") |
MACD XD | https://www.tradingview.com/script/FRk4qK0H/ | Zen_Formless | https://www.tradingview.com/u/Zen_Formless/ | 277 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Follow_market
//@version=5
indicator(title="MACD XD", shorttitle="MACD XD", max_lines_count=500, max_labels_count=500, max_bars_back=3000)
/// Plot colors ///
col_macd1 = input.color(color.blue, "MACD 线(本级别)", group="颜色设置", inline="MACD")
col_signal1 = input.color(color.red, " 信号线(本级别)", group="颜色设置", inline="MACD")
col_macd2 = input.color(color.new(color.green, 40), "MACD 线(高级别)", group="颜色设置", inline="MACD2")
col_signal2 = input.color(color.new(color.orange, 40), " 信号线(高级别)", group="颜色设置", inline="MACD2")
col_cross = input.color(color.black, "MACD 零轴上方金叉或零轴下方死叉", group="颜色设置")
show_cross = input.bool(true, "本级别 MACD 金叉死叉 ", group="颜色设置", inline="Cross")
show_cross2 = input.bool(true, "高级别 MACD 金叉死叉", group="颜色设置", inline="Cross")
col_grow_above = input.color(#26A69A, "零轴上方 上升", group="直方图", inline="Above")
col_fall_above = input.color(#B2DFDB, " 下降", group="直方图", inline="Above")
col_grow_below = input.color(#FFCDD2, "零轴下方 上升", group="直方图", inline="Below")
col_fall_below = input.color(#FF5252, " 下降", group="直方图", inline="Below")
hollow_hist = input.bool(true, "显示空心直方图", group="直方图")
show_area = input.bool(true, "显示直方图面积(红绿柱面积)", group="直方图")
col_sum_above = input.color(#26A69A, "零轴上方面积之和", group="直方图", inline="Sum")
col_sum_below = input.color(#FF5252, " 零轴下方面积之和", group="直方图", inline="Sum")
fontSize = input.string(title="直方图面积字体大小", group="直方图", defval=size.normal, options=[size.small, size.normal, size.large])
manual_ratio = input.bool(false, "手动调整面积倍数 >>", group="直方图", inline="Ratio")
ratio0 = input.float(title=" 倍数", group="直方图", defval=100.0, minval=1.0, maxval=1000000.0, inline="Ratio")
show_decimal = input.bool(true, "显示面积小数位", group="直方图")
pos_up = input.float(title="显示位置 零轴上", group="直方图", defval=1.2, minval=1.0, maxval=10.0, inline="Position")
pos_down = input.float(title=" 零轴下", group="直方图", defval=1.75, minval=1.0, maxval=10.0, inline="Position")
show_line = input.bool(true, "显示背离指示线", group="背离指示线")
col_div_top = input.color(color.purple, "顶背离", group="背离指示线", inline="Div")
col_div_bottom = input.color(color.purple, " 底背离", group="背离指示线", inline="Div")
line_style = input.string(title="指示线类型", group="背离指示线", defval=line.style_dotted, options=[line.style_solid, line.style_dashed, line.style_dotted])
line_width = input.int(title="指示线宽", group="背离指示线", defval=1, minval=1, maxval=3)
show_DD = input.bool(true, "显示多空提示标签", group="多空提示")
col_bottom = input.color(color.new(color.green, 80), "标签颜色 多", group="多空提示", inline="DD")
col_top = input.color(color.new(color.orange, 80), " 空", group="多空提示", inline="DD")
col_DD = input.color(color.new(color.black, 10), "标签文字 颜色", group="多空提示", inline="DD2")
fontSize2 = input.string(title=" 大小", group="多空提示", defval=size.small, options=[size.tiny, size.small, size.normal], inline="DD2")
/// Getting inputs ///
macd_ratio = input.float(title="MACD 和信号线", group="调整显示比例", minval = 0.2, maxval = 3.0, defval = 1.0, tooltip="将此数值设为1可恢复原始 MACD 设置")
hist_ratio = input.float(title="直方图", group="调整显示比例", minval = 0.5, maxval = 3.0, defval = 2.0, tooltip="将此数值设为1可恢复原始 MACD 设置")
src = input.source(title="来源", group="输入设置", defval=close)
sma_source = input.string(title="震荡 MA 类型", group="输入设置", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="信号线 MA 类型", group="输入设置", defval="EMA", options=["SMA", "EMA"])
fast_length1 = input.int(title="快线长度", group="本级别直方图、MACD 线和信号线", defval=12)
slow_length1 = input.int(title="慢线长度", group="本级别直方图、MACD 线和信号线", defval=26)
signal_length1 = input.int(title="信号平滑", group="本级别直方图、MACD 线和信号线", minval = 1, maxval = 50, defval = 9)
fast_length2 = input.int(title="快线长度", group="高级别直方图、MACD 线和信号线", defval=66)
slow_length2 = input.int(title="慢线长度", group="高级别直方图、MACD 线和信号线", defval=143)
signal_length2 = input.int(title="信号平滑", group="高级别直方图、MACD 线和信号线", minval = 1, maxval = 100, defval = 50)
/// Calculations ///
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length1) : ta.ema(src, fast_length1)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length1) : ta.ema(src, slow_length1)
macd1 = fast_ma - slow_ma
signal1 = sma_signal == "SMA" ? ta.sma(macd1, signal_length1) : ta.ema(macd1, signal_length1)
hist1 = macd1 - signal1
macd2 = ta.ema(src, fast_length2) - ta.ema(src, slow_length2)
signal2 = ta.ema(macd2, signal_length2)
hist2 = macd2 - signal2
var ratio = close<10.0 ? 1000.0/close : 1.0
if manual_ratio
ratio := ratio0
//plot(hist1*hist_ratio, title="直方图(本级别)", style=plot.style_columns, color=(hist1 >= 0 ? (hist1[1] < hist1 ? col_grow_above : col_fall_above) : (hist1[1] < hist1 ? col_grow_below : col_fall_below)))
//plotcandle(hist1*hist_ratio, hist1*hist_ratio, 0, 0, title="直方图(本级别)", color=(hist1 >= 0 ? (hist1[1] < hist1 ? na : col_grow_above) : (hist1[1] < hist1 ? na : col_fall_below)), bordercolor=(hist1 >= 0 ? (hist1[1] < hist1 ? col_grow_above : col_grow_above) : (hist1[1] < hist1 ? col_fall_below : col_fall_below)), wickcolor=na)
col1 = hist1 >= 0 ? (hist1[1] < hist1 ? na : col_grow_above) : (hist1[1] < hist1 ? na : col_fall_below)
col2 = hist1 >= 0 ? (hist1[1] < hist1 ? col_grow_above : col_fall_above) : (hist1[1] < hist1 ? col_grow_below : col_fall_below)
plotcandle(hist1*hist_ratio, hist1*hist_ratio, 0, 0, title="直方图(本级别)", color=hollow_hist?col1:col2, bordercolor=hollow_hist?(hist1 >= 0 ? (hist1[1] < hist1 ? col_grow_above : col_grow_above) : (hist1[1] < hist1 ? col_fall_below : col_fall_below)):col2, wickcolor=na)
plot(0, title="零轴", color=color.new(color.gray, 30))
m1 = plot(macd1*macd_ratio, title="MACD 线(本级别)", color=col_macd1, linewidth=1)
s1 = plot(signal1*macd_ratio, title="信号线(本级别)", color=col_signal1, linewidth=1)
m2 = plot(macd2*macd_ratio, title="MACD 线(高级别)", color=col_macd2, linewidth=1)
s2 = plot(signal2*macd_ratio, title="信号线(高级别)", color=col_signal2, linewidth=1)
fill(m1, s1, title="MACD 背景色 (本级别)", color=hist1>0?(hist1>hist1[1]?color.new(color.blue, 80):color.new(color.blue, 90)):(hist1<hist1[1]?color.new(color.red, 75):color.new(color.red, 85)))
fill(m2, s2, title="MACD 背景色 (高级别)", color=hist2>0?(hist2>hist2[1]?color.new(color.green, 80):color.new(color.green, 90)):(hist2<hist2[1]?color.new(color.orange, 75):color.new(color.orange, 85)))
if show_cross and hist1[1] * hist1 < 0
label.new(bar_index, macd1/macd_ratio, (macd1[1]<signal1[1] and macd1>signal1)?'▲':(macd1[1]>signal1[1] and macd1<signal1)?'▼':na, style=label.style_none, textcolor=(macd1[1]<signal1[1] and macd1>signal1)?(macd1>0?col_cross:col_macd1):(macd1[1]>signal1[1] and macd1<signal1)?(macd1<0?col_cross:col_signal1):na)
if show_cross2 and hist2[1] * hist2 < 0
label.new(bar_index, macd2/macd_ratio, (macd2[1]<signal2[1] and macd2>signal2)?'▲':(macd2[1]>signal2[1] and macd2<signal2)?'▼':na, style=label.style_none, textcolor=(macd2[1]<signal2[1] and macd2>signal2)?col_macd2:(macd2[1]>signal2[1] and macd2<signal2)?col_signal2:na)
/// Histogram sums ///
var histM = float(na), var lastHistM = float(na), var llastHistM = float(na), var sum = float(na), var lastSum = float(na), var llastSum = float(na), var barM = int(na), var lastBarM = int(na), var llastBarM = int(na), var line lDiv = na, var label lSum = na, var label lDD = na
var peak = float(na), var lastPeak = float(na), var llastPeak = float(na), var bar0 = int(na)
if hist1[1] * hist1 < 0
if show_area
if show_decimal
label.new(barM, sum>0?(histM*hist_ratio*pos_up):(histM*hist_ratio*pos_down), sum>0?str.format("{0,number,#.#}",sum*macd_ratio):str.format("{0,number,#.#}",sum*(-macd_ratio)), style=label.style_none, textcolor=sum>0?col_sum_above:col_sum_below, yloc=yloc.price, size=fontSize)
else
label.new(barM, sum>0?(histM*hist_ratio*pos_up):(histM*hist_ratio*pos_down), sum>0?str.format("{0,number,integer}",sum*macd_ratio):str.format("{0,number,integer}",sum*(-macd_ratio)), style=label.style_none, textcolor=sum>0?col_sum_above:col_sum_below, yloc=yloc.price, size=fontSize)
llastSum := lastSum, lastSum := sum, llastBarM := lastBarM, lastBarM := barM
llastPeak := lastPeak, lastPeak := peak, llastHistM := lastHistM, lastHistM := histM
sum := hist1 * ratio, histM := hist1, barM := bar_index, bar0 := bar_index, peak := hist1 > 0 ? high : low
else
if hist1 > 0 and hist1 >= histM or hist1 < 0 and hist1 <= histM
histM := hist1, barM := bar_index
if hist1 > 0 and high >= peak or hist1 < 0 and low <= peak
peak := hist1 > 0 ? high : low, bar0 := bar_index
sum := sum + hist1 * ratio
if show_area
label.delete(lSum)
if show_decimal
lSum := label.new(barM, sum>0?(histM*hist_ratio*pos_up):(histM*hist_ratio*pos_down), sum>0?str.format("{0,number,#.#}",sum*macd_ratio):str.format("{0,number,#.#}",sum*(-macd_ratio)), style=label.style_none, textcolor=sum>0?col_sum_above:col_sum_below, yloc=yloc.price, size=fontSize)
else
lSum := label.new(barM, sum>0?(histM*hist_ratio*pos_up):(histM*hist_ratio*pos_down), sum>0?str.format("{0,number,integer}",sum*macd_ratio):str.format("{0,number,integer}",sum*(-macd_ratio)), style=label.style_none, textcolor=sum>0?col_sum_above:col_sum_below, yloc=yloc.price, size=fontSize)
if llastHistM > 0 and histM > 0 and macd1 > 0
if show_line and line.get_y2(lDiv) > 0 and line.get_x2(lDiv) == barM[1]
line.delete(lDiv)
if label.get_x(lDD) == bar0[1]
label.delete(lDD)
if peak > llastPeak and sum < llastSum and histM < llastHistM
if show_line
lDiv := line.new(llastBarM, llastHistM*hist_ratio, barM, histM*hist_ratio, color=col_div_top, style=line_style, width=line_width)
if show_DD
lDD := label.new(bar0, histM*hist_ratio, "空", style=label.style_label_down, color=col_top, textcolor=col_DD, yloc=yloc.price, size=fontSize2)
if llastHistM < 0 and histM < 0 and macd1 < 0
if show_line and line.get_y2(lDiv) < 0 and line.get_x2(lDiv) == barM[1]
line.delete(lDiv)
if label.get_x(lDD) == bar0[1]
label.delete(lDD)
if peak < llastPeak and sum > llastSum and histM > llastHistM
if show_line
lDiv := line.new(llastBarM, llastHistM*hist_ratio, barM, histM*hist_ratio, color=col_div_bottom, style=line_style, width=line_width)
if show_DD
lDD := label.new(bar0, histM*hist_ratio, "多", style=label.style_label_up, color=col_bottom, textcolor=col_DD, yloc=yloc.price, size=fontSize2)
/// Alert conditions ///
alertcondition(label.get_x(lDD[1])<label.get_x(lDD), "多空信号", "出现多空信号")
alertcondition(macd1[1]<signal1[1] and macd1>signal1, "本级别 MACD 金叉", "出现本级别 MACD 金叉")
alertcondition(macd1[1]>signal1[1] and macd1<signal1, "本级别 MACD 死叉", "出现本级别 MACD 死叉")
alertcondition(macd2[1]<signal2[1] and macd2>signal2, "高级别 MACD 金叉", "出现高级别 MACD 金叉")
alertcondition(macd2[1]>signal2[1] and macd2<signal2, "高级别 MACD 死叉", "出现高级别 MACD 死叉")
alertcondition(math.min(hist1,hist1[1],hist1[2])>0 and hist1[2]<hist1[3] and hist1[1]<hist1[2] and hist1>hist1[1], "绿柱力度由弱变强", "绿柱力度由弱变强")
alertcondition(math.min(hist1,hist1[1],hist1[2])>0 and hist1[2]>hist1[3] and hist1[1]>hist1[2] and hist1<hist1[1], "绿柱力度由强变弱", "绿柱力度由强变弱")
alertcondition(math.max(hist1,hist1[1],hist1[2])<0 and hist1[2]<hist1[3] and hist1[1]<hist1[2] and hist1>hist1[1], "红柱力度由强变弱", "红柱力度由强变弱")
alertcondition(math.max(hist1,hist1[1],hist1[2])<0 and hist1[2]>hist1[3] and hist1[1]>hist1[2] and hist1<hist1[1], "红柱力度由弱变强", "红柱力度由弱变强")
/// END /// |
Multi-timeframe EMA | https://www.tradingview.com/script/nCvMqyql-Multi-timeframe-EMA/ | Snufkin420TC | https://www.tradingview.com/u/Snufkin420TC/ | 166 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Snufkin420TC
// Developed with Dumpster Capital and published sans secret sauce
//@version=5
indicator("EMA", overlay=true)
// Create non-repainting security function
fix_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
// Select which EMAs to plot
string EMAs = input.string("Standard", title = "EMAs to show", options = ["Standard", "Fibonacci"])
// User settings
source = input.source(defval=ohlc4, title="Source")
EMA_length = input.int(20, title = "EMA length")
tp = input.float(0, title = "Transparency", minval=0, maxval=100)
visible = input.bool(defval=false, title = "Show only near-timeframe EMAs")
//get Timeframe of current chart and convert to a score for timeframe detection based switches
timeframe = timeframe.period
framescore = 0
framescore := if (timeframe == "M")
13
else if (timeframe == "W")
12
else if (timeframe == "D")
11
else if (timeframe == "240")
10
else if (timeframe == "180")
9
else if (timeframe == "120")
8
else if (timeframe == "60")
7
else if (timeframe == "45")
6
else if (timeframe == "30")
5
else if (timeframe == "15")
4
else if (timeframe == "5")
3
else if (timeframe == "3")
2
else if (timeframe == "1")
1
else
0
//Initialize EMAs
EMA1 = 0.0
EMA2 = 0.0
EMA3 = 0.0
EMA4 = 0.0
EMA5 = 0.0
EMA6 = 0.0
EMA7 = 0.0
EMA8 = 0.0
EMA9 = 0.0
EMA10 = 0.0
EMA11 = 0.0
EMA12 = 0.0
EMA13 = 0.0
EMA14 = 0.0
EMA15 = 0.0
EMA16 = 0.0
// Calculate EMAs
if (EMAs == 'Standard' and visible == false)
EMA1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.ema(source,EMA_length)) : na
EMA2 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.ema(source,EMA_length)) : na
EMA3 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', ta.ema(source,EMA_length)) : na
EMA4 := (framescore <= 4) ? fix_security(syminfo.tickerid, '15', ta.ema(source,EMA_length)) : na
EMA5 := (framescore <= 5) ? fix_security(syminfo.tickerid,'30', ta.ema(source,EMA_length)) : na
EMA6 := (framescore <= 7) ? fix_security(syminfo.tickerid,'60', ta.ema(source,EMA_length)) : na
EMA7 := (framescore <= 8) ? fix_security(syminfo.tickerid, '120', ta.ema(source,EMA_length)) : na
EMA8 := (framescore <= 10) ? fix_security(syminfo.tickerid, '240', ta.ema(source,EMA_length)) : na
EMA9 := (framescore <= 10) ? fix_security(syminfo.tickerid, '480', ta.ema(source,EMA_length)) : na
EMA10 := (framescore <= 11) ? fix_security(syminfo.tickerid, 'D', ta.ema(source,EMA_length)) : na
EMA11 := (framescore <= 12) ? fix_security(syminfo.tickerid, 'W', ta.ema(source,EMA_length)) : na
EMA12 := (framescore <= 13) ? fix_security(syminfo.tickerid, 'M', ta.ema(source,EMA_length)) : na
EMA13 := (framescore <= 14) ? fix_security(syminfo.tickerid, '3M', ta.ema(source,EMA_length)) : na
EMA14 := na
EMA15 := na
EMA16 := na
if (EMAs == 'Standard' and visible == true)
EMA1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.ema(source,EMA_length)) : na
EMA2 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.ema(source,EMA_length)) : na
EMA3 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', ta.ema(source,EMA_length)) : na
EMA4 := (framescore <= 4) ? fix_security(syminfo.tickerid, '15', ta.ema(source,EMA_length)) : na
EMA5 := (framescore <= 5) ? fix_security(syminfo.tickerid,'30', ta.ema(source,EMA_length)) : na
EMA6 := (framescore <= 7) ? fix_security(syminfo.tickerid,'60', ta.ema(source,EMA_length)) : na
EMA7 := (framescore <= 8 and framescore > 1) ? fix_security(syminfo.tickerid, '120', ta.ema(source,EMA_length)) : na
EMA8 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '240', ta.ema(source,EMA_length)) : na
EMA9 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '480', ta.ema(source,EMA_length)) : na
EMA10 := (framescore <= 11 and framescore > 4) ? fix_security(syminfo.tickerid, 'D', ta.ema(source,EMA_length)) : na
EMA11 := (framescore <= 12 and framescore > 5) ? fix_security(syminfo.tickerid, 'W', ta.ema(source,EMA_length)) : na
EMA12 := (framescore <= 13 and framescore > 6) ? fix_security(syminfo.tickerid, 'M', ta.ema(source,EMA_length)) : na
EMA13 := (framescore <= 14 and framescore > 7) ? fix_security(syminfo.tickerid, '3M', ta.ema(source,EMA_length)) : na
EMA14 := na
EMA15 := na
EMA16 := na
else if (EMAs == 'Fibonacci' and visible == false)
EMA1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.ema(source,EMA_length)) : na
EMA2 := (framescore <= 1) ? fix_security(syminfo.tickerid, '2', ta.ema(source,EMA_length)) : na
EMA3 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.ema(source,EMA_length)) : na
EMA4 := (framescore <= 3) ? fix_security(syminfo.tickerid,'5', ta.ema(source,EMA_length)) : na
EMA5 := (framescore <= 3) ? fix_security(syminfo.tickerid, '8', ta.ema(source,EMA_length)) : na
EMA6 := (framescore <= 3) ? fix_security(syminfo.tickerid, '13', ta.ema(source,EMA_length)) : na
EMA7 := (framescore <= 4) ? fix_security(syminfo.tickerid, '21', ta.ema(source,EMA_length)) : na
EMA8 := (framescore <= 5) ? fix_security(syminfo.tickerid, '34', ta.ema(source,EMA_length)) : na
EMA9 := (framescore <= 6) ? fix_security(syminfo.tickerid, '55', ta.ema(source,EMA_length)) : na
EMA10 := (framescore <= 7) ? fix_security(syminfo.tickerid, '89', ta.ema(source,EMA_length)) : na
EMA11 := (framescore <= 8) ? fix_security(syminfo.tickerid, '144', ta.ema(source,EMA_length)) : na
EMA12 := (framescore <= 9) ? fix_security(syminfo.tickerid, '233', ta.ema(source,EMA_length)) : na
EMA13 := (framescore <= 10) ? fix_security(syminfo.tickerid, '377', ta.ema(source,EMA_length)) : na
EMA14 := (framescore <= 10) ? fix_security(syminfo.tickerid, '610', ta.ema(source,EMA_length)) : na
EMA15 := (framescore <= 10) ? fix_security(syminfo.tickerid, '987', ta.ema(source,EMA_length)) : na
EMA16 := (framescore <= 11) ? fix_security(syminfo.tickerid, 'D', ta.ema(source,EMA_length)) : na
else if (EMAs == 'Fibonacci' and visible == true)
EMA1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.ema(source,EMA_length)) : na
EMA2 := (framescore <= 1) ? fix_security(syminfo.tickerid, '2', ta.ema(source,EMA_length)) : na
EMA3 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.ema(source,EMA_length)) : na
EMA4 := (framescore <= 3) ? fix_security(syminfo.tickerid,'5', ta.ema(source,EMA_length)) : na
EMA5 := (framescore <= 3) ? fix_security(syminfo.tickerid, '8', ta.ema(source,EMA_length)) : na
EMA6 := (framescore <= 3) ? fix_security(syminfo.tickerid, '13', ta.ema(source,EMA_length)) : na
EMA7 := (framescore <= 4) ? fix_security(syminfo.tickerid, '21', ta.ema(source,EMA_length)) : na
EMA8 := (framescore <= 5) ? fix_security(syminfo.tickerid, '34', ta.ema(source,EMA_length)) : na
EMA9 := (framescore <= 6) ? fix_security(syminfo.tickerid, '55', ta.ema(source,EMA_length)) : na
EMA10 := (framescore <= 7) ? fix_security(syminfo.tickerid, '89', ta.ema(source,EMA_length)) : na
EMA11 := (framescore <= 8 and framescore > 1) ? fix_security(syminfo.tickerid, '144', ta.ema(source,EMA_length)) : na
EMA12 := (framescore <= 9 and framescore > 2) ? fix_security(syminfo.tickerid, '233', ta.ema(source,EMA_length)) : na
EMA13 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '377', ta.ema(source,EMA_length)) : na
EMA14 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '610', ta.ema(source,EMA_length)) : na
EMA15 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '987', ta.ema(source,EMA_length)) : na
EMA16 := (framescore <= 11 and framescore > 4) ? fix_security(syminfo.tickerid, 'D', ta.ema(source,EMA_length)) : na
//Default rainbow coloring
col1 = color.new(color.silver, tp)
col2 = color.new(color.lime, tp)
col3 = color.new(color.yellow, tp)
col4 = color.new(color.orange, tp)
col5 = color.new(color.red, tp)
col6 = color.new(color.fuchsia, tp)
col7 = color.new(color.purple, tp)
col8 = color.new(color.navy, tp)
col9 = color.new(color.blue, tp)
col10 = color.new(color.teal, tp)
col11 = color.new(color.green, tp)
col12 = color.new(color.olive, tp)
col13 = color.new(color.gray, tp)
col14 = color.new(color.yellow, tp)
col15 = color.new(color.orange, tp)
col16 = color.new(color.red, tp)
//plot EMAs
plot(series=EMA16, title="na/D", style=plot.style_stepline, color=col16)
plot(series=EMA15, title="na/987", style=plot.style_stepline, color=col15)
plot(series=EMA14, title="na/610", style=plot.style_stepline, color=col14)
plot(series=EMA13, title="na/377", style=plot.style_stepline, color=col13)
plot(series=EMA12, title="M/233", style=plot.style_stepline, color=col12)
plot(series=EMA11, title="W/144", style=plot.style_stepline, color=col11)
plot(series=EMA10, title="D/89", style=plot.style_stepline, color=col10)
plot(series=EMA9, title="8H/55", style=plot.style_stepline, color=col9)
plot(series=EMA8, title="4H/34", style=plot.style_stepline, color=col8)
plot(series=EMA7, title="2H/21", style=plot.style_stepline, color=col7)
plot(series=EMA6, title="60/13", style=plot.style_stepline, color=col6)
plot(series=EMA5, title="30/8", style=plot.style_stepline, color=col5)
plot(series=EMA4, title="15/5", style=plot.style_stepline, color=col4)
plot(series=EMA3, title="5/3", style=plot.style_stepline, color=col3)
plot(series=EMA2, title="3/2", style=plot.style_stepline, color=col2)
plot(series=EMA1, title="1/1", style=plot.style_stepline, color=col1)
// END // |
Multi-timeframe Momentum | https://www.tradingview.com/script/DDyJL0wm-Multi-timeframe-Momentum/ | Snufkin420TC | https://www.tradingview.com/u/Snufkin420TC/ | 120 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Snufkin420TC
// Developed with Dumpster Capital and published sans secret sauce
//@version=5
indicator("Momentum", overlay=false)
//User inputs
string MOMs = input.string("Standard", title = "Momentums", options = ["Standard", "Fibonacci"])
source = input.source(defval=ohlc4, title="Source")
EMA_length = input.int(20, title = "EMA length")
visible = input.bool(defval=true, title = "Show only near-timeframe Momentums")
momstyle = input.bool(false, title = "Linear regression", group="Linear regression")
leng = input.int(20, title = "length", group="Linear regression")
ps = input.string("area", title = "Style", options = ["area", "columns"], group="Plot style") // A plot style "line" is also available but limited by plots > 64 for now
coloring = input.string("changebow", title = "Color", options = ["rainbow", "changebow", "redgreen"], group="Plot style")
tp = input.float(0, title = "Transparency", minval=0, maxval=100, group="Plot style")
tp2 = input.float(50, title = "Transparency (leading)", minval=0, maxval=100, group="Plot style")
// Create non-repainting security function
fix_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
//get Timeframe of current chart and convert to a score for timeframe detection based switches
timeframe = timeframe.period
framescore = 0
framescore := if (timeframe == "M")
13
else if (timeframe == "W")
12
else if (timeframe == "D")
11
else if (timeframe == "240")
10
else if (timeframe == "180")
9
else if (timeframe == "120")
8
else if (timeframe == "60")
7
else if (timeframe == "45")
6
else if (timeframe == "30")
5
else if (timeframe == "15")
4
else if (timeframe == "5")
3
else if (timeframe == "3")
2
else if (timeframe == "1")
1
else
0
// Momentum style (rate-of-change smoothed with an EMA and optional further smoothing with linear regression)
momentum = ta.ema(nz(source[0] - source[1]), EMA_length)
// Initialize momentums
MOM1 = 0.0
MOM2 = 0.0
MOM3 = 0.0
MOM4 = 0.0
MOM5 = 0.0
MOM6 = 0.0
MOM7 = 0.0
MOM8 = 0.0
MOM9 = 0.0
MOM10 = 0.0
MOM11 = 0.0
MOM12 = 0.0
MOM13 = 0.0
// Momentum calculations
if (MOMs == 'Standard' and visible == false and momstyle == false)
MOM1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', momentum) : na
MOM2 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', momentum) : na
MOM3 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', momentum) : na
MOM4 := (framescore <= 4) ? fix_security(syminfo.tickerid, '15', momentum) : na
MOM5 := (framescore <= 5) ? fix_security(syminfo.tickerid,'30', momentum) : na
MOM6 := (framescore <= 7) ? fix_security(syminfo.tickerid,'60', momentum) : na
MOM7 := (framescore <= 8) ? fix_security(syminfo.tickerid, '120', momentum) : na
MOM8 := (framescore <= 10) ? fix_security(syminfo.tickerid, '240', momentum) : na
MOM9 := (framescore <= 10) ? fix_security(syminfo.tickerid, '480', momentum) : na
MOM10 := (framescore <= 11) ? fix_security(syminfo.tickerid, 'D', momentum) : na
MOM11 := (framescore <= 12) ? fix_security(syminfo.tickerid, 'W', momentum) : na
MOM12 := (framescore <= 13) ? fix_security(syminfo.tickerid, 'M', momentum) : na
MOM13 := (framescore <= 14) ? fix_security(syminfo.tickerid, '3M', momentum) : na
else if (MOMs == 'Standard' and visible == true and momstyle == false)
MOM1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', momentum) : na
MOM2 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', momentum) : na
MOM3 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', momentum) : na
MOM4 := (framescore <= 4) ? fix_security(syminfo.tickerid, '15', momentum) : na
MOM5 := (framescore <= 5) ? fix_security(syminfo.tickerid,'45', momentum) : na
MOM6 := (framescore <= 7) ? fix_security(syminfo.tickerid,'60', momentum) : na
MOM7 := (framescore <= 8 and framescore > 1) ? fix_security(syminfo.tickerid, '120', momentum) : na
MOM8 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '240', momentum) : na
MOM9 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '480', momentum) : na
MOM10 := (framescore <= 11 and framescore > 4) ? fix_security(syminfo.tickerid, 'D', momentum) : na
MOM11 := (framescore <= 12 and framescore > 5) ? fix_security(syminfo.tickerid, 'W', momentum) : na
MOM12 := (framescore <= 13 and framescore > 6) ? fix_security(syminfo.tickerid, 'M', momentum) : na
MOM13 := (framescore <= 14 and framescore > 7) ? fix_security(syminfo.tickerid, '3M', momentum) : na
else if (MOMs == 'Fibonacci' and momstyle == false)
MOM1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', momentum) : na
MOM2 := (framescore <= 1) ? fix_security(syminfo.tickerid, '2', momentum) : na
MOM3 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', momentum) : na
MOM4 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', momentum) : na
MOM5 := (framescore <= 3) ? fix_security(syminfo.tickerid,'8', momentum) : na
MOM6 := (framescore <= 3) ? fix_security(syminfo.tickerid,'13', momentum) : na
MOM7 := (framescore <= 4) ? fix_security(syminfo.tickerid, '21', momentum) : na
MOM8 := (framescore <= 5) ? fix_security(syminfo.tickerid, '34', momentum) : na
MOM9 := (framescore <= 6) ? fix_security(syminfo.tickerid, '55', momentum) : na
MOM10 := na
MOM11 := na
MOM12 := na
MOM13 := na
else if (MOMs == 'Standard' and visible == false and momstyle == true)
MOM1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.linreg(momentum, leng ,0)) : na
MOM2 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.linreg(momentum, leng ,0)) : na
MOM3 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', ta.linreg(momentum, leng ,0)) : na
MOM4 := (framescore <= 4) ? fix_security(syminfo.tickerid, '15', ta.linreg(momentum, leng ,0)) : na
MOM5 := (framescore <= 5) ? fix_security(syminfo.tickerid,'30', ta.linreg(momentum, leng ,0)) : na
MOM6 := (framescore <= 7) ? fix_security(syminfo.tickerid,'60', ta.linreg(momentum, leng ,0)) : na
MOM7 := (framescore <= 8) ? fix_security(syminfo.tickerid, '120', ta.linreg(momentum, leng ,0)) : na
MOM8 := (framescore <= 10) ? fix_security(syminfo.tickerid, '240', ta.linreg(momentum, leng ,0)) : na
MOM9 := (framescore <= 10) ? fix_security(syminfo.tickerid, '480', ta.linreg(momentum, leng ,0)) : na
MOM10 := (framescore <= 11) ? fix_security(syminfo.tickerid, 'D', ta.linreg(momentum, leng ,0)) : na
MOM11 := (framescore <= 12) ? fix_security(syminfo.tickerid, 'W', ta.linreg(momentum, leng ,0)) : na
MOM12 := (framescore <= 13) ? fix_security(syminfo.tickerid, 'M', ta.linreg(momentum, leng ,0)) : na
MOM13 := (framescore <= 14) ? fix_security(syminfo.tickerid, '3M', ta.linreg(momentum, leng ,0)) : na
else if (MOMs == 'Standard' and visible == true and momstyle == true)
MOM1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.linreg(momentum, leng ,0)) : na
MOM2 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.linreg(momentum, leng ,0)) : na
MOM3 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', ta.linreg(momentum, leng ,0)) : na
MOM4 := (framescore <= 4) ? fix_security(syminfo.tickerid, '15', ta.linreg(momentum, leng ,0)) : na
MOM5 := (framescore <= 5) ? fix_security(syminfo.tickerid,'45', ta.linreg(momentum, leng ,0)) : na
MOM6 := (framescore <= 7) ? fix_security(syminfo.tickerid,'60', ta.linreg(momentum, leng ,0)) : na
MOM7 := (framescore <= 8 and framescore > 1) ? fix_security(syminfo.tickerid, '120', ta.linreg(momentum, leng ,0)) : na
MOM8 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '240', ta.linreg(momentum, leng ,0)) : na
MOM9 := (framescore <= 10 and framescore > 3) ? fix_security(syminfo.tickerid, '480', ta.linreg(momentum, leng ,0)) : na
MOM10 := (framescore <= 11 and framescore > 4) ? fix_security(syminfo.tickerid, 'D', ta.linreg(momentum, leng ,0)) : na
MOM11 := (framescore <= 12 and framescore > 5) ? fix_security(syminfo.tickerid, 'W', ta.linreg(momentum, leng ,0)) : na
MOM12 := (framescore <= 13 and framescore > 6) ? fix_security(syminfo.tickerid, 'M', ta.linreg(momentum, leng ,0)) : na
MOM13 := (framescore <= 14 and framescore > 7) ? fix_security(syminfo.tickerid, '3M', ta.linreg(momentum, leng ,0)) : na
else if (MOMs == 'Fibonacci' and momstyle == true)
MOM1 := (framescore <= 1) ? fix_security(syminfo.tickerid, '1', ta.linreg(momentum, leng ,0)) : na
MOM2 := (framescore <= 1) ? fix_security(syminfo.tickerid, '2', ta.linreg(momentum, leng ,0)) : na
MOM3 := (framescore <= 2) ? fix_security(syminfo.tickerid, '3', ta.linreg(momentum, leng ,0)) : na
MOM4 := (framescore <= 3) ? fix_security(syminfo.tickerid, '5', ta.linreg(momentum, leng ,0)) : na
MOM5 := (framescore <= 3) ? fix_security(syminfo.tickerid,'8', ta.linreg(momentum, leng ,0)) : na
MOM6 := (framescore <= 3) ? fix_security(syminfo.tickerid,'13', ta.linreg(momentum, leng ,0)) : na
MOM7 := (framescore <= 4) ? fix_security(syminfo.tickerid, '21', ta.linreg(momentum, leng ,0)) : na
MOM8 := (framescore <= 5) ? fix_security(syminfo.tickerid, '34', ta.linreg(momentum, leng ,0)) : na
MOM9 := (framescore <= 6) ? fix_security(syminfo.tickerid, '55', ta.linreg(momentum, leng ,0)) : na
MOM10 := na
MOM11 := na
MOM12 := na
MOM13 := na
// Default rainbow coloring
col1 = color.new(color.silver, tp)
col2 = color.new(color.lime, tp)
col3 = color.new(color.yellow, tp)
col4 = color.new(color.orange, tp)
col5 = color.new(color.red, tp)
col6 = color.new(color.fuchsia, tp)
col7 = color.new(color.purple, tp)
col8 = color.new(color.navy, tp)
col9 = color.new(color.blue, tp)
col10 = color.new(color.teal, tp)
col11 = color.new(color.green, tp)
col12 = color.new(color.olive, tp)
col13 = color.new(color.gray, tp)
// Calculate changing colors
if (coloring == 'changebow')
col1 := (MOM1 > 0) ? ((MOM1 > MOM1[1]) ? color.new(color.silver, tp2) : ((MOM1 < MOM1[1]) ? color.new(color.silver, tp) : col1[1])) : ((MOM1 < MOM1[1]) ? color.new(color.silver, tp2) : ((MOM1 > MOM1[1]) ? color.new(color.silver, tp) : col1[1]))
col2 := (MOM2 > 0) ? ((MOM2 > MOM2[1]) ? color.new(color.lime, tp2) : ((MOM2 < MOM2[1]) ? color.new(color.lime, tp) : col2[1])) : ((MOM2 < MOM2[1]) ? color.new(color.lime, tp2) : ((MOM2 > MOM2[1]) ? color.new(color.lime, tp) : col2[1]))
col3 := (MOM3 > 0) ? ((MOM3 > MOM3[1]) ? color.new(color.yellow, tp2) : ((MOM3 < MOM3[1]) ? color.new(color.yellow, tp) : col3[1])) : ((MOM3 < MOM3[1]) ? color.new(color.yellow, tp2) : ((MOM3 > MOM3[1]) ? color.new(color.yellow, tp) : col3[1]))
col4 := (MOM4 > 0) ? ((MOM4 > MOM4[1]) ? color.new(color.orange, tp2) : ((MOM4 < MOM4[1]) ? color.new(color.orange, tp) : col4[1])) : ((MOM4 < MOM4[1]) ? color.new(color.orange, tp2) : ((MOM4 > MOM4[1]) ? color.new(color.orange, tp) : col4[1]))
col5 := (MOM5 > 0) ? ((MOM5 > MOM5[1]) ? color.new(color.red, tp2) : ((MOM5 < MOM5[1]) ? color.new(color.red, tp) : col5[1])) : ((MOM5 < MOM5[1]) ? color.new(color.red, tp2) : ((MOM5 > MOM5[1]) ? color.new(color.red, tp) : col5[1]))
col6 := (MOM6 > 0) ? ((MOM6 > MOM6[1]) ? color.new(color.fuchsia, tp2) : ((MOM6 < MOM6[1]) ? color.new(color.fuchsia, tp) : col6[1])) : ((MOM6 < MOM6[1]) ? color.new(color.fuchsia, tp2) : ((MOM6 > MOM6[1]) ? color.new(color.fuchsia, tp) : col6[1]))
col7 := (MOM7 > 0) ? ((MOM7 > MOM7[1]) ? color.new(color.purple, tp2) : ((MOM7 < MOM7[1]) ? color.new(color.purple, tp) : col7[1])) : ((MOM7 < MOM7[1]) ? color.new(color.purple, tp2) : ((MOM7 > MOM7[1]) ? color.new(color.purple, tp) : col7[1]))
col8 := (MOM8 > 0) ? ((MOM8 > MOM8[1]) ? color.new(color.navy, tp2) : ((MOM8 < MOM8[1]) ? color.new(color.navy, tp) : col8[1])) : ((MOM8 < MOM8[1]) ? color.new(color.navy, tp2) : ((MOM8 > MOM8[1]) ? color.new(color.navy, tp) : col8[1]))
col9 := (MOM9 > 0) ? ((MOM9 > MOM9[1]) ? color.new(color.blue, tp2) : ((MOM9 < MOM9[1]) ? color.new(color.blue, tp) : col9[1])) : ((MOM9 < MOM9[1]) ? color.new(color.blue, tp2) : ((MOM9 > MOM9[1]) ? color.new(color.blue, tp) : col9[1]))
col10 := (MOM10 > 0) ? ((MOM10 > MOM10[1]) ? color.new(color.teal, tp2) : ((MOM10 < MOM10[1]) ? color.new(color.teal, tp) : col10[1])) : ((MOM10 < MOM10[1]) ? color.new(color.teal, tp2) : ((MOM10 > MOM10[1]) ? color.new(color.teal, tp) : col10[1]))
col11 := (MOM11 > 0) ? ((MOM11 > MOM11[1]) ? color.new(color.green, tp2) : ((MOM11 < MOM11[1]) ? color.new(color.green, tp) : col11[1])) : ((MOM11 < MOM11[1]) ? color.new(color.green, tp2) : ((MOM11 > MOM11[1]) ? color.new(color.green, tp) : col11[1]))
col12 := (MOM12 > 0) ? ((MOM12 > MOM12[1]) ? color.new(color.olive, tp2) : ((MOM12 < MOM12[1]) ? color.new(color.olive, tp) : col12[1])) : ((MOM12 < MOM12[1]) ? color.new(color.olive, tp2) : ((MOM12 > MOM12[1]) ? color.new(color.olive, tp) : col12[1]))
col13 := (MOM13 > 0) ? ((MOM13 > MOM13[1]) ? color.new(color.gray, tp2) : ((MOM13 < MOM13[1]) ? color.new(color.gray, tp) : col13[1])) : ((MOM13 < MOM13[1]) ? color.new(color.gray, tp2) : ((MOM13 > MOM13[1]) ? color.new(color.gray, tp) : col13[1]))
else if (coloring == 'redgreen')
col1 := (MOM1 > 0) ? ((MOM1 > MOM1[1]) ? color.new(color.lime, tp) : ((MOM1 < MOM1[1]) ? color.new(color.green, tp) : col1[1])) : ((MOM1 < MOM1[1]) ? color.new(color.red, tp) : ((MOM1 > MOM1[1]) ? color.new(color.maroon, tp) : col1[1]))
col2 := (MOM2 > 0) ? ((MOM2 > MOM2[1]) ? color.new(color.lime, tp) : ((MOM2 < MOM2[1]) ? color.new(color.green, tp) : col2[1])) : ((MOM2 < MOM2[1]) ? color.new(color.red, tp) : ((MOM2 > MOM2[1]) ? color.new(color.maroon, tp) : col2[1]))
col3 := (MOM3 > 0) ? ((MOM3 > MOM3[1]) ? color.new(color.lime, tp) : ((MOM3 < MOM3[1]) ? color.new(color.green, tp) : col3[1])) : ((MOM3 < MOM3[1]) ? color.new(color.red, tp) : ((MOM3 > MOM3[1]) ? color.new(color.maroon, tp) : col3[1]))
col4 := (MOM4 > 0) ? ((MOM4 > MOM4[1]) ? color.new(color.lime, tp) : ((MOM4 < MOM4[1]) ? color.new(color.green, tp) : col4[1])) : ((MOM4 < MOM4[1]) ? color.new(color.red, tp) : ((MOM4 > MOM4[1]) ? color.new(color.maroon, tp) : col4[1]))
col5 := (MOM5 > 0) ? ((MOM5 > MOM5[1]) ? color.new(color.lime, tp) : ((MOM5 < MOM5[1]) ? color.new(color.green, tp) : col5[1])) : ((MOM5 < MOM5[1]) ? color.new(color.red, tp) : ((MOM5 > MOM5[1]) ? color.new(color.maroon, tp) : col5[1]))
col6 := (MOM6 > 0) ? ((MOM6 > MOM6[1]) ? color.new(color.lime, tp) : ((MOM6 < MOM6[1]) ? color.new(color.green, tp) : col6[1])) : ((MOM6 < MOM6[1]) ? color.new(color.red, tp) : ((MOM6 > MOM6[1]) ? color.new(color.maroon, tp) : col6[1]))
col7 := (MOM7 > 0) ? ((MOM7 > MOM7[1]) ? color.new(color.lime, tp) : ((MOM7 < MOM7[1]) ? color.new(color.green, tp) : col7[1])) : ((MOM7 < MOM7[1]) ? color.new(color.red, tp) : ((MOM7 > MOM7[1]) ? color.new(color.maroon, tp) : col7[1]))
col8 := (MOM8 > 0) ? ((MOM8 > MOM8[1]) ? color.new(color.lime, tp) : ((MOM8 < MOM8[1]) ? color.new(color.green, tp) : col8[1])) : ((MOM8 < MOM8[1]) ? color.new(color.red, tp) : ((MOM8 > MOM8[1]) ? color.new(color.maroon, tp) : col8[1]))
col9 := (MOM9 > 0) ? ((MOM9 > MOM9[1]) ? color.new(color.lime, tp) : ((MOM9 < MOM9[1]) ? color.new(color.green, tp) : col9[1])) : ((MOM9 < MOM9[1]) ? color.new(color.red, tp) : ((MOM9 > MOM9[1]) ? color.new(color.maroon, tp) : col9[1]))
col10 := (MOM10 > 0) ? ((MOM10 > MOM10[1]) ? color.new(color.lime, tp) : ((MOM10 < MOM10[1]) ? color.new(color.green, tp) : col10[1])) : ((MOM10 < MOM10[1]) ? color.new(color.red, tp) : ((MOM10 > MOM10[1]) ? color.new(color.maroon, tp) : col10[1]))
col11 := (MOM11 > 0) ? ((MOM11 > MOM11[1]) ? color.new(color.lime, tp) : ((MOM11 < MOM11[1]) ? color.new(color.green, tp) : col11[1])) : ((MOM11 < MOM11[1]) ? color.new(color.red, tp) : ((MOM11 > MOM11[1]) ? color.new(color.maroon, tp) : col11[1]))
col12 := (MOM12 > 0) ? ((MOM12 > MOM12[1]) ? color.new(color.lime, tp) : ((MOM12 < MOM12[1]) ? color.new(color.green, tp) : col12[1])) : ((MOM12 < MOM12[1]) ? color.new(color.red, tp) : ((MOM12 > MOM12[1]) ? color.new(color.maroon, tp) : col12[1]))
col13 := (MOM13 > 0) ? ((MOM13 > MOM13[1]) ? color.new(color.lime, tp) : ((MOM13 < MOM13[1]) ? color.new(color.green, tp) : col13[1])) : ((MOM13 < MOM13[1]) ? color.new(color.red, tp) : ((MOM13 > MOM13[1]) ? color.new(color.maroon, tp) : col13[1]))
//plot momentumss
hline(0, title="zero line", linestyle = hline.style_solid, color = color.new(color.white, 0))
plot(ps == "columns" ? MOM13 : na, title="columns Q", style=plot.style_columns, color=col13)
plot(ps == "columns" ? MOM12 : na, title="columns M", style=plot.style_columns, color=col12)
plot(ps == "columns" ? MOM11 : na, title="columns W", style=plot.style_columns, color=col11)
plot(ps == "columns" ? MOM10 : na, title="columns D", style=plot.style_columns, color=col10)
plot(ps == "columns" ? MOM9 : na, title="columns 240", style=plot.style_columns, color=col9)
plot(ps == "columns" ? MOM8 : na, title="columns 120", style=plot.style_columns, color=col8)
plot(ps == "columns" ? MOM7 : na, title="columns 60", style=plot.style_columns, color=col7)
plot(ps == "columns" ? MOM6 : na, title="columns 45", style=plot.style_columns, color=col6)
plot(ps == "columns" ? MOM5 : na, title="columns 30", style=plot.style_columns, color=col5)
plot(ps == "columns" ? MOM4 : na, title="columns 15", style=plot.style_columns, color=col4)
plot(ps == "columns" ? MOM3 : na, title="columns 5", style=plot.style_columns, color=col3)
plot(ps == "columns" ? MOM2 : na, title="columns 3", style=plot.style_columns, color=col2)
plot(ps == "columns" ? MOM1 : na, title="columns 1", style=plot.style_columns, color=col1)
plot(ps == "area" ? MOM13 : na, title="area Q", style=plot.style_area, color=col13)
plot(ps == "area" ? MOM12 : na, title="area M", style=plot.style_area, color=col12)
plot(ps == "area" ? MOM11 : na, title="area W", style=plot.style_area, color=col11)
plot(ps == "area" ? MOM10 : na, title="area D", style=plot.style_area, color=col10)
plot(ps == "area" ? MOM9 : na, title="area 240", style=plot.style_area, color=col9)
plot(ps == "area" ? MOM8 : na, title="area 120", style=plot.style_area, color=col8)
plot(ps == "area" ? MOM7 : na, title="area 60", style=plot.style_area, color=col7)
plot(ps == "area" ? MOM6 : na, title="area 45", style=plot.style_area, color=col6)
plot(ps == "area" ? MOM5 : na, title="area 30", style=plot.style_area, color=col5)
plot(ps == "area" ? MOM4 : na, title="area 15", style=plot.style_area, color=col4)
plot(ps == "area" ? MOM3 : na, title="area 5", style=plot.style_area, color=col3)
plot(ps == "area" ? MOM2 : na, title="area 3", style=plot.style_area, color=col2)
plot(ps == "area" ? MOM1 : na, title="area 1", style=plot.style_area, color=col1)
// end // |
BTC Price Trend | https://www.tradingview.com/script/h3tMdZqB-BTC-Price-Trend/ | crypto_tycho | https://www.tradingview.com/u/crypto_tycho/ | 27 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © marvixino
//@version=5
indicator("BTC Price Trend", overlay=true)
string BTC_TREND = 'Config » BTC Trend'
btcDownPerc_in = input.float(2, "BTC Down %", step=0.1, group=BTC_TREND, tooltip="Disable trading if price decreases down by x%")
btcDownTF = input.timeframe("240", "BTC Down Timeframe", group=BTC_TREND,options=['30','60','120','240','D'], tooltip="Time in minutes.")
btcUpPerc_in = input.float(0.1, "BTC Up %", step=0.1, group=BTC_TREND, tooltip="Enable trading if price increased by x%")
btcUpTF = input.timeframe("5", "BTC UP Timeframe", group=BTC_TREND,options=['1','5','10','15','30','60','240', 'D'], tooltip="Time in minutes.")
getSecurity(sym, tf, src) =>
request.security(sym, tf, src[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
bool btcTrend = na
//-- Down
btcNow = getSecurity("BINANCE:BTCUSD", btcDownTF, close)
btcBefore = getSecurity("BINANCE:BTCUSD", btcDownTF, close[1])
btcDownPerc = math.round(100* (btcNow-btcBefore)/btcNow, 1)
if(btcDownPerc < btcDownPerc_in)
btcTrend := false
//-- up
btcNowUp = getSecurity("BINANCE:BTCUSD", btcUpTF, close)
btcBeforeUp = getSecurity("BINANCE:BTCUSD", btcUpTF, close[1])
btcUpPerc = math.round(100* (btcNowUp-btcBeforeUp)/btcNowUp, 1)
if(btcUpPerc > btcUpPerc_in)
btcTrend := true
color = btcTrend ? color.lime : color.maroon
barcolor(color)
|
Aarika Heikin Ashi | https://www.tradingview.com/script/BuGJBEWH-Aarika-Heikin-Ashi/ | hlsolanki | https://www.tradingview.com/u/hlsolanki/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hlsolanki
//@version=5
indicator('Aarika Heikin Ashi', shorttitle='AHA', overlay=false)
// inputs
src = input.source(close, 'EMA Source', tooltip='Source of EMA (default: close price)', group='EMA')
length_fast = input.int(8, 'fast length', tooltip='Fast EMA length, adjust it according to different timeframe', group='EMA')
length_slow = input.int(21, 'slow length', tooltip='Slow EMA length, adjust it according to different timeframe', group='EMA')
// get Heikin-Ashi OHLC
[ha_open, ha_high, ha_low, ha_close] = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, [open, high, low, close])
// 2 EMAs for trend recognition
ema_fast = ta.ema(src, length_fast)
ema_slow = ta.ema(src, length_slow)
// define colors
c = ha_close > ha_open ? color.new (color.lime, 0) : color.new (color.red, 0)
// plot Heikin-Ashi candlesticks
plotcandle(ha_open, ha_high, ha_low, ha_close, color=c)
// plot 2 ema lines
plot(ema_fast, color=color.new(color.blue, 0), linewidth=2)
plot(ema_slow, color=color.new(color.black, 0), linewidth=2)
|
Modular FizzBuzz Test | https://www.tradingview.com/script/Xpc2FxUy-Modular-FizzBuzz-Test/ | PrismBot | https://www.tradingview.com/u/PrismBot/ | 16 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PrismBot
//@version=5
indicator("Modular FizzBuzz Test", overlay = true)
// Inspired by having watched the Tom Scott video on FizzBuzz,
// this indicator was my attempt at doing FizzBuzz in Tradingview,
// in a simple and modular way. Mostly for fun but also to,
// even with my experience, learn something new and find out
// more about my own habits with repeating myself in code.
//
// The goal is to show the simplest path to plotting Fizz or Buzz
// or FizzBuzz if the bar index of a given bar is equal to some
// multiples or is a multiple of both numbers.
//
// We check for this using the modulo to see if a bar_index value has
// a remainder. If there is no remainder, output some text string.
//
// I tried to make this as modular as possible so it would be very
// easy to add more lines and checks for "Fuzz" or "Bizz", etc.
// and avoid as much repetition as possible through use of functions.
bar = bar_index
fizz_input = input.int(3, title = "Fizz", group = "FizzBuzz")
buzz_input = input.int(5, title = "Buzz", group = "FizzBuzz")
//fuzz_input = input.int(7, title = "Fuzz", group = "FizzBuzz")
// define strings
fizz = "Fizz"
buzz = "Buzz"
//fuzz = "Fuzz"
fb_calc(x,y) => bar % x == 0 ? y : na // calculates the remainder and if no remainder, output some string.
// contatenate all strings together in a function from the fb_calc()
fb_check() =>
fb_calc(fizz_input,fizz) +
fb_calc(buzz_input,buzz)// +
// fb_calc(fuzz_input,fuzz)
output = str.tostring(fb_check())
if output != na // plot the text as long as some text exists
label.new(x = bar_index, y = high, yloc = yloc.abovebar, text = output, textcolor = color.new(color.gray, 0), color = color.new(color.black, 100))
plotshape(str.contains(output, buzz), style = shape.circle, color = color.new(color.green,0), location = location.abovebar)
plotshape(str.contains(output, fizz), style = shape.cross, color = color.new(color.red,0), location = location.abovebar)
//plotshape(shape.star, color.new(color.blue, (output == fuzz ? 0 : 100)), text = output, location = location.abovebar)
|
Break of structure indicator | https://www.tradingview.com/script/D4971P0E-Break-of-structure-indicator/ | rintveld | https://www.tradingview.com/u/rintveld/ | 403 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
indicator(title="Break of structure indicator", shorttitle="BOS", overlay=true)
long_break_out = input.price(title="Long Breakout Price", defval=0.0, confirm=true)
short_break_out = input.price(title="Short Breakout Price", defval=0.0, confirm=true)
offset = input.int(title="Offset", defval=5)
symbol = input.symbol(defval = "", title = "Symbol", confirm = true)
longAlert = long_break_out > 0 and close > long_break_out
shortAlert = short_break_out > 0 and close < short_break_out
plot(long_break_out > 0 and str.contains(symbol, syminfo.tickerid) ? long_break_out : na, title="Long Breakout Price", color=color.green, offset=offset)
plot(short_break_out > 0 and str.contains(symbol, syminfo.tickerid) ? short_break_out : na, title="Short Breakout Price", color=color.red, offset=offset)
alertcondition(longAlert or shortAlert, title="BOS Alert!", message="BOS alert for {{ticker}} on price {{close}}") |
Joker Linear Regression Channel | https://www.tradingview.com/script/ulsY2QL4-Joker-Linear-Regression-Channel/ | Mr_Joker_Bot | https://www.tradingview.com/u/Mr_Joker_Bot/ | 18 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mr_Joker_Bot
//@version=5
indicator(title='Joker Linear Regression Channel', shorttitle='Joker LR', overlay = true)
src = input(title = "Source", defval = close)
len = input.int(title = "Length", defval = 100, minval = 10)
mult = input.float(title = "Deviation", defval = 2.0, minval = 0.1, step = 0.1)
lin_reg_channel(s, l) => // Linear Regresion Channel return: [y1, y2, dev, slope]
mid = math.sum(s, l) / l
slope = ta.linreg(s, l, 0) - ta.linreg(s, l, 1)
intercept = mid - slope * math.floor(l / 2) + (1 - l % 2) / 2 * slope
endy = intercept + slope * (l - 1)
dev = 0.0
for x = 0 to l - 1 by 1
dev := dev + math.pow(s[x] - (slope * (l - x) + intercept), 2)
dev
dev := math.sqrt(dev / l)
[intercept, endy, dev, slope]
[y1, y2, d, _] = lin_reg_channel(src, len)
float dev = d * mult
plot(y2 + dev, 'LR_U', color.fuchsia)
plot(y2, 'LR_M', color.fuchsia)
plot(y2 - dev, 'LR_L', color.fuchsia)
|
Pulse | https://www.tradingview.com/script/eWjhKrB5-Pulse/ | s3raphic333 | https://www.tradingview.com/u/s3raphic333/ | 184 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Original code by TradeStation
// s3raphic333 modified length, mulitpilier, and type of moving average
// @version=5
indicator(title='Pulse', shorttitle='Pulse', format=format.volume)
showMA = input(false, title='Show Moving Avg')
volmalen = input(16, title='Avg Length')
volmult = input(1.8, title='Avg Multiplier')
volma = ta.ema(volume, volmalen)
volcolor = close > open and volume > volma * volmult ? color.new(#29d430, 50) : close < open and volume > volma * volmult ? color.new(#ff0000, 50) : color.new(#787b86, 65)
plot(volume, color=volcolor, style=plot.style_columns, title='Volume', transp=65)
plot(showMA ? volma * volmult : na, style=plot.style_area, color=color.new(color.white, 85), title='Volume MA')
|
Trendicator | https://www.tradingview.com/script/kSPh8P99-Trendicator/ | dannhau2 | https://www.tradingview.com/u/dannhau2/ | 171 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dannhau2
//@version=5
indicator("Trendicator", overlay = true)
EMABuy = ta.ema(close,1)
EMASell = ta.ema(open,1)
EMA = ta.ema(input(ohlc4,"Moving Average Source"),input(20,"Moving Average Length"))
var col = color.new(color.black,transp=50)
Buy1 = EMABuy>EMA
Buy2 = EMASell>EMA
Sell1 = EMASell<EMA
Sell2 = EMABuy<EMA
if Buy1 and Buy2
col := color.new(color.lime,transp=0)
if Sell1 and Sell2
col := color.new(color.red,transp=0)
p=plot(EMA, "Moving Average", color = col, linewidth=3)
q=plot(close,color=color.new(color.black,transp=100))
fill(p, q, color= Buy1 and Buy2 ? color.new(color.lime,70):color.new(color.red,100))
fill(p, q, color= Sell1 and Sell2 ? color.new(color.red,70):color.new(color.lime,100))
alertcondition(Buy1 and Buy2, title="Uptrend", message="Buy")
alertcondition(Sell1 and Sell2, title="Downtrend", message="Sell")
|
RSI Divergence Scanner by zdmre | https://www.tradingview.com/script/6DYxwhtZ-RSI-Divergence-Scanner-by-zdmre/ | zdmre | https://www.tradingview.com/u/zdmre/ | 1,172 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © zdmre
//@version=5
indicator("RSI Divergence Scanner by zdmre", overlay=false, max_bars_back = 500)
////INPUTs
inputgroup = "**********INPUTs**********"
shdiv = input.bool(defval = true, title = "Show Divergences", group=inputgroup)
shpoints = input.bool(defval = true, title = "Show Points", group=inputgroup)
shdate = input.bool(defval = true, title = "Show Dates", group=inputgroup)
shtline = input.bool(defval = true, title = "Show Trend Lines", group=inputgroup)
shbg = input.bool(defval = false, title = "Show StdDev Background", group=inputgroup)
////ALERTs
alertgroup = "**********ALERTs**********"
i_detectLongs = input(true, "Detect Longs", group=alertgroup)
i_detectShorts = input(true, "Detect Shorts", group=alertgroup)
////RSI
rsigroup = "**********RSI**********"
len = input.int(14, minval=1, title='RSI Length', group = rsigroup)
src = input(close, 'RSI Source', group = rsigroup)
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
plot(rsi, 'RSI', color=color.new(#7E57C2, 0))
band1 = hline(70, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(30, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")
ob= ta.cross(rsi, 70) == 1 and rsi >= 70
os = ta.cross(rsi, 30) == 1 and rsi <= 30
plot(ob and shpoints ? rsi : na ,title='Overbought', style=plot.style_circles, color=color.new(color.red, 0), linewidth=5)
plot(os and shpoints ? rsi : na ,title='Oversold ', style=plot.style_circles, color=color.new(color.green, 0), linewidth=5)
////STDDEV
drawLine(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, 1)
line.delete(Line[1])
rsdcr2(PeriodMinusOne, Deviations, Estimate) =>
var period = PeriodMinusOne + 1
var devDenominator = Estimate == 'Unbiased' ? PeriodMinusOne : period
Ex = 0.0
Ex2 = 0.0
Exy = 0.0
Ey = 0.0
for i = 0 to PeriodMinusOne by 1
closeI = nz(rsi[i])
Ex := Ex + i
Ex2 := Ex2 + i * i
Exy := Exy + closeI * i
Ey := Ey + closeI
Ey
ExEx = Ex * Ex
slope = Ex2 == ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0
for i = 0 to PeriodMinusOne by 1
deviation := deviation + math.pow(nz(rsi[i]) - (intercept - bar_index[i] * slope), 2.0)
deviation
deviation := Deviations * math.sqrt(deviation / devDenominator)
correlate = ta.correlation(rsi, bar_index, period)
r2 = math.pow(correlate, 2.0)
[linearRegression, slope, deviation, correlate, r2]
periodTrend = 140
deviationsAmnt = 1.1
estimatorType = 'Unbiased'
var extendType = 'Right'
periodMinusOne = periodTrend - 1
[linReg, slope, deviation, correlate, r2] = rsdcr2(periodMinusOne, deviationsAmnt, estimatorType)
endPointBar = bar_index - periodTrend + 1
endPointY = linReg + slope * periodMinusOne
////TRENDLINEs
trendgroup = "**********TREND LINE**********"
length = input(21, title='Zigzag Length')
r = rsi[length]
l = rsi[14]
ph = ta.pivothigh(rsi,length,length)
pl = ta.pivotlow(rsi,length,length)
valH = ta.valuewhen(ph,r,0)
valL = ta.valuewhen(pl,r,0)
valpH = ta.valuewhen(ph,r,1)
valpL = ta.valuewhen(pl,r,1)
d = math.abs(r)
n = bar_index
label lbl = na
HIH = valH > valpH ? "HH" : na
HIL = valH < valpH ? "LH" : na
LOL = valL < valpL ? "LL" : na
LOH = valL > valpL ? "HL" : na
if ph and valH > valpH and shtline
lbl := label.new(n[length],math.max(r,l),HIH,color=#ff1100 ,
style=label.style_label_down,textcolor=color.white,size=size.tiny)
label.delete(lbl[1])
linehh = line.new(n[length],math.max(r,l), bar_index, math.max(r,l), extend=extend.right, color=color.red)
line.delete(linehh[1])
else if ph and valH < valpH and shtline
lbl := label.new(n[length],math.max(r,l),HIL,color=#e79700 ,
style=label.style_label_down,textcolor=color.white,size=size.tiny)
label.delete(lbl[1])
linehl = line.new(n[length],math.max(r,l), bar_index, math.max(r,l), extend=extend.right, color=color.orange)
line.delete(linehl[1])
else if pl and valL < valpL and shtline
lbl := label.new(n[length],math.min(r,l),LOL,color=#009c0c ,
style=label.style_label_up,textcolor=color.white,size=size.tiny)
label.delete(lbl[1])
linell = line.new(n[length],math.min(r,l), bar_index, math.min(r,l), extend=extend.right, color=color.green)
line.delete(linell[1])
else if pl and valL > valpL and shtline
lbl := label.new(n[length],math.min(r,l),LOH,color= #0073ee ,
style=label.style_label_up,textcolor=color.white,size=size.tiny)
label.delete(lbl[1])
linelh = line.new(n[length],math.min(r,l), bar_index, math.min(r,l), extend=extend.right, color=color.blue)
line.delete(linelh[1])
label.delete(lbl[200])
barcolor(rsi > linReg + deviation and ta.pivothigh(rsi, length, 0) and rsi >= 65 and shbg ? color.white : rsi < linReg - deviation and ta.pivotlow(rsi, length, 1) and rsi <= 35 and shbg ? color.yellow : na)
bgcolor(rsi > linReg + deviation and ta.pivothigh(rsi, length, 0) and rsi >= 65 and shbg ? color.new(color.red,50) : rsi < linReg - deviation and ta.pivotlow(rsi, length, 1) and rsi <= 35 and shbg ? color.new(color.green, 50) : na)
////WEDGE
wedgegroup = "**********WEDGE**********"
//Inputs
lengthdiv = input.int(21, 'Leftbars Length',minval=0, group=wedgegroup)
lengthright = input.int(0, 'Rightbars Length', tooltip = "0 for Instant",minval=0, group=wedgegroup)
extendOptionUp = input.string("none", title="Upper Line Extension",
options=["none", "left", "right", "both"],group=wedgegroup)
extendOptionLow = input.string("none", title="Lower Line Extension",
options=["none", "left", "right", "both"])
astart = input.int(1, 'Draw Upper Line From Pivot',minval=1, inline='pivot')
aend = input.int(0, 'To Pivot #',minval=0, inline='pivot')
bstart = input.int(1, 'Draw Lower Line From Pivot',minval=1, inline='pivot2')
bend = input.int(0, 'To Pivot #', minval=0,inline='pivot2')
stylewg = input.string('Dot', 'Line Style:', options=['Dot', 'Dash', 'Solid'], inline='custom2')
colorwg = input.string('Red/Green', 'Line Color:', options=['Red/Green', 'White', 'Yellow', 'Blue'], inline='custom2')
lwidth = input.int(2,'Line Width:', minval=0,maxval=4, inline='custom2')
lengthwg = lengthright
length2wg = lengthright
//Conditions
upwg = ta.pivothigh(rsi, lengthdiv, lengthright)
dnwg = ta.pivotlow(rsi, lengthdiv, lengthright)
upchart = ta.pivothigh(close, lengthdiv, lengthright)
dnchart = ta.pivotlow(close, lengthdiv, lengthright)
nw = bar_index
a1 = ta.valuewhen(not na(upwg), nw, astart)
b1 = ta.valuewhen(not na(dnwg), nw, bstart)
a2 = ta.valuewhen(not na(upwg), nw, aend)
b2 = ta.valuewhen(not na(dnwg), nw, bend)
ach1 = ta.valuewhen(not na(upchart), nw, astart)
bch1 = ta.valuewhen(not na(dnchart), nw, bstart)
ach2 = ta.valuewhen(not na(upchart), nw, aend)
bch2 = ta.valuewhen(not na(dnchart), nw, bend)
//Styles
style = line.style_dotted
if stylewg == 'Dash'
style := line.style_dashed
if stylewg == 'Solid'
style := line.style_solid
if stylewg == 'Dot'
style := line.style_dotted
//Colors
color1 = color.red
color2 = color.green
if colorwg == 'White'
color1 := color.white
color2 := color.white
color2
if colorwg == 'Yellow'
color1 := color.yellow
color2 := color.yellow
color2
if colorwg == 'Blue'
color1 := color.blue
color2 := color.blue
color2
if colorwg == 'Red/Green'
color1 := color.red
color2 := color.green
color2
//Lines
lineExtendUp = extendOptionUp == "left" ? extend.left :
extendOptionUp == "right" ? extend.right :
extendOptionUp == "both" ? extend.both :
extend.none
lineExtendLow = extendOptionLow == "left" ? extend.left :
extendOptionLow == "right" ? extend.right :
extendOptionLow == "both" ? extend.both :
extend.none
//DIVERGENCE
div1 = upwg[nw - a2] < upwg[nw - a1] and upchart[nw - ach2] > upchart[nw - ach1] and upchart > high[nw - ach1]
div2 = dnwg[nw - b2] > dnwg[nw - b1] and dnchart[nw - bch2] < dnchart[nw - bch1] and dnchart < low[nw - bch1]
if div1 and shdiv and i_detectShorts
line.new(nw[nw - a1 + lengthwg], upwg[nw - a1], nw[nw - a2 + lengthwg], upwg[nw - a2], extend=lineExtendUp,color=color1, width=lwidth,style=style)
label1 = label.new(nw[nw - a2 + lengthwg], 70 , text="Divergence\n|", style=label.style_label_down, color=color.new(color.red,100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.red)
if div2 and shdiv and i_detectLongs
line.new(nw[nw - b1 + length2wg], dnwg[nw - b1], nw[nw - b2 + length2wg], dnwg[nw - b2], extend=lineExtendLow, color=color2, width=lwidth, style=style)
label2 = label.new(nw[nw - b2 + length2wg], 30, text="|\nDivergence", style=label.style_label_up, color=color.new(color.green,100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.green)
if div1 and shdate and i_detectShorts
label1 = label.new(nw[nw - a2 + lengthwg], 80 , text = str.format("{0,date, y\nMMM-d\n}", time[nw - a2 + lengthwg]), style=label.style_label_down, color=color.new(color.red,100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.red)
if div2 and shdate and i_detectLongs
label2 = label.new(nw[nw - b2 + length2wg], 20 , text = str.format("{0,date, \ny\nMMM-d}", time[nw - b2 + length2wg]), style=label.style_label_up, color=color.new(color.green,100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.green)
////ALERT
// Trigger an alert on crosses.
enterShort = i_detectShorts and div1
enterLong = i_detectLongs and div2
enterPos = i_detectLongs and i_detectShorts and (div1 or div2)
//Conditions
alertcondition(enterLong, "Divergence Alert (Long)", "Go Long ▲\n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(enterShort, "Divergence Alert (Short)", "Go Short ▼\n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(enterPos, "Divergences Alert", "Ticker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}") |
Relative Volume Force Index | https://www.tradingview.com/script/NZGuNg0M-Relative-Volume-Force-Index/ | wbelini | https://www.tradingview.com/u/wbelini/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wbelini
//@version=5
indicator(title="Relative Volume Force Index", shorttitle="RVFI", format=format.price, precision=1, timeframe="", timeframe_gaps=true)
periodK = input.int(1, title="Short Average", minval=1)
periodD = input.int(10, title="Long Average", minval=1)
VolMax = ta.highest(volume,10)
FV =((close-open)/(close))/volume*VolMax
FVAcu= ta.cum(FV)
FVAcuMed = ta.sma(FVAcu,periodK)
FVAcuMedM = ta.sma(FVAcu, periodD)
DifMedia = (FVAcuMed - FVAcuMedM)*100
cor = FV>0 ? color.green : color.red
cor1 = DifMedia < 0 ? color.red : color.green
//plot(FV, title="RVFI Index", color=cor, style=plot.style_columns)
//plot(FVAcu, title="RVFI Acu")
//plot(FVAcuMed, title="RVFI Acu Average", color=#FF6D00)
//plot(FVAcuMedM, title="RVFI Acu Average Longer", color=color.black)
plot(DifMedia, title="Cross averages RVFI", color=cor1, style=plot.style_area)
//h0 = hline(200, "Upper Band", color=#787B86)
//hline(0, "Middle Band", color=color.new(#787B86, 50))
//h1 = hline(-200, "Lower Band", color=#787B86)
//fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")
|
Moving Average Filters Add-on w/ Expanded Source Types [Loxx] | https://www.tradingview.com/script/x6otWKAc-Moving-Average-Filters-Add-on-w-Expanded-Source-Types-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 261 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Moving Average Filters Add-on w/ Expanded Source Types [Loxx]",
shorttitle = "MAFAEST [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true,
max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
_kama(src, len, kama_fastend, kama_slowend) =>
xvnoise = math.abs(src - src[1])
nfastend = kama_fastend
nslowend = kama_slowend
nsignal = math.abs(src - src[len])
nnoise = math.sum(xvnoise, len)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = 0.0
nAMA := nz(nAMA[1]) + nsmooth * (src - nz(nAMA[1]))
nAMA
_ama(src, len, fl, sl)=>
flout = 2/(fl + 1)
slout = 2/(sl + 1)
hh = ta.highest(len + 1)
ll = ta.lowest(len + 1)
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0
ssc = mltp * (flout - slout) + slout
ama = 0.
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))
ama
_t3(src, len) =>
xe1_1 = ta.ema(src, len)
xe2_1 = ta.ema(xe1_1, len)
xe3_1 = ta.ema(xe2_1, len)
xe4_1 = ta.ema(xe3_1, len)
xe5_1 = ta.ema(xe4_1, len)
xe6_1 = ta.ema(xe5_1, len)
b_1 = 0.7
c1_1 = -b_1 * b_1 * b_1
c2_1 = 3 * b_1 * b_1 + 3 * b_1 * b_1 * b_1
c3_1 = -6 * b_1 * b_1 - 3 * b_1 - 3 * b_1 * b_1 * b_1
c4_1 = 1 + 3 * b_1 + b_1 * b_1 * b_1 + 3 * b_1 * b_1
nT3Average = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1
nT3Average
_trendreg(o, h, l, c)=>
compute = 0.
if (c > o)
compute := ((h + c)/2.0)
else
compute := ((l + c)/2.0)
compute
_trendext(o, h, l, c) =>
compute = 0.
if (c > o)
compute := h
else if (c < o)
compute := l
else
compute := c
compute
//ADXvma - Average Directional Volatility Moving Average
_adxvma(src, len)=>
tpdm = 0., tmdm = 0.
pdm = 0., mdm = 0., pdi = 0., mdi = 0., out = 0., val = 0.
tpdi = 0., tmdi = 0., thi = 0., tlo = 0., tout = 0., vi = 0.
diff = src - nz(src[1])
tpdm := diff > 0 ? diff : tpdm
tmdm := diff > 0 ? tmdm : -diff
pdm := ((len- 1.0) * nz(pdm[1]) + tpdm) / len
mdm := ((len- 1.0) * nz(mdm[1]) + tmdm) / len
trueRange = pdm + mdm
tpdi := nz(pdm / trueRange)
tmdi := nz(mdm / trueRange)
pdi := ((len- 1.0) * nz(pdi[1]) + tpdi) / len
mdi := ((len- 1.0) * nz(mdi[1]) + tmdi) / len
tout := (pdi + mdi) > 0 ? math.abs(pdi - mdi) / (pdi + mdi) : tout
out := ((len- 1.0) * nz(out[1]) + tout) / len
thi := math.max(out, nz(out[1]))
tlo := math.min(out, nz(out[1]))
for j = 2 to len
thi := math.max(nz(out[j]), thi)
tlo := math.min(nz(out[j]), tlo)
vi := (thi - tlo) > 0 ? (out - tlo) / (thi - tlo) : vi
val := ((len- vi) * nz(val[1]) + vi * src) / len
[val, val[1], false]
//Ahrens Moving Average
_ahrma(src, len)=>
ahrma = 0.
medMA = (nz(ahrma[1]) + nz(ahrma[len])) / 2.0
ahrma := nz(ahrma[1]) + ((src - medMA) / len)
[ahrma, ahrma[1], false]
//Alexander Moving Average - ALXMA
_alxma(src, len)=>
sumw = len - 2
sum = sumw * src
for k = 1 to len
weight = len - k - 2
sumw += weight
sum += weight * nz(src[k])
out = len < 4 ? src : sum/sumw
[out, out[1], false]
//Double Exponential Moving Average - DEMA
_dema(src, len)=>
e1 = ta.ema(src, len)
e2 = ta.ema(e1, len)
dema = 2 * e1 - e2
[dema, dema[1], false]
//Double Smoothed Exponential Moving Average - DSEMA
_dsema(src, len)=>
alpha = 2.0 / (1.0 + math.sqrt(len))
_ema1 = 0., _ema2 = 0.
_ema1 := nz(_ema1[1]) + alpha * (src - nz(_ema1[1]))
_ema2 := nz(_ema2[1]) + alpha * (_ema1 - nz(_ema2[1]))
[_ema2, _ema2[1], false]
//Exponential Moving Average - EMA
_ema(src, len)=>
out = ta.ema(src, len)
[out, out[1], false]
//Fast Exponential Moving Average - FEMA
_fema(src, len)=>
alpha = (2.0 / (2.0 + (len - 1.0) / 2.0))
out = 0.
out := nz(out[1]) + alpha * (src - nz(out[1]))
[out, out[1], false]
//hull moving averge
_hma(src, len)=>
out = ta.hma(src, len)
[out, out[1], false]
//IE/2 - Early T3 by Tim Tilson
_ie2(src, len)=>
sumx=0., sumxx=0., sumxy=0., sumy=0.
for k = 0 to len - 1
price = nz(src[k])
sumx += k
sumxx += k * k
sumxy += k * price
sumy += price
slope = (len * sumxy - sumx * sumy) / (sumx * sumx - len * sumxx)
average = sumy/len
out = (((average + slope) + (sumy + slope * sumx) / len) / 2.0)
[out, out[1], false]
//Fractal Adaptive Moving Average - FRAMA
_frama(src, len, FC, SC) =>
len1 = len / 2
e = math.e
w = math.log(2 / (SC + 1)) / math.log(e) // Natural logarithm (ln(2/(SC+1))) workaround
H1 = ta.highest(high, len1)
L1 = ta.lowest(low, len1)
N1 = (H1 - L1) / len1
H2 = ta.highest(high, len1)[len1]
L2 = ta.lowest(low, len1)[len1]
N2 = (H2 - L2) / len1
H3 = ta.highest(high, len)
L3 = ta.lowest(low, len)
N3 = (H3 - L3) / len
dimen1 = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
dimen = N1 > 0 and N2 > 0 and N3 > 0 ? dimen1 : nz(dimen1[1])
alpha1 = math.exp(w * (dimen - 1))
oldalpha = alpha1 > 1 ? 1 : alpha1 < 0.01 ? 0.01 : alpha1
oldN = (2 - oldalpha) / oldalpha
N = (SC - FC) * (oldN - 1) / (SC - 1) + FC
alpha_ = 2 / (N + 1)
alpha = alpha_ < 2 / (SC + 1) ? 2 / (SC + 1) : alpha_ > 1 ? 1 : alpha_
out = 0.0
out := (1 - alpha) * nz(out[1]) + alpha * src
[out, out[1], false]
//Instantaneous Trendline
_instant(src, alpha) =>
itrend = 0.0
itrend := bar_index < 7 ? (src + 2 * nz(src[1]) + nz(src[2])) / 4 :
(alpha - math.pow(alpha, 2) / 4) * src + 0.5 * math.pow(alpha, 2) * nz(src[1]) - (alpha - 0.75 * math.pow(alpha, 2)) * nz(src[2]) + 2 * (1 - alpha) * nz(itrend[1]) - math.pow(1 - alpha, 2) * nz(itrend[2])
trigger = 2 * itrend - nz(itrend[2])
[trigger, itrend, false]
//Integral of Linear Regression Slope - ILRS
_ilrs(src, len)=> // Integral of linear regression slope
sum = len * (len -1) * 0.5
sum2 = (len - 1) * len * (2 * len - 1) / 6.0
sum1 = 0., sumy = 0., slope = 0.
for i = 0 to len - 1
sum1 += i * nz(src[i])
sumy += nz(src[i])
num1 = len * sum1 - sum * sumy
num2 = sum * sum - len * sum2
slope := num2 != 0. ? num1/num2 : 0.
ilrs = slope + ta.sma(src, len)
[ilrs, ilrs[1], false]
//Laguerre Filter
_laguerre(src, alpha)=>
L0 = 0.0, L1 = 0.0, L2 = 0.0, L3 = 0.0
L0 := alpha * src + (1 - alpha) * nz(L0[1])
L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1])
L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1])
L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1])
lf = (L0 + 2 * L1 + 2 * L2 + L3) / 6
[lf, lf[1], false]
//Leader Exponential Moving Average
_leader(src, len)=>
alpha = 2.0/(len + 1.0)
ldr = 0.,ldr2 = 0.
ldr := nz(ldr[1]) + alpha * (src - nz(ldr[1]))
ldr2 := nz(ldr2[1]) + alpha * (src - ldr - nz(ldr2[1]))
out = ldr + ldr2
[out, out[1], false]
//Linear Regression Value - LSMA (Least Squares Moving Average)
_lsma(src, len, offset)=>
out = ta.linreg(src, len, offset)
[out, out[1], false]
//Linear Weighted Moving Average - LWMA
_lwma(src, len)=>
out = ta.wma(src, len)
[out, out[1], false]
//McGinley Dynamic
_mcginley(src, len)=>
mg = 0.0
t = ta.ema(src, len)
mg := na(mg[1]) ? t : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
[mg, mg[1], false]
//McNicholl EMA
_mcNicholl(src, len)=>
alpha = 2 / (len + 1)
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
out = ((2 - alpha) * ema1 - ema2) / (1 - alpha)
[out, out[1], false]
//Non lag moving average
_nonlagma(src, len)=>
cycle = 4.0
coeff = 3.0 * math.pi
phase = len - 1.0
_len = int(len * cycle + phase)
weight = 0., alfa = 0., out = 0.
alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
[out, out[1], false]
//Parabolic Weighted Moving Average
_pwma(src, len, pwr)=>
sum = 0.0, weightSum = 0.0
for i = 0 to len - 1 by 1
weight = math.pow(len - i, pwr)
sum += nz(src[i]) * weight
weightSum += weight
weightSum
out = sum / weightSum
[out, out[1], false]
//Recursive Moving Trendline
_rmta(src, len)=>
alpha = 2 / (len + 1)
b = 0.0
b := (1 - alpha) * nz(b[1], src) + src
rmta = 0.0
rmta := (1 - alpha) * nz(rmta[1], src) + alpha * (src + b - nz(b[1]))
[rmta, rmta[1], false]
//Simple decycler - SDEC
_decycler(src, len)=>
alphaArg = 2 * math.pi / (len * math.sqrt(2))
alpha = 0.0
alpha := math.cos(alphaArg) != 0 ? (math.cos(alphaArg) + math.sin(alphaArg) - 1) / math.cos(alphaArg) : nz(alpha[1])
hp = 0.0
hp := math.pow(1 - alpha / 2, 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(hp[1]) - math.pow(1 - alpha, 2) * nz(hp[2])
decycler = src - hp
[decycler, decycler[1], false]
//Simple Moving Average
_sma(src, len)=>
out = ta.sma(src, len)
[out, out[1], false]
//Sine Weighted Moving Average
_swma(src, len)=>
sum = 0.0, weightSum = 0.0
for i = 0 to len - 1 by 1
weight = math.sin((i + 1) * math.pi / (len + 1))
sum += nz(src[i]) * weight
weightSum += weight
weightSum
swma = sum / weightSum
[swma, swma[1], false]
//Smoothed linear weighted moving average
_slwma(src, len)=>
out = ta.wma(ta.wma(src, len), math.floor(math.sqrt(len)))
[out, out[1], false]
//Smoothed Moving Average - SMMA
_smma(src, len)=>
out = ta.rma(src, len)
[out, out[1], false]
//Ehlers super smoother
_super(src, len) =>
f = (1.414 * math.pi)/len
a = math.exp(-f)
c2 = 2 * a * math.cos(f)
c3 = -a*a
c1 = 1-c2-c3
smooth = 0.0
smooth := c1*(src+src[1])*0.5+c2*nz(smooth[1])+c3*nz(smooth[2])
[smooth, smooth[1], false]
//Smoother filter
_smoother(src, len)=>
wrk = src, wrk2 = src, wrk4 = src
wrk0 = 0., wrk1 = 0., wrk3 = 0.
alpha = 0.45 * (len - 1.0) / (0.45 * (len - 1.0) + 2.0)
wrk0 := src + alpha * (nz(wrk[1]) - src)
wrk1 := (src - wrk) * (1 - alpha) + alpha * nz(wrk1[1])
wrk2 := wrk0 + wrk1
wrk3 := (wrk2 - nz(wrk4[1])) * math.pow(1.0 - alpha, 2) + math.pow(alpha, 2) * nz(wrk3[1])
wrk4 := wrk3 + nz(wrk4[1])
[wrk4, wrk4[1], false]
//Triangular moving average - TMA
_tma(src, len)=>
filt = 0.0, coef = 0.0, l2 = len / 2.0
for i = 1 to len
c = i < l2 ? i : i > l2 ? len + 1 - i : l2
filt := filt + (c * nz(src[i - 1]))
coef := coef + c
filt := coef != 0 ? filt / coef : 0
[filt, filt[1], false]
//Tripple exponential moving average - TEMA
_tema(src, len)=>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
out = 3 * (ema1 - ema2) + ema3
[out, out[1], false]
//Volume weighted ema - VEMA
_vwema(src, len) =>
p = ta.ema(volume * src, len)
v = ta.ema(volume, len)
vwema = p / v
[vwema, vwema[1], false]
//Volume weighted moving average - VWMA
_vwma(src, len)=>
ma = ta.vwma(src, len)
[ma, ma[1], false]
//Zero-lag dema
_zlagdema(src, len)=>
_zdema1 = ta.ema(src, len)
_zdema2 = ta.ema(_zdema1, len)
dema1 = 2 * _zdema1 - _zdema2
_zdema12 = ta.ema(dema1, len)
_zdema22 = ta.ema(_zdema12, len)
demaout = 2 * _zdema12 - _zdema22
[demaout, demaout[1], false]
//Zero lag moving average
_zlagma(src, len)=>
alpha = 2.0/(1.0 + len)
per = math.ceil((len - 1.0) / 2.0 )
zlagma = 0.
zlagma := nz(zlagma[1]) + alpha * (2.0 * src - nz(zlagma[per]) - nz(zlagma[1]))
[zlagma, zlagma[1], false]
//Zero-lag tema
_zlagtema(src, len)=>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
out = 3 * (ema1 - ema2) + ema3
ema1a = ta.ema(out, len)
ema2a = ta.ema(ema1a, len)
ema3a = ta.ema(ema2a, len)
outf = 3 * (ema1a - ema2a) + ema3a
[outf, outf[1], false]
//Three pole Ehlers Butterworth
_3polebuttfilt(src, len)=>
a1 = 0., b1 = 0., c1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0., coef4 = 0.
bttr = 0., trig = 0.
a1 := math.exp(-math.pi / len)
b1 := 2 * a1 * math.cos(1.738 * math.pi / len)
c1 := a1 * a1
coef2 := b1 + c1
coef3 := -(c1 + b1 * c1)
coef4 := c1 * c1
coef1 := (1 - b1 + c1) * (1 - c1) / 8
bttr := coef1 * (src + 3 * nz(src[1]) + 3 * nz(src[2]) + nz(src[3])) + coef2 * nz(bttr[1]) + coef3 * nz(bttr[2]) + coef4 * nz(bttr[3])
bttr := bar_index < 4 ? src : bttr
trig := nz(bttr[1])
[bttr, trig, true]
//Three pole Ehlers smoother
_3polesss(src, len)=>
a1 = 0., b1 = 0., c1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0., coef4 = 0.
filt = 0., trig = 0.
a1 := math.exp(-math.pi / len)
b1 := 2 * a1 * math.cos(1.738 * math.pi / len)
c1 := a1 * a1
coef2 := b1 + c1
coef3 := -(c1 + b1 * c1)
coef4 := c1 * c1
coef1 := 1 - coef2 - coef3 - coef4
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2]) + coef4 * nz(filt[3])
filt := bar_index < 4 ? src : filt
trig := nz(filt[1])
[filt, trig, true]
//Two pole Ehlers Butterworth
_2polebutter(src, len)=>
a1 = 0., b1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0.
bttr = 0., trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := (1 - b1 + a1 * a1) / 4
bttr := coef1 * (src + 2 * nz(src[1]) + nz(src[2])) + coef2 * nz(bttr[1]) + coef3 * nz(bttr[2])
bttr := bar_index < 3 ? src : bttr
trig := nz(bttr[1])
[bttr, trig, true]
//Two pole Ehlers smoother
_2poless(src, len)=>
a1 = 0., b1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0.
filt = 0., trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := 1 - coef2 - coef3
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])
filt := bar_index < 3 ? src : filt
trig := nz(filt[1])
[filt, trig, true]
srcoption = input.string("Close", "SMA Source Options", group= "Basic Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
smthtype = input.string("AMA", "Filter Options", options = ["AMA", "T3", "Kaufman"], group= "Basic Settings")
len = input.int(55, "Period", minval = 1, group = "Basic Settings")
type = input.string("Simple Moving Average - SMA", "Moving Average Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title='* Laguerre Filter (LF) Only - Alpha', minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, '* Parabolic Weighted Moving Average (PWMA) Only - Power', minval=0, group = "Moving Average Inputs")
kama_fastend=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
kama_slowend=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
fastLength = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
slowLength = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
showsignal = input.bool(false, "Show Signal Line??", group = "UI Options")
rclose = close
ropen = open
rhigh = high
rlow = low
rmedian = hl2
rtypical = hlc3
rweighted = hlcc4
raverage = ohlc4
ravemedbody = (open + close)/2
rtrendb = _trendreg(ropen, rhigh, rlow, rclose)
rtrendbext = _trendext(ropen, rhigh, rlow, rclose)
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
haavemedbody = (haopen + haclose)/2
hatrendb = _trendreg(haopen, hahigh, halow, haclose)
hatrendbext = _trendext(haopen, hahigh, halow, haclose)
habingest = (ropen + rclose)/2 + (((rclose - ropen)/(rhigh - rlow)) * math.abs((rclose - ropen)/2))
habclose = smthtype == "AMA" ? _ama(habingest, 2, fastLength, slowLength) : smthtype == "T3" ? _t3(habingest, 3) : _kama(habingest, 2, kama_fastend, kama_slowend)
habopen = 0.
habopen := (nz(habopen[1]) + nz(habclose[1]))/2
habhigh = math.max(rhigh, habopen, habclose)
hablow = math.min(rlow, habopen, habclose)
habmedian = (habhigh + hablow)/2
habtypical = (habhigh + hablow + habclose)/3
habweighted = (habhigh + hablow + habclose + habclose)/4
habaverage = (habopen + habhigh + hablow + habclose)/4
habavemedbody = (habopen + habclose)/2
habtrendb = _trendreg(habopen, habhigh, hablow, habclose)
habtrendbext = _trendext(habopen, habhigh, hablow, habclose)
float src = switch srcoption
"Close" => rclose
"Open" => ropen
"High" => rhigh
"Low" => rlow
"Median" => rmedian
"Typical" => rtypical
"Weighted" => rweighted
"Average" => raverage
"Average Median Body" => ravemedbody
"Trend Biased" => rtrendb
"Trend Biased (Extreme)" => rtrendbext
"HA Close" => haclose
"HA Open" => haopen
"HA High" => hahigh
"HA Low" => halow
"HA Median" => hamedian
"HA Typical" => hatypical
"HA Weighted" => haweighted
"HA Average" => haaverage
"HA Average Median Body" => haavemedbody
"HA Trend Biased" => hatrendb
"HA Trend Biased (Extreme)" => hatrendbext
"HAB Close" => habclose
"HAB Open" => habopen
"HAB High" => habhigh
"HAB Low" => hablow
"HAB Median" => habmedian
"HAB Typical" => habtypical
"HAB Weighted" => habweighted
"HAB Average" => habaverage
"HAB Average Median Body" => habavemedbody
"HAB Trend Biased" => habtrendb
"HAB Trend Biased (Extreme)" => habtrendbext
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = _adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = _ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = _alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = _dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = _dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = _ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = _fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = _frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = _hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = _ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = _ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = _instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = _laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = _leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = _lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = _lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = _mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = _mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = _nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = _pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = _rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = _sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = _swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = _smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = _smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = _super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = _3polebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = _3polesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = _tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = _tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = _2polebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = _2poless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = _vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = _zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = _zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = _zlagtema(src, len)
sig := s
trig := t
special := b
[trig, sig, special]
[trig, sig, special] = variant(type, src, len)
plot(trig, "Moving Average", color = trig > sig ? greencolor : redcolor, linewidth = 3)
plot(showsignal ? sig : na, "Signal", color = color.white, linewidth = 1)
barcolor(colorbars ? trig > sig ? greencolor : redcolor : na)
|
SMA Spread as % | https://www.tradingview.com/script/zWlTw4WU-SMA-Spread-as/ | swagmoneytrader | https://www.tradingview.com/u/swagmoneytrader/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ericdwyang
//@version=5
indicator("Spread as %")
// SMA Variables
smaInput = input(200, "Length")
sma = ta.sma(close, smaInput)
// Spread
spread = (close - sma)
// Spread as % of last close
spread2 = spread / sma
// TEST PLOT
// plot(spread)
// plot(sma)
// plot(close)
plot(spread2, title="Spread", color=spread2 >= 0 ? color.blue : color.orange, style=plot.style_columns)
|
MultiTimeFrame Stochastic | https://www.tradingview.com/script/nDUY1tC0-MultiTimeFrame-Stochastic/ | biswasdebasish9475 | https://www.tradingview.com/u/biswasdebasish9475/ | 71 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © biswasdebasish9475
//@version=5
indicator("MultiTimeFrame Stochastic", shorttitle ="MTF_Stoch")
higher_timeframe = input.timeframe(title="Higher_Timeframe", defval="D")
fast_stoch = input(15, title = "Stochastic Period", group = "HTF_STOCHASTIC")
medium_stoch = input(30, title = "Stochastic Period", group = "HTF_STOCHASTIC")
slow_stoch = input(70, title = "Stochastic Period", group = "HTF_STOCHASTIC")
too_slow_stoch = input(116, title = "Stochastic Period", group = "HTF_STOCHASTIC")
fast_current = input(15, title = "Stochastic Period", group = "current_STOCHASTIC")
medium_current = input(30, title = "Stochastic Period", group = "current_STOCHASTIC")
slow_current = input(70, title = "Stochastic Period", group = "current_STOCHASTIC")
too_slow_current = input(116, title = "Stochastic Period", group = "current_STOCHASTIC")
overBrought = input(90, "OB",group = "OVERBOUGHT BAND", inline = "xx", tooltip ="RedBand")
overBrought2 = input(99, "OB2",group = "OVERBOUGHT BAND", inline = "xx",tooltip ="RedBand")
overSold = input(10, "OS",group = "OVERSOLD BAND", inline = "x")
overSold2 = input(1, "OS2",group = "OVERSOLD BAND", inline = "x",tooltip ="GreenBand")
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
faststoch = request.security(syminfo.tickerid, higher_timeframe, ta.stoch(close, high,low, fast_stoch),gaps = barmerge.gaps_on)
mediumstoch = request.security(syminfo.tickerid, higher_timeframe, ta.stoch(close, high,low, medium_stoch),gaps = barmerge.gaps_on)
slowstoch = request.security(syminfo.tickerid, higher_timeframe, ta.stoch(close, high,low, slow_stoch),gaps = barmerge.gaps_on)
tooslowstoch = request.security(syminfo.tickerid, higher_timeframe, ta.stoch(close, high,low, too_slow_stoch),gaps = barmerge.gaps_on)
fastcurrent = ta.stoch(close, high, low, fast_current)
mediumcurrent = ta.stoch(close, high, low, medium_current)
slowcurrent = ta.stoch(close, high, low, slow_current)
tooslowcurrent = ta.stoch(close, high, low, too_slow_current)
plot (faststoch, title= "Fast Stoch HTF", color = color.new(color.red,0), linewidth =2)
plot (mediumstoch, title= "Medium Stoch HTF", color = color.new(color.green,0), linewidth =2)
plot (slowstoch, title= "Slow Stoch HTF", color = color.new(color.blue,0), linewidth =2)
plot (tooslowstoch, title= "Too Slow Stoch HTF", color = color.new(color.gray,0), linewidth =2)
plot (fastcurrent, title= "Fast Current", color = color.new(color.red,0))
plot (mediumcurrent, title= "Medium Current", color = color.new(color.green,0))
plot (slowcurrent, title= "Slow Current", color = color.new(color.blue,0))
plot (tooslowcurrent, title= "Too Slow Current", color = color.new(color.gray,0))
lineOB = plot (overBrought, title= "overBought", color = color.new(color.red,100))
lineOB2 = plot (overBrought2, title= "overBought2", color = color.new(color.red,100))
fill(lineOB, lineOB2, color= color.new(color.red,70))
lineOS = plot (overSold, title= "overSold", color = color.new(color.green,100))
lineOS2 = plot (overSold2, title= "overSold2", color = color.new(color.green,100))
fill(lineOS, lineOS2, color = color.new(color.green,70))
|
Colorful Regression | https://www.tradingview.com/script/DTe3ePDp/ | faytterro | https://www.tradingview.com/u/faytterro/ | 130 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © faytterro
//@version=5
indicator("Colorful Regression", overlay=true, max_lines_count=500)
src=input(hlc3,title="source")
len=input.int(40,title="lenght", maxval=500)
cr(x, y) =>
z = 0.0
weight = 0.0
for i = 0 to y-1
z:=z + x[i]*((y-1)/2+1-math.abs(i-(y-1)/2))
z/(((y+1)/2)*(y+1)/2)
cr= cr(src,2*len-1)
width=input.int(2, title="linewidth", minval=1)
crm=ta.change(cr)
//plot(cr, color=(cr>=cr[1])? #35cf02 : #cf0202 , linewidth=width,offset=-len+1)
///////////
dx(x) =>
x-x[1]
pm = dx(cr)
/////////////////////////
y = math.abs(pm)
n = bar_index
m = math.min(math.max(n-2*len+2,1),500)
t = ta.wma(y,m)//ta.cum(y)/n
fd(x) =>
100-100/(math.pow(1+2/t,x)+1)
f = fd(pm)
f:= f*2.5
plot(cr, color= color.rgb(math.min(510-2*f,255),math.min(2*f,255),0), linewidth=width,offset=-len+1, display = display.pane)
/////////////////////////
// extrapolation
diz = array.new_float(501)
var lin=array.new_line()
if barstate.islast
for k=0 to len-1
sum=0.0
for i=0 to 2*len-2-k
sum +=(len-math.abs(len-1-k-i))*src[i]/(len*len-k*(k+1)/2)
array.set(diz,k, sum )
for i=0 to (len-1)
array.push(lin, line.new(na, na, na, na))
fp= 2.5*fd(array.get(diz,i+1)-array.get(diz,i))
line.set_color(array.get(lin,i),color.blue)//array.get(diz,i+1)>=array.get(diz,i)? #35cf02 : #cf0202)
line.set_xy1(array.get(lin,i), bar_index[len]+i+1, array.get(diz,i))
line.set_xy2(array.get(lin,i), bar_index[len]+i+2,array.get(diz,i+1))
line.set_color(array.get(lin,i), color.rgb(math.min(510-2*fp,255),math.min(2*fp,255),0))
line.set_width(array.get(lin,i),width)
bool buy=ta.change(ta.change(cr))>0 and ta.change(cr)<0
bool sell=ta.change(ta.change(cr))<0 and ta.change(cr)>0
//buy:= buy and buy[1]==false
for i=1 to len
buy:= buy and buy[i]==false
sell:= sell and sell[i]==false
alert=buy or sell
alertcondition(alert, title="Alarm", message="buy or sell signal!")
plotshape(buy, style = shape.triangleup, location = location.belowbar, color = color.rgb(0, 255, 0, 0), textcolor = color.white, size = size.tiny)
plotshape(sell, style = shape.triangledown, location = location.abovebar, color = color.rgb(255, 0, 0), textcolor = color.white, size = size.tiny)
fp= 2.5*fd(array.get(diz,1)-array.get(diz,0))
plot(ta.wma(src,len), color = color.rgb(math.min(510-2*fp,255),math.min(2*fp,255),0,100))
|
RSI Overlay | https://www.tradingview.com/script/zwl0XhRV-RSI-Overlay/ | MarkLefevre | https://www.tradingview.com/u/MarkLefevre/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MarkLefevre
//@version=5
indicator(title="Relative Strength Index", shorttitle="RSI", overlay=true,format=format.price, precision=2, timeframe="", timeframe_gaps=true)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = ma(rsi*close/48, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"
plot(rsi*close/48, "RSI", color=#7E57C2)
rsiUpperBand = plot(70*close/48, "RSI Upper Band", color=#787B86)
rsiLowerBand = plot(30*close/48, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill") |
Market Structure Patterns (Nephew_Sam_) | https://www.tradingview.com/script/eCwAa4wI-Market-Structure-Patterns-Nephew-Sam/ | nephew_sam_ | https://www.tradingview.com/u/nephew_sam_/ | 2,599 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Nephew_Sam_
//@version=5
indicator('Market Structure (Nephew_Sam_)', overlay=true, max_bars_back=500, max_labels_count=500)
// --------------- INPUTS ---------------
var GRP1 = "Settings"
length = input.int(defval=5, title='Pivot strength', minval=2, maxval=20, group=GRP1)
showzz = input(false, title='Show Zigzag', group=GRP1)
showbosline = input(false, title='Show BOS Lines', group=GRP1)
showhhll = input(true, title='Show HH/LL', group=GRP1)
showPatternMatch = input(true, title='Show Pattern Matches', group=GRP1)
var GRP2 = "Bull Patterns"
bullCond1 = input.string(defval='LL,LH,LL,HH,HL', title='Bull 1', inline="11", group=GRP2)
bullTxt1 = input.string(defval='BOS HL 1', title='', inline="11", group=GRP2)
bullBool1 = input.bool(true, "", inline="11", group = GRP2)
bullCond2 = input.string(defval='LL,LH,HL,LH,LL,HH,HL', title='Bull 2', inline="22", group=GRP2)
bullTxt2 = input.string(defval='BOS HL 2', title='', inline="22", group=GRP2)
bullBool2 = input.bool(true, "", inline="22", group = GRP2)
bullCond3 = input.string(defval='LL,LH,LL,LH,HL,HH,HL', title='Bull 3', inline="33", group=GRP2)
bullTxt3 = input.string(defval='BOS HL 3', title='', inline="33", group=GRP2)
bullBool3 = input.bool(true, "", inline="33", group = GRP2)
bullCond4 = input.string(defval='', title='Bull 4', inline="44", group=GRP2)
bullTxt4 = input.string(defval='', title='', inline="44", group=GRP2)
bullBool4 = input.bool(true, "", inline="44", group = GRP2)
bullCond5 = input.string(defval='', title='Bull 5', inline="55", group=GRP2)
bullTxt5 = input.string(defval='', title='', inline="55", group=GRP2)
bullBool5 = input.bool(true, "", inline="55", group = GRP2)
bullCond6 = input.string(defval='', title='Bull 6', inline="66", group=GRP2)
bullTxt6 = input.string(defval='', title='', inline="66", group=GRP2)
bullBool6 = input.bool(true, "", inline="66", group = GRP2)
bullCond7 = input.string(defval='', title='Bull 7', inline="77", group=GRP2)
bullTxt7 = input.string(defval='', title='', inline="77", group=GRP2)
bullBool7 = input.bool(true, "", inline="77", group = GRP2)
var GRP3 = "Bear Patterns"
bearCond1 = input.string(defval='HH,HL,HH,LL,LH', title='Bear 1', inline="11", group=GRP3)
bearTxt1 = input.string(defval='BOS LH 1', title='', inline="11", group=GRP3)
bearBool1 = input.bool(true, "", inline="11", group = GRP3)
bearCond2 = input.string(defval='HH,HL,LH,HL,HH,LL,LH', title='Bear 2', inline="22", group=GRP3)
bearTxt2 = input.string(defval='BOS LH 2', title='', inline="22", group=GRP3)
bearBool2 = input.bool(true, "", inline="22", group = GRP3)
bearCond3 = input.string(defval='HH,HL,HH,HL,LH,LL,LH', title='Bear 3', inline="33", group=GRP3)
bearTxt3 = input.string(defval='BOS LH 3', title='', inline="33", group=GRP3)
bearBool3 = input.bool(true, "", inline="33", group = GRP3)
bearCond4 = input.string(defval='', title='Bear 4', inline="44", group=GRP3)
bearTxt4 = input.string(defval='', title='', inline="44", group=GRP3)
bearBool4 = input.bool(true, "", inline="44", group = GRP3)
bearCond5 = input.string(defval='', title='Bear 5', inline="55", group=GRP3)
bearTxt5 = input.string(defval='', title='', inline="55", group=GRP3)
bearBool5 = input.bool(true, "", inline="55", group = GRP3)
bearCond6 = input.string(defval='', title='Bear 6', inline="66", group=GRP3)
bearTxt6 = input.string(defval='', title='', inline="66", group=GRP3)
bearBool6 = input.bool(true, "", inline="66", group = GRP3)
bearCond7 = input.string(defval='', title='Bear 7', inline="77", group=GRP3)
bearTxt7 = input.string(defval='', title='', inline="77", group=GRP3)
bearBool7 = input.bool(true, "", inline="77", group = GRP3)
var GRP4 = "Styles"
upcol = input(defval=color.green, title='HHLL Up Color', group=GRP4)
dncol = input(defval=color.red, title='HHLL Down Color', group=GRP4)
uplabeltextcol = input(defval=color.white, title='Label Text Up Color', group=GRP4)
dnlabeltextcol = input(defval=color.white, title='Label Text Down Color', group=GRP4)
uplabelcol = input(defval=color.green, title='Label BG Up Color', group=GRP4)
dnlabelcol = input(defval=color.red, title='Label BG Down Color', group=GRP4)
zzstyle = input.string(defval='Dashed', title='Zig Zag Line Style', options=['Dashed', 'Dotted'], group=GRP4)
zzwidth = input.int(defval=1, title='Zig zag Line Width', minval=1, maxval=4, group=GRP4)
var max_array_size = 10
// --------------- INPUTS ---------------
// --------------- Functions ---------------
isMatching(_str, _arr) =>
if _str == ""
false
else
hhll_join = array.join(_arr, ",")
_temp0 = str.replace_all(_str, " ", "")
_temp1 = str.upper(_str)
_temp2 = str.split(_str, ",")
array.reverse(_temp2)
_temp3 = array.join(_temp2, ",")
str.startswith(hhll_join, _temp3)
addToString(_str, _val) =>
_temp0 = _str == "" ? _str : _str + "\n"
_temp0 + _val
add_to_zigzag(arr, value) =>
array.unshift(arr, value)
if array.size(arr) > max_array_size
array.pop(arr)
update_zigzag(arr, value, direction, _skip=false) =>
if array.size(arr) == 0
add_to_zigzag(arr, value)
else
if _skip
array.set(arr, 0, value)
else if direction == "ph" and value > array.get(arr, 0) or direction == "pl" and value < array.get(arr, 0)
array.set(arr, 0, value)
0.
// --------------- Functions ---------------
// --------------- Calculate Pivots ---------------
float pivoth = ta.highestbars(high, length) == 0 ? high : na
float pivotl = ta.lowestbars(low, length) == 0 ? low : na
var direction = "na"
iff_ = pivotl and na(pivoth) ? "pl" : direction
direction := pivoth and na(pivotl) ? "ph" : iff_
// --------------- Calculate Pivots ---------------
// --------------- Zigzags vars ---------------
var zigzag_price = array.new_float(0)
oldzigzag_price = array.copy(zigzag_price)
var zigzag_barindex = array.new_int(0)
oldzigzag_barindex = array.copy(zigzag_barindex)
var zigzag_hhll = array.new_string(0)
oldzigzag_hhll = array.copy(zigzag_hhll)
direction_changed = direction != direction[1] //ta.change(direction)
if pivoth or pivotl
if direction_changed
add_to_zigzag(zigzag_price, direction == "ph" ? pivoth : pivotl)
add_to_zigzag(zigzag_barindex, bar_index)
if array.size(zigzag_price) >= 3
_text = direction == "ph" ? array.get(zigzag_price, 0) > array.get(zigzag_price, 2) ? 'HH' : 'LH' : array.get(zigzag_price, 0) < array.get(zigzag_price, 2) ? 'LL' : 'HL'
add_to_zigzag(zigzag_hhll, _text)
else
update_zigzag(zigzag_price, direction == "ph" ? pivoth : pivotl, direction)
update_zigzag(zigzag_barindex, bar_index, direction, true)
if array.size(zigzag_price) >= 3
_text = direction == "ph" ? array.get(zigzag_price, 0) > array.get(zigzag_price, 2) ? 'HH' : 'LH' : array.get(zigzag_price, 0) < array.get(zigzag_price, 2) ? 'LL' : 'HL'
array.set(zigzag_hhll, 0, _text)
// --------------- Zigzags vars ---------------
// --------------- Plot ---------------
if array.size(zigzag_price) >= 3 and array.size(zigzag_hhll) >= 3
var line zzline = na
var label zzlabel = na
var label pattern_label_bull = na
var label pattern_label_bear = na
price0 = array.get(zigzag_price, 0)
price1 = array.get(zigzag_price, 1)
price2 = array.get(zigzag_price, 2)
old_price0 = array.get(oldzigzag_price, 0)
old_price1 = array.get(oldzigzag_price, 1)
barindex0 = math.round(array.get(zigzag_barindex, 0))
barindex1 = math.round(array.get(zigzag_barindex, 1))
old_barindex0 = math.round(array.get(oldzigzag_barindex, 0))
old_barindex1 = math.round(array.get(oldzigzag_barindex, 1))
zigzag0 = array.get(zigzag_hhll, 0)
zigzag1 = array.get(zigzag_hhll, 1)
old_zigzag0 = array.get(oldzigzag_hhll, 0)
old_zigzag1 = array.get(oldzigzag_hhll, 1)
hhlltxt = direction == "ph" ? price0 > price2 ? 'HH' : 'LH' : price0 < price2 ? 'LL' : 'HL'
txtcol = direction == "ph" ? price0 > price2 ? upcol : dncol : price0 < price2 ? dncol : upcol
if price0 != old_price0 and barindex0 != old_barindex0
// Update line and label
if price1 == old_price1 and barindex1 == old_barindex1
line.delete(zzline)
label.delete(zzlabel)
label.delete(pattern_label_bull)
label.delete(pattern_label_bear)
// plot lines
if showzz
zzline := line.new(
x1=barindex0, y1=price0,
x2=barindex1, y2=price1,
color=direction == "ph" ? upcol : dncol,
width=zzwidth,
style=zzstyle == 'Dashed' ? line.style_dashed : line.style_dotted)
// plot labels
if showhhll
zzlabel := label.new(
x=barindex0,
y=price0,
text=hhlltxt,
// color=labelcol,
textcolor=txtcol,
yloc=direction == "ph" ? yloc.abovebar : yloc.belowbar,
style=label.style_none)
// Plot pattern matches
if showPatternMatch
bull1Met = bullBool1 ? isMatching(bullCond1, zigzag_hhll) : false
bull2Met = bullBool2 ? isMatching(bullCond2, zigzag_hhll) : false
bull3Met = bullBool3 ? isMatching(bullCond3, zigzag_hhll) : false
bull4Met = bullBool4 ? isMatching(bullCond4, zigzag_hhll) : false
bull5Met = bullBool5 ? isMatching(bullCond5, zigzag_hhll) : false
bull6Met = bullBool6 ? isMatching(bullCond6, zigzag_hhll) : false
bull7Met = bullBool7 ? isMatching(bullCond7, zigzag_hhll) : false
bear1Met = bearBool1 ? isMatching(bearCond1, zigzag_hhll) : false
bear2Met = bearBool2 ? isMatching(bearCond2, zigzag_hhll) : false
bear3Met = bearBool3 ? isMatching(bearCond3, zigzag_hhll) : false
bear4Met = bearBool4 ? isMatching(bearCond4, zigzag_hhll) : false
bear5Met = bearBool5 ? isMatching(bearCond5, zigzag_hhll) : false
bear6Met = bearBool6 ? isMatching(bearCond6, zigzag_hhll) : false
bear7Met = bearBool7 ? isMatching(bearCond7, zigzag_hhll) : false
bullPatternText = ""
bullPatternText := bull1Met ? addToString(bullPatternText, bullTxt1) : bullPatternText
bullPatternText := bull2Met ? addToString(bullPatternText, bullTxt2) : bullPatternText
bullPatternText := bull3Met ? addToString(bullPatternText, bullTxt3) : bullPatternText
bullPatternText := bull4Met ? addToString(bullPatternText, bullTxt4) : bullPatternText
bullPatternText := bull5Met ? addToString(bullPatternText, bullTxt5) : bullPatternText
bullPatternText := bull6Met ? addToString(bullPatternText, bullTxt6) : bullPatternText
bullPatternText := bull7Met ? addToString(bullPatternText, bullTxt7) : bullPatternText
bearPatternText = ""
bearPatternText := bear1Met ? addToString(bearPatternText, bearTxt1) : bearPatternText
bearPatternText := bear2Met ? addToString(bearPatternText, bearTxt2) : bearPatternText
bearPatternText := bear3Met ? addToString(bearPatternText, bearTxt3) : bearPatternText
bearPatternText := bear4Met ? addToString(bearPatternText, bearTxt4) : bearPatternText
bearPatternText := bear5Met ? addToString(bearPatternText, bearTxt5) : bearPatternText
bearPatternText := bear6Met ? addToString(bearPatternText, bearTxt6) : bearPatternText
bearPatternText := bear7Met ? addToString(bearPatternText, bearTxt7) : bearPatternText
pattern_label_bull := label.new(
barindex0,
y=price0,
yloc=yloc.belowbar,
text=bullPatternText != "" ? bullPatternText : "",
color=uplabelcol,
textcolor=uplabeltextcol,
style=bullPatternText != "" ? label.style_label_up : label.style_none)
pattern_label_bear := label.new(
barindex0,
y=price0,
yloc=yloc.abovebar,
text=bearPatternText != "" ? bearPatternText : "",
color=dnlabelcol,
textcolor=dnlabeltextcol,
style=bearPatternText != "" ? label.style_label_down : label.style_none)
// --------------- Plot ---------------
// --------------- BOS ---------------
bosBearMatchPattern = "HL,HH,LL"
bosBullMatchPattern = "LH,LL,HH"
if array.size(zigzag_price) >= 3 and array.size(zigzag_hhll) >= 3 and showbosline
isBullMatching = isMatching(bosBullMatchPattern, zigzag_hhll)
isBearMatching = isMatching(bosBearMatchPattern, zigzag_hhll)
if isBearMatching and not isBearMatching[1]
_bi = array.get(zigzag_barindex, 2)
line.new(bar_index[bar_index - _bi], low[bar_index - _bi], bar_index, low[bar_index - _bi], color=dncol)
label.new(bar_index, low[bar_index - _bi], "bos ", style=label.style_none, size=size.small, textcolor=dncol)
if isBullMatching and not isBullMatching[1]
_bi = array.get(zigzag_barindex, 2)
line.new(bar_index[bar_index - _bi], high[bar_index - _bi], bar_index, high[bar_index - _bi], color=upcol)
label.new(bar_index, high[bar_index - _bi], "bos ", style=label.style_none, size=size.small, textcolor=upcol)
// --------------- BOS ---------------
// if barstate.islast
// label.new(bar_index, low, str.tostring(zigzag_hhll), yloc=yloc.belowbar)
// WATERMARK
if barstate.islast
_table = table.new("bottom_left", 1, 2)
table.cell(_table, 0, 0, text="@Nephew_Sam_", text_size=size.small, text_color=color.new(color.gray, 50)) |
Follow The Ranging Hull - study | https://www.tradingview.com/script/bGQQkbF2-Follow-The-Ranging-Hull-study/ | flygalaxies | https://www.tradingview.com/u/flygalaxies/ | 71 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © flygalaxies
// Strategy based on the Follow Line Indicator by Dreadblitz, Hull Suite by InSilico and Range Filter Buy and Sell 5 min by guikroth
// Designed for the purpose of back testing
// Strategy:
// - When the Range Filter Color Changes, And the HULL Suite is in that direction, Enter In that direction
// - e.g Range Filter Changes color from red to green, and Hull Suite is in Green. Enter Long
// - e.g Range Filter Changes color from green to red, and Hull Suite is in red. Enter Short
//
// - When the Following Line Color Changes, And the HULL Suite is in that direction, Enter In that direction
// - e.g Following Line Changes color from red to green, and Hull Suite is in Green. Enter Long
// - e.g Following Line Changes color from green to red, and Hull Suite is in red. Enter Short
//
// Credits:
// Hull Suite by InSilico https://www.tradingview.com/u/InSilico/
// Range Filter Buy and Sell 5 min https://www.tradingview.com/u/guikroth/
// Follow Line Indicator by Dreadblitz https://www.tradingview.com/u/Dreadblitz/
//@version=5
// strategy("Follow The Ranging Hull", overlay=true, initial_capital = 50000, process_orders_on_close = true)
indicator("Follow The Ranging Hull", overlay=true)
/////////////////////////
// STRATEGY SETTINGS ///
///////////////////////
fromDate = input.time(title="From", defval=timestamp("01 Jan 2022 00:00 GMT+2"), inline="1", group="Date Range")
toDate = input.time(title="To", defval=timestamp("01 Jan 2022 23:00 GMT+2"), inline="1", group="Date Range")
inDate = time >= fromDate and time <= toDate
isStrategy = input.bool(title="IS STRATEGY", defval = false, group="Trading Rules")
isPointRule = input.bool(title="Apply Point Rule", defval = false, group="Trading Rules")
pointRulePoints = input.int(title="Points (The points that it uses to take profit)", defval = 80, group="Trading Rules")
////////////////////////////////////
// FOLLOWING, ENTRY, EXIT RULES ///
//////////////////////////////////
followLineUseATR = input.bool(title="Use ATR for the Following Line (if false, it will use the slow range filter)", defval = false, group="Following, Entry, Exit Rules")
followRngFilterEntry = input.bool(title="use Following line or Slow Range Filter as entry point", defval = false, group="Following, Entry, Exit Rules")
showStatusWindow = input.bool(title="Show Status Window", defval = true, group="Following, Entry, Exit Rules")
hl = input.bool(defval = true, title = "Hide Labels", group = "Following, Entry, Exit Rules")
exitRule = input.session("Hull", title="Exit Rule", options=["Hull", "RangeFilter", "Following/SlowRangeFilter"], group="Following, Entry, Exit Rules")
////////////////////
// COLOR INPUTS ///
//////////////////
rngFilterColorUp = input.color(title="Fast Range Filter Color Up", defval = color.green, group="Range Filter Colors")
rngFilterColorDown = input.color(title="Fast Range Filter Color Down", defval = color.red, group="Range Filter Colors")
rngFilterColorUpSlow = input.color(title="Slow Range Filter Color Up", defval = color.green, group="Range Filter Colors")
rngFilterColorDownSlow = input.color(title="Slow Range Filter Color Down", defval = color.red, group="Range Filter Colors")
hullColorUp = input.color(title="Hull Color Up", defval = color.green, group="Hull Suite Colors")
hullColorDown = input.color(title="Hull Color Down", defval = color.red, group="Hull Suite Colors")
fliColorUp = input.color(title="Follow Line Color Up", defval = color.green, group="Following Line Colors")
fliColorDown = input.color(title="Follow Line Color Down", defval = color.red, group="Following Line Colors")
///////////////////////////
// Range Filter INPUTS ///
/////////////////////////
// Fast Inputs
src = input(defval=ohlc4, title="Range Filter Fast Source", group="Range Filter Fast")
per = input.int(defval=33, minval=1, title="Range Filter Fast Sampling Period", group="Range Filter Fast")
mult = input.float(defval=2.1, minval=0.1, title="Range Filter Fast Multiplier", group="Range Filter Fast", step=0.1)
// Slow Inputs
srcSlow = input(defval=ohlc4, title="Range Filter Slow Source", group="Range Filter Slow")
perSlow = input.int(defval=48, minval=1, title="Range Filter Slow Sampling Period", group="Range Filter Slow")
multSlow = input.float(defval=3.4, minval=0.1, title="Range Filter Slow Multiplier", group="Range Filter Slow", step=0.1)
/////////////////////////
// Hull Suite INPUTS ///
///////////////////////
srcHull = input(close, title="Source", group="Hull Suite")
modeSwitch = input.session("Ehma", title="Hull Variation", options=["Hma", "Thma", "Ehma"], group="Hull Suite")
length = input(55, title="Length(180-200 for floating S/R , 55 for swing entry)")
switchColor = input(true, "Color Hull according to trend?", group="Hull Suite")
visualSwitch = input(true, title="Show as a Band?", group="Hull Suite")
thicknesSwitch = input(1, title="Line Thickness", group="Hull Suite")
transpSwitch = input.int(40, title="Band Transparency",step=5, group="Hull Suite")
//////////////////////////
// FOLLOW LINE INPUTS ///
////////////////////////
BBperiod = input.int(defval = 21, title = "BB Period", minval = 1, group = "Following Line ")
BBdeviations = input.float(defval = 1.00, title = "BB Deviations", minval = 0.1, step=0.05, group = "Following Line")
UseATRfilter = input.bool(defval = true, title = "ATR Filter", group = "Following Line ")
ATRperiod = input.int(defval = 5, title = "ATR Period", minval = 1, group = "Following Line ")
//////////////////////////
// TSI INPUTS ///////////
////////////////////////
tsiSrc = input(title="Source", defval=close, group = "TSI")
longLength = input.int(title="Long Length", defval=6, group = "TSI")
shortLength = input.int(title="Short Length" , defval=13, group = "TSI")
signalLength = input.int(title="Signal Length" , defval=4, group = "TSI")
//////////////////////////
// Range Filter Logic ///
////////////////////////
// Fast
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult)
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(src, smrng)
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
filtcolor = upward > 0 ? rngFilterColorUp : downward > 0 ? rngFilterColorDown : color.orange
filtplot = plot(filt, color=filtcolor, linewidth=3, title="Fast Range Filter ")
// Slow
smoothrngSlow(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrngSlow = ta.ema(avrng, wper) * m
smoothrngSlow
smrngSlow = smoothrngSlow(srcSlow, perSlow, multSlow)
rngfiltSlow(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filtSlow = rngfiltSlow(srcSlow, smrngSlow)
upwardSlow = 0.0
upwardSlow := filtSlow > filtSlow[1] ? nz(upwardSlow[1]) + 1 : filtSlow < filtSlow[1] ? 0 : nz(upwardSlow[1])
downwardSlow = 0.0
downwardSlow := filtSlow < filtSlow[1] ? nz(downwardSlow[1]) + 1 : filtSlow > filtSlow[1] ? 0 : nz(downwardSlow[1])
filtcolorSlow = upwardSlow > 0 ? rngFilterColorUpSlow : downwardSlow > 0 ? rngFilterColorDownSlow : color.orange
filtplotSlow = plot(followLineUseATR == false ? filtSlow : na, color=filtcolorSlow, linewidth=3, title="Slow Range Filter")
////////////////////////
// Hull Suite Logic ///
//////////////////////
HMA(_srcHull, _length) => ta.wma(2 * ta.wma(_srcHull, _length / 2) - ta.wma(_srcHull, _length), math.round(math.sqrt(_length)))
EHMA(_srcHull, _length) => ta.ema(2 * ta.ema(_srcHull, _length / 2) - ta.ema(_srcHull, _length), math.round(math.sqrt(_length)))
THMA(_srcHull, _length) => ta.wma(ta.wma(_srcHull,_length / 3) * 3 - ta.wma(_srcHull, _length / 2) - ta.wma(_srcHull, _length), _length)
Mode(modeSwitch, src, len) =>
modeSwitch == "Hma" ? HMA(src, len) :
modeSwitch == "Ehma" ? EHMA(src, len) :
modeSwitch == "Thma" ? THMA(src, len/2) : na
_hull = Mode(modeSwitch, src, int(length))
HULL = _hull
MHULL = HULL[0]
SHULL = HULL[2]
// HIGHER TIMEFRAME HULL
HULL1 = request.security(syminfo.ticker, "1", _hull)
HULL5 = request.security(syminfo.ticker, "5", _hull)
HULL15 = request.security(syminfo.ticker, "15", _hull)
HULL3 = request.security(syminfo.ticker, "3", _hull)
hullColor = switchColor ? (HULL > HULL[2] ? hullColorUp : hullColorDown) : #ff9800
// Fi1 = plot(MHULL, title="MHULL", color=hullColor, linewidth=thicknesSwitch, transp=50)
Fi1 = plot(MHULL, title="MHULL", color=color.new(hullColor, 50), linewidth=thicknesSwitch)
// Fi2 = plot(visualSwitch ? SHULL : na, title="SHULL", color=hullColor, linewidth=thicknesSwitch, transp=50)
Fi2 = plot(visualSwitch ? SHULL : na, title="SHULL", color=color.new(hullColor, 50), linewidth=thicknesSwitch)
fill(Fi1, Fi2, title="Band Filler", color=color.new(hullColor, transpSwitch))
/////////////////////////
// Follow Line Logic ///
///////////////////////
BBUpper=ta.sma (close,BBperiod)+ta.stdev(close, BBperiod)*BBdeviations
BBLower=ta.sma (close,BBperiod)-ta.stdev(close, BBperiod)*BBdeviations
TrendLine = 0.0
iTrend = 0.0
buy = 0.0
sell = 0.0
atr = ta.atr(ATRperiod)
BBSignal = close>BBUpper? 1 : close<BBLower? -1 : 0
if BBSignal == 1 and UseATRfilter == 1
TrendLine:=low-atr
if TrendLine<TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 1
TrendLine:=high+atr
if TrendLine>TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 1
TrendLine:=TrendLine[1]
if BBSignal == 1 and UseATRfilter == 0
TrendLine:=low
if TrendLine<TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 0
TrendLine:=high
if TrendLine>TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 0
TrendLine:=TrendLine[1]
iTrend:=iTrend[1]
if TrendLine>TrendLine[1]
iTrend:=1
if TrendLine<TrendLine[1]
iTrend:=-1
buy:= iTrend[1]==-1 and iTrend==1 and followLineUseATR == true ? 1 : na
sell:= iTrend[1]==1 and iTrend==-1 and followLineUseATR == true ? 1 : na
plot(followLineUseATR == true ? TrendLine : na, color=iTrend > 0? fliColorUp : fliColorDown ,style=plot.style_line,linewidth=2,title="Trend Line")
//////////////////////////
// TSI Logic ///////////
////////////////////////
mom = ta.change(tsiSrc)
numerator = ta.ema(ta.ema(mom, longLength), shortLength)
denominator = ta.ema(ta.ema(math.abs(mom), longLength), shortLength)
tsi = 100 * numerator / denominator
signal = ta.ema(tsi, signalLength)
trendColor = tsi > signal ? hullColorUp : hullColorDown
// tsiColor = applyRibbonFilling ? trendColor : #ff3e7d
// signalColor = applyRibbonFilling ? trendColor : #3c78d8
TSI1 = request.security(syminfo.ticker, "1", trendColor)
TSI3 = request.security(syminfo.ticker, "3", trendColor)
TSI5 = request.security(syminfo.ticker, "5", trendColor)
TSI15 = request.security(syminfo.ticker, "15", trendColor)
///////////////////////////
// STATUS WINDOW LOGIC ///
/////////////////////////
if(showStatusWindow == true )
var table statuswindow = table.new(position.top_right, 100, 100, border_width=2)
HullTxt1 = " Hull 1 min "
TsiTxt1 = " TSI 1 min "
if(HULL1 > HULL1[2])
table.cell(statuswindow, 1, 1, text=HullTxt1, bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 1, 1, text=HullTxt1, bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
table.cell(statuswindow, 1, 2, text=TsiTxt1, bgcolor=TSI1, text_color=color.white, text_size=size.small)
HullTxt3 = " Hull 3 min "
TsiTxt3 = " TSI 3 min "
if(HULL3 > HULL3[2])
table.cell(statuswindow, 2, 1, text=HullTxt3, bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 2, 1, text=HullTxt3, bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
table.cell(statuswindow, 2, 2, text=TsiTxt3, bgcolor=TSI3, text_color=color.white, text_size=size.small)
HullTxt5 = " Hull 5 min "
TsiTxt5 = " TSI 5 min "
if(HULL5 > HULL5[2])
table.cell(statuswindow, 3, 1, text=HullTxt5, bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 3, 1, text=HullTxt5, bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
table.cell(statuswindow, 3, 2, text=TsiTxt5, bgcolor=TSI5, text_color=color.white, text_size=size.small)
HullTxt15 = " Hull 15 min "
TsiTxt15 = " TSI 15 min "
if(HULL15 > HULL15[2])
table.cell(statuswindow, 4, 1, text=HullTxt15, bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 4, 1, text=HullTxt15, bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
table.cell(statuswindow, 4, 2, text=TsiTxt15, bgcolor=TSI15, text_color=color.white, text_size=size.small)
////////////////////////////////////////////
// ALERTS & LABELS BASED ON ENTRY POINT ///
//////////////////////////////////////////
//////////////////////////////////
// STRATEGY ENTRY POINT LOGIC ///
////////////////////////////////
// if(inDate and isStrategy)
// // RANGE FILTER ENTRY LONG WITH HULL
// if(filtcolor[1] == rngFilterColorDown and filtcolor == rngFilterColorUp)
// strategy.entry("rngFiltLong", strategy.long, when = HULL > HULL[2])
// // RANGE FILTER ENTRY SHORT WITH HULL
// if(filtcolor[1] == rngFilterColorUp and filtcolor == rngFilterColorDown)
// strategy.entry("rngFiltShort", strategy.short, when = HULL < HULL[2])
// // FOLLOW LINE OR SLOW RANGE FILTER ENTRY, IF ENABLED
// if(followRngFilterEntry == true)
// if(followLineUseATR == true)
// // FOLLOWING LINE ENTRY SHORT WITH HULL
// if(buy == 1)
// strategy.entry("fliLong", strategy.long, when = HULL > HULL[2])
// // FOLLOWING LINE ENTRY SHORT WITH HULL
// if(sell == 1)
// strategy.entry("fliShort", strategy.short, when = HULL < HULL[2])
// else
// // SLOW RANGE FILTER ENTRY WITH HULL
// if(filtcolorSlow[1] == rngFilterColorDownSlow and filtcolorSlow == rngFilterColorUpSlow)
// strategy.entry("slowRngFiltLong", strategy.long, when = HULL > HULL[2])
// // SLOW RANGE FILTER ENTRY SHORT WITH HULL
// if(filtcolorSlow[1] == rngFilterColorUpSlow and filtcolorSlow == rngFilterColorDownSlow)
// strategy.entry("slowRngFiltShort", strategy.short, when = HULL < HULL[2])
// if(isPointRule)
// strategy.exit('exitRngFiltLong', 'rngFiltLong', profit=pointRulePoints)
// strategy.exit('exitRngFiltShort', 'rngFiltShort', profit=pointRulePoints)
// strategy.exit('exitSlowRngFiltLong', 'slowRngFiltLong', profit=pointRulePoints)
// strategy.exit('exitSlowRngFiltShort', 'slowRngFiltShort', profit=pointRulePoints)
// strategy.exit('exitFliLong', 'fliLong', profit=pointRulePoints, when = sell == 1)
// strategy.exit('exitFliShort', 'fliShort', profit=pointRulePoints , when = buy == 1)
// closingRuleLong = exitRule == "Hull" ? HULL > HULL[2] : exitRule == "RangeFilter" ? (filtcolor[2] == rngFilterColorUp and filtcolor == rngFilterColorDown) : exitRule == "Following/SlowRangeFilter" ? followLineUseATR == false? (sell == 1): (filtcolor[2] == rngFilterColorUp and filtcolor == rngFilterColorDown): na
// closingRuleShort = exitRule == "Hull" ? HULL > HULL[2] : exitRule == "RangeFilter" ? (filtcolor[1] == rngFilterColorDown and filtcolor == rngFilterColorUp) : exitRule == "Following/SlowRangeFilter" ? followLineUseATR == true ? (buy == 1) : (filtcolor[2] == rngFilterColorDown and filtcolor == rngFilterColorUp) : na
// strategy.close("rngFiltLong", when = closingRuleLong)
// strategy.close("rngFiltShort", when = closingRuleShort)
// strategy.close("slowRngFiltLong", when = closingRuleLong)
// strategy.close("slowRngFiltShort", when = closingRuleShort)
// strategy.close("fliLong", when = closingRuleLong)
// strategy.close("fliShort", when = closingRuleShort)
|
Daily Short Volume Ratio | https://www.tradingview.com/script/YbF0y6ua-Daily-Short-Volume-Ratio/ | Snufkin420TC | https://www.tradingview.com/u/Snufkin420TC/ | 99 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Snufkin420TC
//@version=5
indicator('Daily Short Volume Ratio', shorttitle="SVR", timeframe="D", timeframe_gaps=true)
smooth = input.bool(false, title = "Smooth")
leng = input.int(10, title = "Smoothing length")
showindex1 = input.bool(true, title = "Show index 1", group="Index tickers")
index1_sym = input.string(defval="SPY",title="Index 1", group="Index tickers")
showindex2 = input.bool(false, title = "Show index 2", group="Index tickers")
index2_sym = input.string(defval="DIA",title="Index 2", group="Index tickers")
showindex3 = input.bool(false, title = "Show index 3", group="Index tickers")
index3_sym = input.string(defval="IWM",title="Index 3", group="Index tickers")
//initialize values
sv_ratio_ticker = 0.0
sv_ratio_ticker1 = 0.0
sv_ratio_ticker2 = 0.0
sv_ratio_ticker3 = 0.0
sv_ratio_ticker4 = 0.0
sv_ratio_index1 = 0.0
sv_ratio_index2 = 0.0
sv_ratio_index3 = 0.0
// Grab quandle data for ticker from NYSE and NASDAQ exchange and combine; use chart symbol .. 1 day
sv_ticker_NASDAQ = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
sv_ticker_NYSE = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
tv_ticker_NASDAQ = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
tv_ticker_NYSE = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
sv_ticker = sv_ticker_NASDAQ + sv_ticker_NYSE
tv_ticker = tv_ticker_NASDAQ + tv_ticker_NYSE
// Grab quandle data for ticker from NYSE and NASDAQ exchange and combine; use chart symbol .. 2 days
sv_ticker_NASDAQ1 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[1]
sv_ticker_NYSE1 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[1]
tv_ticker_NASDAQ1 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[1]
tv_ticker_NYSE1 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[1]
sv_ticker1 = sv_ticker_NASDAQ + sv_ticker_NYSE + sv_ticker_NASDAQ1 + sv_ticker_NYSE1
tv_ticker1 = tv_ticker_NASDAQ + tv_ticker_NYSE + tv_ticker_NASDAQ1 + tv_ticker_NYSE1
// Grab quandle data for ticker from NYSE and NASDAQ exchange and combine; use chart symbol .. 3 days
sv_ticker_NASDAQ2 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[2]
sv_ticker_NYSE2 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[2]
tv_ticker_NASDAQ2 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[2]
tv_ticker_NYSE2 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[2]
sv_ticker2 = sv_ticker_NASDAQ + sv_ticker_NYSE + sv_ticker_NASDAQ1 + sv_ticker_NYSE1 + sv_ticker_NASDAQ2 + sv_ticker_NYSE2
tv_ticker2 = tv_ticker_NASDAQ + tv_ticker_NYSE + tv_ticker_NASDAQ1 + tv_ticker_NYSE1 + tv_ticker_NASDAQ2 + tv_ticker_NYSE2
// Grab quandle data for ticker from NYSE and NASDAQ exchange and combine; use chart symbol .. 4 days
sv_ticker_NASDAQ3 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[3]
sv_ticker_NYSE3 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[3]
tv_ticker_NASDAQ3 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[3]
tv_ticker_NYSE3 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[3]
sv_ticker3 = sv_ticker_NASDAQ + sv_ticker_NYSE + sv_ticker_NASDAQ1 + sv_ticker_NYSE1 + sv_ticker_NASDAQ2 + sv_ticker_NYSE2 + sv_ticker_NASDAQ3 + sv_ticker_NYSE3
tv_ticker3 = tv_ticker_NASDAQ + tv_ticker_NYSE + tv_ticker_NASDAQ1 + tv_ticker_NYSE1 + tv_ticker_NASDAQ2 + tv_ticker_NYSE2 + tv_ticker_NASDAQ3 + tv_ticker_NYSE3
// Grab quandle data for ticker from NYSE and NASDAQ exchange and combine; use chart symbol .. 5 days
sv_ticker_NASDAQ4 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[4]
sv_ticker_NYSE4 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)[4]
tv_ticker_NASDAQ4 = request.quandl("FINRA/FNSQ_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[4]
tv_ticker_NYSE4 = request.quandl("FINRA/FNYX_" + syminfo.ticker, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)[4]
sv_ticker4 = sv_ticker_NASDAQ + sv_ticker_NYSE + sv_ticker_NASDAQ1 + sv_ticker_NYSE1 + sv_ticker_NASDAQ2 + sv_ticker_NYSE2 + sv_ticker_NASDAQ3 + sv_ticker_NYSE3 + sv_ticker_NASDAQ4 + sv_ticker_NYSE4
tv_ticker4 = tv_ticker_NASDAQ + tv_ticker_NYSE + tv_ticker_NASDAQ1 + tv_ticker_NYSE1 + tv_ticker_NASDAQ2 + tv_ticker_NYSE2 + tv_ticker_NASDAQ3 + tv_ticker_NYSE3 + tv_ticker_NASDAQ4 + tv_ticker_NYSE4
// values to plot
sv_ratio_ticker := (smooth == false) ? (sv_ticker/tv_ticker) : ta.linreg(sv_ticker/tv_ticker, leng, 0)
sv_ratio_ticker1 := (smooth == false) ? (sv_ticker1/tv_ticker1) : ta.linreg(sv_ticker1/tv_ticker1, leng, 0)
sv_ratio_ticker2 := (smooth == false) ? (sv_ticker2/tv_ticker2) : ta.linreg(sv_ticker2/tv_ticker2, leng, 0)
sv_ratio_ticker3 := (smooth == false) ? (sv_ticker3/tv_ticker3) : ta.linreg(sv_ticker3/tv_ticker3, leng, 0)
sv_ratio_ticker4 := (smooth == false) ? (sv_ticker4/tv_ticker4) : ta.linreg(sv_ticker4/tv_ticker4, leng, 0)
// Convert index reference symbol into symbol for quandle
index1_NASDAQ = "FINRA/FNSQ_" + index1_sym // convert to Nasdaq exchange for quandle
index1_NYSE = "FINRA/FNYX_" + index1_sym // convert to NYSE exchange for quandle
// Grab quandle data for index reference from NYSE and NASDAQ exchange and combine
sv_index1_NASDAQ = request.quandl(index1_NASDAQ, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
sv_index1_NYSE = request.quandl(index1_NYSE, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
tv_index1_NASDAQ = request.quandl(index1_NASDAQ, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
tv_index1_NYSE = request.quandl(index1_NYSE, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
sv_index1 = sv_index1_NASDAQ + sv_index1_NYSE
tv_index1 = tv_index1_NASDAQ + tv_index1_NYSE
// Convert index reference symbol into symbol for quandle
index2_NASDAQ = "FINRA/FNSQ_" + index2_sym // convert to Nasdaq exchange for quandle
index2_NYSE = "FINRA/FNYX_" + index2_sym // convert to NYSE exchange for quandle
// Grab quandle data for index reference from NYSE and NASDAQ exchange and combine
sv_index2_NASDAQ = request.quandl(index2_NASDAQ, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
sv_index2_NYSE = request.quandl(index2_NYSE, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
tv_index2_NASDAQ = request.quandl(index2_NASDAQ, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
tv_index2_NYSE = request.quandl(index2_NYSE, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
sv_index2 = sv_index2_NASDAQ + sv_index2_NYSE
tv_index2 = tv_index2_NASDAQ + tv_index2_NYSE
// Convert index reference symbol into symbol for quandle
index3_NASDAQ = "FINRA/FNSQ_" + index3_sym // convert to Nasdaq exchange for quandle
index3_NYSE = "FINRA/FNYX_" + index3_sym // convert to NYSE exchange for quandle
// Grab quandle data for index reference from NYSE and NASDAQ exchange and combine
sv_index3_NASDAQ = request.quandl(index3_NASDAQ, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
sv_index3_NYSE = request.quandl(index3_NYSE, barmerge.gaps_off, index = 0, ignore_invalid_symbol = true)
tv_index3_NASDAQ = request.quandl(index3_NASDAQ, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
tv_index3_NYSE = request.quandl(index3_NYSE, barmerge.gaps_off, index = 2, ignore_invalid_symbol = true)
sv_index3 = sv_index3_NASDAQ + sv_index3_NYSE
tv_index3 = tv_index3_NASDAQ + tv_index3_NYSE
// conditionals for plotting
if (showindex1 == true)
sv_ratio_index1 := (smooth == false) ? (sv_index1/tv_index1) : ta.linreg(sv_index1/tv_index1, leng, 0)
if (showindex2 == true)
sv_ratio_index2 := (smooth == false) ? (sv_index2/tv_index2) : ta.linreg(sv_index2/tv_index2, leng, 0)
if (showindex3 == true)
sv_ratio_index3 := (smooth == false) ? (sv_index3/tv_index3) : ta.linreg(sv_index3/tv_index3, leng, 0)
//plot boundary bars
hbear5 = hline(0.0, linestyle=hline.style_solid, color=color.new(color.green,45), linewidth=1, editable=false)
hbear4 = hline(0.1, linestyle=hline.style_solid, color=color.new(color.green,55), linewidth=1, editable=false)
hbear3 = hline(0.2, linestyle=hline.style_solid, color=color.new(color.green,65), linewidth=1, editable=false)
hbear2 = hline(0.3, linestyle=hline.style_solid, color=color.new(color.green,75), linewidth=1, editable=false)
hbear1 = hline(0.4, linestyle=hline.style_solid, color=color.new(color.green,85), linewidth=1, editable=false)
hcenter = hline(0.5, linestyle=hline.style_dashed, color=color.new(color.gray,0), linewidth=1, editable=false)
hbull1 = hline(0.6, linestyle=hline.style_solid, color=color.new(color.red,85), linewidth=1, editable=false)
hbull2 = hline(0.7, linestyle=hline.style_solid, color=color.new(color.red, 75), linewidth=1, editable=false)
hbull3 = hline(0.8, linestyle=hline.style_solid, color=color.new(color.red,65), linewidth=1, editable=false)
hbull4 = hline(0.9, linestyle=hline.style_solid, color=color.new(color.red,55), linewidth=1, editable=false)
hbull5 = hline(1.0, linestyle=hline.style_solid, color=color.new(color.red,45), linewidth=1, editable=false)
//colors
col_index1 = color.new(color.gray, 30)
col_index2 = color.new(color.maroon, 30)
col_index3 = color.new(color.olive, 30)
col1 = color.new(color.lime, 0)
col2 = color.new(color.yellow, 0)
col3 = color.new(color.orange, 0)
col4 = color.new(color.red, 0)
col5 = color.new(color.fuchsia, 0)
//plots
plot(sv_ratio_ticker, title="SVR 1 day", color=col1)
plot(sv_ratio_ticker1, title="SVR 2 days", color=col2)
plot(sv_ratio_ticker2, title="SVR 3 days", color=col3)
plot(sv_ratio_ticker3, title="SVR 4 days", color=col4)
plot(sv_ratio_ticker4, title="SVR 5 days", color=col5)
plot(sv_ratio_index1, title="Index 1 SVR 1 day", color=col_index1)
plot(sv_ratio_index2, title="Index 2 SVR 1 day", color=col_index2)
plot(sv_ratio_index3, title="Index 3 SVR 1 day", color=col_index3)
// END |
STD Stepped Ehlers Optimal Tracking Filter MTF w/ Alerts [Loxx] | https://www.tradingview.com/script/4ebYbQYv-STD-Stepped-Ehlers-Optimal-Tracking-Filter-MTF-w-Alerts-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 356 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator('STD Step Ehlers Optimal Tracking Filter MTF w/ Alerts [Loxx]',
shorttitle = "STDSEOTFMTFA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
_filt(src, len, filt)=>
price = src
filtdev = filt * ta.stdev(src, len)
price := math.abs(price - price[1]) < filtdev ? price[1] : price
price
_otf(src)=>
value1 = 0., value2 = 0., lambda = 0., value3 = 0.
value1 := 0.2 * (src - nz(src[1])) + 0.8 * nz(value1[1])
value2 := 0.1 * (high - low) + 0.8 * nz(value2[1])
lambda := math.abs(value1 / value2)
alpha = (-lambda * lambda + math.sqrt(lambda * lambda * lambda * lambda + 16 * lambda * lambda)) / 8
value3 := alpha * src + (1 - alpha) * nz(value3[1])
value3
src = input.source(hl2, "Soruce", group= "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "Ehlers OTF", "Both"], group= "Basic Settings")
len = input.int(15, "Filter Length", group= "Basic Settings", minval = 1)
filtdev = input.float(0.5, "Filter Devaitions", minval = 0, group= "Basic Settings", step = 0.01)
colorbars = input.bool(false, "Color bars?", group= "UI Options")
showSigs = input.bool(false, "Show signals?", group= "UI Options")
price = filterop == "Both" or filterop == "Price" ? _filt(src, len, filtdev) : src
otfout = _otf(price)
out = filterop == "Both" or filterop == "Ehlers OTF" ? _filt(otfout, len, filtdev) : otfout
goLong_pre = ta.crossover(out, out[1])
goShort_pre = ta.crossunder(out, out[1])
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plot(out,"EOTF", color = contSwitch == 1 ? greencolor : redcolor, linewidth = 3)
barcolor(colorbars ? contSwitch == 1 ? greencolor : redcolor : na)
plotshape(showSigs and goLong, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.belowbar, size = size.small)
plotshape(showSigs and goShort, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.abovebar, size = size.small)
alertcondition(goLong, title="Long", message="Ehlers Step OTF: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Ehlers Step OTF: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Better Heiken-Ashi Candles w/ Expanded Source Types [Loxx] | https://www.tradingview.com/script/AdBj6Sva-Better-Heiken-Ashi-Candles-w-Expanded-Source-Types-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 205 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Better Heiken-Ashi Candles w/ Expanded Source Types [Loxx]",
shorttitle = "BHACECT [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
_ama(src, len, fl, sl)=>
flout = 2/(fl + 1)
slout = 2/(sl + 1)
hh = ta.highest(len + 1)
ll = ta.lowest(len + 1)
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0
ssc = mltp * (flout - slout) + slout
ama = 0.
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))
ama
_t3(src, len) =>
xe1_1 = ta.ema(src, len)
xe2_1 = ta.ema(xe1_1, len)
xe3_1 = ta.ema(xe2_1, len)
xe4_1 = ta.ema(xe3_1, len)
xe5_1 = ta.ema(xe4_1, len)
xe6_1 = ta.ema(xe5_1, len)
b_1 = 0.7
c1_1 = -b_1 * b_1 * b_1
c2_1 = 3 * b_1 * b_1 + 3 * b_1 * b_1 * b_1
c3_1 = -6 * b_1 * b_1 - 3 * b_1 - 3 * b_1 * b_1 * b_1
c4_1 = 1 + 3 * b_1 + b_1 * b_1 * b_1 + 3 * b_1 * b_1
nT3Average = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1
nT3Average
_kama(src, len, kama_fastend, kama_slowend) =>
xvnoise = math.abs(src - src[1])
nfastend = kama_fastend
nslowend = kama_slowend
nsignal = math.abs(src - src[len])
nnoise = math.sum(xvnoise, len)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = 0.0
nAMA := nz(nAMA[1]) + nsmooth * (src - nz(nAMA[1]))
nAMA
_trendreg(o, h, l, c)=>
compute = 0.
if (c > o)
compute := ((h + c)/2.0)
else
compute := ((l + c)/2.0)
compute
_trendext(o, h, l, c) =>
compute = 0.
if (c > o)
compute := h
else if (c < o)
compute := l
else
compute := c
compute
candletype = input.string("Regular", "Candle Type", options = ["Regular", "HA Regular", "HA Better"], group= "Basic Settings")
smthtype = input.string("AMA", "Filter Options", options = ["AMA", "T3", "Kaufman"], group= "Basic Settings")
srcoption = input.string("Close", "SMA Source Options", group= "SMA Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
smalen = input.int(60, title="SMA Length", group = "SMA Settings")
kama_fastend=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
kama_slowend=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
fastLength = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
slowLength = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
rclose = close
ropen = open
rhigh = high
rlow = low
rmedian = hl2
rtypical = hlc3
rweighted = hlcc4
raverage = ohlc4
ravemedbody = (open + close)/2
rtrendb = _trendreg(ropen, rhigh, rlow, rclose)
rtrendbext = _trendext(ropen, rhigh, rlow, rclose)
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
haavemedbody = (haopen + haclose)/2
hatrendb = _trendreg(haopen, hahigh, halow, haclose)
hatrendbext = _trendext(haopen, hahigh, halow, haclose)
habingest = (ropen + rclose)/2 + (((rclose - ropen)/(rhigh - rlow)) * math.abs((rclose - ropen)/2))
habclose = smthtype == "AMA" ? _ama(habingest, 2, fastLength, slowLength) : smthtype == "T3" ? _t3(habingest, 3) : _kama(habingest, 2, kama_fastend, kama_slowend)
habopen = 0.
habopen := (nz(habopen[1]) + nz(habclose[1]))/2
habhigh = math.max(rhigh, habopen, habclose)
hablow = math.min(rlow, habopen, habclose)
habmedian = (habhigh + hablow)/2
habtypical = (habhigh + hablow + habclose)/3
habweighted = (habhigh + hablow + habclose + habclose)/4
habaverage = (habopen + habhigh + hablow + habclose)/4
habavemedbody = (habopen + habclose)/2
habtrendb = _trendreg(habopen, habhigh, hablow, habclose)
habtrendbext = _trendext(habopen, habhigh, hablow, habclose)
close_out = candletype == "Regular" ? rclose : candletype == "HA Regular" ? haclose : habclose
open_out = candletype == "Regular" ? ropen : candletype == "HA Regular" ? haopen : habopen
high_out = candletype == "Regular" ? rhigh : candletype == "HA Regular" ? hahigh : habhigh
low_out = candletype == "Regular" ? rlow : candletype == "HA Regular" ? halow : hablow
colorout = close_out >= open_out ? greencolor : redcolor
plotcandle(open_out, high_out, low_out, close_out, color = colorout, wickcolor = colorout)
barcolor(colorbars ? colorout : na)
float srcma = switch srcoption
"Close" => rclose
"Open" => ropen
"High" => rhigh
"Low" => rlow
"Median" => rmedian
"Typical" => rtypical
"Weighted" => rweighted
"Average" => raverage
"Average Median Body" => ravemedbody
"Trend Biased" => rtrendb
"Trend Biased (Extreme)" => rtrendbext
"HA Close" => haclose
"HA Open" => haopen
"HA High" => hahigh
"HA Low" => halow
"HA Median" => hamedian
"HA Typical" => hatypical
"HA Weighted" => haweighted
"HA Average" => haaverage
"HA Average Median Body" => haavemedbody
"HA Trend Biased" => hatrendb
"HA Trend Biased (Extreme)" => hatrendbext
"HAB Close" => habclose
"HAB Open" => habopen
"HAB High" => habhigh
"HAB Low" => hablow
"HAB Median" => habmedian
"HAB Typical" => habtypical
"HAB Weighted" => habweighted
"HAB Average" => habaverage
"HAB Average Median Body" => habavemedbody
"HAB Trend Biased" => habtrendb
"HAB Trend Biased (Extreme)" => habtrendbext
=> haclose
outma = ta.sma(srcma, 14)
plot(outma, color = srcma >= outma ? color.yellow : color.fuchsia, linewidth = 2)
|
Volume [Educational] | https://www.tradingview.com/script/a226z19x-Volume-Educational/ | LonesomeTheBlue | https://www.tradingview.com/u/LonesomeTheBlue/ | 629 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue
//@version=5
indicator("Volume [Educational]", "Vol", overlay = true, max_lines_count = 500, format = format.volume)
colorup = input.color(defval = color.new(#26a69a, 50), title = "Colors", inline = "cols")
colordn = input.color(defval = color.new(#ef5350, 50), title = "", inline = "cols")
var float bottomMargin = 8.0 / 82.0
var times = array.new_float(0)
array.unshift(times, time)
visibleBars = 0
if time == chart.right_visible_bar_time
visibleBars := array.indexof(times, chart.left_visible_bar_time) + 1
lowest = ta.lowest(visibleBars > 0 ? visibleBars : 1)
bottomline = lowest - (ta.highest(visibleBars > 0 ? visibleBars : 1) - lowest) * bottomMargin
maxVol = ta.highest(volume, visibleBars > 0 ? visibleBars : 1)
if visibleBars > 0 and time == chart.right_visible_bar_time
var volLines = array.new_line(0)
for x = 0 to (array.size(volLines) > 0 ? array.size(volLines) - 1 : na)
line.delete(array.pop(volLines))
maxVolLevel = (lowest - bottomline) * 4
for x = 0 to math.min(visibleBars, 500)
array.push(volLines,
line.new(x1 = bar_index - x, y1 = bottomline, x2 = bar_index - x, y2 = bottomline + volume[x] * maxVolLevel / maxVol,
width = 5,
color = close[x] >= open[x] ? colorup : colordn))
plotarrow(volume, colorup=color.new(chart.fg_color, 100), colordown=color.new(chart.fg_color, 100), maxheight = 0)
|
Parabolic sar with breaks | https://www.tradingview.com/script/XpeJ7l6a-Parabolic-sar-with-breaks/ | carlpwilliams2 | https://www.tradingview.com/u/carlpwilliams2/ | 211 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © carlpwilliams2
//@version=5
indicator("Sar with breaks", overlay=true)
import carlpwilliams2/CarlLib/7 as carlLib
showBreakLabels = input.bool(true,title="Show breakouts", group="Breakout Labels")
showVolumeBreakLabels = input.bool(true,title="Show Breakouts with high volume", group="Breakout Labels")
timeframe = input.timeframe("",title="Timeframe")
[Open, High, Low, Close, Volume] = request.security(syminfo.tickerid,timeframe,[open,high,low,close,volume])
[bodySize, wickSize, upperShadow, lowerShadow, lowerShadowPercentage,upperShadowPercentage,shadowRatio,wickPercentage] = carlLib.candleDetails(Open,High,Low,Close)
ma50 = ta.ema(Close, 50)
volSpikeThresh = input.float(30,title="Spike Threshold %", group="Volume Spike")
volAverage = ta.sma(Volume,10)
volumeDifference = ((Volume-Volume[1])/Volume)*100
volumeAverageDifference = ((Volume-volAverage)/Volume)*100
volumeSpike = volumeDifference>volSpikeThresh and volumeAverageDifference>60
start = input(0.02, title="start", group="Parabolic SAR")
increment = input(0.02, title="Increment", group="Parabolic SAR")
maximum = input(0.2, "Max Value", group="Parabolic SAR")
out = request.security(syminfo.tickerid,timeframe, ta.sar(start, increment, maximum), gaps=barmerge.gaps_off)
sarChange = ta.change(out<High)
var prevSar = out
if(sarChange)
prevSar := out[1] + ((out[1]/100)*0.02)
crossOverLong = out< Close and Close> Open and (ta.crossover(Close,prevSar) or ta.crossover(Close[1],prevSar))
crossOverShort = out > Close and Close < Open and ta.crossunder(Close,prevSar)
plotshape(showBreakLabels and crossOverLong ? out :na, text="Weak\nBreakout", location = location.absolute, style=shape.labelup, textcolor=color.white, color=color.green, title = "Long Signals" )
plotshape(showBreakLabels and crossOverShort ? out:na, text="Weak\nBreakout", location = location.absolute, style=shape.labeldown, textcolor=color.white, color=color.maroon, title="Short Signals" )
plotshape(showVolumeBreakLabels and crossOverLong and volumeSpike ? out :na, text="Strong\nBreakout", location = location.absolute, style=shape.labelup, textcolor=color.white, color=color.blue, title = "Long Signals" )
plotshape(showVolumeBreakLabels and crossOverShort and volumeSpike ? out:na, text="Strong\nBreakout", location = location.absolute, style=shape.labeldown, textcolor=color.white, color=color.orange, title="Short Signals" )
plot(sarChange?na:prevSar, style=plot.style_linebr, offset=-1, color=out<high?color.new(color.lime,50):color.new(color.red,50), title="Break Lines", linewidth=2)
plot(out, "ParabolicSAR", style=plot.style_cross, color=#2962FF)
alertcondition(crossOverLong, title = "Bullish Breakout", message="Sar with breaks - bullish Breakout on {{ticker}}({{interval}}m)")
alertcondition(crossOverShort, title = "Beaish Breakout", message="Sar with breaks - bearish Breakout on {{ticker}}({{interval}}m)")
alertcondition(crossOverLong and volumeSpike, title = "Strong Bullish Breakout", message="Sar with breaks - strong bullish Breakout on {{ticker}}({{interval}}m)")
alertcondition(crossOverShort and volumeSpike, title = "Strong Bearish Breakout ", message="Sar with breaks - strong bearish Breakout on {{ticker}}({{interval}}m)") |
Simple Hashmap | https://www.tradingview.com/script/mEib4Bux-Simple-Hashmap/ | ramihoteit321 | https://www.tradingview.com/u/ramihoteit321/ | 9 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ramihoteit321
//@version=4
study("Simple Hashmap")
create_dict() =>
indices = array.new_int(0)
elements = array.new_float(0)
[indices, elements]
add_key (key, i, e) =>
// check if key exists
if array.indexof(i,key) == -1
array.push(i, key)
array.push(e, key)
get_value (key, i, e) =>
array.get(e, array.indexof(i,key))
change_value (key, i, e, value) =>
array.set(e, array.indexof(i,key), value)
[ind, el] = create_dict()
add_key(20, ind, el)
change_value(20, ind, el, 70.3)
if barstate.islast
label.new(bar_index, low, tostring(get_value(20, ind, el)) )
plot(close)
|
U/D ACR% [vnhilton] | https://www.tradingview.com/script/Lr0jyTlP-U-D-ACR-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vnhilton
//@version=5
indicator(title="U/D ACR% [vnhilton]", shorttitle='ACR%', overlay=false, format=format.mintick, timeframe="D", timeframe_gaps=false)
length = input(10, title='Length')
uACR = (ta.sma(high, length) - ta.sma(low, length)) * 100 / ta.sma(low, length)
dACR = (ta.sma(low, length) - ta.sma(high, length)) * 100 / ta.sma(high, length)
plot(uACR, color=color.new(color.green, 0), title='UACR%', linewidth=1)
plot(dACR, color=color.new(color.red, 0), title='DACR%', linewidth=1) |
((Bullish)) Candle below EMA | https://www.tradingview.com/script/1Fw1hJdN-Bullish-Candle-below-EMA/ | LuxTradeVenture | https://www.tradingview.com/u/LuxTradeVenture/ | 128 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MINTYFRESH97
//@version=5
indicator(title="((Bullish)) Candle below EMA", overlay=true)
// Calculate moving averages
var g_ema = "EMA Filter"
emaLength9 = input.int(title="9MA", defval=21, tooltip="Length of the EMA filter", group=g_ema)
emaLength50 = input.int(title="50EMA", defval=50, tooltip="Length of the EMA filter", group=g_ema)
emaLength100 = input.int(title="100EMA", defval=100, tooltip="Length of the EMA filter", group=g_ema)
emaLength200 = input.int(title="200EMA", defval=200, tooltip="Length of the EMA filter", group=g_ema)
// Create table
var table myTable = table.new(position.top_right, 5, 6, border_width=4)
if barstate.ishistory
txt1 = "ONLY USE WHEN THE MARKET IS TRENDING \n"
table.cell(myTable, 0, 0, text=txt1, bgcolor=color.white, text_size=size.large , text_color=color.lime)
fastMA = ta.ema(close, emaLength9)
fastMA50= ta.ema(close, emaLength50)
fastMA100= ta.ema(close, emaLength100)
// Get EMA filter
ema1 = ta.ema(close, emaLength200)
emaFilterLong = close > ema1
swingLow1 = low == ta.lowest(low,12) or low[1] ==ta.lowest(low,12)
//longsignal
longsignal= ta.crossover(close, fastMA)
longsignal1= ta.crossover(close, fastMA50)
longsignal2= ta.crossover(close, fastMA100)
bullishcandlesfilter =longsignal and emaFilterLong
bullishcandlesfilter1 =longsignal1 and emaFilterLong
bullishcandlesfilter2 =longsignal2 and emaFilterLong
plotshape(bullishcandlesfilter1, style=shape.arrowup, color=color.lime, size=size.small, text="Below50ema", title="Bullish Price below 50ema" , location=location.belowbar)
barcolor(bullishcandlesfilter1 ? color.lime :na)
alertcondition(bullishcandlesfilter1, "Bullish Price below 50ema", "Bullish Price below 50ema{{ticker}}")
plotshape(bullishcandlesfilter2, style=shape.arrowup, color=color.lime, size=size.small, text="Below100ema", title="Bullish Price below 100ema" , location=location.belowbar)
barcolor(bullishcandlesfilter2 ? color.lime :na)
alertcondition(bullishcandlesfilter2, "Bullish Price below 100ema", "Bullish Price below 100ema{{ticker}}")
plotshape(bullishcandlesfilter, style=shape.arrowup, color=color.lime, size=size.small, text="Below21ema", title="Bullish Price below 21ema" , location=location.belowbar)
barcolor(bullishcandlesfilter ? color.lime :na)
alertcondition(bullishcandlesfilter, "Bullish Price below 21ema", "Bullish Price below 21eam{{ticker}}")
|
Cumulative Delta | https://www.tradingview.com/script/hbsPI7ra-Cumulative-Delta/ | noop-noop | https://www.tradingview.com/u/noop-noop/ | 1,026 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © noop42
//@version=5
indicator("Cumulative Delta")
reset_everyday = input.bool(true, "Reset Delta everyday", group="Options")
show_high_low = input.bool(true, "Show Daily High and Low levels", group="Options")
show_histogram = input.bool(true, "Show histogram", group="Options")
show_candles = input.bool(true, "Show candles", group="Options")
show_moving_average = input.bool(true, "Show moving average", group="Options")
ma_len = input.int(50, "Moving average Length", group="Parameters")
ma_color = input.color(color.white, "Moving average color", group="Display colors")
hist_neg_high = input.color(#383838, "Higher negative delta", group="Display colors")
hist_neg_low = input.color(#636161, "Lower negative delta", group="Display colors")
hist_pos_high = input.color(#636161, "higher positive delta", group="Display colors")
hist_pos_low = input.color(#383838, "Lower positive delta", group="Display colors")
reset_color = input.color(color.white, "Reset mark color", group="Display colors")
up_candle = input.color(color.lime, "Up volume", group="Display colors")
down_candle = input.color(#ff0000, "Down volume", group="Display colors")
var counter = 1
var daily_lowest = 0.0
var daily_highest = 0.0
reset_delta = ta.change(dayofweek)
var cvd = 0.0
bot = 0.0
top = 0.0
col = #00000000
if reset_everyday and reset_delta
daily_lowest := bot
daily_highest := top
cvd := 0.0
counter := 1
if open < close
bot := cvd
top := cvd+volume
col := color.lime
cvd += volume
else
top := cvd
bot := cvd-volume
col := #ff0000
cvd -= volume
bar_col = (cvd > 0) ? (cvd > cvd[1] ? hist_pos_high : hist_pos_low) : (cvd > cvd[1] ? hist_neg_high: hist_neg_low)
plot(show_histogram ? cvd : na, style=plot.style_columns, color=bar_col)
bgcolor(reset_everyday and reset_delta ? reset_color : na)
plotcandle(show_candles ? top : na, show_candles ? top : na, show_candles ? bot : na, show_candles ? bot : na, color=col, bordercolor=col)
if top > daily_highest
daily_highest := top
if bot < daily_lowest
daily_lowest := bot
plot(show_high_low ? daily_highest : na, color=up_candle)
plot(show_high_low ? daily_lowest : na, color=down_candle)
m = ta.sma(cvd, (counter < ma_len ? counter : ma_len))
plot(show_moving_average ? m : na, color=color.white)
counter += 1 |
All-in-one CPR indicator | https://www.tradingview.com/script/EqEDjZsl-All-in-one-CPR-indicator/ | johntradingwick | https://www.tradingview.com/u/johntradingwick/ | 1,814 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©johntradingwick
// @version=4
//***************GUIDE***********************************
//CPR - Applicable only for daily pivots
//CPR S/R - All 3 S/R levels are disabled by default
//CPR Pivot - Central Pivot is a Red line by default and it's color can be changed from the settings
//CPR TC and BC - Top Range & Bottom Range. Both are Blue by default and can be changed from the settings
//Daily Pivots - Daily S1, S2, S3 and R1, R2, R3 are enabled by default. S4 and R4 can be enabled as per the need.
//Daily Pivots - Resistance(R) lines are Red in colour by default
//Daily Pivots - Support(S) lines are Green in colour by default
//Weekly Pivots - Pivot is Blue in color by default
//Weekly Pivots - 4 levels provided - S1/R1, S2/R2, S3/R3/ S4/R4. Disabled by default. Can be enabled from the settings.
//Weekly Pivots - Resistance(R) lines are Red in color by default
//Weekly Pivots - Support(S) lines are Green in color by default
//Monthly Pivots - Pivot is Blue in color by default
//Monthly Pivots - 3 levels provided - S1/R1, S2/R2, S3/R3. Disabled by default. Can be enabled from the settings.
//Monthly Pivots - Resistance(R) lines are Red in color by default
//Monthly Pivots - Support(S) lines are Green in color by default
//Tomorrow Pivots - Central Pivot is Red in color by default
//Tomorrow TC and BC - Top Range & Bottom Range. Both are Blue by default and can be changed from the settings
//Tomorrow Pivots - Resistance(R) lines are Red in color by default
//Tomorrow Pivots - Support(S) lines are Green in color by default
//Previous Day High (PDH) and Previous Day Low (PDL) is also provided.
//Simple Moving Average - 3 SMAs are provided because in general all the strategies can be built using the 20MA, 50MA and 200MA.
//VWAP - Volume Weighted Average Price is also provided for the convenience of the user. Can be useful in case of Futures.
// Hull Ribbon for trend identification
// Coloured volume candles to determine the strenngth of the trend
study("All-in-one CPR indicator by johntradingwick", overlay = true, shorttitle="All-in-one CPR", precision=1)
//******************CALCULATIONS**************************
//Central Pivot Range
pivot = (high + low + close) /3 //Central Povit
BC = (high + low) / 2 //Below Central povit
TC = (pivot - BC) + pivot //Top Central povot
//3 support levels
S1 = (pivot * 2) - high
S2 = pivot - (high - low)
S3 = low - 2 * (high - pivot)
S4 = low - 3 * (high - pivot)
//3 resistance levels
R1 = (pivot * 2) - low
R2 = pivot + (high - low)
R3 = high + 2 * (pivot-low)
R4 = high + 3 * (pivot-low)
//Checkbox inputs
CPRPlot = input(title = "Show Daily CPR", type=input.bool, defval=true)
DayS1R1 = input(title = "Show Daily S1/R1", type=input.bool, defval=false)
DayS2R2 = input(title = "Show Daily S2/R2", type=input.bool, defval=false)
DayS3R3 = input(title = "Show Daily S3/R3", type=input.bool, defval=false)
DayS4R4 = input(title = "Show Daily S4/R4", type=input.bool, defval=false)
WeeklyPivotInclude = input(title = "Show Weekly Pivot", type=input.bool, defval=false)
WeeklyS1R1 = input(title = "Show Weekly S1/R1", type=input.bool, defval=false)
WeeklyS2R2 = input(title = "Show Weekly S2/R2", type=input.bool, defval=false)
WeeklyS3R3 = input(title = "Show Weekly S3/R3", type=input.bool, defval=false)
WeeklyS4R4 = input(title = "Show Weekly S4/R4", type=input.bool, defval=false)
MonthlyPivotInclude = input(title = "Show Monthly Pivot", type=input.bool, defval=false)
MonthlyS1R1 = input(title = "Show Monthly S1/R1", type=input.bool, defval=false)
MonthlyS2R2 = input(title = "Show Monthly S2/R2", type=input.bool, defval=false)
MonthlyS3R3 = input(title = "Show Monthly S3/R3", type=input.bool, defval=false)
//******************DAYWISE CPR & PIVOTS**************************
// Getting daywise CPR
DayPivot = security(syminfo.tickerid, "D", pivot[1], barmerge.gaps_off, barmerge.lookahead_on)
DayBC = security(syminfo.tickerid, "D", BC[1], barmerge.gaps_off, barmerge.lookahead_on)
DayTC = security(syminfo.tickerid, "D", TC[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks daywise for CPR
CPColour = DayPivot != DayPivot[1] ? color.red : color.red
BCColour = DayBC != DayBC[1] ? color.blue : color.blue
TCColour = DayTC != DayTC[1] ? color.blue : color.blue
//Plotting daywise CPR
plot(DayPivot, title = "Daily Pivot" , style = plot.style_circles, color=color.red, linewidth =2)
plot(CPRPlot ? DayBC : na , title = "Daily BC" , style = plot.style_circles, color=color.black, linewidth =2)
plot(CPRPlot ? DayTC : na , title = "Daily TC" , style = plot.style_circles, color=color.black, linewidth =2)
// Getting daywise Support levels
DayS1 = security(syminfo.tickerid, "D", S1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayS2 = security(syminfo.tickerid, "D", S2[1], barmerge.gaps_off, barmerge.lookahead_on)
DayS3 = security(syminfo.tickerid, "D", S3[1], barmerge.gaps_off, barmerge.lookahead_on)
DayS4 = security(syminfo.tickerid, "D", S4[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for daywise Support levels
DayS1Color =DayS1 != DayS1[1] ? color.green : color.green
DayS2Color =DayS2 != DayS2[1] ? color.green : color.green
DayS3Color =DayS3 != DayS3[1] ? color.green : color.green
DayS4Color =DayS4 != DayS4[1] ? color.green : color.green
//Plotting daywise Support levels
plot(DayS1R1 ? DayS1 : na, title = "Daily S1" , style = plot.style_circles, color=color.green, linewidth =1)
plot(DayS2R2 ? DayS2 : na, title = "Daily S2" , style = plot.style_circles, color=color.green, linewidth =1)
plot(DayS3R3 ? DayS3 : na, title = "Daily S3" , style = plot.style_circles, color=color.green, linewidth =1)
plot(DayS4R4 ? DayS4 : na, title = "Daily S4" , style = plot.style_circles, color=color.green, linewidth =1)
// Getting daywise Resistance levels
DayR1 = security(syminfo.tickerid, "D", R1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayR2 = security(syminfo.tickerid, "D", R2[1], barmerge.gaps_off, barmerge.lookahead_on)
DayR3 = security(syminfo.tickerid, "D", R3[1], barmerge.gaps_off, barmerge.lookahead_on)
DayR4 = security(syminfo.tickerid, "D", R4[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for daywise Support levels
DayR1Color =DayR1 != DayR1[1] ? color.red : color.red
DayR2Color =DayR2 != DayR2[1] ? color.red : color.red
DayR3Color =DayR3 != DayR3[1] ? color.red : color.red
DayR4Color =DayR4 != DayR4[1] ? color.red : color.red
//Plotting daywise Resistance levels
plot(DayS1R1 ? DayR1 : na, title = "Daily R1" , style = plot.style_circles, color=color.red, linewidth =1)
plot(DayS2R2 ? DayR2 : na, title = "Daily R2" , style = plot.style_circles, color=color.red, linewidth =1)
plot(DayS3R3 ? DayR3 : na, title = "Daily R3" , style = plot.style_circles, color=color.red, linewidth =1)
plot(DayS4R4 ? DayR4 : na, title = "Daily R4" , style = plot.style_circles, color=color.red, linewidth =1)
//******************WEEKLY PIVOTS**************************
// Getting Weely Pivot
WPivot = security(syminfo.tickerid, "W", pivot[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for Weely Pivot
WeeklyPivotColor =WPivot != WPivot[1] ? na : color.blue
//Plotting Weely Pivot
plot(WeeklyPivotInclude ? WPivot:na, title = "Weekly Pivot" , style = plot.style_circles, linewidth =1)
// Getting Weekly Support levels
WS1 = security(syminfo.tickerid, "W", S1[1],barmerge.gaps_off, barmerge.lookahead_on)
WS2 = security(syminfo.tickerid, "W", S2[1],barmerge.gaps_off, barmerge.lookahead_on)
WS3 = security(syminfo.tickerid, "W", S3[1],barmerge.gaps_off, barmerge.lookahead_on)
WS4 = security(syminfo.tickerid, "W", S4[1],barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for weekly Support levels
WS1Color =WS1 != WS1[1] ? color.green : color.green
WS2Color =WS2 != WS2[1] ? color.green : color.green
WS3Color =WS3 != WS3[1] ? color.green : color.green
WS4Color =WS4 != WS4[1] ? color.green : color.green
//Plotting Weekly Support levels
plot(WeeklyS1R1 ? WS1 : na, title = "Weekly S1" , style = plot.style_circles, color=color.green, linewidth =1)
plot(WeeklyS2R2 ? WS2 : na, title = "Weekly S2" , style = plot.style_circles, color=color.green, linewidth =1)
plot(WeeklyS3R3 ? WS3 : na, title = "Weekly S3" , style = plot.style_circles, color=color.green, linewidth =1)
plot(WeeklyS4R4 ? WS4 : na, title = "Weekly S4" , style = plot.style_circles, color=color.green, linewidth =1)
// Getting Weekly Resistance levels
WR1 = security(syminfo.tickerid, "W", R1[1], barmerge.gaps_off, barmerge.lookahead_on)
WR2 = security(syminfo.tickerid, "W", R2[1], barmerge.gaps_off, barmerge.lookahead_on)
WR3 = security(syminfo.tickerid, "W", R3[1], barmerge.gaps_off, barmerge.lookahead_on)
WR4 = security(syminfo.tickerid, "W", R4[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for weekly Resistance levels
WR1Color = WR1 != WR1[1] ? color.red : color.red
WR2Color = WR2 != WR2[1] ? color.red : color.red
WR3Color = WR3 != WR3[1] ? color.red : color.red
WR4Color = WR4 != WR4[1] ? color.red : color.red
//Plotting Weekly Resistance levels
plot(WeeklyS1R1 ? WR1 : na , title = "Weekly R1" , style = plot.style_circles, color=color.red, linewidth =1)
plot(WeeklyS2R2 ? WR2 : na , title = "Weekly R2" , style = plot.style_circles, color=color.red, linewidth =1)
plot(WeeklyS3R3 ? WR3 : na , title = "Weekly R3" , style = plot.style_circles, color=color.red, linewidth =1)
plot(WeeklyS4R4 ? WR4 : na , title = "Weekly R4" , style = plot.style_circles, color=color.red, linewidth =1)
//******************MONTHLY PIVOTS**************************
// Getting Monhly Pivot
MPivot = security(syminfo.tickerid, "M", pivot[1],barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for Monthly Support levels
MonthlyPivotColor =MPivot != MPivot[1] ? na : color.blue
//Plotting Monthly Pivot
plot(MonthlyPivotInclude? MPivot:na, title = " Monthly Pivot" , style = plot.style_circles, linewidth =2)
// Getting Monthly Support levels
MS1 = security(syminfo.tickerid, "M", S1[1],barmerge.gaps_off, barmerge.lookahead_on)
MS2 = security(syminfo.tickerid, "M", S2[1],barmerge.gaps_off, barmerge.lookahead_on)
MS3 = security(syminfo.tickerid, "M", S3[1],barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for Monthly Support levels
MS1Color =MS1 != MS1[1] ? color.green : color.green
MS2Color =MS2 != MS2[1] ? color.green : color.green
MS3Color =MS3 != MS3[1] ? color.green : color.green
//Plotting Monthly Support levels
plot(MonthlyS1R1 ? MS1 : na, title = "Monthly S1" , style = plot.style_circles, color=color.green, linewidth =1)
plot(MonthlyS2R2 ? MS2 : na, title = "Monthly S2" , style = plot.style_circles, color=color.green, linewidth =1)
plot(MonthlyS3R3 ? MS3 : na, title = "Monthly S3" , style = plot.style_circles, color=color.green, linewidth =1)
// Getting Monthly Resistance levels
MR1 = security(syminfo.tickerid, "M", R1[1],barmerge.gaps_off, barmerge.lookahead_on)
MR2 = security(syminfo.tickerid, "M", R2[1],barmerge.gaps_off, barmerge.lookahead_on)
MR3 = security(syminfo.tickerid, "M", R3[1],barmerge.gaps_off, barmerge.lookahead_on)
MR1Color =MR1 != MR1[1] ? color.red : color.red
MR2Color =MR2 != MR2[1] ? color.red : color.red
MR3Color =MR3 != MR3[1] ? color.red : color.red
//Plotting Monthly Resistance levels
plot(MonthlyS1R1 ? MR1 : na , title = "Monthly R1" , style = plot.style_circles, color=color.red, linewidth =1)
plot(MonthlyS2R2 ? MR2 : na , title = "Monthly R2" , style = plot.style_circles, color=color.red, linewidth =1)
plot(MonthlyS3R3 ? MR3 : na , title = "Monthly R3" , style = plot.style_circles, color=color.red, linewidth =1)
// Calculate Tomorrow's CPR
// Get High, Low and Close
th_d = security(syminfo.tickerid, "D", high, barmerge.gaps_off, barmerge.lookahead_on)
tl_d = security(syminfo.tickerid, "D", low, barmerge.gaps_off, barmerge.lookahead_on)
tc_d = security(syminfo.tickerid, "D", close, barmerge.gaps_off, barmerge.lookahead_on)
// Pivot Range
tP = (th_d + tl_d + tc_d) / 3
tTC = (th_d + tl_d)/2
tBC = (tP - tTC) + tP
// Resistance Levels
tR3 = th_d + 2*(tP - tl_d)
tR2 = tP + (th_d - tl_d)
tR1 = (tP * 2) - tl_d
// Support Levels
tS1 = (tP * 2) - th_d
tS2 = tP - (th_d - tl_d)
tS3 = tl_d - 2*(th_d - tP)
disp_tomorrowcpr = input(title="Show Tomorrow Pivots", type=input.bool, defval=false)
plot (disp_tomorrowcpr ? tP : na, title="Tomorrow Pivot", linewidth=1, color=color.red, style=plot.style_circles)
plot (disp_tomorrowcpr ? tTC : na, title="Tomorrow TC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (disp_tomorrowcpr ? tBC : na, title="Tomorrow BC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (disp_tomorrowcpr ? tS1 : na, title="Tomorrow S1", linewidth=1, color=color.green, style=plot.style_circles)
plot (disp_tomorrowcpr ? tS2 : na, title="Tomorrow S2", linewidth=1, color=color.green, style=plot.style_circles)
plot (disp_tomorrowcpr ? tS3 : na, title="Tomorrow S3", linewidth=1, color=color.green, style=plot.style_circles)
plot (disp_tomorrowcpr ? tR1 : na, title="Tomorrow R1", linewidth=1, color=color.red, style=plot.style_circles)
plot (disp_tomorrowcpr ? tR2 : na, title="Tomorrow R2", linewidth=1, color=color.red, style=plot.style_circles)
plot (disp_tomorrowcpr ? tR3 : na, title="Tomorrow R3", linewidth=1, color=color.red, style=plot.style_circles)
//*****************************INDICATORS**************************
//SMA 1
PlotSMA1 = input(title = "Plot SMA 1", type=input.bool, defval=false)
SMALength1 = input(title="SMA Length", type=input.integer, defval=20)
SMASource1 = input(title="SMA Source", type=input.source, defval=close)
SMAvg1 = sma (SMASource1, SMALength1)
plot(PlotSMA1 ? SMAvg1 : na, color= color.green, title="SMA 1")
//SMA 2
PlotSMA2 = input(title = "Plot SMA 2", type=input.bool, defval=false)
SMALength2 = input(title="SMA Length", type=input.integer, defval=50)
SMASource2 = input(title="SMA Source", type=input.source, defval=close)
SMAvg2 = sma (SMASource2, SMALength2)
plot(PlotSMA2 ? SMAvg2 : na, color= color.blue, title="SMA 2")
//SMA 3
PlotSMA3 = input(title = "Plot SMA 3", type=input.bool, defval=false)
SMALength3 = input(title="SMA Length", type=input.integer, defval=200)
SMASource3 = input(title="SMA Source", type=input.source, defval=close)
SMAvg3 = sma (SMASource3, SMALength3)
plot(PlotSMA3 ? SMAvg3 : na, color= color.blue, title="SMA 3")
//VWAP
PlotVWAP = input(title = "Plot VWAP?", type=input.bool, defval=false)
VWAPSource = input(title="VWAP Source", type=input.source, defval=close)
VWAPrice = vwap (VWAPSource)
plot(PlotVWAP ? VWAPrice : na, color= color.teal, title="VWAP")
//PDH and PDL
pdh = security(syminfo.tickerid, "D", high[1], barmerge.gaps_off, barmerge.lookahead_on)
pdl = security(syminfo.tickerid, "D", low[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(pdh, "Previous Day High", color.black, linewidth = 1, style = plot.style_circles)
plot(pdl, "Previous Day Low", color.black, linewidth = 1, style = plot.style_circles)
//MARKET STRUCTURE
//Description: Enhanced Zig Zag indicator that plot points on the chart whenever prices reverse by a percentage greater than a pre-chosen variable.
// Hull trend
tf = input("10", title = "Timeframe for HMA", type = input.resolution, options = ["1", "5", "10", "15", "30", "60","120", "240","360","720", "D", "W", "Y"])
src = input(hl2)
length = input(24, title = "Period", type = input.integer)
shift = input(0, title = "Offset", type = input.integer)
showcross = input(true, "Show Buy/Sell signal")
hma(_src, _length)=>
wma((2 * wma(_src, _length / 2)) - wma(_src, _length), round(sqrt(_length)))
hma3(_src, _length)=>
p = length/2
wma(wma(close,p/3)*3 - wma(close,p/2) - wma(close,p),p)
a = security(syminfo.tickerid, tf, hma(src, length)[shift])
b =security(syminfo.tickerid, tf, hma3(src, length)[shift])
c = b > a ? color.lime : color.red
p1 = plot(a,color=c,linewidth=1,transp=75)
p2 = plot(b,color=c,linewidth=1,transp=75)
fill(p1,p2,color=c,transp=25)
crossdn = a > b and a[1] < b[1]
crossup = b > a and b[1] < a[1]
plotshape(showcross and crossdn ? a : na, location=location.absolute, style=shape.labeldown, color=color.red, size=size.tiny, text="Sell", textcolor=color.white, transp=0, offset=0)
plotshape(showcross and crossup ? a : na, location=location.absolute, style=shape.labelup, color=color.green, size=size.tiny, text="Buy", textcolor=color.white, transp=0, offset=0)
alertcondition(showcross and crossdn ? a : na, title = 'hma long', message = 'hma: long ')
alertcondition(showcross and crossup ? a : na, title = 'hma short', message = 'hma: short ')
//
len=input(20)
// Draw channel.
channelType = input(defval="Bollinger", title="Channel Type", options=["NONE", "Donchian", "Bollinger", "Envelope"])
channelLen = input(14, minval=1, title="Channel Length")
envPer = input(4, title="Envelope %", type=input.float, minval=0) / 100
getChannels(src, len) =>
if channelType == "Bollinger"
ma = ema(src, len)
dev = stdev(src, len)
bbUp = ma + 2*dev
bbDown = ma - 2*dev
[bbUp, bbDown]
else
if channelType == "Donchian"
donUp = highest(high[1], len)
donDown = lowest(low[1], len)
[donUp, donDown]
else
if channelType == "Envelope"
ma = ema(src, len)
envUp = ma * (1 + envPer)
envDown = ma * (1 - envPer)
[envUp, envDown]
else
[na, na]
[upperchannel, lowerchannel] = getChannels(src, len)
u = plot(upperchannel, linewidth=1, color=color.black, title="Band High")
plot(avg(upperchannel, lowerchannel), linewidth=1, color=color.red, title="Band Middle")
l = plot(lowerchannel, linewidth=1, color=color.black, title="Band Low")
fill(u, l)
// Coloured volume candles
lengthbar=input(13, "length", minval=1)
avrg=sma(volume,lengthbar)
vold1 = volume > avrg*1.5 and close<open
vold2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close<open
vold3 = volume < avrg *0.5 and close<open
volu1 = volume > avrg*1.5 and close>open
volu2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close>open
volu3 = volume< avrg*0.5 and close>open
cold1=color.maroon
cold2=color.red
cold3=color.gray
colu1=color.green
colu2=color.lime
colu3=color.gray
color = vold1 ? cold1 : vold2 ? cold2 : vold3 ? cold3 : volu1 ? colu1 : volu2 ? colu2 : volu3 ? colu3 : na
barcolor(color) |
Equivolume - volume as candle width | https://www.tradingview.com/script/ZYPO9wRX-Equivolume-volume-as-candle-width/ | ant_tv | https://www.tradingview.com/u/ant_tv/ | 150 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ant_tv
// Inspired by NinjaTrader's Equivolume candles: https://ninjatrader.com/blog/combine-price-volume-with-new-equivolume-charts/
//@version=5
indicator("Equivolume candles", overlay=true, max_lines_count=500, max_boxes_count=500)
// User configurable parameters
lookback_choice = input.int(title='Lookback candle count', defval=500, maxval=500, minval=1, tooltip='A maximum of 500 candles can be displayed with volume information')
use_color = input.bool(title='Use color', defval=false, tooltip='Vary transparency of candle to indicate relative volume')
use_width = input.bool(title='Use width', defval=true, tooltip='Vary width of candle to indicate relative volume')
bar_width_multiplier = input.int(20, title='Candle width multiplier', minval=1, maxval=50, tooltip='Increase the width of the candles to show volume more clearly')
show_closing_price_line = input.bool(title='Show closing price line', defval=true, tooltip='Shows background closing price line graph for context')
transparency_choice = input.string(title="Transparency range", defval="Medium", options=["High", "Medium", "Low"], tooltip='Alters how transparent low volume candles appear')
bull_color = input.color(title='Bull color', defval=color.green)
bear_color = input.color(title='Bear color', defval=color.red)
transparency_level = switch transparency_choice
"High" => 100
"Medium" => 75
"Low" => 50
bars_available = ta.barssince(barstate.isfirst)
lookback_candles = lookback_choice > bars_available
? bars_available
: lookback_choice
max_volume = ta.highest(volume, lookback_candles + 1)
plot(show_closing_price_line ? close : na, color=color.new(color.blue, transparency_level - 25))
plotchar(volume, title='Volume', char='', color=color.new(color.purple, 100))
if barstate.islast
for i = lookback_candles to 0
relative_volume = volume[i] / max_volume
color = close[i] >= open[i] ? bull_color : bear_color
color_alpha = color.new(color, (1 - relative_volume) * transparency_level)
bar_width = int(relative_volume * bar_width_multiplier)
candle_color = use_color ? color_alpha : color
// Candle wick (use boxes rather than lines here so I can use box and line limit of 500 for each)
box.new(
bar_index[i],
high[i],
bar_index[i],
low[i],
border_width=1,
bgcolor=candle_color,
border_color=candle_color)
// Candle body
line.new(
bar_index[i],
open[i],
bar_index[i],
close[i],
width=use_width ? bar_width : 3,
color=candle_color)
|
Candle Volume (Alender) | https://www.tradingview.com/script/Jzv0VXLN-candle-volume-alender/ | mob.alender | https://www.tradingview.com/u/mob.alender/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mob.alender
//@version=5
indicator(title='Candle Volume (Alender)', overlay=true)
length = input(20, title='length', group='Candle Volume settings')
avrg = ta.sma(volume, length)
color_volume = #ffffff
red = 255
green = 255
blue = 255
if open < close
if volume > avrg
green := 15 + (240 - math.round(60 * (volume / avrg)))
if green < 15
green := 15
red := 0
blue := 0
else
blue := 15 + (240 - math.round(240 * (volume / avrg)))
if blue < 15
blue := 15
red := 15 + (240 - math.round(240 * (volume / avrg)))
if red < 15
red := 15
else
if volume > avrg
red := 15 + (240 - math.round(60 * (volume / avrg)))
if red < 15
red := 15
green := 0
blue := 0
else
blue := 15 + (240 - math.round(240 * (volume / avrg)))
if blue < 15
blue := 15
green := 15 + (240 - math.round(240 * (volume / avrg)))
if green < 15
green := 15
color_volume := color.rgb(red, green, blue)
barcolor(color_volume, title='Bar Colors')
|
Ichimoku Kinkō hyō 目均衡表 | https://www.tradingview.com/script/HG385dBY-Ichimoku-Kink%C5%8D-hy%C5%8D-%E7%9B%AE%E5%9D%87%E8%A1%A1%E8%A1%A8/ | RickSimpson | https://www.tradingview.com/u/RickSimpson/ | 4,032 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RickSimpson
//@version=5
indicator('Ichimoku Kinkō hyō 目均衡表', 'Ichimoku Kinkō hyō 目均衡表', overlay=true, max_bars_back=500, max_lines_count=500, max_labels_count=500)
///////////////////////////////////
// Ichimoku Kinkō hyō 目均衡表 // Original Work by Goichi Hosoda - More information on : https://en.wikipedia.org/wiki/Ichimoku_Kinkō_Hyō
//////////////////////////////////
//◀─── Groups Setup ───►
gsrc = 'SOURCE SETUP'
gichi = 'ICHIMOKU SETTINGS'
gsr = 'SUPPORTS/RESISTANCES SETTINGS'
gpsylvl = 'PSYCHOLOGICAL LEVELS'
gadvset = 'ADVANCED SETTINGS'
gvosc = 'VOLUME OSCILLATOR SETTINGS'
gvrindex = 'RELATIVE VOLUME STRENGTH INDEX SETTINGS'
gatr = 'VOLATILITY SETTINGS'
gbarcol = 'BAR COLOR SETTINGS'
gtable = 'PANEL SETTINGS'
//◀─── Constant String Declaration ───►
string obvstr = 'On Balance Volume'
string cvdstr = 'Cumulative Volume Delta'
string pvtstr = 'Price Volume Trend'
//◀─── Inputs ───►
i_src = input.source(close, 'Source', group=gsrc)
i_altsrc = input.string('(close > open ? high : low)', 'Alternative Source', options=['Default Source', '(open + close +3 * (high + low)) / 8', 'close + high + low -2 * open', '(close +5 * (high + low) -7 * (open)) / 4', '(open + close +5 * (high + low)) / 12', '(close > open ? high : low)', 'Heiken-Ashi'], group=gsrc)
i_uha = input(true, 'Use Volume Heikin Ashi?', group=gsrc)
i_wmas = input.bool(true, 'Weighted Moving Average Smoothing?', group=gsrc)
i_showlabels = input.bool(true, 'Show Labels?', group=gichi)
i_showprice = input.bool(true, 'Show Tenkan-Sen/kijun-Sen Price Labels?', group=gichi)
i_showtenkan = input.bool(true, 'Tenkan-Sen', group=gichi, inline='tenkan')
i_tenkancolor = input.color(color.new(#007FFF, 0), '', group=gichi, inline='tenkan')
i_tkminlen = input.int(9, 'Tenkan Min Length', minval=1, group=gichi, inline='tenkanlength')
i_tkmaxlen = input.int(30, 'Tenkan Max Length', minval=1, group=gichi, inline='tenkanlength')
i_tkdynperc = input.float(96.85, 'Tenkan Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
i_tkvolsetup = input.bool(true, 'Volume', group=gichi, inline='tenkanfilter')
i_tkatrsetup = input.bool(true, 'Volatility', group=gichi, inline='tenkanfilter')
i_tkchfilter = input.bool(true, 'Chikou Trend Filter', group=gichi, inline='tenkanfilter')
i_showkijun = input.bool(true, 'Kijun-Sen ', group=gichi, inline='kijun')
i_kijuncolor = input.color(color.new(#FF0016, 0), '', group=gichi, inline='kijun')
i_showkjhlabels = input.bool(true, 'Show Hidden Kijun-Sen Labels?', group=gichi)
i_showkjhsr = input.bool(false, 'Show Hidden Kijun-Sen Supports/Resistances?', group=gichi)
i_kjminlen = input.int(20, 'Kijun Min Length', minval=1, group=gichi, inline='kijunlength')
i_kjmaxlen = input.int(60, 'Kijun Max Length', minval=1, group=gichi, inline='kijunlength')
i_kjdynperc = input.float(96.85, 'Kijun Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
i_kjdivider = input.int(1, 'Kijun Divider Tool', minval=1, maxval=4, group=gichi)
i_kjvolsetup = input.bool(true, 'Volume', group=gichi, inline='kijunfilter')
i_kjatrsetup = input.bool(true, 'Volatility', group=gichi, inline='kijunfilter')
i_kjchfilter = input.bool(true, 'Chikou Trend Filter', group=gichi, inline='kijunfilter')
i_showchikou = input.bool(true, 'Chikou Span', group=gichi)
i_chbearcol = input.color(color.new(#FF0016, 0), 'Bear', group=gichi, inline='chikoucolor')
i_chbullcol = input.color(color.new(#459915, 0), 'Bull', group=gichi, inline='chikoucolor')
i_chconsocol = input.color(color.new(#FF9800, 0), 'Consolidation', group=gichi, inline='chikoucolor')
i_chminlen = input.int(26, 'Chikou Min Length', minval=1, group=gichi, inline='chikoulength')
i_chmaxlen = input.int(50, 'Chikou Max Length', minval=1, group=gichi, inline='chikoulength')
i_chdynperc = input.float(96.85, 'Chikou Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
i_chfiltper = input.int(25, 'Chikou Filter Period', minval=1, group=gichi)
i_chlb = input.int(50, 'Chikou Filter Percentage Lookback', minval=1, maxval=89, group=gichi)
i_chvolsetup = input.bool(true, 'Volume', group=gichi, inline='chikoufilter')
i_chatrsetup = input.bool(true, 'Volatility', group=gichi, inline='chikoufilter')
i_chtfilter = input.bool(true, 'Chikou Trend Filter', group=gichi, inline='chikoufilter')
I_ska = input.bool(true, 'Senkou-Span A', group=gichi, inline='senkou')
I_skb = input.bool(true, 'Senkou-Span B', group=gichi, inline='senkou')
I_skbear = input.color(color.new(#FF0016, 0), 'Bear', group=gichi, inline='senkoucolor')
I_skbull = input.color(color.new(#459915, 0), 'Bull', group=gichi, inline='senkoucolor')
I_skconso = input.color(color.new(#CED7DF, 0), 'Consolidation', group=gichi, inline='senkoucolor')
I_skminlen = input.int(50, 'Senkou-Span Min Length', minval=1, group=gichi, inline='senkoulength')
I_skmaxlen = input.int(120, 'Senkou-Span Max Length', minval=1, group=gichi, inline='senkoulength')
I_skperc = input.float(96.85, 'Senkou Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
I_skoffset = input.int(26, 'Senkou-Span Offset', minval=1, group=gichi)
I_skvolsetup = input.bool(true, 'Volume', group=gichi, inline='sn_chks')
I_atrsetup = input.bool(true, 'Volatility', group=gichi, inline='sn_chks')
I_skchfilter = input.bool(true, 'Chikou Trend Filter', group=gichi, inline='sn_chks')
I_kumofill = input.bool(true, 'Kumo Fill', group=gichi, inline='kumo')
I_kumofillt = input.int(65, 'Transparency', minval=1, group=gichi, inline='kumo')
I_volsetup = input.bool(true, 'Volume?', group=gadvset)
I_tkkjcross = input.bool(true, 'Tenkan-Sen/Kijun-Sen Cross?', group=gadvset)
I_atrvolatility = input.bool(true, 'Volatility?', group=gadvset)
I_tkeqkj = input.bool(true, 'Tenkan-Sen Equal Kijun-Sen?', group=gadvset)
I_chgtp = input.bool(true, 'Chikou Greater Than Price?', group=gadvset)
I_chmom = input.bool(true, 'Chikou Momentum?', group=gadvset)
I_pgtk = input.bool(true, 'Price Greater Than Kumo?', group=gadvset)
I_pgttk = input.bool(true, 'Price Greater Than Tenkan-Sen?', group=gadvset)
I_pgtchf = input.bool(true, 'Chikou Trend Filter?', group=gadvset)
I_volosctype = input.string('On Balance Volume', 'Volume Oscillator Type', options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypetk = input.string('On Balance Volume', 'Volume Oscillator Type for Tenkan-Sen', options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypekj = input.string('On Balance Volume', 'Volume Oscillator Type for Kijun-Sen', options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypesk = input.string('On Balance Volume', 'Volume Oscillator Type for Senkou', options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypech = input.string('On Balance Volume', 'Volume Oscillator Type for Chikou', options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volumelen = input.int(30, 'Volume Length', minval=1, group=gvosc)
I_volzonelen = input.int(21, 'Volume Zone Length', minval=1, group=gvosc)
I_volfastlen = input.int(34, 'Volume Fast Length', minval=1, group=gvosc)
I_volslowlen = input.int(55, 'Volume Slow Length', minval=1, group=gvosc)
I_rvolumetype = input.string(pvtstr, 'Relative Volume Strength Index Type', options=[obvstr, cvdstr, pvtstr], group=gvrindex)
I_rvolumelen = input.int(14, 'Relative Volume Strength Index Length', minval=1, group=gvrindex)
I_volpeak = input.int(50, 'Relative Volume Strength Index Peak', minval=1, group=gvrindex)
i_emalen1 = input.int(8, 'EMA 1 Length', minval=1, group=gvrindex)
i_emalen2 = input.int(21, 'EMA 2 Length', minval=1, group=gvrindex)
i_atrfastlen = input.int(14, 'Average True Range Fast Length', group=gatr)
i_atrslowlen = input.int(46, 'Average True Range Slow Length', group=gatr)
i_showsr = input.bool(true, 'Show Supports/Resistances?', group=gsr)
i_rescol = input.color(color.new(color.red, 0), 'Resistance Color', group=gsr, inline='srcol')
i_supcol = input.color(color.new(color.green, 0), 'Support Color', group=gsr, inline='srcol')
i_maxline = input.int(2, 'Maximum Lines', minval=1, maxval=500, group=gsr, inline='lines')
i_layout = input.string('Wick', 'Lines Type', options=['Wick', 'Zone'], group=gsr, inline='lines')
i_linewidth = input.int(1, 'Lines Width ', minval=1, maxval=3, group=gsr, inline='lines style')
i_linestyle = input.string('Solid', 'Lines Style', options=['Solid', 'Dotted', 'Dashed'], group=gsr, inline='lines style')
i_extend = input.bool(true, 'Extend Lines', group=gsr, inline='lines style')
i_psylevels = input(false, 'Display Psychological Levels?', group=gpsylvl)
i_linescounter = input(4, 'Lines Above/Below', group=gpsylvl)
i_psylinescol = input.color(color.new(color.gray, 0), 'Lines Color', group=gpsylvl)
i_showbc = input.bool(true, 'Use Bar Color?', group=gbarcol)
i_bearbarcol = input.color(color.new(#910000, 0), 'Bear', group=gbarcol, inline='barcolor')
i_bullbarcol = input.color(color.new(#006400, 0), 'Bull', group=gbarcol, inline='barcolor')
i_consobarcol = input.color(color.new(#FF9800, 0), 'Consolidation', group=gbarcol, inline='barcolor')
i_neutralbarcol = input.color(color.new(#000000, 100), 'Neutral', group=gbarcol, inline='barcolor')
i_showtable = input(true, 'Show Panel?', group=gtable)
i_tablepresets = input.string('Custom', 'Presets', options=['Custom', '9/26/52/26 - 6D Markets (Default)', '8/22/44/22 - 5D Markets', '9/30/60/30 - 24h/7D Markets (Crypto)', '20/60/120/60 - 24h/7D Markets (Slow Version)'], group=gtable)
i_tableloc = input.string('Bottom Right', 'Position', options=['Bottom Right', 'Top Right', 'Bottom Left', 'Top Left', 'Top', 'Right', 'Bottom', 'Left'], group=gtable)
i_tabletxtsize = input.string('Small', 'Text Size', options=['Tiny', 'Small', 'Normal', 'Large'], group=gtable)
i_tabletxtcol = input.color(color.new(color.white, 0), 'Text Color', group=gtable)
i_tablebgcol = input.color(color.new(#696969, 80), 'Background Color', group=gtable)
i_tabletkpc = input.bool(true, 'Display Tenkan-Sen Price Cross?', group=gtable)
i_tablekjpc = input.bool(true, 'Display Kijun-Sen Price Cross?', group=gtable)
i_tablechpc = input.bool(true, 'Display Chikou Span Price Cross?', group=gtable)
i_tablekumobr = input.bool(true, 'Display Kumo Breakout?', group=gtable)
i_tablekumotw = input.bool(true, 'Display Kumo Twist?', group=gtable)
//◀─── Volume Heikin Ashi Calculation ───►
//Constant Price Variables
haclose = i_uha ? ohlc4 : close
vol = volume
//Heikin Ashi Function
f_openha() =>
haopen = float(na)
haopen := na(haopen[1]) ? (open + close) / 2 : (nz(haopen[1]) + nz(haclose[1])) / 2
haopen
//Conditions
haopen = i_uha ? f_openha() : open
haboolean = f_openha()
//◀─── Price Variables Declaration ───►
open_ = open
high_ = high
low_ = low
close_ = close
bar_index_ = bar_index
//Alternative Price Variables Declaration
alternativesrc = i_altsrc == '(open + close +3 * (high + low)) / 8' ? (open + close +3 * (high + low)) / 8 :
i_altsrc == 'close + high + low -2 * open' ? close + high + low -2 * open :
i_altsrc == '(close +5 * (high + low) -7 * (open)) / 4' ? (close +5 * (high + low) -7 * (open)) / 4 :
i_altsrc == '(open + close +5 * (high + low)) / 12' ? (open + close +5 * (high + low)) / 12 :
i_altsrc == '(close > open ? high : low)' ? (close > open ? high : low) :
i_altsrc == 'Heiken-Ashi' ? (ohlc4 > haboolean ? high : low) :
i_src
altsrcres = i_wmas ? ta.swma(alternativesrc) : alternativesrc
//◀─── Global Functions ───►
//Color Call Function
fzonecolor(srcolor, _call) =>
c1 = color.r(srcolor)
c2 = color.g(srcolor)
c3 = color.b(srcolor)
color.rgb(c1, c2, c3, _call)
//Lines Styles String Function
f_i_linestyle(_style) =>
_style == 'Solid' ? line.style_solid : _style == 'Dotted' ? line.style_dotted : line.style_dashed
//Volume Oscillator Functions
f_patternrate(cond, tw, bw, body) =>
ret = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body)
ret := nz(ret) == 0 ? 0.5 : ret
ret
f_volcalc(vol_src, _open, _high, _low, _close) =>
float result = 0
tw = _high - math.max(_open, _close)
bw = math.min(_open, _close) - _low
body = math.abs(_close - _open)
deltaup = vol_src * f_patternrate(_open <= _close, tw, bw, body)
deltadown = vol_src * f_patternrate(_open > _close, tw, bw, body)
delta = _close >= _open ? deltaup : -deltadown
cumdelta = ta.cum(delta)
float ctl = na
ctl := cumdelta
cv = I_rvolumetype == obvstr ? ta.obv : I_rvolumetype == cvdstr ? ctl : ta.pvt
ema1 = ta.ema(cv, i_emalen1)
ema2 = ta.ema(cv, i_emalen2)
result := ema1 - ema2
result
f_zone(_src, _type, _len) =>
vp = _src > _src[1] ? _type : _src < _src[1] ? -_type : _src == _src[1] ? 0 : 0
z = 100 * (ta.ema(vp, _len) / ta.ema(_type, _len))
z
f_volzosc(vol_src, _close) =>
float result = 0
zLen = I_volzonelen
result := f_zone(_close, vol_src, zLen)
result
f_volosc(type, vol_src, vol_len, _open, _high, _low, _close) =>
float result = 0
if type == 'TFS Volume Oscillator'
iff_1 = _close < _open ? -vol_src : 0
naccvol = math.sum(_close > _open ? vol_src : iff_1, vol_len)
result := naccvol / vol_len
result
if type == 'On Balance Volume'
result := ta.cum(math.sign(ta.change(_close)) * vol_src)
result
if type == 'Klinger Volume Oscillator'
fastx = I_volfastlen
slowx = I_volslowlen
xtrend = _close > _close[1] ? vol * 100 : -vol * 100
xfast = ta.ema(xtrend, fastx)
xslow = ta.ema(xtrend, slowx)
result := xfast - xslow
result
if type == 'Cumulative Volume Oscillator'
result := f_volcalc(vol_src, _open, _high, _low, _close)
result
if type == 'Volume Zone Oscillator'
result := f_volzosc(vol_src, _close)
result
result
//Kijun V2 Function
f_kjv2(src, len) =>
var float result = 0.0
kijun = math.avg(ta.lowest(len), ta.highest(len))
conversionLine = math.avg(ta.lowest(len / i_kjdivider), ta.highest(len / i_kjdivider))
delta = (kijun + conversionLine) / 2
result := delta
result
//◀─── Relative Volume Strength Index calculation ───►
tksignal = f_volosc(I_volosctypetk, vol, I_rvolumelen, haopen, high, low, haclose)
kjsignal = f_volosc(I_volosctypekj, vol, I_rvolumelen, haopen, high, low, haclose)
sksignal = f_volosc(I_volosctypesk, vol, I_rvolumelen, haopen, high, low, haclose)
chsignal = f_volosc(I_volosctypech, vol, I_rvolumelen, haopen, high, low, haclose)
sumsignal = f_volosc(I_volosctype, vol, I_rvolumelen, haopen, high, low, haclose)
//◀─── Volume Breakout Calculation ───►
tkbrvoldn = tksignal < I_volpeak
tkbrvolup = tksignal > I_volpeak
kjbrvoldn = kjsignal < I_volpeak
kjbrvolup = kjsignal > I_volpeak
skbrvoldn = sksignal < I_volpeak
skbrvolup = sksignal > I_volpeak
chbrvoldn = chsignal < I_volpeak
chbrvolup = chsignal > I_volpeak
//Conditions
signalbrvoldn = sumsignal < I_volpeak
signalbrvolup = sumsignal > I_volpeak
//◀─── Volatility Strength ───►
atrvolmeter = ta.atr(i_atrfastlen) > ta.atr(i_atrslowlen)
//Adaptive Chikou Function
f_chikou(float src, simple int len, float _high, float _low, color bull_col, color bear_col, color r_col) =>
var isup = bool(na)
var isdown = bool(na)
var _re = bool(na)
var sig = int(na)
var color _clr = color.new(na, 0)
isup := src > ta.highest(_high, len)[len]
isdown := src < ta.lowest(_low, len)[len]
_re := src < ta.highest(_high, len)[len] and src > ta.lowest(_low, len)[len]
_clr := isdown ? bear_col : isup ? bull_col : r_col
sig := isup ? 1 : isdown ? -1 : 0
[_clr, sig]
[chikou_clr, chikoufiltersig] = f_chikou(altsrcres, i_chfiltper, high, low, i_chbullcol, i_chbearcol, i_chconsocol)
//Arrays Index Functions
f_boolean(chka, reference_a) =>
var result_bool = bool(na)
for i = 0 to array.size(chka) -1
if array.get(chka, i) == true
result_bool := array.get(reference_a, i)
break
for i = 0 to array.size(chka) -1
result_bool := array.get(chka, i) ? array.get(reference_a, i) and result_bool : result_bool
result_bool
//Boolean Calculation
bool[] tkarray = array.from(i_tkvolsetup,
i_tkatrsetup,
i_tkchfilter)
bool[] kjarray = array.from(i_kjvolsetup,
i_kjatrsetup,
i_kjchfilter)
bool[] skarray = array.from(I_skvolsetup,
I_atrsetup,
I_skchfilter)
bool[] charray = array.from(i_chvolsetup,
i_chatrsetup,
i_chtfilter)
bool[] tkvolarray = array.from(tkbrvolup,
atrvolmeter,
chikoufiltersig == 1)
bool[] kjvolarray = array.from(kjbrvolup,
atrvolmeter,
chikoufiltersig == 1)
bool[] skvolarray = array.from(skbrvolup,
atrvolmeter,
chikoufiltersig == 1)
bool[] chvolarray = array.from(chbrvolup,
atrvolmeter,
chikoufiltersig == 1)
//Boolean to Conditions
booltkup = f_boolean(tkarray, tkvolarray)
boolkjup = f_boolean(kjarray, kjvolarray)
boolchup = f_boolean(charray, chvolarray)
boolskup = f_boolean(skarray, skvolarray)
//Dynamic Length Function
f_dyn(bool para, float adapt_Pct, simple int minLength, simple int maxLength) =>
var dyna_len = int(na)
var float i_len = math.avg(minLength, maxLength)
i_len := para ? math.max(minLength, i_len * adapt_Pct) : math.min(maxLength, i_len * (2-adapt_Pct))
dyna_len := int(i_len)
dyna_len
//Dynamic Length Conditions
dyntk = f_dyn(booltkup, i_tkdynperc, i_tkminlen, i_tkmaxlen)
dynkj = f_dyn(boolkjup , i_kjdynperc, i_kjminlen, i_kjmaxlen)
dynsk = f_dyn(boolskup , I_skperc, I_skminlen, I_skmaxlen)
dynch = f_dyn(boolchup , i_chdynperc, i_chminlen, i_chmaxlen)
//◀─── Index Calculation ───►
tenkansen = f_kjv2(altsrcres, dyntk)
kijunsen = f_kjv2(altsrcres, dynkj)
senkoua = math.avg(tenkansen, kijunsen)
senkoub = math.avg(ta.highest(high, dynsk), ta.lowest(low, dynsk))
chikouspan = altsrcres
//Tenkan-Sen/kijun-Sen Boolean Conditions to Float
var float tkbool = na
if tenkansen
tkbool := tenkansen
tkbool
var float kjbool = na
if kijunsen
kjbool := kijunsen
kjbool
//◀─── Dynamic Type Calculation ───►
bearmomentum = ta.mom(altsrcres, dynch - 1) < 0
bullmomentum = ta.mom(altsrcres, dynch - 1) > 0
cloudhigh = math.max(senkoua[I_skoffset - 1], senkoub[I_skoffset - 1])
cloudlow = math.min(senkoua[I_skoffset - 1], senkoub[I_skoffset - 1])
pbk = altsrcres < cloudhigh
pak = altsrcres > cloudhigh
//Boolean Arrays Variables
bool[] indexarray = array.from(I_volsetup,
I_atrvolatility,
I_tkkjcross,
I_chmom,
I_chgtp,
I_pgtk,
I_pgttk,
I_pgtchf)
bool[] downvolumearray = array.from(signalbrvoldn,
atrvolmeter,
tenkansen < kijunsen,
bearmomentum,
chikouspan < altsrcres[int(dynch)],
pbk,
altsrcres < tenkansen,
chikoufiltersig == -1)
bool[] uppervolumearray = array.from(signalbrvolup,
atrvolmeter,
tenkansen > kijunsen,
bullmomentum,
chikouspan > altsrcres[int(dynch)],
pak,
tenkansen,
chikoufiltersig == 1)
//Conditions Calculation
bearfilterdn = f_boolean(indexarray, downvolumearray)
bullfilterup = f_boolean(indexarray, uppervolumearray)
bearcondition = I_tkeqkj ? tenkansen == kijunsen and tenkansen[1] > kijunsen[1] or bearfilterdn : bearfilterdn
bullcondition = I_tkeqkj ? tenkansen == kijunsen and tenkansen[1] < kijunsen[1] or bullfilterup : bullfilterup
isdown = bearcondition
isup = bullcondition
//Conditions
sell = isdown and not isdown[1]
buy = isup and not isup[1]
//Sig Calculation
var sig = 0
if sell and sig >= 0
sig := -1
if buy and sig <= 0
sig := 1
//Sig Conditions
shortcr = sig == -1 and sig[1] != -1
longcr = sig == 1 and sig[1] != 1
//Boolean Conditions to Float
var float ichibearprice = na
if shortcr
ichibearprice := bar_index
ichibearprice
var float ichibullprice = na
if longcr
ichibullprice := bar_index
ichibullprice
//Labels Calculation
if i_showlabels
l = ta.change(ichibearprice) ? label.new(bar_index, ichibearprice[1] + 0.01, str.tostring(math.round_to_mintick(high)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_down, yloc=yloc.abovebar, size=size.small) : ta.change(ichibullprice) ? label.new(bar_index, ichibullprice[1] - 0.01, str.tostring(math.round_to_mintick(low)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_up, yloc=yloc.belowbar, size=size.small) : na
l
//Volatility Coordination Constant Variable
atrxy = 0.85 * ta.atr(5)
//◀─── Plotting ───►
plotshape(i_showlabels and shortcr ? (high) + atrxy : na, style=shape.triangledown, color=i_rescol, location=location.absolute, size=size.small)
plotshape(i_showlabels and longcr ? (low) - atrxy : na, style=shape.triangleup, color=i_supcol, location=location.absolute, size=size.small)
plotshape(i_showlabels and sell ? high + atrxy : na, style=shape.circle, color=i_rescol, location=location.absolute, size=size.tiny)
plotshape(i_showlabels and buy ? low - atrxy : na, style=shape.circle, color=i_supcol, location=location.absolute, size=size.tiny)
plotchikouspan = plot(chikouspan, title='Chikou', color=not i_showchikou ? na : chikou_clr, linewidth=1, offset=-dynch)
f_colorgradient(_source, _min, _max, _cbear, _cbull) =>
var float _center = _min + (_max - _min) / 2
color _return = _source >= _center ?
color.from_gradient(_source, _min, _center, color.new(_cbear, 0), color.new(_cbear, 100)) :
color.from_gradient(_source, _center, _max, color.new(_cbull, 100), color.new(_cbull, 0))
skclr = (senkoua - senkoub) / altsrcres * 100
skfill = senkoua > senkoub ? color.from_gradient(ta.rsi(math.avg(senkoua , senkoub), 14) , 0, 100, I_skconso, I_skbull) :
senkoua < senkoub ? color.from_gradient(ta.rsi(math.avg(senkoua , senkoub), 14) , 0, 100, I_skconso, I_skbear) : I_skconso
plottenkansen = plot(tenkansen, title='Tenkan-Sen', color=not i_showtenkan ? na : i_tenkancolor, linewidth=1, offset=0)
plotkijunsen = plot(kijunsen, title='Kijun-Sen', color=not i_showkijun ? na : i_kijuncolor, linewidth=1, offset=0)
plotsenkoua = plot(senkoua, title='Senkou-Span A', color=not I_ska ? na : I_skbull, linewidth=1, offset=I_skoffset-1)
plotsenkoub = plot(senkoub, title='Senkou-Span B', color=not I_skb ? na : I_skbear, linewidth=1, offset=I_skoffset-1)
fill(plotsenkoua, plotsenkoub, color=not I_kumofill ? na : color.new(skfill, I_kumofillt))
//Tenkan-Sen/kijun-Sen Price Plotting
if i_showtenkan and i_showprice
l1 = label.new(bar_index, tkbool, 'Tenkan-Sen - ' + str.tostring(math.round_to_mintick(tkbool)), color=color.new(i_tenkancolor, 100), textcolor=color.new(i_tenkancolor, 0), style=label.style_label_left, yloc=yloc.price, size=size.small)
l1
label.delete(l1[1])
if i_showkijun and i_showprice
l1 = label.new(bar_index, kjbool, 'Kijun-Sen - ' + str.tostring(math.round_to_mintick(kjbool)), color=color.new(i_kijuncolor, 100), textcolor=color.new(i_kijuncolor, 0), style=label.style_label_left, yloc=yloc.price, size=size.small)
l1
label.delete(l1[1])
//Bar Color Plotting
colbar(src, tenkansen, kijunsen) =>
vbarcolor = color.new(na, 0)
vbarcolor := src > tenkansen and src > kijunsen? i_bullbarcol :
src < tenkansen and src < kijunsen ? i_bearbarcol :
src > tenkansen and src < kijunsen ? i_consobarcol :
src < tenkansen and src > kijunsen ? i_neutralbarcol : na
vbarcolor
bc = colbar(close, tenkansen, kijunsen)
barcolor(i_showbc ? bc : na)
//◀─── Kijun-Sen Hidden Supports/Resistances ───►
//Smoothed MA Calculation
smma1 = 0.0
smma2 = 0.0
smakj1 = ta.sma(close, i_kjminlen)
smakj2 = ta.sma(close, i_kjmaxlen)
smma1 := na(smma1[1]) ? smakj1 : (smma1[1] * (20 - 1) + close) / 20
smma2 := na(smma2[1]) ? smakj2 : (smma2[1] * (60 - 1) + close) / 60
//Kijun-Sen Calculation
kjsmma = math.avg(ta.lowest(26), ta.highest(26))
//Conditions
hiddenbearkj = ta.crossunder(smma1, kjsmma) and kjsmma < smma2 and close < smma1
hiddenbullkj = ta.crossover(smma1, kjsmma) and kjsmma > smma2 and close > smma1
//Boolean Conditions to Float
var float bearhkj = na
if hiddenbearkj
bearhkj := high
bearhkj
var float bullhkj = na
if hiddenbullkj
bullhkj := low
bullhkj
//Labels Calculation
if i_showkjhlabels
l = ta.change(bearhkj) ? label.new(bar_index, bearhkj[1] + 0.01, str.tostring(math.round_to_mintick(bearhkj)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_down, yloc=yloc.abovebar, size=size.small) : ta.change(bullhkj) ? label.new(bar_index, bullhkj[1] - 0.01, str.tostring(math.round_to_mintick(bullhkj)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_up, yloc=yloc.belowbar, size=size.small) : na
l
//Plotting
plotshape(i_showkjhlabels ? hiddenbearkj : na, title='Bearish Hidden Kijun-Sen', style=shape.triangledown, location=location.abovebar, color=i_rescol, size=size.tiny)
plotshape(i_showkjhlabels ? hiddenbullkj : na, title='Bullish Hidden Kijun-Sen', style=shape.triangleup, location=location.belowbar, color=i_supcol, size=size.tiny)
//Hidden Kijun S/R Variables Declaration
var int numberofline2 = i_maxline
var float upperphzone2 = na
var float upperplzone2 = na
var float lowerphzone2 = na
var float lowerplzone2 = na
var line[] upperphzonearr2 = array.new_line(0, na)
var line[] upperplzonearr2 = array.new_line(0, na)
var line[] lowerphzonearr2 = array.new_line(0, na)
var line[] lowerplzonearr2 = array.new_line(0, na)
var line upperphzoneline2 = na
var line upperplzoneline2 = na
var line lowerphzoneline2 = na
var line lowerplzoneline2 = na
var bool[] upperzonetestedarr2 = array.new_bool(0, false)
var bool[] lowerzonetestedarr2 = array.new_bool(0, false)
var bool upperzonetested2 = false
var bool lowerzonetested2 = false
var bool nobool2 = true
var color upperzonecolor2 = color.red
var color lowerzonecolor2 = color.green
var label[] labelpharr2 = array.new_label(0, na)
var label[] labelplarr2 = array.new_label(0, na)
var label labelph2 = na
var label labelpl2 = na
//Hidden Kijun Resistances Calculation
if i_showsr and i_showkjhsr and hiddenbearkj
upperphzone2 := high_
upperplzone2 := close_ < open_ ? close_ : open_
upperplzoneline2 := i_layout == 'Zone' ? line.new(bar_index_, upperplzone2, bar_index, upperplzone2, width=i_linewidth) : na
upperphzoneline2 := nobool2 ? line.new(bar_index_, upperphzone2, bar_index, upperphzone2, width=i_linewidth) : line.new(bar_index_, (upperphzone2 + upperplzone2) / 2, bar_index, (upperphzone2 + upperplzone2) / 2, width=i_linewidth)
labelph2 := i_showsr ? label.new(bar_index_, nobool2 ? upperphzone2 : (upperphzone2 + upperplzone2) / 2, text=str.tostring(bar_index - bar_index_), textcolor=upperzonecolor2, style=label.style_none) : na
if array.size(upperphzonearr2) > numberofline2
line.delete(array.shift(upperphzonearr2))
line.delete(array.shift(upperplzonearr2))
array.shift(upperzonetestedarr2)
label.delete(array.shift(labelpharr2))
array.push(upperphzonearr2, upperphzoneline2)
array.push(upperplzonearr2, upperplzoneline2)
array.push(upperzonetestedarr2, i_extend ? true : false)
array.push(labelpharr2, labelph2)
if array.size(upperplzonearr2) > 0
for i = 0 to array.size(upperplzonearr2) - 1 by 1
line tempupperline2 = array.get(upperphzonearr2, i)
line templowerline2 = array.get(upperplzonearr2, i)
label linepricelabel2 = array.get(labelpharr2, i)
bool tested2 = array.get(upperzonetestedarr2, i)
line.set_style(tempupperline2, f_i_linestyle(i_linestyle))
line.set_style(templowerline2, f_i_linestyle(i_linestyle))
line.set_color(tempupperline2, color.from_gradient(i, 1, numberofline2, fzonecolor(upperzonecolor2, 00), fzonecolor(upperzonecolor2, 00)))
line.set_color(templowerline2, color.from_gradient(i, 1, numberofline2, fzonecolor(upperzonecolor2, 00), fzonecolor(upperzonecolor2, 00)))
label.set_textcolor(linepricelabel2, color.from_gradient(i, 1, numberofline2, fzonecolor(upperzonecolor2, 00), upperzonecolor2))
label.set_text(linepricelabel2, str.tostring(math.round_to_mintick(line.get_y1(tempupperline2))))
label.set_text(linepricelabel2, ' Hidden Kijun Resistance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempupperline2))))
label.set_x(linepricelabel2, bar_index)
crossed = high > line.get_y1(tempupperline2)
if crossed and not tested2
array.set(upperzonetestedarr2, i, true)
label.delete(linepricelabel2)
else if i_extend ? tested2 : not tested2
line.set_x2(tempupperline2, bar_index)
array.set(upperphzonearr2, i, tempupperline2)
line.set_x2(templowerline2, bar_index)
array.set(upperplzonearr2, i, templowerline2)
//Hidden Kijun Supports Calculation
if i_showsr and i_showkjhsr and hiddenbullkj
lowerplzone2 := low_
lowerphzone2 := close_ > open_ ? open_ : close_
lowerphzoneline2 := i_layout == 'Zone' ? line.new(bar_index_, lowerphzone2, bar_index, lowerphzone2, width=i_linewidth) : na
lowerplzoneline2 := nobool2 ? line.new(bar_index_, lowerplzone2, bar_index, lowerplzone2, width=i_linewidth) : line.new(bar_index_, (lowerphzone2 + lowerplzone2) / 2, bar_index, (lowerphzone2 + lowerplzone2) / 2, width=i_linewidth)
labelpl2 := i_showsr ? label.new(bar_index_, nobool2 ? lowerplzone2 : (lowerphzone2 + lowerplzone2) / 2, text=str.tostring(bar_index - bar_index_), textcolor=lowerzonecolor2, style=label.style_none) : na
if array.size(lowerphzonearr2) > numberofline2
line.delete(array.shift(lowerphzonearr2))
line.delete(array.shift(lowerplzonearr2))
array.shift(lowerzonetestedarr2)
label.delete(array.shift(labelplarr2))
array.push(lowerphzonearr2, lowerphzoneline2)
array.push(lowerplzonearr2, lowerplzoneline2)
array.push(lowerzonetestedarr2, i_extend ? true : false)
array.push(labelplarr2, labelpl2)
if array.size(lowerplzonearr2) > 0
for i = 0 to array.size(lowerplzonearr2) - 1 by 1
line tempupperline2 = array.get(lowerphzonearr2, i)
line templowerline2 = array.get(lowerplzonearr2, i)
label linepricelabel2 = array.get(labelplarr2, i)
bool tested2 = array.get(lowerzonetestedarr2, i)
line.set_style(tempupperline2, f_i_linestyle(i_linestyle))
line.set_style(templowerline2, f_i_linestyle(i_linestyle))
line.set_color(tempupperline2, color.from_gradient(i, 1, numberofline2, fzonecolor(lowerzonecolor2, 00), fzonecolor(lowerzonecolor2, 00)))
line.set_color(templowerline2, color.from_gradient(i, 1, numberofline2, fzonecolor(lowerzonecolor2, 00), fzonecolor(lowerzonecolor2, 00)))
label.set_textcolor(linepricelabel2, color.from_gradient(i, 1, numberofline2, fzonecolor(lowerzonecolor2, 00), lowerzonecolor2))
label.set_text(linepricelabel2, str.tostring(math.round_to_mintick(line.get_y1(templowerline2))))
label.set_text(linepricelabel2, ' Hidden Kijun Support - ' + str.tostring(math.round_to_mintick(line.get_y1(templowerline2))))
label.set_x(linepricelabel2, bar_index)
crossed = low < line.get_y1(templowerline2)
if crossed and not tested2
array.set(lowerzonetestedarr2, i, true)
label.delete(linepricelabel2)
else if i_extend ? tested2 : not tested2
line.set_x2(tempupperline2, bar_index)
array.set(lowerphzonearr2, i, tempupperline2)
line.set_x2(templowerline2, bar_index)
array.set(lowerplzonearr2, i, templowerline2)
//◀─── Table Calculation ───►
//Constant Colors Variables
itablestrongbearcol = color.new(color.red, 0)
itablebearcol = color.new(color.maroon, 0)
itableneutralbearcol = color.new(color.silver, 0)
itablestrongbullcol = color.new(color.lime, 0)
itablebullcol = color.new(color.green, 0)
itableneutralbullcol = color.new(color.silver, 0)
itableconsocol = color.new(color.orange, 0)
//Boolean Dynamic Settings To Integer Conditions
var int dyntkint = 0
if dyntk
dyntkint := dyntk
dyntkint
var int dynkjint = 0
if dynkj
dynkjint := dynkj
dynkjint
var int dynskint = 0
if dynsk
dynskint := dynsk
dynskint
var int dynchint = 0
if dynch
dynchint := dynch
dynchint
//Global Functions
donchian(len) =>
math.avg(ta.lowest(len), ta.highest(len))
f_presets(p) =>
if p == 'Custom'
[dyntkint, dynkjint, dynskint, dynch]
else if p == '9/26/52/26 - 6D Markets (Default)'
[9, 26, 52, 26]
else if p == '8/22/44/22 - 5D Markets'
[8, 22, 44, 22]
else if p == '9/30/60/30 - 24h/7D Markets (Crypto)'
[10, 30, 60, 30]
else if p == '20/60/120/60 - 24h/7D Markets (Slow Version)'
[20, 60, 120, 60]
else
[0, 0, 0, 0]
f_tablestringpos(p) =>
p == 'Bottom Right' ? position.bottom_right : p == 'Top Right' ? position.top_right : p == 'Bottom Left' ? position.bottom_left : p == 'Top Left' ? position.top_left : p == 'Top' ? position.top_center : p == 'Right' ? position.middle_right : p == 'Bottom' ? position.bottom_center : p == 'Left' ? position.middle_left : na
f_tablestringdirsym(trend) =>
trend == 1 ? '▲ Strong' : trend == 2 ? '▲ Neutral' : trend == 3 ? '▲ Weak' : trend == -1 ? '▼ Strong' : trend == -2 ? '▼ Neutral' : trend == -3 ? '▼ Weak' : '■ Consolidation'
f_tablestringcolor(trend, c_up, c_down, c_consolidation) =>
trend > 0 ? c_up : trend < 0 ? c_down : c_consolidation
f_tablestringcolordir(trend, c_up, c_down) =>
trend > 0 ? c_up : c_down
f_tablecloudtrend(l1, l2) =>
l1 > l2 ? 1 : -1
f_tabletrendsum(sum, count) =>
sum == count ? 1 : sum == -count ? -1 : 0
f_tablestrengthconditions(pos, uptrend) =>
uptrend ? pos == 1 ? 1 : pos == 0 ? 2 : 3 : pos == -1 ? -1 : pos == 0 ? -2 : -3
//Presets Calculation
[i_conversion_len, i_base_len, i_lagging_len, i_offset] = f_presets(i_tablepresets)
//Presets Conditions
i_conversion = donchian(i_conversion_len)
i_base = donchian(i_base_len)
i_lead1 = math.avg(i_conversion, i_base)
i_lead2 = donchian(i_lagging_len)
i_cloud_top2 = math.max(i_lead1, i_lead2)
i_cloud_bot2 = math.min(i_lead1, i_lead2)
//Constant Array Variable
tablearrindex = array.new_int(0)
//Signals Conditions Function
f_tableconditions(enabled, signal) =>
if enabled
array.push(tablearrindex, signal)
//Calculation
i_lead1_current = i_lead1[i_offset - 1]
i_lead2_current = i_lead2[i_offset - 1]
i_cloud_top = math.max(i_lead1_current, i_lead2_current)
i_cloud_bot = math.min(i_lead1_current, i_lead2_current)
table_base_position = i_base > i_cloud_top ? 1 : i_base < i_cloud_bot ? -1 : 0
table_base_breakout = close > i_base ? f_tablestrengthconditions(table_base_position, true) : f_tablestrengthconditions(table_base_position, false)
table_cloud2_trend = f_tablecloudtrend(i_conversion, i_base)
table_cloud2_top = math.max(i_base, i_conversion)
table_cloud2_bot = math.min(i_base, i_conversion)
table_cloud2_position = table_cloud2_bot > i_cloud_top ? 1 : table_cloud2_top < i_cloud_bot ? -1 : 0
table_cloud2_cross = table_cloud2_trend == 1 ? f_tablestrengthconditions(table_cloud2_position, true) : f_tablestrengthconditions(table_cloud2_position, false)
table_lagging_lead1 = i_lead1_current[i_offset - 1]
table_lagging_lead2 = i_lead2_current[i_offset - 1]
table_lagging_cloud_top = math.max(table_lagging_lead1, table_lagging_lead2)
table_lagging_cloud_bot = math.min(table_lagging_lead1, table_lagging_lead2)
table_lagging_high = high[i_offset - 1]
table_lagging_low = low[i_offset - 1]
table_lagging_trend = close > table_lagging_high ? 1 : close < table_lagging_low ? -1 : 0
table_lagging_position = close > i_cloud_top ? 1 : close < i_cloud_bot ? -1 : 0
table_lagging_cross = table_lagging_trend == 1 ? f_tablestrengthconditions(table_lagging_position, true) : table_lagging_trend == -1 ? f_tablestrengthconditions(table_lagging_position, false) : 0
table_cloud_breakout = close > i_cloud_top ? 1 : close < i_cloud_bot ? -1 : 0
table_cloud_trend = f_tablecloudtrend(i_lead1, i_lead2)
table_lead_cross = table_cloud_trend == 1 ? f_tablestrengthconditions(table_cloud_breakout, true) : f_tablestrengthconditions(table_cloud_breakout, false)
//Conditions Functions
f_tableconditions(i_tablekjpc, table_base_breakout)
f_tableconditions(i_tabletkpc, table_cloud2_cross)
f_tableconditions(i_tablechpc, table_lagging_cross)
f_tableconditions(i_tablekumobr, table_cloud_breakout)
f_tableconditions(i_tablekumotw, table_lead_cross)
//Conditions
table_signal_max = array.max(tablearrindex)
table_signal_min = array.min(tablearrindex)
table_signal = table_signal_min > 0 ? table_signal_max : table_signal_max < 0 ? table_signal_min : 0
table_changed = table_signal != table_signal[1]
table_downtrend = table_changed and table_signal == -1
table_uptrend = table_changed and table_signal == 1
table_consolidation = table_changed and table_signal == 0
table_consolidation_downtrend = table_consolidation and table_signal[1] == -1
table_consolidation_uptrend = table_consolidation and table_signal[1] == 1
//Colors String Function
f_tablecolors(t) =>
t == 1 ? itablestrongbullcol : t == 2 ? itableneutralbullcol : t == 3 ? itablebullcol : t == -1 ? itablestrongbearcol : t == -2 ? itableneutralbearcol : t == -3 ? itablebearcol : itableconsocol
//String to Variable
i_panel_c_signal_text = f_tablecolors(table_signal)
//Table Text Size String Function
tabletxtwi = i_tabletxtsize == 'Tiny' ? size.tiny : i_tabletxtsize == 'Small' ? size.small : i_tabletxtsize == 'Normal' ? size.normal : i_tabletxtsize == 'Large' ? size.large : size.normal
//Plotting
var table i_panel = na
insertRow(i, text_1, trend, col) =>
table.cell(i_panel, 0, i, text_1, text_color=col, text_halign=text.align_right, text_size=tabletxtwi)
table.cell(i_panel, 1, i, f_tablestringdirsym(trend), text_color=f_tablecolors(trend), text_halign=text.align_left, text_size=tabletxtwi)
i + 1
if i_showtable and array.size(tablearrindex) > 0
i_panel := table.new(position=f_tablestringpos(i_tableloc), columns=2, rows=20, bgcolor=i_tablebgcol, border_width=0)
i = 0
if i_tabletkpc
i := insertRow(i, 'Tenkan-Sen Price Cross', table_cloud2_cross, i_tabletxtcol)
i
if i_tablekjpc
i := insertRow(i, 'Kijun-Sen Price Cross', table_base_breakout, i_tabletxtcol)
i
if i_tablechpc
i := insertRow(i, 'Chikou Span Price Cross', table_lagging_cross, i_tabletxtcol)
i
if i_tablekumobr
i := insertRow(i, 'Kumo Breakout', table_cloud_breakout, i_tabletxtcol)
i
if i_tablekumotw
i := insertRow(i, 'Kumo Twist', table_lead_cross, i_tabletxtcol)
i
table.cell(i_panel, 0, i, 'Status', bgcolor=i_tablebgcol, text_color=i_panel_c_signal_text, text_halign=text.align_right, text_size=tabletxtwi)
table.cell(i_panel, 1, i, f_tablestringdirsym(table_signal), bgcolor=i_tablebgcol, text_color=i_panel_c_signal_text, text_halign=text.align_left, text_size=tabletxtwi)
//◀─── Support/Resistance Lines Variables Declaration ───►
var int numberofline = i_maxline
var float upperphzone = na
var float upperplzone = na
var float lowerphzone = na
var float lowerplzone = na
var line[] upperphzonearr = array.new_line(0, na)
var line[] upperplzonearr = array.new_line(0, na)
var line[] lowerphzonearr = array.new_line(0, na)
var line[] lowerplzonearr = array.new_line(0, na)
var line upperphzoneline = na
var line upperplzoneline = na
var line lowerphzoneline = na
var line lowerplzoneline = na
var bool[] upperzonetestedarr = array.new_bool(0, false)
var bool[] lowerzonetestedarr = array.new_bool(0, false)
var bool upperzonetested = false
var bool lowerzonetested = false
var bool nobool = true
var bool showprice = true
var color upperzonecolor = i_rescol
var color lowerzonecolor = i_supcol
var label[] labelpharr = array.new_label(0, na)
var label[] labelplarr = array.new_label(0, na)
var label labelph = na
var label labelpl = na
//Resistance Lines Calculation
if i_showsr and shortcr
upperphzone := high_
upperplzone := close_ < open_ ? close_ : open_
upperplzoneline := i_layout == 'Zone' ? line.new(bar_index_, upperplzone, bar_index, upperplzone, width=i_linewidth) : na
upperphzoneline := nobool ? line.new(bar_index_, upperphzone, bar_index, upperphzone, width=i_linewidth) : line.new(bar_index_, (upperphzone + upperplzone) / 2, bar_index, (upperphzone + upperplzone) / 2, width=i_linewidth)
labelph := showprice ? label.new(bar_index_, nobool ? upperphzone : (upperphzone + upperplzone) / 2, text=str.tostring(math.round_to_mintick(bar_index - bar_index_)), textcolor=upperzonecolor, style=label.style_none) : na
if array.size(upperphzonearr) > numberofline
line.delete(array.shift(upperphzonearr))
line.delete(array.shift(upperplzonearr))
array.shift(upperzonetestedarr)
label.delete(array.shift(labelpharr))
array.push(upperphzonearr, upperphzoneline)
array.push(upperplzonearr, upperplzoneline)
array.push(upperzonetestedarr, i_extend ? true : false)
array.push(labelpharr, labelph)
if array.size(upperplzonearr) > 0
for i = 0 to array.size(upperplzonearr) - 1 by 1
line tempupperline = array.get(upperphzonearr, i)
line templowerline = array.get(upperplzonearr, i)
label linepricelabel = array.get(labelpharr, i)
bool tested = array.get(upperzonetestedarr, i)
line.set_style(tempupperline, f_i_linestyle(i_linestyle))
line.set_style(templowerline, f_i_linestyle(i_linestyle))
line.set_color(tempupperline, color.from_gradient(i, 1, numberofline, fzonecolor(upperzonecolor, 00), fzonecolor(upperzonecolor, 00)))
line.set_color(templowerline, color.from_gradient(i, 1, numberofline, fzonecolor(upperzonecolor, 00), fzonecolor(upperzonecolor, 00)))
label.set_textcolor(linepricelabel, color.from_gradient(i, 1, numberofline, fzonecolor(upperzonecolor, 00), upperzonecolor))
label.set_text(linepricelabel, str.tostring(math.round_to_mintick(line.get_y1(tempupperline))))
label.set_text(linepricelabel, ' Resistance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempupperline))))
label.set_x(linepricelabel, bar_index)
crossed = high > line.get_y1(tempupperline)
if crossed and not tested
array.set(upperzonetestedarr, i, true)
label.delete(linepricelabel)
else if i_extend ? tested : not tested
line.set_x2(tempupperline, bar_index)
array.set(upperphzonearr, i, tempupperline)
line.set_x2(templowerline, bar_index)
array.set(upperplzonearr, i, templowerline)
//Support Lines Calculation
if i_showsr and longcr
lowerplzone := low_
lowerphzone := close_ > open_ ? open_ : close_
lowerphzoneline := i_layout == 'Zone' ? line.new(bar_index_, lowerphzone, bar_index, lowerphzone, width=i_linewidth) : na
lowerplzoneline := nobool ? line.new(bar_index_, lowerplzone, bar_index, lowerplzone, width=i_linewidth) : line.new(bar_index_, (lowerphzone + lowerplzone) / 2, bar_index, (lowerphzone + lowerplzone) / 2, width=i_linewidth)
labelpl := showprice ? label.new(bar_index_, nobool ? lowerplzone : (lowerphzone + lowerplzone) / 2, text=str.tostring(math.round_to_mintick(bar_index - bar_index_)), textcolor=lowerzonecolor, style=label.style_none) : na
if array.size(lowerphzonearr) > numberofline
line.delete(array.shift(lowerphzonearr))
line.delete(array.shift(lowerplzonearr))
array.shift(lowerzonetestedarr)
label.delete(array.shift(labelplarr))
array.push(lowerphzonearr, lowerphzoneline)
array.push(lowerplzonearr, lowerplzoneline)
array.push(lowerzonetestedarr, i_extend ? true : false)
array.push(labelplarr, labelpl)
if array.size(lowerplzonearr) > 0
for i = 0 to array.size(lowerplzonearr) - 1 by 1
line tempupperline = array.get(lowerphzonearr, i)
line templowerline = array.get(lowerplzonearr, i)
label linepricelabel = array.get(labelplarr, i)
bool tested = array.get(lowerzonetestedarr, i)
line.set_style(tempupperline, f_i_linestyle(i_linestyle))
line.set_style(templowerline, f_i_linestyle(i_linestyle))
line.set_color(tempupperline, color.from_gradient(i, 1, numberofline, fzonecolor(lowerzonecolor, 00), fzonecolor(lowerzonecolor, 00)))
line.set_color(templowerline, color.from_gradient(i, 1, numberofline, fzonecolor(lowerzonecolor, 00), fzonecolor(lowerzonecolor, 00)))
label.set_textcolor(linepricelabel, color.from_gradient(i, 1, numberofline, fzonecolor(lowerzonecolor, 00), lowerzonecolor))
label.set_text(linepricelabel, str.tostring(math.round_to_mintick(line.get_y1(templowerline))))
label.set_text(linepricelabel, ' Support - ' + str.tostring(math.round_to_mintick(line.get_y1(templowerline))))
label.set_x(linepricelabel, bar_index)
crossed = low < line.get_y1(templowerline)
if crossed and not tested
array.set(lowerzonetestedarr, i, true)
label.delete(linepricelabel)
else if i_extend ? tested : not tested
line.set_x2(tempupperline, bar_index)
array.set(lowerphzonearr, i, tempupperline)
line.set_x2(templowerline, bar_index)
array.set(lowerplzonearr, i, templowerline)
//◀─── Psychological Levels ───►
//Constant Variable
var incr = syminfo.type == 'cfd' ? syminfo.mintick * 5000 : syminfo.type == 'crypto' ? syminfo.mintick * 5000 : syminfo.mintick * 500
//Calculation
if i_psylevels and barstate.islast
for counter = 0 to i_linescounter - 1 by 1
incrup = math.ceil(close / incr) * incr + counter * incr
incrdown = math.floor(close / incr) * incr - counter * incr
//Plotting
line.new(bar_index, incrup, bar_index - 1, incrup, xloc=xloc.bar_index, extend=extend.both, color=i_psylinescol, width=1, style=line.style_solid)
line.new(bar_index, incrdown, bar_index - 1, incrdown, xloc=xloc.bar_index, extend=extend.both, color=i_psylinescol, width=1, style=line.style_solid)
//◀─── Alerts ───►
if sell ? high + atrxy : na
alert('Sell Condition! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(sell ? high + atrxy : na, 'Sell Condition!', 'Sell Condition!')
if buy ? low - atrxy : na
alert('Buy Condition! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(buy ? low - atrxy : na, 'Buy Condition!', 'Buy Condition!')
if shortcr ? (high) + atrxy : na
alert('Sell Continuity/Reversal! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(shortcr ? (high) + atrxy : na, 'Sell Continuity/Reversal!', 'Sell Continuity/Reversal!')
if longcr ? (low) - atrxy : na
alert('Buy Continuity/Reversal! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(longcr ? (high) + atrxy : na, 'Buy Continuity/Reversal!', 'Buy Continuity/Reversal!')
if i_showtable and table_downtrend
alert('Panel : Bearish Trend! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(i_showtable and table_downtrend, 'Panel : Bearish Trend!', 'Panel : Bearish Trend!')
if i_showtable and table_uptrend
alert('Panel : Bullish Trend! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(i_showtable and table_uptrend, 'Panel : Bullish Trend!', 'Panel : Bullish Trend!')
if i_showtable and table_consolidation
alert('Panel : Trend Consolidation! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
alertcondition(i_showtable and table_consolidation, 'Panel : Trend Consolidation!', 'Panel : Trend Consolidation!')
|
Nasdaq or US Composite Total Volume | https://www.tradingview.com/script/kO12fVaL-Nasdaq-or-US-Composite-Total-Volume/ | TraderBotA | https://www.tradingview.com/u/TraderBotA/ | 57 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TraderBotA
//@version=5
//This script intends to use the NASDAQ Composite total volume index, index ticker : TVOLQ, or the NYSE Composite total volume index, index ticker : TVOL, as a classical volume indicator on chart
indicator("Nasdaq or US Composite Total Volume", overlay=false)
src = input(title="SMA Lenght", defval=100)
i_sym = input.symbol("TVOLQ", "TVOLQ->NASDAQ TVOL->NYSE")
s = request.security(i_sym, 'D', close)
SMA = ta.sma(s,src)
plot(s, title="Growing & falling volume", color = open < close ? color.white : color.red, linewidth=2, style=plot.style_histogram)
plot (SMA, title="SMA", color=color.orange, linewidth=2, style=plot.style_line)
|
STD Adaptive ADXm w/ Floating Levels [Loxx] | https://www.tradingview.com/script/AOMSW1VA-STD-Adaptive-ADXm-w-Floating-Levels-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 137 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("STD Adaptive ADXm w/ Floating Levels [Loxx]", shorttitle = "STDAADXMFL [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
super(src, len) =>
f = (math.sqrt(2) * math.pi) / len
a = math.exp(-f)
c2 = 2 * a * math.cos(f)
c3 = -a * a
c1 = 1 - c2 - c3
smooth = 0.0
smooth := c1 * (src + src[1]) * 0.5 + c2 * nz(smooth[1]) + c3 * nz(smooth[2])
smooth
period = input.int(14, "Period", group = "Basic Settings")
Smooth = input.int(15, "Smoothing Period", group = "Basic Settings")
AdaptPeriod = input.int(14, "Adaptive Period", group = "Basic Settings")
upLevel = input.int(90, "Upper Boundary", group = "Basic Settings")
downLevel = input.int(10, "Lower Boundary", group = "Basic Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
showfloat = input.bool(true, "Show Floating Levels?", group = "UI Options")
showfill = input.bool(true, "Fil Floating Levels?", group = "UI Options")
dev = ta.stdev(close, AdaptPeriod)
avg = ta.sma(dev, AdaptPeriod)
tperiod = dev != 0 ? math.ceil(period * avg / dev) : period
alpha = 2.0/(tperiod + 1.0)
workSsm11 = super(high, Smooth)
workSsm12 = super(low, Smooth)
workSsm13 = super(nz(close[1]), Smooth)
workSsm14 = super(nz(high[1]), Smooth)
workSsm15 = super(nz(low[1]), Smooth)
dh = math.max(workSsm11 - workSsm14, 0)
dl = math.max(workSsm15 - workSsm12, 0)
if(dh == dl)
dh:=0
dl:=0
else if(dh < dl)
dh:=0
else if(dl < dh)
dl:=0
ttr = math.max(workSsm11, workSsm13) - math.min(workSsm12, workSsm13)
dhk = 0., dlk = 0.
dhk := ttr != 0 ? 100.0*dh/ttr : dhk
dlk := ttr != 0 ? 100.0*dl/ttr : dlk
workzdh = 0., workzdl = 0.
workzdh := nz(workzdh[1]) + alpha * (dhk- nz(workzdh[1]))
workzdl := nz(workzdl[1]) + alpha * (dlk- nz(workzdl[1]))
dDI = workzdh - workzdl
div = math.abs(workzdh + workzdl)
temp = 0.
temp := div != 0.0 ? 100 * dDI/div : temp
aADX = 0.
aADX := nz(aADX[1]) + alpha * (temp - nz(aADX[1]))
flLevelUp = upLevel
flLevelDown = downLevel
maxi = ta.highest(aADX, nz(math.ceil(tperiod), 1))
mini = ta.lowest(aADX, nz(math.ceil(tperiod), 1))
rrange = maxi - mini
flu = mini + flLevelUp * rrange / 100.0
fld = mini + flLevelDown * rrange / 100.0
flm = mini + 0.5 * rrange
colorout = aADX > nz(aADX[1]) ? greencolor : redcolor
plot(aADX, "ADX", color = colorout, linewidth = 3)
top = plot(showfloat ? flu : na, "Top float", color = color.new(greencolor, 50), linewidth = 1)
mid = plot(showfloat ? flm : na, "Mid float", color = color.new(redcolor, 50), linewidth = 1)
bot = plot(showfloat ? fld : na, "Bottom Float", color = color.new(color.white, 50), linewidth = 1)
fill(top, mid, title = "Top fill color", color = showfill ? color.new(greencolor, 95) : na)
fill(bot, mid, title = "Bottom fill color", color = showfill ? color.new(redcolor, 95) : na)
barcolor(colorbars ? colorout : na)
|
candles by sam | https://www.tradingview.com/script/gaVcVeDq-candles-by-sam/ | ashsam9396 | https://www.tradingview.com/u/ashsam9396/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ashsam9396
//@version=5
indicator("candles by sam" , overlay= true )
A = (close < open and close [1] < open [1] and close [2] < open [2] and high < open [1] and high [1] < open [2] and low < low[1] and low[1] < low[2])
barcolor (A ? color.yellow : na, offset = -2)
barcolor ( A ? color.yellow : na, offset=-1)
barcolor (A ? color.yellow : na)
B = (close > open and close [1] > open [1] and close [2] > open [2] and low > open [1] and low [1] > open [2] and high > high [1] and high [1] > high [2])
barcolor (B ? color.purple : na, offset = -2)
barcolor ( B ? color.purple : na, offset=-1)
barcolor (B ? color.purple : na) |
TURK RSI+ICHIMOKU | https://www.tradingview.com/script/vIfyJuAw-TURK-RSI-ICHIMOKU/ | alen746 | https://www.tradingview.com/u/alen746/ | 219 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © turk_shariq
//@version=5
indicator('TURK RSI+ICHIMOKU', overlay=false, max_bars_back=1500)
// rsi divergence
// input
rsig = 'RSI'
rb = input(2, 'How many Right Bars for Pivots', group=rsig)
lb = input(15, 'How many Left Bars for Pivots', group=rsig)
sph = input(close, 'Pivot source for Bear Divs', group=rsig)
spl = input(close, 'Pivots Source for Bull Divs', group=rsig)
len = input.int(14, ' RSI Length', minval=1, group=rsig)
lvl = input.int(5, 'Lookback Level for Divs', options=[1, 2, 3, 4, 5], group=rsig)
// pivot
ph = ta.pivothigh(sph, lb, rb)
pl = ta.pivotlow(spl, lb, rb)
hi0 = ta.valuewhen(ph, sph[rb], 0)
hi1 = ta.valuewhen(ph, sph[rb], 1)
hi2 = ta.valuewhen(ph, sph[rb], 2)
hi3 = ta.valuewhen(ph, sph[rb], 3)
hi4 = ta.valuewhen(ph, sph[rb], 4)
hi5 = ta.valuewhen(ph, sph[rb], 5)
lo0 = ta.valuewhen(pl, spl[rb], 0)
lo1 = ta.valuewhen(pl, spl[rb], 1)
lo2 = ta.valuewhen(pl, spl[rb], 2)
lo3 = ta.valuewhen(pl, spl[rb], 3)
lo4 = ta.valuewhen(pl, spl[rb], 4)
lo5 = ta.valuewhen(pl, spl[rb], 5)
lox0 = ta.valuewhen(pl, bar_index[rb], 0)
lox1 = ta.valuewhen(pl, bar_index[rb], 1)
lox2 = ta.valuewhen(pl, bar_index[rb], 2)
lox3 = ta.valuewhen(pl, bar_index[rb], 3)
lox4 = ta.valuewhen(pl, bar_index[rb], 4)
lox5 = ta.valuewhen(pl, bar_index[rb], 5)
hix0 = ta.valuewhen(ph, bar_index[rb], 0)
hix1 = ta.valuewhen(ph, bar_index[rb], 1)
hix2 = ta.valuewhen(ph, bar_index[rb], 2)
hix3 = ta.valuewhen(ph, bar_index[rb], 3)
hix4 = ta.valuewhen(ph, bar_index[rb], 4)
hix5 = ta.valuewhen(ph, bar_index[rb], 5)
rsi = ta.rsi(close, len)
rh0 = ta.valuewhen(ph, rsi[rb], 0)
rh1 = ta.valuewhen(ph, rsi[rb], 1)
rh2 = ta.valuewhen(ph, rsi[rb], 2)
rh3 = ta.valuewhen(ph, rsi[rb], 3)
rh4 = ta.valuewhen(ph, rsi[rb], 4)
rh5 = ta.valuewhen(ph, rsi[rb], 5)
rl0 = ta.valuewhen(pl, rsi[rb], 0)
rl1 = ta.valuewhen(pl, rsi[rb], 1)
rl2 = ta.valuewhen(pl, rsi[rb], 2)
rl3 = ta.valuewhen(pl, rsi[rb], 3)
rl4 = ta.valuewhen(pl, rsi[rb], 4)
rl5 = ta.valuewhen(pl, rsi[rb], 5)
// bull & bear divergence logic
bull_div_1= lo0<lo1
and rl1<rl0
bull_div_2= lo0<lo1 and lo0<lo2
and rl2<rl0 and rl2<rl1 and lvl>=2
bull_div_3= lo0<lo1 and lo0<lo2 and lo0<lo3
and rl3<rl0 and rl3<rl1 and rl3<rl2 and lvl>=3
bull_div_4= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4
and rl4<rl0 and rl4<rl1 and rl4<rl2 and rl4<rl3 and lvl>=4
bull_div_5= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4 and lo0<lo5
and rl5<rl0 and rl5<rl1 and rl5<rl2 and rl5<rl3 and rl5<rl4 and lvl>=5
bear_div_1= hi0>hi1
and rh1>rh0
bear_div_2= hi0>hi1 and hi0>hi2
and rh2>rh0 and rh2>rh1 and lvl>=2
bear_div_3= hi0>hi1 and hi0>hi2 and hi0>hi3
and rh3>rh0 and rh3>rh1 and rh3>rh2 and lvl>=3
bear_div_4= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4
and rh4>rh0 and rh4>rh1 and rh4>rh2 and rh4>rh3 and lvl>=4
bear_div_5= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4 and hi0>hi5
and rh5>rh0 and rh5>rh1 and rh5>rh2 and rh5>rh3 and rh5>rh4 and lvl>=5
new_bull1= bull_div_1 and not bull_div_1[1]
new_bull2= bull_div_2 and not bull_div_2[1]
new_bull3= bull_div_3 and not bull_div_3[1]
new_bull4= bull_div_4 and not bull_div_4[1]
new_bull5= bull_div_5 and not bull_div_5[1]
new_bear1= bear_div_1 and not bear_div_1[1]
new_bear2= bear_div_2 and not bear_div_2[1]
new_bear3= bear_div_3 and not bear_div_3[1]
new_bear4= bear_div_4 and not bear_div_4[1]
new_bear5= bear_div_5 and not bear_div_5[1]
recall(x) =>
ta.barssince(not na(x))
// bull divergence line plot
rbull1 = line(na)
rbull1 := new_bull1 and not new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox1, rl1, color=#ff9800, width=2) : na
rbull2 = line(na)
rbull2 := new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox2, rl2, color=#ff9800, width=2) : na
rbull3 = line(na)
rbull3 := new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox3, rl3, color=#ff9800, width=2) : na
rbull4 = line(na)
rbull4 := new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox4, rl4, color=#ff9800, width=2) : na
rbull5 = line(na)
rbull5 := new_bull5 ? line.new(lox0, rl0, lox5, rl5, color=#ff9800, width=2) : na
xbull21 = ta.valuewhen(recall(rbull2) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull31 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull41 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull51 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull32 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull42 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull52 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull43 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull53 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull54 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull4) == 0, bar_index, 0)
if new_bull2 and lo2 == ta.valuewhen(new_bull1, lo1, 0) and xbull21 >= 0
line.delete(rbull1[xbull21])
if new_bull3 and lo3 == ta.valuewhen(new_bull1, lo1, 0) and xbull31 >= 0
line.delete(rbull1[xbull31])
if new_bull4 and lo4 == ta.valuewhen(new_bull1, lo1, 0) and xbull41 >= 0
line.delete(rbull1[xbull41])
if new_bull5 and lo5 == ta.valuewhen(new_bull1, lo1, 0) and xbull51 >= 0
line.delete(rbull1[xbull51])
if new_bull3 and lo3 == ta.valuewhen(new_bull2, lo2, 0) and xbull32 >= 0
line.delete(rbull2[xbull32])
if new_bull4 and lo4 == ta.valuewhen(new_bull2, lo2, 0) and xbull42 >= 0
line.delete(rbull2[xbull42])
if new_bull5 and lo5 == ta.valuewhen(new_bull2, lo2, 0) and xbull52 >= 0
line.delete(rbull2[xbull52])
if new_bull4 and lo4 == ta.valuewhen(new_bull3, lo3, 0) and xbull43 >= 0
line.delete(rbull3[xbull43])
if new_bull5 and lo5 == ta.valuewhen(new_bull3, lo3, 0) and xbull53 >= 0
line.delete(rbull3[xbull53])
if new_bull5 and lo5 == ta.valuewhen(new_bull4, lo4, 0) and xbull54 >= 0
line.delete(rbull4[xbull54])
// bear divergence line plot
rbear1 = line(na)
rbear1 := new_bear1 and not new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix1, rh1, color=#ff9800, width=2) : na
rbear2 = line(na)
rbear2 := new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix2, rh2, color=#ff9800, width=2) : na
rbear3 = line(na)
rbear3 := new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix3, rh3, color=#ff9800, width=2) : na
rbear4 = line(na)
rbear4 := new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix4, rh4, color=#ff9800, width=2) : na
rbear5 = line(na)
rbear5 := new_bear5 ? line.new(hix0, rh0, hix5, rh5, color=#ff9800, width=2) : na
xbear21 = ta.valuewhen(recall(rbear2) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear31 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear41 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear51 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear32 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear42 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear52 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear43 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear53 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear54 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear4) == 0, bar_index, 0)
if new_bear2 and hi2 == ta.valuewhen(new_bear1, hi1, 0) and xbear21 >= 0
line.delete(rbear1[xbear21])
if new_bear3 and hi3 == ta.valuewhen(new_bear1, hi1, 0) and xbear31 >= 0
line.delete(rbear1[xbear31])
if new_bear4 and hi4 == ta.valuewhen(new_bear1, hi1, 0) and xbear41 >= 0
line.delete(rbear1[xbear41])
if new_bear5 and hi5 == ta.valuewhen(new_bear1, hi1, 0) and xbear51 >= 0
line.delete(rbear1[xbear51])
if new_bear3 and hi3 == ta.valuewhen(new_bear2, hi2, 0) and xbear32 >= 0
line.delete(rbear2[xbear32])
if new_bear4 and hi4 == ta.valuewhen(new_bear2, hi2, 0) and xbear42 >= 0
line.delete(rbear2[xbear42])
if new_bear5 and hi5 == ta.valuewhen(new_bear2, hi2, 0) and xbear52 >= 0
line.delete(rbear2[xbear52])
if new_bear4 and hi4 == ta.valuewhen(new_bear3, hi3, 0) and xbear43 >= 0
line.delete(rbear3[xbear43])
if new_bear5 and hi5 == ta.valuewhen(new_bear3, hi3, 0) and xbear53 >= 0
line.delete(rbear3[xbear53])
if new_bear5 and hi5 == ta.valuewhen(new_bear4, hi4, 0) and xbear54 >= 0
line.delete(rbear4[xbear54])
plotshape(title='bull_div_1', series=new_bull1 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_2', series=new_bull2 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_3', series=new_bull3 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_4', series=new_bull4 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_5', series=new_bull5 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_1', series=new_bear1 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_2', series=new_bear2 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_3', series=new_bear3 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_4', series=new_bear4 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_5', series=new_bear5 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
// rsi candle (with wick)
// rsi configuration
rsrc = close
ad = true
// rsi function
pine_rsi(rsrc, len) =>
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
rs = ta.rma(u, len) / ta.rma(d, len)
res = 100 - 100 / (1 + rs)
res
pine_rma(rsrc, length) =>
b = 1 / length
sum = 0.0
sum := na(sum[1]) ? ta.sma(rsrc, length) : b * rsrc + (1 - b) * nz(sum[1])
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
b = 1 / len
ruh = b * math.max(high - close[1], 0) + (1 - b) * ta.rma(u, len)[1]
rdh = (1 - b) * ta.rma(d, len)[1]
rul = (1 - b) * ta.rma(u, len)[1]
rdl = b * math.max(close[1] - low, 0) + (1 - b) * ta.rma(d, len)[1]
function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced
rsiha = 100 - 100 / (1 + ruh / rdh)
rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(rsrc, len)
rsih = if ad
function(rsiha, len)
else
rsiha
rsil = if ad
function(rsila, len)
else
rsila
// rsi bought & sold zone
plot_bands = true
reb = hline(plot_bands ? 70 : na, 'Extreme Bought', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
rmb = hline(plot_bands ? 50 : na, 'Middle Line', color.new(#fbc02d, 80), linewidth=4, linestyle=hline.style_solid)
res = hline(plot_bands ? 30 : na, 'Extreme Sold', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
// candle
plotcandle(rsi[1], rsih, rsil, rsi, 'RSI_Candle', color=ta.change(rsi) > 0 ? #ffffff : #000000, wickcolor=#000000, bordercolor=#2a2e39)
plot(rsi, 'RSI_Line', color= ta.change(rsi) > 0 ? color.black : color.black, display=display.none, linewidth=2)
// linear regression
// input
lrg = 'Linear Regression'
linreg = input(true, 'Linear Regression On / Off')
periodTrend = input.int(100, 'Trend Period', minval=4, group=lrg)
deviationsAmnt = input.float(2, 'Deviation', minval=0.1, step=0.1, group=lrg)
estimatorType = input.string('Unbiased', 'Estimator', options=['Biased', 'Unbiased'], group=lrg)
var extendType = input.string('Right', 'Extend', options=['Right', 'Segment'], group=lrg) == 'Right' ? extend.right : extend.none
// drawline configuration
drawLine(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := linreg ? line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, width=2) : na
line.delete(Line[1])
rsdcr2(PeriodMinusOne, Deviations, Estimate) =>
var period = PeriodMinusOne + 1
var devDenominator = Estimate == 'Unbiased' ? PeriodMinusOne : period
Ex = 0.0
Ex2 = 0.0
Exy = 0.0
Ey = 0.0
for i = 0 to PeriodMinusOne by 1
closeI = nz(rsi[i])
Ex := Ex + i
Ex2 := Ex2 + i * i
Exy := Exy + closeI * i
Ey := Ey + closeI
Ey
ExEx = Ex * Ex
slope = Ex2 == ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0
for i = 0 to PeriodMinusOne by 1
deviation := deviation + math.pow(nz(rsi[i]) - (intercept - bar_index[i] * slope), 2.0)
deviation
deviation := Deviations * math.sqrt(deviation / devDenominator)
correlate = ta.correlation(rsi, bar_index, period)
r2 = math.pow(correlate, 2.0)
[linearRegression, slope, deviation, correlate, r2]
periodMinusOne = periodTrend - 1
[linReg, slope, deviation, correlate, r2] = rsdcr2(periodMinusOne, deviationsAmnt, estimatorType)
endPointBar = bar_index - periodTrend + 1
endPointY = linReg + slope * periodMinusOne
// drawline plot
drawLine(endPointBar, endPointY + deviation, bar_index, linReg + deviation, extendType, #e91e63, line.style_solid)
drawLine(endPointBar, endPointY, bar_index, linReg, extendType, #e91e63, line.style_dotted)
drawLine(endPointBar, endPointY - deviation, bar_index, linReg - deviation, extendType, #e91e63, line.style_solid)
// ichimoku
// input
ichig = 'Ichimoku'
conversionPeriods = input.int(9, minval=1, title='Conversion Line Periods', group=ichig)
basePeriods = input.int(26, minval=1, title='Base Line Periods', group=ichig)
laggingSpan2Periods = input.int(52, minval=1, title='Lagging Span 2 Periods', group=ichig)
displacement = input.int(26, minval=1, title='Displacement', group=ichig)
// calc
donchian(len) => math.avg(ta.lowest(rsil, len), ta.highest(rsih, len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
// plot
p1 = plot(leadLine1, offset = displacement- 1, color=color.new(#4caf50, 100), title="LeadLine A", linewidth=3)
p2 = plot(leadLine2, offset = displacement - 1, color=color.new(#f23645, 100), title="LeadLine B", linewidth=3)
fill(p1, p2, color = leadLine1 > leadLine2 ? color.new(#4caf50, 70) : color.new(#f23645, 70), title='Ichimoku Cloud') |
{QG}Spread Candelsticks | https://www.tradingview.com/script/jDB8WetF-QG-Spread-Candelsticks/ | QuantG | https://www.tradingview.com/u/QuantG/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © QuantG
//@version=5
indicator("QG-Spread Candelsticks")
instrument1 = input.string(defval="NQ1!",title='Instrument1')
instrument2 = input.string(defval="ES1!",title='Instrument2')
mult1 = input.float(defval = 2.0,title='Multiplier1')
mult2 = input.float(defval = 5.0,title='Multiplier2')
var color bullColor = input(title='Bull Color', defval=#26a69a)
var color bearColor = input(title='Bear Color', defval=#ef5350)
candleColor = close >= open ? bullColor : bearColor
calculateSpread(t1, t2, Mult1, Mult2, source) =>
s1 = request.security(t1, timeframe.period, source)*Mult1
s2 = request.security(t2, timeframe.period, source)*Mult2
s1 - s2
_open = calculateSpread(instrument1,instrument2,mult1,mult2,open)
_high = calculateSpread(instrument1,instrument2,mult1,mult2,high)
_low = calculateSpread(instrument1,instrument2,mult1,mult2,low)
_close = calculateSpread(instrument1,instrument2,mult1,mult2,close)
plotcandle(_open, _high, _low, _close, title='Value Candle', color=candleColor, bordercolor=candleColor, wickcolor=color.white)
plot(_close, title='🔌SpreadCandelsticks🔌',display= display.none)
|
MTF EMAS | https://www.tradingview.com/script/lXcoenNG-MTF-EMAS/ | JoaoKunha | https://www.tradingview.com/u/JoaoKunha/ | 12 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JoaoKunha
//@version=4
study("MTF EMAS", overlay=true)
MA_Source = input(title="Source", type=input.source, defval=close, group="Source")
MA_Period1 = input(title="MA 1 Length", type=input.integer, defval=12, minval=1, group="Moving Average")
MA_Period2 = input(title="MA 2 Length", type=input.integer, defval=26, minval=1, group="Moving Average")
MA_Period3 = input(title="MA 3 Length", type=input.integer, defval=100, minval=1, group="Moving Average")
MA_Period4 = input(title="MA 4 Length", type=input.integer, defval=200, minval=1, group="Moving Average")
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src)
MA_Function1 = f_secureSecurity(syminfo.tickerid, timeframe.period, ema(MA_Source, MA_Period1))
MA_Function2 = f_secureSecurity(syminfo.tickerid, timeframe.period, ema(MA_Source, MA_Period2))
MA_Function3 = f_secureSecurity(syminfo.tickerid, timeframe.period, ema(MA_Source, MA_Period3))
MA_Function4 = f_secureSecurity(syminfo.tickerid, timeframe.period, ema(MA_Source, MA_Period4))
plot(series=MA_Function1, title="Moving Average 1 CTF", color=color.red, style=plot.style_line, linewidth=1)
plot(series=MA_Function2, title="Moving Average 2 CTF", color=color.green, style=plot.style_line, linewidth=1)
plot(series=MA_Function3, title="Moving Average 3 CTF", color=color.orange, style=plot.style_line, linewidth=1)
plot(series=MA_Function4, title="Moving Average 4 CTF", color=color.yellow, style=plot.style_line, linewidth=1)
float MA2_Function1 = na
float MA2_Function2 = na
float MA2_Function3 = na
float MA2_Function4 = na
if (timeframe.isminutes and timeframe.multiplier < 5)
MA2_Function1 := f_secureSecurity(syminfo.tickerid, "5", ema(MA_Source, MA_Period1))
MA2_Function2 := f_secureSecurity(syminfo.tickerid, "5", ema(MA_Source, MA_Period2))
MA2_Function3 := f_secureSecurity(syminfo.tickerid, "5", ema(MA_Source, MA_Period3))
MA2_Function4 := f_secureSecurity(syminfo.tickerid, "5", ema(MA_Source, MA_Period4))
if (timeframe.isminutes and timeframe.multiplier >= 5)
MA2_Function1 := f_secureSecurity(syminfo.tickerid, "D", ema(MA_Source, MA_Period1))
MA2_Function2 := f_secureSecurity(syminfo.tickerid, "D", ema(MA_Source, MA_Period2))
MA2_Function3 := f_secureSecurity(syminfo.tickerid, "D", ema(MA_Source, MA_Period3))
MA2_Function4 := f_secureSecurity(syminfo.tickerid, "D", ema(MA_Source, MA_Period4))
if (timeframe.isdaily)
MA2_Function1 := f_secureSecurity(syminfo.tickerid, "W", ema(MA_Source, MA_Period1))
MA2_Function2 := f_secureSecurity(syminfo.tickerid, "W", ema(MA_Source, MA_Period2))
MA2_Function3 := f_secureSecurity(syminfo.tickerid, "W", ema(MA_Source, MA_Period3))
MA2_Function4 := f_secureSecurity(syminfo.tickerid, "W", ema(MA_Source, MA_Period4))
if (timeframe.isweekly)
MA2_Function1 := f_secureSecurity(syminfo.tickerid, "M", ema(MA_Source, MA_Period1))
MA2_Function2 := f_secureSecurity(syminfo.tickerid, "M", ema(MA_Source, MA_Period2))
MA2_Function3 := f_secureSecurity(syminfo.tickerid, "M", ema(MA_Source, MA_Period3))
MA2_Function4 := f_secureSecurity(syminfo.tickerid, "M", ema(MA_Source, MA_Period4))
plot(series=MA2_Function1, title="Moving Average 1 HTF", color=color.red, style=plot.style_line, linewidth=2)
plot(series=MA2_Function2, title="Moving Average 2 HTF", color=color.green, style=plot.style_line, linewidth=2)
plot(series=MA2_Function3, title="Moving Average 3 HTF", color=color.orange, style=plot.style_line, linewidth=2)
plot(series=MA2_Function4, title="Moving Average 4 HTF", color=color.yellow, style=plot.style_line, linewidth=2)
|
ATR Adaptive EMA [Loxx] | https://www.tradingview.com/script/G2kTA9oF-ATR-Adaptive-EMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 145 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("ATR adaptive EMA [Loxx]", shorttitle = "ATRAEMA [Loxx]", overlay = true, timeframe="", timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
src = input.source(close, "Source", group = "Basic Settings")
len = input.int(28, "Length", group = "Basic Settings")
colorbars = input.bool(true, title='Color bars?', group = "UI Options")
_atr_adapt_ema(src, len)=>
atr = ta.atr(len)
atr /= len
atrMax = ta.highest(atr, len)
atrMin = ta.lowest(atr, len)
coeff = atrMin != atrMax ? 1 - (atr - atrMin) / (atrMax - atrMin) : 0.5
alpha = 2.0 / (1 + len * (coeff + 1.0) / 2.0)
emaout = 0.0
emaout := nz(emaout[1]) + alpha * (src - nz(emaout[1]))
emaout
out = _atr_adapt_ema(src, len)
plot(out, color = src >= out ? greencolor : redcolor, linewidth = 3)
barcolor(color = src >= out ? greencolor : redcolor) |
Stock Screener | https://www.tradingview.com/script/sG6VO3Ta-Stock-Screener/ | yosimadsu | https://www.tradingview.com/u/yosimadsu/ | 65 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © yosimadsu
// QQE Mod by Glaz, modified
// RMO by LazyBear
//@version=5
indicator("Stock Screener")
t01 = input.symbol("BATS:META", "Ticker 1", group="Tickers", inline="a")
t02 = input.symbol("BATS:META", "Ticker 2", group="Tickers", inline="b")
t03 = input.symbol("BATS:META", "Ticker 3", group="Tickers", inline="c")
t04 = input.symbol("BATS:META", "Ticker 4", group="Tickers", inline="d")
t05 = input.symbol("BATS:META", "Ticker 5", group="Tickers", inline="e")
t06 = input.symbol("BATS:META", "Ticker 6", group="Tickers", inline="f")
t07 = input.symbol("BATS:META", "Ticker 7", group="Tickers", inline="g")
t08 = input.symbol("BATS:META", "Ticker 8", group="Tickers", inline="h")
t09 = input.symbol("BATS:META", "Ticker 9", group="Tickers", inline="i")
t10 = input.symbol("BATS:META", "Ticker 10", group="Tickers", inline="j")
t11 = input.symbol("BATS:META", "Ticker 11", group="Tickers", inline="k")
t12 = input.symbol("BATS:META", "Ticker 12", group="Tickers", inline="l")
t13 = input.symbol("BATS:META", "Ticker 13", group="Tickers", inline="m")
t14 = input.symbol("BATS:META", "Ticker 14", group="Tickers", inline="n")
t15 = input.symbol("BATS:META", "Ticker 15", group="Tickers", inline="o")
t16 = input.symbol("BATS:META", "Ticker 16", group="Tickers", inline="p")
t17 = input.symbol("BATS:META", "Ticker 17", group="Tickers", inline="q")
t18 = input.symbol("BATS:META", "Ticker 18", group="Tickers", inline="r")
t19 = input.symbol("BATS:META", "Ticker 19", group="Tickers", inline="s")
t20 = input.symbol("BATS:META", "Ticker 20", group="Tickers", inline="t")
c01 = input.color(color.yellow, "", group="Tickers", inline="a")
c02 = input.color(color.yellow, "", group="Tickers", inline="b")
c03 = input.color(color.yellow, "", group="Tickers", inline="c")
c04 = input.color(color.yellow, "", group="Tickers", inline="d")
c05 = input.color(color.yellow, "", group="Tickers", inline="e")
c06 = input.color(color.yellow, "", group="Tickers", inline="f")
c07 = input.color(color.yellow, "", group="Tickers", inline="g")
c08 = input.color(color.yellow, "", group="Tickers", inline="h")
c09 = input.color(color.yellow, "", group="Tickers", inline="i")
c10 = input.color(color.yellow, "", group="Tickers", inline="j")
c11 = input.color(color.yellow, "", group="Tickers", inline="k")
c12 = input.color(color.yellow, "", group="Tickers", inline="l")
c13 = input.color(color.yellow, "", group="Tickers", inline="m")
c14 = input.color(color.yellow, "", group="Tickers", inline="n")
c15 = input.color(color.yellow, "", group="Tickers", inline="o")
c16 = input.color(color.yellow, "", group="Tickers", inline="p")
c17 = input.color(color.yellow, "", group="Tickers", inline="q")
c18 = input.color(color.yellow, "", group="Tickers", inline="r")
c19 = input.color(color.yellow, "", group="Tickers", inline="s")
c20 = input.color(color.yellow, "", group="Tickers", inline="t")
//
// QQE MOD
//
RSI_Period = input(6, title='RSI Length', group="Settings")
RSI_Smooth = input(5, title='RSI Smoothing', group="Settings")
QQE = input(3, title='Fast QQE Factor', group="Settings")
Threshold = input(3, title='Thresh-hold', group="Settings")
tfLow = input.timeframe('120', "Lower Timeframe", group="Settings")
tfHigh = input.timeframe('D', "Higher Timeframe", group="Settings")
length = input.int(50, minval=1, title='Bollinger Length', group="Settings")
mult = input.float(0.35, minval=0.001, maxval=5, step=0.1, title='BB Multiplier', group="Settings")
Wilders_Period = RSI_Period * 2 - 1
qqermo(src) =>
longband = 0.0
shortband = 0.0
trend = 0
Rsi = ta.rsi(src, RSI_Period)
RsiMa = ta.ema(Rsi, RSI_Smooth)
AtrRsi = math.abs(RsiMa[1] - RsiMa)
MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ta.ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RsiMa + DeltaFastAtrRsi
newlongband = RsiMa - DeltaFastAtrRsi
longband := RsiMa[1] > longband[1] and RsiMa > longband[1] ? math.max(longband[1], newlongband) : newlongband
shortband := RsiMa[1] < shortband[1] and RsiMa < shortband[1] ? math.min(shortband[1], newshortband) : newshortband
cross_1 = ta.cross(longband[1], RsiMa)
trend := ta.cross(RsiMa, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
basis = ta.sma(FastAtrRsiTL - 50, length)
dev = mult * ta.stdev(FastAtrRsiTL - 50, length)
upper = basis + dev
lower = basis - dev
Greenbar1 = RsiMa - 50 > Threshold
Greenbar2 = RsiMa - 50 > upper
Redbar1 = RsiMa - 50 < 0 - Threshold
Redbar2 = RsiMa - 50 < lower
qqe_result = Greenbar1 and Greenbar2 ? "🔹" : Redbar1 and Redbar2 ? "🔸" : RsiMa - 50 > Threshold ? "◽" : ""
//
// RMO
//
ma1 = ta.sma(src, 2)
ma2 = ta.sma(ma1, 2)
ma3 = ta.sma(ma2, 2)
ma4 = ta.sma(ma3, 2)
ma5 = ta.sma(ma4, 2)
ma6 = ta.sma(ma5, 2)
ma7 = ta.sma(ma6, 2)
ma8 = ta.sma(ma7, 2)
ma9 = ta.sma(ma8, 2)
ma10 = ta.sma(ma9, 2)
SwingTrd1 = 100 * (src - (ma1 + ma2 + ma3 + ma4 + ma5 + ma6 + ma7 + ma8 + ma9 + ma10) / 10) / (ta.highest(src, 10) - ta.lowest(src, 10))
SwingTrd2 = ta.ema(SwingTrd1, 30)
SwingTrd3 = ta.ema(SwingTrd2, 30)
RMO = ta.ema(SwingTrd1, 81)
Bull_Trend = ta.ema(SwingTrd1, 81) > 0
Impulse_UP = SwingTrd2 > 0
Impulse_Down = RMO < 0
bg_result = Impulse_UP ? color.aqua : Impulse_Down ? color.red : Bull_Trend ? color.aqua : color.white
[qqe_result, bg_result]
//
// TICKERS
//
[m01, p01] = request.security(t01, tfHigh, qqermo(close))
[m02, p02] = request.security(t02, tfHigh, qqermo(close))
[m03, p03] = request.security(t03, tfHigh, qqermo(close))
[m04, p04] = request.security(t04, tfHigh, qqermo(close))
[m05, p05] = request.security(t05, tfHigh, qqermo(close))
[m06, p06] = request.security(t06, tfHigh, qqermo(close))
[m07, p07] = request.security(t07, tfHigh, qqermo(close))
[m08, p08] = request.security(t08, tfHigh, qqermo(close))
[m09, p09] = request.security(t09, tfHigh, qqermo(close))
[m10, p10] = request.security(t10, tfHigh, qqermo(close))
[m11, p11] = request.security(t11, tfHigh, qqermo(close))
[m12, p12] = request.security(t12, tfHigh, qqermo(close))
[m13, p13] = request.security(t13, tfHigh, qqermo(close))
[m14, p14] = request.security(t14, tfHigh, qqermo(close))
[m15, p15] = request.security(t15, tfHigh, qqermo(close))
[m16, p16] = request.security(t16, tfHigh, qqermo(close))
[m17, p17] = request.security(t17, tfHigh, qqermo(close))
[m18, p18] = request.security(t18, tfHigh, qqermo(close))
[m19, p19] = request.security(t19, tfHigh, qqermo(close))
[m20, p20] = request.security(t20, tfHigh, qqermo(close))
[q01, r01] = request.security(t01, tfLow, qqermo(close))
[q02, r02] = request.security(t02, tfLow, qqermo(close))
[q03, r03] = request.security(t03, tfLow, qqermo(close))
[q04, r04] = request.security(t04, tfLow, qqermo(close))
[q05, r05] = request.security(t05, tfLow, qqermo(close))
[q06, r06] = request.security(t06, tfLow, qqermo(close))
[q07, r07] = request.security(t07, tfLow, qqermo(close))
[q08, r08] = request.security(t08, tfLow, qqermo(close))
[q09, r09] = request.security(t09, tfLow, qqermo(close))
[q10, r10] = request.security(t10, tfLow, qqermo(close))
[q11, r11] = request.security(t11, tfLow, qqermo(close))
[q12, r12] = request.security(t12, tfLow, qqermo(close))
[q13, r13] = request.security(t13, tfLow, qqermo(close))
[q14, r14] = request.security(t14, tfLow, qqermo(close))
[q15, r15] = request.security(t15, tfLow, qqermo(close))
[q16, r16] = request.security(t16, tfLow, qqermo(close))
[q17, r17] = request.security(t17, tfLow, qqermo(close))
[q18, r18] = request.security(t18, tfLow, qqermo(close))
[q19, r19] = request.security(t19, tfLow, qqermo(close))
[q20, r20] = request.security(t20, tfLow, qqermo(close))
//
// TABLE
//
var tabel = table.new(position = position.middle_center, columns = 27, rows = 10, bgcolor = na, border_color=na, border_width = 1)
if barstate.islast
table.cell(table_id = tabel, row = 0, column = 0, text = q01[7], bgcolor=r01[7])
table.cell(table_id = tabel, row = 0, column = 1, text = q01[6], bgcolor=r01[6])
table.cell(table_id = tabel, row = 0, column = 2, text = q01[5], bgcolor=r01[5])
table.cell(table_id = tabel, row = 0, column = 3, text = q01[4], bgcolor=r01[4])
table.cell(table_id = tabel, row = 0, column = 4, text = q01[3], bgcolor=r01[3])
table.cell(table_id = tabel, row = 0, column = 5, text = q01[2], bgcolor=r01[2])
table.cell(table_id = tabel, row = 0, column = 6, text = q01[1], bgcolor=r01[1])
table.cell(table_id = tabel, row = 0, column = 7, text = q01[0], bgcolor=r01[0])
table.cell(table_id = tabel, row = 0, column = 8, text = t01, bgcolor=c01)
table.cell(table_id = tabel, row = 0, column = 9, text = m01[3], bgcolor=p01[3])
table.cell(table_id = tabel, row = 0, column = 10, text = m01[2], bgcolor=p01[2])
table.cell(table_id = tabel, row = 0, column = 11, text = m01[1], bgcolor=p01[1])
table.cell(table_id = tabel, row = 0, column = 12, text = m01[0], bgcolor=p01[0])
table.cell(table_id = tabel, row = 0, column = 13, text = " ")
table.cell(table_id = tabel, row = 0, column = 14, text = q02[7], bgcolor=r02[7])
table.cell(table_id = tabel, row = 0, column = 15, text = q02[6], bgcolor=r02[6])
table.cell(table_id = tabel, row = 0, column = 16, text = q02[5], bgcolor=r02[5])
table.cell(table_id = tabel, row = 0, column = 17, text = q02[4], bgcolor=r02[4])
table.cell(table_id = tabel, row = 0, column = 18, text = q02[3], bgcolor=r02[3])
table.cell(table_id = tabel, row = 0, column = 19, text = q02[2], bgcolor=r02[2])
table.cell(table_id = tabel, row = 0, column = 20, text = q02[1], bgcolor=r02[1])
table.cell(table_id = tabel, row = 0, column = 21, text = q02[0], bgcolor=r02[0])
table.cell(table_id = tabel, row = 0, column = 22, text = t02, bgcolor=c02)
table.cell(table_id = tabel, row = 0, column = 23, text = m02[3], bgcolor=p02[3])
table.cell(table_id = tabel, row = 0, column = 24, text = m02[2], bgcolor=p02[2])
table.cell(table_id = tabel, row = 0, column = 25, text = m02[1], bgcolor=p02[1])
table.cell(table_id = tabel, row = 0, column = 26, text = m02[0], bgcolor=p02[0])
table.cell(table_id = tabel, row = 1, column = 0, text = q03[7], bgcolor=r03[7])
table.cell(table_id = tabel, row = 1, column = 1, text = q03[6], bgcolor=r03[6])
table.cell(table_id = tabel, row = 1, column = 2, text = q03[5], bgcolor=r03[5])
table.cell(table_id = tabel, row = 1, column = 3, text = q03[4], bgcolor=r03[4])
table.cell(table_id = tabel, row = 1, column = 4, text = q03[3], bgcolor=r03[3])
table.cell(table_id = tabel, row = 1, column = 5, text = q03[2], bgcolor=r03[2])
table.cell(table_id = tabel, row = 1, column = 6, text = q03[1], bgcolor=r03[1])
table.cell(table_id = tabel, row = 1, column = 7, text = q03[0], bgcolor=r03[0])
table.cell(table_id = tabel, row = 1, column = 8, text = t03, bgcolor=c03)
table.cell(table_id = tabel, row = 1, column = 9, text = m03[3], bgcolor=p03[3])
table.cell(table_id = tabel, row = 1, column = 10, text = m03[2], bgcolor=p03[2])
table.cell(table_id = tabel, row = 1, column = 11, text = m03[1], bgcolor=p03[1])
table.cell(table_id = tabel, row = 1, column = 12, text = m03[0], bgcolor=p03[0])
table.cell(table_id = tabel, row = 1, column = 13, text = " ")
table.cell(table_id = tabel, row = 1, column = 14, text = q04[7], bgcolor=r04[7])
table.cell(table_id = tabel, row = 1, column = 15, text = q04[6], bgcolor=r04[6])
table.cell(table_id = tabel, row = 1, column = 16, text = q04[5], bgcolor=r04[5])
table.cell(table_id = tabel, row = 1, column = 17, text = q04[4], bgcolor=r04[4])
table.cell(table_id = tabel, row = 1, column = 18, text = q04[3], bgcolor=r04[3])
table.cell(table_id = tabel, row = 1, column = 19, text = q04[2], bgcolor=r04[2])
table.cell(table_id = tabel, row = 1, column = 20, text = q04[1], bgcolor=r04[1])
table.cell(table_id = tabel, row = 1, column = 21, text = q04[0], bgcolor=r04[0])
table.cell(table_id = tabel, row = 1, column = 22, text = t04, bgcolor=c04)
table.cell(table_id = tabel, row = 1, column = 23, text = m04[3], bgcolor=p04[3])
table.cell(table_id = tabel, row = 1, column = 24, text = m04[2], bgcolor=p04[2])
table.cell(table_id = tabel, row = 1, column = 25, text = m04[1], bgcolor=p04[1])
table.cell(table_id = tabel, row = 1, column = 26, text = m04[0], bgcolor=p04[0])
table.cell(table_id = tabel, row = 2, column = 0, text = q05[7], bgcolor=r05[7])
table.cell(table_id = tabel, row = 2, column = 1, text = q05[6], bgcolor=r05[6])
table.cell(table_id = tabel, row = 2, column = 2, text = q05[5], bgcolor=r05[5])
table.cell(table_id = tabel, row = 2, column = 3, text = q05[4], bgcolor=r05[4])
table.cell(table_id = tabel, row = 2, column = 4, text = q05[3], bgcolor=r05[3])
table.cell(table_id = tabel, row = 2, column = 5, text = q05[2], bgcolor=r05[2])
table.cell(table_id = tabel, row = 2, column = 6, text = q05[1], bgcolor=r05[1])
table.cell(table_id = tabel, row = 2, column = 7, text = q05[0], bgcolor=r05[0])
table.cell(table_id = tabel, row = 2, column = 8, text = t05, bgcolor=c05)
table.cell(table_id = tabel, row = 2, column = 9, text = m05[3], bgcolor=p05[3])
table.cell(table_id = tabel, row = 2, column = 10, text = m05[2], bgcolor=p05[2])
table.cell(table_id = tabel, row = 2, column = 11, text = m05[1], bgcolor=p05[1])
table.cell(table_id = tabel, row = 2, column = 12, text = m05[0], bgcolor=p05[0])
table.cell(table_id = tabel, row = 2, column = 13, text = " ")
table.cell(table_id = tabel, row = 2, column = 14, text = q06[7], bgcolor=r06[7])
table.cell(table_id = tabel, row = 2, column = 15, text = q06[6], bgcolor=r06[6])
table.cell(table_id = tabel, row = 2, column = 16, text = q06[5], bgcolor=r06[5])
table.cell(table_id = tabel, row = 2, column = 17, text = q06[4], bgcolor=r06[4])
table.cell(table_id = tabel, row = 2, column = 18, text = q06[3], bgcolor=r06[3])
table.cell(table_id = tabel, row = 2, column = 19, text = q06[2], bgcolor=r06[2])
table.cell(table_id = tabel, row = 2, column = 20, text = q06[1], bgcolor=r06[1])
table.cell(table_id = tabel, row = 2, column = 21, text = q06[0], bgcolor=r06[0])
table.cell(table_id = tabel, row = 2, column = 22, text = t06, bgcolor=c06)
table.cell(table_id = tabel, row = 2, column = 23, text = m06[3], bgcolor=p06[3])
table.cell(table_id = tabel, row = 2, column = 24, text = m06[2], bgcolor=p06[2])
table.cell(table_id = tabel, row = 2, column = 25, text = m06[1], bgcolor=p06[1])
table.cell(table_id = tabel, row = 2, column = 26, text = m06[0], bgcolor=p06[0])
table.cell(table_id = tabel, row = 3, column = 0, text = q07[7], bgcolor=r07[7])
table.cell(table_id = tabel, row = 3, column = 1, text = q07[6], bgcolor=r07[6])
table.cell(table_id = tabel, row = 3, column = 2, text = q07[5], bgcolor=r07[5])
table.cell(table_id = tabel, row = 3, column = 3, text = q07[4], bgcolor=r07[4])
table.cell(table_id = tabel, row = 3, column = 4, text = q07[3], bgcolor=r07[3])
table.cell(table_id = tabel, row = 3, column = 5, text = q07[2], bgcolor=r07[2])
table.cell(table_id = tabel, row = 3, column = 6, text = q07[1], bgcolor=r07[1])
table.cell(table_id = tabel, row = 3, column = 7, text = q07[0], bgcolor=r07[0])
table.cell(table_id = tabel, row = 3, column = 8, text = t07, bgcolor=c07)
table.cell(table_id = tabel, row = 3, column = 9, text = m07[3], bgcolor=p07[3])
table.cell(table_id = tabel, row = 3, column = 10, text = m07[2], bgcolor=p07[2])
table.cell(table_id = tabel, row = 3, column = 11, text = m07[1], bgcolor=p07[1])
table.cell(table_id = tabel, row = 3, column = 12, text = m07[0], bgcolor=p07[0])
table.cell(table_id = tabel, row = 3, column = 13, text = " ")
table.cell(table_id = tabel, row = 3, column = 14, text = q08[7], bgcolor=r08[7])
table.cell(table_id = tabel, row = 3, column = 15, text = q08[6], bgcolor=r08[6])
table.cell(table_id = tabel, row = 3, column = 16, text = q08[5], bgcolor=r08[5])
table.cell(table_id = tabel, row = 3, column = 17, text = q08[4], bgcolor=r08[4])
table.cell(table_id = tabel, row = 3, column = 18, text = q08[3], bgcolor=r08[3])
table.cell(table_id = tabel, row = 3, column = 19, text = q08[2], bgcolor=r08[2])
table.cell(table_id = tabel, row = 3, column = 20, text = q08[1], bgcolor=r08[1])
table.cell(table_id = tabel, row = 3, column = 21, text = q08[0], bgcolor=r08[0])
table.cell(table_id = tabel, row = 3, column = 22, text = t08, bgcolor=c08)
table.cell(table_id = tabel, row = 3, column = 23, text = m08[3], bgcolor=p08[3])
table.cell(table_id = tabel, row = 3, column = 24, text = m08[2], bgcolor=p08[2])
table.cell(table_id = tabel, row = 3, column = 25, text = m08[1], bgcolor=p08[1])
table.cell(table_id = tabel, row = 3, column = 26, text = m08[0], bgcolor=p08[0])
table.cell(table_id = tabel, row = 4, column = 0, text = q09[7], bgcolor=r09[7])
table.cell(table_id = tabel, row = 4, column = 1, text = q09[6], bgcolor=r09[6])
table.cell(table_id = tabel, row = 4, column = 2, text = q09[5], bgcolor=r09[5])
table.cell(table_id = tabel, row = 4, column = 3, text = q09[4], bgcolor=r09[4])
table.cell(table_id = tabel, row = 4, column = 4, text = q09[3], bgcolor=r09[3])
table.cell(table_id = tabel, row = 4, column = 5, text = q09[2], bgcolor=r09[2])
table.cell(table_id = tabel, row = 4, column = 6, text = q09[1], bgcolor=r09[1])
table.cell(table_id = tabel, row = 4, column = 7, text = q09[0], bgcolor=r09[0])
table.cell(table_id = tabel, row = 4, column = 8, text = t09, bgcolor=c09)
table.cell(table_id = tabel, row = 4, column = 9, text = m09[3], bgcolor=p09[3])
table.cell(table_id = tabel, row = 4, column = 10, text = m09[2], bgcolor=p09[2])
table.cell(table_id = tabel, row = 4, column = 11, text = m09[1], bgcolor=p09[1])
table.cell(table_id = tabel, row = 4, column = 12, text = m09[0], bgcolor=p09[0])
table.cell(table_id = tabel, row = 4, column = 13, text = " ")
table.cell(table_id = tabel, row = 4, column = 14, text = q10[7], bgcolor=r10[7])
table.cell(table_id = tabel, row = 4, column = 15, text = q10[6], bgcolor=r10[6])
table.cell(table_id = tabel, row = 4, column = 16, text = q10[5], bgcolor=r10[5])
table.cell(table_id = tabel, row = 4, column = 17, text = q10[4], bgcolor=r10[4])
table.cell(table_id = tabel, row = 4, column = 18, text = q10[3], bgcolor=r10[3])
table.cell(table_id = tabel, row = 4, column = 19, text = q10[2], bgcolor=r10[2])
table.cell(table_id = tabel, row = 4, column = 20, text = q10[1], bgcolor=r10[1])
table.cell(table_id = tabel, row = 4, column = 21, text = q10[0], bgcolor=r10[0])
table.cell(table_id = tabel, row = 4, column = 22, text = t10, bgcolor=c10)
table.cell(table_id = tabel, row = 4, column = 23, text = m10[3], bgcolor=p10[3])
table.cell(table_id = tabel, row = 4, column = 24, text = m10[2], bgcolor=p10[2])
table.cell(table_id = tabel, row = 4, column = 25, text = m10[1], bgcolor=p10[1])
table.cell(table_id = tabel, row = 4, column = 26, text = m10[0], bgcolor=p10[0])
table.cell(table_id = tabel, row = 5, column = 0, text = q11[7], bgcolor=r11[7])
table.cell(table_id = tabel, row = 5, column = 1, text = q11[6], bgcolor=r11[6])
table.cell(table_id = tabel, row = 5, column = 2, text = q11[5], bgcolor=r11[5])
table.cell(table_id = tabel, row = 5, column = 3, text = q11[4], bgcolor=r11[4])
table.cell(table_id = tabel, row = 5, column = 4, text = q11[3], bgcolor=r11[3])
table.cell(table_id = tabel, row = 5, column = 5, text = q11[2], bgcolor=r11[2])
table.cell(table_id = tabel, row = 5, column = 6, text = q11[1], bgcolor=r11[1])
table.cell(table_id = tabel, row = 5, column = 7, text = q11[0], bgcolor=r11[0])
table.cell(table_id = tabel, row = 5, column = 8, text = t11, bgcolor=c11)
table.cell(table_id = tabel, row = 5, column = 9, text = m11[3], bgcolor=p11[3])
table.cell(table_id = tabel, row = 5, column = 10, text = m11[2], bgcolor=p11[2])
table.cell(table_id = tabel, row = 5, column = 11, text = m11[1], bgcolor=p11[1])
table.cell(table_id = tabel, row = 5, column = 12, text = m11[0], bgcolor=p11[0])
table.cell(table_id = tabel, row = 5, column = 13, text = " ")
table.cell(table_id = tabel, row = 5, column = 14, text = q12[7], bgcolor=r12[7])
table.cell(table_id = tabel, row = 5, column = 15, text = q12[6], bgcolor=r12[6])
table.cell(table_id = tabel, row = 5, column = 16, text = q12[5], bgcolor=r12[5])
table.cell(table_id = tabel, row = 5, column = 17, text = q12[4], bgcolor=r12[4])
table.cell(table_id = tabel, row = 5, column = 18, text = q12[3], bgcolor=r12[3])
table.cell(table_id = tabel, row = 5, column = 19, text = q12[2], bgcolor=r12[2])
table.cell(table_id = tabel, row = 5, column = 20, text = q12[1], bgcolor=r12[1])
table.cell(table_id = tabel, row = 5, column = 21, text = q12[0], bgcolor=r12[0])
table.cell(table_id = tabel, row = 5, column = 22, text = t12, bgcolor=c12)
table.cell(table_id = tabel, row = 5, column = 23, text = m12[3], bgcolor=p12[3])
table.cell(table_id = tabel, row = 5, column = 24, text = m12[2], bgcolor=p12[2])
table.cell(table_id = tabel, row = 5, column = 25, text = m12[1], bgcolor=p12[1])
table.cell(table_id = tabel, row = 5, column = 26, text = m12[0], bgcolor=p12[0])
table.cell(table_id = tabel, row = 6, column = 0, text = q13[7], bgcolor=r13[7])
table.cell(table_id = tabel, row = 6, column = 1, text = q13[6], bgcolor=r13[6])
table.cell(table_id = tabel, row = 6, column = 2, text = q13[5], bgcolor=r13[5])
table.cell(table_id = tabel, row = 6, column = 3, text = q13[4], bgcolor=r13[4])
table.cell(table_id = tabel, row = 6, column = 4, text = q13[3], bgcolor=r13[3])
table.cell(table_id = tabel, row = 6, column = 5, text = q13[2], bgcolor=r13[2])
table.cell(table_id = tabel, row = 6, column = 6, text = q13[1], bgcolor=r13[1])
table.cell(table_id = tabel, row = 6, column = 7, text = q13[0], bgcolor=r13[0])
table.cell(table_id = tabel, row = 6, column = 8, text = t13, bgcolor=c13)
table.cell(table_id = tabel, row = 6, column = 9, text = m13[3], bgcolor=p13[3])
table.cell(table_id = tabel, row = 6, column = 10, text = m13[2], bgcolor=p13[2])
table.cell(table_id = tabel, row = 6, column = 11, text = m13[1], bgcolor=p13[1])
table.cell(table_id = tabel, row = 6, column = 12, text = m13[0], bgcolor=p13[0])
table.cell(table_id = tabel, row = 6, column = 13, text = " ")
table.cell(table_id = tabel, row = 6, column = 14, text = q14[7], bgcolor=r14[7])
table.cell(table_id = tabel, row = 6, column = 15, text = q14[6], bgcolor=r14[6])
table.cell(table_id = tabel, row = 6, column = 16, text = q14[5], bgcolor=r14[5])
table.cell(table_id = tabel, row = 6, column = 17, text = q14[4], bgcolor=r14[4])
table.cell(table_id = tabel, row = 6, column = 18, text = q14[3], bgcolor=r14[3])
table.cell(table_id = tabel, row = 6, column = 19, text = q14[2], bgcolor=r14[2])
table.cell(table_id = tabel, row = 6, column = 20, text = q14[1], bgcolor=r14[1])
table.cell(table_id = tabel, row = 6, column = 21, text = q14[0], bgcolor=r14[0])
table.cell(table_id = tabel, row = 6, column = 22, text = t14, bgcolor=c14)
table.cell(table_id = tabel, row = 6, column = 23, text = m14[3], bgcolor=p14[3])
table.cell(table_id = tabel, row = 6, column = 24, text = m14[2], bgcolor=p14[2])
table.cell(table_id = tabel, row = 6, column = 25, text = m14[1], bgcolor=p14[1])
table.cell(table_id = tabel, row = 6, column = 26, text = m14[0], bgcolor=p14[0])
table.cell(table_id = tabel, row = 7, column = 0, text = q15[7], bgcolor=r15[7])
table.cell(table_id = tabel, row = 7, column = 1, text = q15[6], bgcolor=r15[6])
table.cell(table_id = tabel, row = 7, column = 2, text = q15[5], bgcolor=r15[5])
table.cell(table_id = tabel, row = 7, column = 3, text = q15[4], bgcolor=r15[4])
table.cell(table_id = tabel, row = 7, column = 4, text = q15[3], bgcolor=r15[3])
table.cell(table_id = tabel, row = 7, column = 5, text = q15[2], bgcolor=r15[2])
table.cell(table_id = tabel, row = 7, column = 6, text = q15[1], bgcolor=r15[1])
table.cell(table_id = tabel, row = 7, column = 7, text = q15[0], bgcolor=r15[0])
table.cell(table_id = tabel, row = 7, column = 8, text = t15, bgcolor=c15)
table.cell(table_id = tabel, row = 7, column = 9, text = m15[3], bgcolor=p15[3])
table.cell(table_id = tabel, row = 7, column = 10, text = m15[2], bgcolor=p15[2])
table.cell(table_id = tabel, row = 7, column = 11, text = m15[1], bgcolor=p15[1])
table.cell(table_id = tabel, row = 7, column = 12, text = m15[0], bgcolor=p15[0])
table.cell(table_id = tabel, row = 7, column = 13, text = " ")
table.cell(table_id = tabel, row = 7, column = 14, text = q16[7], bgcolor=r16[7])
table.cell(table_id = tabel, row = 7, column = 15, text = q16[6], bgcolor=r16[6])
table.cell(table_id = tabel, row = 7, column = 16, text = q16[5], bgcolor=r16[5])
table.cell(table_id = tabel, row = 7, column = 17, text = q16[4], bgcolor=r16[4])
table.cell(table_id = tabel, row = 7, column = 18, text = q16[3], bgcolor=r16[3])
table.cell(table_id = tabel, row = 7, column = 19, text = q16[2], bgcolor=r16[2])
table.cell(table_id = tabel, row = 7, column = 20, text = q16[1], bgcolor=r16[1])
table.cell(table_id = tabel, row = 7, column = 21, text = q16[0], bgcolor=r16[0])
table.cell(table_id = tabel, row = 7, column = 22, text = t16, bgcolor=c16)
table.cell(table_id = tabel, row = 7, column = 23, text = m16[3], bgcolor=p16[3])
table.cell(table_id = tabel, row = 7, column = 24, text = m16[2], bgcolor=p16[2])
table.cell(table_id = tabel, row = 7, column = 25, text = m16[1], bgcolor=p16[1])
table.cell(table_id = tabel, row = 7, column = 26, text = m16[0], bgcolor=p16[0])
table.cell(table_id = tabel, row = 8, column = 0, text = q17[7], bgcolor=r17[7])
table.cell(table_id = tabel, row = 8, column = 1, text = q17[6], bgcolor=r17[6])
table.cell(table_id = tabel, row = 8, column = 2, text = q17[5], bgcolor=r17[5])
table.cell(table_id = tabel, row = 8, column = 3, text = q17[4], bgcolor=r17[4])
table.cell(table_id = tabel, row = 8, column = 4, text = q17[3], bgcolor=r17[3])
table.cell(table_id = tabel, row = 8, column = 5, text = q17[2], bgcolor=r17[2])
table.cell(table_id = tabel, row = 8, column = 6, text = q17[1], bgcolor=r17[1])
table.cell(table_id = tabel, row = 8, column = 7, text = q17[0], bgcolor=r17[0])
table.cell(table_id = tabel, row = 8, column = 8, text = t17, bgcolor=c17)
table.cell(table_id = tabel, row = 8, column = 9, text = m17[3], bgcolor=p17[3])
table.cell(table_id = tabel, row = 8, column = 10, text = m17[2], bgcolor=p17[2])
table.cell(table_id = tabel, row = 8, column = 11, text = m17[1], bgcolor=p17[1])
table.cell(table_id = tabel, row = 8, column = 12, text = m17[0], bgcolor=p17[0])
table.cell(table_id = tabel, row = 8, column = 13, text = " ")
table.cell(table_id = tabel, row = 8, column = 14, text = q18[7], bgcolor=r18[7])
table.cell(table_id = tabel, row = 8, column = 15, text = q18[6], bgcolor=r18[6])
table.cell(table_id = tabel, row = 8, column = 16, text = q18[5], bgcolor=r18[5])
table.cell(table_id = tabel, row = 8, column = 17, text = q18[4], bgcolor=r18[4])
table.cell(table_id = tabel, row = 8, column = 18, text = q18[3], bgcolor=r18[3])
table.cell(table_id = tabel, row = 8, column = 19, text = q18[2], bgcolor=r18[2])
table.cell(table_id = tabel, row = 8, column = 20, text = q18[1], bgcolor=r18[1])
table.cell(table_id = tabel, row = 8, column = 21, text = q18[0], bgcolor=r18[0])
table.cell(table_id = tabel, row = 8, column = 22, text = t18, bgcolor=c18)
table.cell(table_id = tabel, row = 8, column = 23, text = m18[3], bgcolor=p18[3])
table.cell(table_id = tabel, row = 8, column = 24, text = m18[2], bgcolor=p18[2])
table.cell(table_id = tabel, row = 8, column = 25, text = m18[1], bgcolor=p18[1])
table.cell(table_id = tabel, row = 8, column = 26, text = m18[0], bgcolor=p18[0])
table.cell(table_id = tabel, row = 9, column = 0, text = q19[7], bgcolor=r19[7])
table.cell(table_id = tabel, row = 9, column = 1, text = q19[6], bgcolor=r19[6])
table.cell(table_id = tabel, row = 9, column = 2, text = q19[5], bgcolor=r19[5])
table.cell(table_id = tabel, row = 9, column = 3, text = q19[4], bgcolor=r19[4])
table.cell(table_id = tabel, row = 9, column = 4, text = q19[3], bgcolor=r19[3])
table.cell(table_id = tabel, row = 9, column = 5, text = q19[2], bgcolor=r19[2])
table.cell(table_id = tabel, row = 9, column = 6, text = q19[1], bgcolor=r19[1])
table.cell(table_id = tabel, row = 9, column = 7, text = q19[0], bgcolor=r19[0])
table.cell(table_id = tabel, row = 9, column = 8, text = t19, bgcolor=c19)
table.cell(table_id = tabel, row = 9, column = 9, text = m19[3], bgcolor=p19[3])
table.cell(table_id = tabel, row = 9, column = 10, text = m19[2], bgcolor=p19[2])
table.cell(table_id = tabel, row = 9, column = 11, text = m19[1], bgcolor=p19[1])
table.cell(table_id = tabel, row = 9, column = 12, text = m19[0], bgcolor=p19[0])
table.cell(table_id = tabel, row = 9, column = 13, text = " ")
table.cell(table_id = tabel, row = 9, column = 14, text = q20[7], bgcolor=r20[7])
table.cell(table_id = tabel, row = 9, column = 15, text = q20[6], bgcolor=r20[6])
table.cell(table_id = tabel, row = 9, column = 16, text = q20[5], bgcolor=r20[5])
table.cell(table_id = tabel, row = 9, column = 17, text = q20[4], bgcolor=r20[4])
table.cell(table_id = tabel, row = 9, column = 18, text = q20[3], bgcolor=r20[3])
table.cell(table_id = tabel, row = 9, column = 19, text = q20[2], bgcolor=r20[2])
table.cell(table_id = tabel, row = 9, column = 20, text = q20[1], bgcolor=r20[1])
table.cell(table_id = tabel, row = 9, column = 21, text = q20[0], bgcolor=r20[0])
table.cell(table_id = tabel, row = 9, column = 22, text = t20, bgcolor=c20)
table.cell(table_id = tabel, row = 9, column = 23, text = m20[3], bgcolor=p20[3])
table.cell(table_id = tabel, row = 9, column = 24, text = m20[2], bgcolor=p20[2])
table.cell(table_id = tabel, row = 9, column = 25, text = m20[1], bgcolor=p20[1])
table.cell(table_id = tabel, row = 9, column = 26, text = m20[0], bgcolor=p20[0]) |
SRT Indicator script based on Knowledge sharing by NK | https://www.tradingview.com/script/1yFXj9ko-SRT-Indicator-script-based-on-Knowledge-sharing-by-NK/ | rvc8280 | https://www.tradingview.com/u/rvc8280/ | 83 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rvc8280
//@version=5
indicator("SRT_NK",shorttitle = "SRT")
// 1. In a year, there are 248/ 252 trading days .
// 2. Half of this is 124. Even 125/ 126 can be taken.
sma_period = 124
srt_sma = ta.sma(close, sma_period)
SRT_124 = close / srt_sma
plot( SRT_124, color=color.blue)
Lev_70 = plot(0.7, title='L_70', color=color.new(color.gray, 0))
Lev_80 = plot(0.8, title='L_80', color=color.new(color.gray, 0))
lev_90 = plot(.9, title='L_90', color=color.new(color.gray, 0)) |
Adaptive ATR Keltner Channels [Loxx] | https://www.tradingview.com/script/2Jm61kad-Adaptive-ATR-Keltner-Channels-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 195 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Adaptive ATR Keltner Channels [Loxx]", shorttitle = "AATRKC [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
src = input.source(close, "Source", group = "Basic Settings")
len = input.int(20, "Length", group = "Basic Settings")
minMult = input.int(1, "Min Multiplier", group = "Basic Settings")
midMult = input.int(2, "Mid Multiplier", group = "Basic Settings")
maxMult = input.int(3, "Max Multiplier", group = "Basic Settings")
showmin = input.bool(true, "Show min channels?", group = "UI Options")
showmid = input.bool(true, "Show mid channels?", group = "UI Options")
showmax = input.bool(true, "Show max channels?", group = "UI Options")
fillcolor = input.bool(true, "Show fill color?", group = "UI Options")
mlen = (len > 1) ? len : 1
fast = math.max(mlen / 2.0, 1)
slow = mlen * 5
signal = 0., noise = 0., atr = 0., val = 0.
diff = src - nz(src[1])
diff := diff < 0 ? diff * -1.0 : diff
if (bar_index > mlen)
signal := src - nz(src[1])
signal := signal < 0 ? signal * -1.0 : signal
noise := nz(noise[1]) + diff - nz(diff[mlen])
else
noise := diff
for k = 1 to mlen
noise += nz(diff[k])
efratio = noise != 0 ? signal/noise : 1
avgper = noise != 0 ? ((signal/noise) * (slow - fast)) + fast : mlen
atr := nz(atr[1]) + (2.0 / (1.0 + avgper)) * ((high - low) - nz(atr[1]))
val := nz(val[1]) + (2.0 / (1.0 + avgper)) * (src - nz(val[1]))
minUp = val + minMult * atr
minDn = val - minMult * atr
midUp = val + midMult * atr
midDn = val - midMult * atr
maxUp = val + maxMult * atr
maxDn = val - maxMult * atr
midplot = plot(val, "mid", color = close >= val ? greencolor : redcolor, linewidth = 3)
plot(showmin ? minUp : na, "minUp", color = color.new(greencolor, 50))
plot(showmin ? minDn : na, "minDn", color = color.new(redcolor, 50))
plot(showmid ? midUp : na, "midUp", color = color.new(greencolor, 50))
plot(showmid ? midDn : na, "midDn", color = color.new(redcolor, 50))
mupplot = plot(showmax ? maxUp : na, "maxUp", color = color.new(greencolor, 50))
mdnplot = plot(showmax ? maxDn : na, "maxDn", color = color.new(redcolor, 50))
fill(mupplot, midplot, fillcolor ? color.new(greencolor, 95) : na)
fill(mdnplot, midplot, fillcolor ? color.new(redcolor, 95) : na)
|
STD Aadaptive, floating RSX Dynamic Momentum Index [Loxx] | https://www.tradingview.com/script/op8EVyOq-STD-Aadaptive-floating-RSX-Dynamic-Momentum-Index-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 134 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("STD Aadaptive, floating RSX Dynamic Momentum Index [Loxx]", shorttitle = "SADMIFL [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
_rsx_rsi(src, len)=>
src_out = 100 * src
mom0 = ta.change(src_out)
moa0 = math.abs(mom0)
Kg = 3 / (len + 2.0)
Hg = 1 - Kg
//mom
f28 = 0.0, f30 = 0.0
f28 := Kg * mom0 + Hg * nz(f28[1])
f30 := Hg * nz(f30[1]) + Kg * f28
mom1 = f28 * 1.5 - f30 * 0.5
f38 = 0.0, f40 = 0.0
f38 := Hg * nz(f38[1]) + Kg * mom1
f40 := Kg * f38 + Hg * nz(f40[1])
mom2 = f38 * 1.5 - f40 * 0.5
f48 = 0.0, f50 = 0.0
f48 := Hg * nz(f48[1]) + Kg * mom2
f50 := Kg * f48 + Hg * nz(f50[1])
mom_out = f48 * 1.5 - f50 * 0.5
//moa
f58 = 0.0, f60 = 0.0
f58 := Hg * nz(f58[1]) + Kg * moa0
f60 := Kg * f58 + Hg * nz(f60[1])
moa1 = f58 * 1.5 - f60 * 0.5
f68 = 0.0, f70 = 0.0
f68 := Hg * nz(f68[1]) + Kg * moa1
f70 := Kg * f68 + Hg * nz(f70[1])
moa2 = f68 * 1.5 - f70 * 0.5
f78 = 0.0, f80 = 0.0
f78 := Hg * nz(f78[1]) + Kg * moa2
f80 := Kg * f78 + Hg * nz(f80[1])
moa_out = f78 * 1.5 - f80 * 0.5
rsiout = math.max(math.min((mom_out / moa_out + 1.0) * 50.0, 100.00), 0.00)
rsiout
_volatilityRatio(src, per) =>
sumd = 0.
deviation = ta.stdev(src, per)
sumd1 = math.sum(deviation, per)
if (bar_index > per)
sumd := nz(sumd[1]) + deviation - nz(deviation[per])
else
sumd := deviation
sumd := sumd1
out = (sumd > 0 ? per * deviation / sumd : 1)
out
src = input.source(close, "Source", group = "Basic Settings")
dmiper = input.int(15, "DMI Period", group = "Basic Settings")
dmilow = input.int(10, "DMI Lower Limit", group = "Basic Settings")
dmihigh = input.int(50, "DMI Upper Limit", group = "Basic Settings")
devper = input.int(10, "Standard Deviation Period", group = "Basic Settings")
dslper = input.int(10, "Discontinued Signal Lines (DSL) Period", group = "Basic Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
levu = 0., levd = 0., levm = 0.
_dslPeriod = (dslper > 1 ? dslper : 1)
vr = _volatilityRatio(src, devper)
td = (dmiper / vr)
if (td > dmihigh)
td := dmihigh
if (td < dmilow)
td := dmilow
val = _rsx_rsi(src, td)
_alpha = 2.0 / (1.0 + _dslPeriod / vr)
levu := (val >= 50) ? nz(levu[1]) + _alpha * (val - nz(levu[1])) : nz(levu[1])
levd := (val < 50) ? nz(levd[1]) + _alpha * (val - nz(levd[1])) : nz(levd[1])
levm := (levu + levd) / 2.0
colorout = val > levu ? greencolor : val < levd ? redcolor : color.gray
plot(val, color = colorout, linewidth = 3)
plot(levu, color = bar_index % 2 ? color.gray : na)
plot(levm, color = bar_index % 2 ? color.gray : na)
plot(levd, color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout : na)
|
Multi EMA with labels (Any timeframe) | https://www.tradingview.com/script/yUpFoOS7-Multi-EMA-with-labels-Any-timeframe/ | chipmonk | https://www.tradingview.com/u/chipmonk/ | 273 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chipmonk
//@version=5
indicator(title="Multi EMA with labels (Any timeframe)", shorttitle="Multi EMA", overlay=true)
get_timeframe_title(simple string tf = "") =>
chartTf = timeframe.isminutes == true and timeframe.multiplier > 59 ? (timeframe.multiplier/60 % 2 == 0 ? str.tostring(timeframe.multiplier/60)+"h" : str.tostring(timeframe.multiplier)+"m") : timeframe.isminutes == true ? str.tostring(timeframe.multiplier)+"m" : timeframe.period
result = tf == "" ? "" : request.security(syminfo.tickerid, tf, chartTf)
distance = input(2, "Label Distance")
show_prices = input.bool(true, "Show price labels")
ema1_enable = input.bool(true, "Enable EMA 1", group = "EMA Options")
ema1_timeframe = input.timeframe("", "EMA 1 Timeframe", group = "EMA Options")
ema1_len = input.int(20, minval=1, title="EMA 1 Length", group = "EMA Options")
ema1_out = ta.ema(close, ema1_len)
ema1_color_input = input(color.new(#A5D6A7, 20), title="EMA 1 Color", group = "EMA Options")
ema1_color = ema1_enable ? ema1_color_input : na
ema2_enable = input.bool(true, "Enable EMA 2", group = "EMA Options")
ema2_timeframe = input.timeframe("", "EMA 2 Timeframe", group = "EMA Options")
ema2_len = input.int(50, minval=1, title="EMA 2 Length", group = "EMA Options")
ema2_out = ta.ema(close, ema2_len)
ema2_color_input = input(color.new(#F2AF29, 20), title="EMA 2 Color", group = "EMA Options")
ema2_color = ema2_enable ? ema2_color_input : na
ema3_enable = input.bool(true, "Enable EMA 3", group = "EMA Options")
ema3_timeframe = input.timeframe("", "EMA 3 Timeframe", group = "EMA Options")
ema3_len = input.int(200, minval=1, title="EMA 3 Length", group = "EMA Options")
ema3_out = ta.ema(close, ema3_len)
ema3_color_input = input(color.new(#725AC1, 20), title="EMA 3 Color", group = "EMA Options")
ema3_color = ema3_enable ? ema3_color_input : na
ema4_enable = input.bool(false, "Enable EMA 4", group = "EMA Options")
ema4_timeframe = input.timeframe("", "EMA 4 Timeframe", group = "EMA Options")
ema4_len = input.int(100, minval=1, title="EMA 4 Length", group = "EMA Options")
ema4_out = ta.ema(close, ema4_len)
ema4_color_input = input(color.new(#FE5E41, 20), title="EMA 4 Color", group = "EMA Options")
ema4_color = ema4_enable ? ema4_color_input : na
ema5_enable = input.bool(false, "Enable EMA 5", group = "EMA Options")
ema5_timeframe = input.timeframe("", "EMA 5 Timeframe", group = "EMA Options")
ema5_len = input.int(400, minval=1, title="EMA 5 Length", group = "EMA Options")
ema5_out = ta.ema(close, ema5_len)
ema5_color_input = input(color.new(#243E36, 20), title="EMA 5 Color", group = "EMA Options")
ema5_color = ema5_enable ? ema5_color_input : na
ema6_enable = input.bool(false, "Enable EMA 6", group = "EMA Options")
ema6_timeframe = input.timeframe("", "EMA 6 Timeframe", group = "EMA Options")
ema6_len = input.int(9, minval=1, title="EMA 6 Length", group = "EMA Options")
ema6_out = ta.ema(close, ema6_len)
ema6_color_input = input(color.new(#3B3923, 20), title="EMA 6 Color", group = "EMA Options")
ema6_color = ema6_enable ? ema6_color_input : na
ema7_enable = input.bool(false, "Enable EMA 7", group = "EMA Options")
ema7_timeframe = input.timeframe("", "EMA 7 Timeframe", group = "EMA Options")
ema7_len = input.int(26, minval=1, title="EMA 7 Length", group = "EMA Options")
ema7_out = ta.ema(close, ema7_len)
ema7_color_input = input(color.new(#3A7CA5, 20), title="EMA 7 Color", group = "EMA Options")
ema7_color = ema7_enable ? ema7_color_input : na
ema8_enable = input.bool(false, "Enable EMA 8", group = "EMA Options")
ema8_timeframe = input.timeframe("", "EMA 8 Timeframe", group = "EMA Options")
ema8_len = input.int(12, minval=1, title="EMA 8 Length", group = "EMA Options")
ema8_out = ta.ema(close, ema8_len)
ema8_color_input = input(color.new(#795663, 20), title="EMA 8 Color", group = "EMA Options")
ema8_color = ema8_enable ? ema8_color_input : na
securityNoRepaint(sym, tf, src) => request.security(sym, tf, src[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
ema1_tf = securityNoRepaint(syminfo.tickerid, ema1_timeframe, ema1_out)
ema2_tf = securityNoRepaint(syminfo.tickerid, ema2_timeframe, ema2_out)
ema3_tf = securityNoRepaint(syminfo.tickerid, ema3_timeframe, ema3_out)
ema4_tf = securityNoRepaint(syminfo.tickerid, ema4_timeframe, ema4_out)
ema5_tf = securityNoRepaint(syminfo.tickerid, ema5_timeframe, ema5_out)
ema6_tf = securityNoRepaint(syminfo.tickerid, ema6_timeframe, ema6_out)
ema7_tf = securityNoRepaint(syminfo.tickerid, ema7_timeframe, ema7_out)
ema8_tf = securityNoRepaint(syminfo.tickerid, ema8_timeframe, ema8_out)
plot(ema1_tf, title="EMA", color=ema1_color, linewidth=2, style=plot.style_line)
plot(ema2_tf, title="EMA", color=ema2_color, linewidth=2, style=plot.style_line)
plot(ema3_tf, title="EMA", color=ema3_color, linewidth=2, style=plot.style_line)
plot(ema4_tf, title="EMA", color=ema4_color, linewidth=2, style=plot.style_line)
plot(ema5_tf, title="EMA", color=ema5_color, linewidth=2, style=plot.style_line)
plot(ema6_tf, title="EMA", color=ema6_color, linewidth=2, style=plot.style_line)
plot(ema7_tf, title="EMA", color=ema7_color, linewidth=2, style=plot.style_line)
plot(ema8_tf, title="EMA", color=ema8_color, linewidth=2, style=plot.style_line)
var label ema1_label = na
ema1_label_size = size.normal
var label ema2_label = na
ema2_label_size = size.normal
var label ema3_label = na
ema3_label_size = size.normal
var label ema4_label = na
ema4_label_size = size.normal
var label ema5_label = na
ema5_label_size = size.normal
var label ema6_label = na
ema6_label_size = size.normal
var label ema7_label = na
ema7_label_size = size.normal
var label ema8_label = na
ema8_label_size = size.normal
timeframe_text = get_timeframe_title(ema1_timeframe)
timeframe2_text = get_timeframe_title(ema2_timeframe)
timeframe3_text = get_timeframe_title(ema3_timeframe)
timeframe4_text = get_timeframe_title(ema4_timeframe)
timeframe5_text = get_timeframe_title(ema5_timeframe)
timeframe6_text = get_timeframe_title(ema6_timeframe)
timeframe7_text = get_timeframe_title(ema7_timeframe)
timeframe8_text = get_timeframe_title(ema8_timeframe)
label_x = time + math.round(ta.change(time)*distance)
ema1_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema1_tf)) : ""
ema2_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema2_tf)) : ""
ema3_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema3_tf)) : ""
ema4_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema4_tf)) : ""
ema5_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema5_tf)) : ""
ema6_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema6_tf)) : ""
ema7_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema7_tf)) : ""
ema8_p_str = show_prices ? " - "+str.tostring(math.round_to_mintick(ema8_tf)) : ""
labelpadding = " "
ema1_label_txt = timeframe_text == "" ? labelpadding+"EMA "+str.tostring(ema1_len)+ema1_p_str : labelpadding+"EMA "+str.tostring(ema1_len)+" ("+timeframe_text+")"+ema1_p_str
ema1_label := label.new(label_x, ema1_tf, text = ema1_label_txt, xloc=xloc.bar_time, color = ema1_color, textcolor = ema1_color, style = label.style_none, size=size.normal)
label.delete(ema1_label[1])
ema2_label_txt = timeframe2_text == "" ? labelpadding+"EMA "+str.tostring(ema2_len)+ema2_p_str : labelpadding+"EMA "+str.tostring(ema2_len)+" ("+timeframe2_text+")"+ema2_p_str
ema2_label := label.new(label_x, ema2_tf, text = ema2_label_txt, xloc=xloc.bar_time, color = ema2_color, textcolor = ema2_color, style = label.style_none, size=size.normal)
label.delete(ema2_label[1])
ema3_label_txt = timeframe3_text == "" ? labelpadding+"EMA "+str.tostring(ema3_len)+ema3_p_str : labelpadding+"EMA "+str.tostring(ema3_len)+" ("+timeframe3_text+")"+ema3_p_str
ema3_label := label.new(label_x, ema3_tf, text = ema3_label_txt, xloc=xloc.bar_time, color = ema3_color, textcolor = ema3_color, style = label.style_none, size=size.normal)
label.delete(ema3_label[1])
ema4_label_txt = timeframe4_text == "" ? labelpadding+"EMA "+str.tostring(ema4_len)+ema4_p_str : labelpadding+"EMA "+str.tostring(ema4_len)+" ("+timeframe4_text+")"+ema4_p_str
ema4_label := label.new(label_x, ema4_tf, text = ema4_label_txt, xloc=xloc.bar_time, color = ema4_color, textcolor = ema4_color, style = label.style_none, size=size.normal)
label.delete(ema4_label[1])
ema5_label_txt = timeframe5_text == "" ? labelpadding+"EMA "+str.tostring(ema5_len)+ema5_p_str : labelpadding+"EMA "+str.tostring(ema5_len)+" ("+timeframe5_text+")"+ema5_p_str
ema5_label := label.new(label_x, ema5_tf, text = ema5_label_txt, xloc=xloc.bar_time, color = ema5_color, textcolor = ema5_color, style = label.style_none, size=size.normal)
label.delete(ema5_label[1])
ema6_label_txt = timeframe6_text == "" ? labelpadding+"EMA "+str.tostring(ema6_len)+ema6_p_str : labelpadding+"EMA "+str.tostring(ema6_len)+" ("+timeframe6_text+")"+ema6_p_str
ema6_label := label.new(label_x, ema6_tf, text = ema6_label_txt, xloc=xloc.bar_time, color = ema6_color, textcolor = ema6_color, style = label.style_none, size=size.normal)
label.delete(ema6_label[1])
ema7_label_txt = timeframe7_text == "" ? labelpadding+"EMA "+str.tostring(ema7_len)+ema7_p_str : labelpadding+"EMA "+str.tostring(ema7_len)+" ("+timeframe7_text+")"+ema7_p_str
ema7_label := label.new(label_x, ema7_tf, text = ema7_label_txt, xloc=xloc.bar_time, color = ema7_color, textcolor = ema7_color, style = label.style_none, size=size.normal)
label.delete(ema7_label[1])
ema8_label_txt = timeframe8_text == "" ? labelpadding+"EMA "+str.tostring(ema8_len)+ema8_p_str : labelpadding+"EMA "+str.tostring(ema8_len)+" ("+timeframe8_text+")"+ema8_p_str
ema8_label := label.new(label_x, ema8_tf, text = ema8_label_txt, xloc=xloc.bar_time, color = ema8_color, textcolor = ema8_color, style = label.style_none, size=size.normal)
label.delete(ema8_label[1]) |
Bitcoin Golden Pi Cycles | https://www.tradingview.com/script/tDVofaC5-Bitcoin-Golden-Pi-Cycles/ | NgUTech | https://www.tradingview.com/u/NgUTech/ | 811 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NgUTech
//@version=5
indicator("Bitcoin Golden Pi Cycles", overlay=true)
auto = input.bool(true, 'Auto Calculate Fast MA period', tooltip='Fast MA days are calculated to give the best approximatation to π and πϕ (ignores entered number). See indicator description for more information.')
a_days = input.int(111, 'Top Fast MA (Days)', inline='A')
a_mult = input.int(1, 'Multiplier', options=[1, 2, 3, 5, 8, 13, 21, 34], inline='A')
b_days = input.int(350, 'Top Slow MA (Days)', inline='B')
b_mult = input.int(2, 'Multiplier', options=[1, 2, 3, 5, 8, 13, 21, 34], inline='B')
c_days = input.int(138, 'Bottom Fast MA (Days)', inline='C')
c_mult = input.int(1, 'Multiplier', options=[1, 2, 3, 5, 8, 13, 21, 34], inline='C')
d_days = input.int(700, 'Bottom Slow MA (Days)', inline='D')
d_mult = input.int(1, 'Multiplier', options=[1, 2, 3, 5, 8, 13, 21, 34], inline='D')
[a_, b_, c_, d_] = request.security(syminfo.tickerid, 'D', [ta.sma(close, auto ? math.round(b_days/math.pi) : a_days)[barstate.isrealtime ? 1 : 0], ta.sma(close, b_days)[barstate.isrealtime ? 1 : 0], ta.sma(close, auto ? math.round(d_days/math.pi/math.phi) : c_days)[barstate.isrealtime ? 1 : 0], ta.sma(close, d_days)[barstate.isrealtime ? 1 : 0]])
a = a_mult*a_[barstate.isrealtime ? 0 : 1]
b = b_mult*b_[barstate.isrealtime ? 0 : 1]
c = c_mult*c_[barstate.isrealtime ? 0 : 1]
d = d_mult*d_[barstate.isrealtime ? 0 : 1]
plot(a, 'Top Fast MA', color= color.orange)
plot(b, 'Top Slow MA', color= color.red)
plot(c, 'Bottom Fast MA', color= color.teal)
plot(d, 'Bottom Slow MA', color= color.blue)
isTop = ta.crossover(a, b)
isBottom = ta.crossover(d, c)
plotshape(isTop, 'Top Labels', shape.labeldown, location.abovebar, color.green, text='Top', textcolor=color.white, size=size.large)
plotshape(isBottom, 'Bottom Labels', shape.labelup, location.belowbar, color.red, text='Bottom', textcolor=color.white, size=size.large)
alertcondition(isTop, "Cycle Top", message="Pi Cycle Top")
alertcondition(isBottom, 'Cycle Bottom', message="Golden Pi Cycle Bottom") |
Adaptive Parabolic SAR (PSAR) [Loxx] | https://www.tradingview.com/script/6cwVq3p7-Adaptive-Parabolic-SAR-PSAR-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 310 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Adaptive Parabolic SAR (PSAR) [Loxx]",
shorttitle = "APSAR [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
//thanks to @Bjorgum
calcBaseUnit() =>
bool isForexSymbol = syminfo.type == "forex"
bool isYenPair = syminfo.currency == "JPY"
float result = isForexSymbol ? isYenPair ? 0.01 : 0.0001 : syminfo.mintick
greencolor = #2DD204
redcolor = #D2042D
_afact(mode,input, per, smooth) =>
eff = 0., seff = 0.
len = 0, sum = 0., max = 0., min = 1000000000.
len := mode == "Kaufman" ? math.ceil(per) : math.ceil(math.max(20, 5 * per))
for i = 0 to len
if (mode == "Kaufman")
sum += math.abs(input[i] - input[i + 1])
else
max := input[i] > max ? input[i] : max
min := input[i] < min ? input[i] : min
if (mode == "Kaufman" and sum != 0)
eff := math.abs(input - input[len]) / sum
else
if (mode == "Ehlers" and (max - min) > 0)
eff := (input - min) / (max - min)
seff := ta.ema(eff, smooth)
seff
src = input.source(close, "Sourse", group = "Basic Settings")
startAFactor = input.float(0.02, "Starting Acceleration Factor", step = 0.001, group = "Basic Settings")
minStep = input.float(0.0, "Min Step", step = 0.001, group = "Basic Settings")
maxStep = input.float(0.02, "Max Step", step = 0.001, group = "Basic Settings")
maxAFactor = input.float(0.2, "Max Acceleration Factor", step = 0.001, group = "Basic Settings")
hiloMode = input.string("Off", "HiLo Mode", options = ["Off", "On"], group = "Advanced Settings")
adaptMode = input.string("Off", "Adaptive Mode", options = ["Off", "Kaufman", "Ehlers"], group = "Advanced Settings")
adaptSmth = input.int(5, "Adaptive Smoothing Period", minval = 1, group = "Advanced Settings")
filt = input.float(0.0, "Filter in Pips", group = "Advanced Settings", minval = 0)
minChng = input.float(0.0, "Min Change in Pips", group = "Advanced Settings", minval = 0)
SignalMode = input.string("Only Stops", "Signal Mode", options = ["Only Stops", "Signals & Stops"], group = "Advanced Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
hVal2 = nz(high[2]), hVal1 = nz(high[1]), hVal0 = high
lowVal2 = nz(low[2]), lowVal1 = nz(low[1]), lowVal0 = low
hiprice2 = nz(high[2]), hiprice1 = nz(high[1]), hiprice0 = high
loprice2 = nz(low[2]), loprice1 = nz(low[1]), loprice0 = low
upSig = 0., dnSig = 0.
aFactor = 0., step = 0., trend = 0.
upTrndSAR = 0., dnTrndSAR = 0.
length = (2 / maxAFactor - 1)
if (hiloMode == "On")
hiprice0 := high
loprice0 := low
else
hiprice0 := src
loprice0 := hiprice0
if bar_index == 1
trend := 1
hVal1 := hiprice1
hVal0 := math.max(hiprice0, hVal1)
lowVal1 := loprice1
lowVal0 := math.min(loprice0, lowVal1)
aFactor := startAFactor
upTrndSAR := lowVal0
dnTrndSAR := 0.
else
hVal0 := hVal1
lowVal0 := lowVal1
trend := nz(trend[1])
aFactor := nz(aFactor[1])
inputs = 0.
inprice = src
if (adaptMode != "Off")
if (hiloMode == "On")
inprice := src
else
inprice := hiprice0
if (adaptMode == "Kaufman")
inputs := inprice
else
if (adaptMode == "Ehlers")
if (nz(upTrndSAR[1]) != 0.)
inputs := math.abs(inprice - nz(upTrndSAR[1]))
else
if (nz(dnTrndSAR[1]) != 0.)
inputs := math.abs(inprice - nz(dnTrndSAR[1]))
step := minStep + _afact(adaptMode, inputs, length, adaptSmth) * (maxStep - minStep)
else
step := maxStep
upTrndSAR := 0., dnTrndSAR := 0., upSig := 0., dnSig := 0.
if (nz(trend[1]) > 0)
if (nz(trend[1]) == nz(trend[2]))
aFactor := hVal1 > hVal2 ? nz(aFactor[1]) + step : aFactor
aFactor := aFactor > maxAFactor ? maxAFactor : aFactor
aFactor := hVal1 < hVal2 ? startAFactor : aFactor
else
aFactor := nz(aFactor[1])
upTrndSAR := nz(upTrndSAR[1]) + aFactor * (hVal1 - nz(upTrndSAR[1]))
upTrndSAR := upTrndSAR > loprice1 ? loprice1 : upTrndSAR
upTrndSAR := upTrndSAR > loprice2 ? loprice2 : upTrndSAR
else
if (nz(trend[1]) == nz(trend[2]))
aFactor := lowVal1 < lowVal2 ? nz(aFactor[1]) + step : aFactor
aFactor := aFactor > maxAFactor ? maxAFactor : aFactor
aFactor := lowVal1 > lowVal2 ? startAFactor : aFactor
else
aFactor := nz(aFactor[1])
dnTrndSAR := nz(dnTrndSAR[1]) + aFactor * (lowVal1 - nz(dnTrndSAR[1]))
dnTrndSAR := dnTrndSAR < hiprice1 ? hiprice1 : dnTrndSAR
dnTrndSAR := dnTrndSAR < hiprice2 ? hiprice2 : dnTrndSAR
hVal0 := hiprice0 > hVal0 ? hiprice0 : hVal0
lowVal0 := loprice0 < lowVal0 ? loprice0 : lowVal0
if (minChng > 0)
if (upTrndSAR - nz(upTrndSAR[1]) < minChng * calcBaseUnit() and upTrndSAR != 0. and nz(upTrndSAR[1]) != 0.)
upTrndSAR := nz(upTrndSAR[1])
if (nz(dnTrndSAR[1]) - dnTrndSAR < minChng * calcBaseUnit() and dnTrndSAR != 0. and nz(dnTrndSAR[1]) != 0.)
dnTrndSAR := nz(dnTrndSAR[1])
dnTrndSAR := trend < 0 and dnTrndSAR > nz(dnTrndSAR[1]) ? nz(dnTrndSAR[1]) : dnTrndSAR
upTrndSAR := trend > 0 and upTrndSAR < nz(upTrndSAR[1]) ? nz(upTrndSAR[1]) : upTrndSAR
if (trend < 0 and hiprice0 >= dnTrndSAR + filt * calcBaseUnit())
trend := 1
upTrndSAR := lowVal0
upSig := SignalMode == "Signals & Stops" ? lowVal0 : upSig
dnTrndSAR := 0.
aFactor := startAFactor
lowVal0 := loprice0
hVal0 := hiprice0
else if (trend > 0 and loprice0 <= upTrndSAR - filt * calcBaseUnit())
trend := -1
dnTrndSAR := hVal0
dnSig := SignalMode == "Signals & Stops" ? hVal0 : dnSig
upTrndSAR := 0.
aFactor := startAFactor
lowVal0 := loprice0
hVal0 := hiprice0
outer = upTrndSAR > 0 ? upTrndSAR : dnTrndSAR
colorout = outer >= src ? redcolor : greencolor
plot(upTrndSAR > 0 ? upTrndSAR : dnTrndSAR, color = colorout, style = plot.style_cross, linewidth = 2)
barcolor(colorbars ? colorout : na)
plotshape(SignalMode == "Signals & Stops" ? dnSig : na, color = redcolor, textcolor = redcolor, style = shape.triangledown, location = location.abovebar, size = size.small, title='Short', text='S')
plotshape(SignalMode == "Signals & Stops" ? upSig : na, color = greencolor, textcolor = greencolor, style = shape.triangleup, location = location.belowbar, size = size.small, title='Long', text='L')
|
Adaptive Supertrend w/ Floating Levels [Loxx] | https://www.tradingview.com/script/Ph4tuBZW-Adaptive-Supertrend-w-Floating-Levels-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 255 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Adaptive Supertrend w/ Floating Levels [Loxx]", shorttitle = "ASTFL [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
RMA(x, t) =>
EMA1 = x
EMA1 := na(EMA1[1]) ? x : (x - nz(EMA1[1])) * (1/t) + nz(EMA1[1])
EMA1
pine_supertrend(src, factor, atrPeriod) =>
atr = RMA(ta.tr(true), atrPeriod)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
src = input.source(hl2, "Source", group = "Basic Settings")
period = input.int(7, "Period", group = "Basic Settings")
mult = input.float(3.0, "Period", group = "Basic Settings")
adapt = input.bool(true, "Make it adaptive?", group = "Basic Settings")
flLookBack = input.int(25, "Floating Level Lookbacl Period", group = "Advanced Settings")
flLevelUp = input.float(90, "Floating Levels Up Level %", group = "Advanced Settings")
flLevelDown = input.float(25, "Floating Levels Down Level %", group = "Advanced Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
showfloat = input.bool(true, "Show Floating Levels?", group = "UI Options")
showfill = input.bool(true, "Fil Floating Levels?", group = "UI Options")
SumX = 0., SumXX = 0., SumXY = 0., SumYY = 0., SumY = 0.
for k = 0 to period-1 by 1
SumX += SumX+(k+1)
SumXX += SumXX+((k+1)*(k+1))
SumXY += SumXY+((k+1)*src)
SumYY += SumYY+(src*src)
SumY += SumY+src
Q1 = SumXY - SumX*SumY/period
Q2 = SumXX - SumX*SumX/period
Q3 = SumYY - SumY*SumY/period
iRsq= (Q1*Q1)/(Q2*Q3)
[supertrend, direction] = pine_supertrend(src, mult, adapt ? math.ceil(period + period * (iRsq-0.25)) : period)
mini = ta.lowest(supertrend, flLookBack)
maxi = ta.highest(supertrend, flLookBack)
rrange = maxi-mini
flu = mini+flLevelUp*rrange/100.0
fld = mini+flLevelDown*rrange/100.0
flm = mini+0.5*rrange
top = plot(showfloat ? flu : na, "Top float", color = color.new(greencolor, 50), linewidth = 1)
bot = plot(showfloat ? fld : na, "bottom float", color = color.new(redcolor, 50), linewidth = 1)
mid = plot(showfloat ? flm : na, "Mid Float", color = color.new(color.white, 10), linewidth = 1)
fill(top, mid, title = "Top fill color", color = showfill ? color.new(greencolor, 95) : na)
fill(bot, mid,title = "Bottom fill color", color = showfill ? color.new(redcolor, 95) : na)
barcolor(colorbars ? direction == -1 ? greencolor : redcolor : na)
plot(supertrend, "Supertrend", color = direction == -1 ? greencolor : redcolor, linewidth = 3)
|
Trend Ribbon on Heiken Ashi | https://www.tradingview.com/script/2jtdmFdk-Trend-Ribbon-on-Heiken-Ashi/ | yosimadsu | https://www.tradingview.com/u/yosimadsu/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © yosimadsu
//@version=5
indicator(title="Trend Ribbon on Heiken Ashi", shorttitle="Trend Ribbon", overlay=true, timeframe="", timeframe_gaps=false)
lenF = input.int(5, minval=1, title="Fast Length")
lenS = input.int(8, minval=1, title="Slow Length ")
useHA = input.bool(true, "Use Heiken Ashi")
OPEN = open
CLOSE = useHA ? (open + close + high + low) / 4 : close
outf = ta.sma(CLOSE, lenF)
outs = ta.sma(CLOSE, lenS)
a = plot(outf, color=na, title="Fast MA")
b = plot(outs, color=na, title="Slow MA")
col = outf < outs ? color.new(color.red, 70) : color.new(color.green, 70)
fill(a, b, col, "Trend Ribbon")
CLOSE := (open + close + high + low) / 4
OPEN := na(OPEN[1]) ? (OPEN + CLOSE) / 2: (OPEN[1] + CLOSE[1]) / 2
HIGH = math.max(high, math.max(OPEN, CLOSE))
LOW = math.min(low, math.min(OPEN, CLOSE))
c = (OPEN + HIGH + LOW + CLOSE) / 4
o = (OPEN[1] + CLOSE[1]) / 2
h = math.max(HIGH, math.max(o, c))
l = math.min(LOW, math.min(o, c))
plotcandle(o, h, l, c, "Heikin Ashi", color = o < c ? color.new(color.aqua, 60) : color.new(color.fuchsia, 60), bordercolor=na) |
SMC Rules | https://www.tradingview.com/script/ccGecMbw-SMC-Rules/ | Swiss_Traders | https://www.tradingview.com/u/Swiss_Traders/ | 944 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Swiss_Traders
//@version=5
indicator("Flutschi - SMC Rules", overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=1000)
//Visitiblity Section
visibility_group = "Visibility"
inside_bar_show = input.bool(true, "Show Inside Bar", group = visibility_group)
show_imbalance = input.bool(true, "Show Imbalances", group = visibility_group)
show_rules = input.bool(true, "Show Rules", group=visibility_group)
show_session = input.bool(false, "Show Trading Sessions Bars", group=visibility_group)
show_box = input.bool(false, "Show Boxes Sessions", group=visibility_group, inline="boxes")
show_box_history = input.bool(true, "Show Boxes History", group=visibility_group, inline="boxes")
show_lines = input.bool(false, "Show Lines", group=visibility_group)
show_pips = input.bool(false, "Show Pips (beta)", group=visibility_group, tooltip = "Use this on higher timeframe then 5m, somehow it breaks below that..", inline="pips")
show_pips_history = input.bool(true, "Show Pips History", group=visibility_group, inline="pips")
// Start Session
session_group = "Start Session Group"
show_session_color = input.bool(true, "Show Sessions", group = session_group)
show_fr_session_color = input.bool(true, "Frankfurt", group = session_group, inline="sess")
show_ln_session_color = input.bool(true, "London", group = session_group, inline="sess")
show_ny_session_color = input.bool(true, "New York", group = session_group, inline="sess")
show_as_session_color = input.bool(true, "Asia", group = session_group, inline="sess")
fr_session_color = input.color(color.red, "Frankfurt", group = session_group, inline="sess_color")
ln_session_color = input.color(color.red, "London", group = session_group, inline="sess_color")
ny_session_color = input.color(color.red, "New York", group = session_group, inline="sess_color")
as_session_color = input.color(color.red, "Asia", group = session_group, inline="sess_color")
fr_session = false
ln_session = false
ny_session = false
as_session = false
if show_session_color
if show_fr_session_color
fr_session := not na(time(timeframe.period, "0200-0201"))
if show_ln_session_color
ln_session := not na(time(timeframe.period, "0300-0301"))
if show_ny_session_color
ny_session := not na(time(timeframe.period, "0800-0801"))
if show_as_session_color
as_session := not na(time(timeframe.period, "2100-2101"))
barcolor(fr_session ? fr_session_color : na)
barcolor(ln_session ? ln_session_color : na)
barcolor(ny_session ? ny_session_color : na)
barcolor(as_session ? as_session_color : na)
//Rules Section
table_color_groups = "Table Settings"
bg_table_color = input.color(#e0fff5, "Table Color", group = table_color_groups, inline = "02")
bg_border_color = input.color(color.new(color.green, 70), "Table Border", group = table_color_groups, inline = "02")
title_text_color = input.color(color.blue, "Table Title", group = table_color_groups, inline = "02")
farme_color = input.color(color.gray, "Frame Color", group = table_color_groups, inline = "02")
table_width = input.int(3, 'Table Width', minval=1, group=table_color_groups, inline = "03")
frame_width = input.int(3, 'Frame Width', minval=1, group=table_color_groups, inline = "03")
table_text_size = input.string("Large", "Text Size", options = ["Small", "Normal", "Large"], group = "Table Text Size")
h1_size = size.huge //big title
h2_size = size.large //titles
h3_size = size.normal //text
h4_size = size.small //footer
switch table_text_size
"Large" =>
h1_size := size.huge
h2_size := size.large
h3_size := size.normal
h4_size := size.small
"Normal" =>
h1_size := size.large
h2_size := size.normal
h3_size := size.small
h4_size := size.tiny
"Small" =>
h1_size := size.normal
h2_size := size.small
h3_size := size.tiny
h4_size := size.tiny
trend_settings_group = "Trend Settings"
general_group = "General"
market_structure_group = "Market Structure"
snd_group = "Supply & Demand"
liquidity_group = "Liquidity"
more_confluences_group = "More Confluences"
before_trade_group = "Before Trade"
table_footers = "Footers"
table_title = "Rules"
headerColor = color.new(color.blue, 80)
infoColor = color.new(color.red, 80)
Trend_Title = input.string("Trend Settings", "General Title", group = trend_settings_group)
swing_structure_4h = input.string("Bearish", "4h Swing Structure", options = ["Bearish", "Bullish"], group = trend_settings_group)
swing_structure_15m = input.string("Bearish", "15m Swing Structure", options = ["Bearish", "Bullish"], group = trend_settings_group)
swing_structure_color_bull = input.color(#abe69b, "Bull", group = "Colors", inline = "01")
swing_structure_color_bear = input.color(#ffdbd2, "Bear", group = "Colors", inline = "01")
swing_structure_4h_color = color.green
swing_structure_15m_color = color.green
if swing_structure_4h == "Bearish"
swing_structure_4h_color := swing_structure_color_bear
else
swing_structure_4h_color := swing_structure_color_bull
if swing_structure_15m == "Bearish"
swing_structure_15m_color := swing_structure_color_bear
else
swing_structure_15m_color := swing_structure_color_bull
General_Title = input.string("General Infos", "General Title", group = general_group)
General_Infos = input.text_area("!! Dont trade outside Peak Hours !!\nalways take the extreme, unless the flip sweeps!", "General Infos", group = general_group, tooltip = "use '\\n' for new line")
Market_Structure_Title = input.string("Market Structure", "Market Structure Title", group = market_structure_group)
Market_Structure_Info = input.text_area("4h comes first, then you do 15m.\n(4h = 80 Pips, 15m = 30 Pips)", "Market Structure Info", group = market_structure_group, tooltip = "use '\\n' for new line")
SnD_Title = input.string("Supply & Demand", "Supply & Demand Title", group = snd_group)
SnD_Info = input.text_area("We focus on 15m POI's, but we dont ignore 4h!\nmore confluences are:\nSweeps\nInteractions (Flip zones)\nInducement\nPvsD (Premium vs Discount)\nMitigation", "Supply & Demand Info", group = snd_group, tooltip = "use '\\n' for new line")
Liquidity_Title = input.string("Liquidity", "Liquidity Title", group = liquidity_group)
Liquidity_Info = input.text_area("Its either 'Inducements' or 'Sweep Zones'\nIt's mostly Equal Highs/Lows that get swept.", "Liquidity Info", group = liquidity_group, tooltip = "use '\\n' for new line")
more_confluences_title = input.string("More Confluences", "More Confluences Title", group = more_confluences_group)
more_confluences_info = input.text_area("PvsD (Premium vs Discount)\nSession Ranges (Asia mostly..)\nHTF Extremes", "More Confluences Info", group = more_confluences_group, tooltip = "use '\\n' for new line")
before_trade_title = input.string("Before you take a trade", "Before Trade Title", group = before_trade_group)
before_trade_info = input.text_area("Is the price near the HFT POI?\nDid the price take any LQ and left any LQ behind?\nDid you get Wyckoff at all?\nIf no, please, for the love of god, dont take the trade!", "Before Trade Info", group = before_trade_group, tooltip = "use '\\n' for new line")
table_footer = "Many thanks to the people in this Discord\nhttps://discord.gg/5resvCpZEr"
var maTable = table.new(
position=position.top_right, columns=2, rows=21, bgcolor=bg_table_color,
frame_color=farme_color, frame_width=frame_width, border_color=bg_border_color, border_width=table_width)
if barstate.islast and show_rules
Cell = 0
// Header
table.cell(maTable, 0, 0, text = table_title, text_size = h1_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//Trend Settings
Cell += 1
table.cell(maTable, 0, Cell, text = Trend_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = "4h Swing Structure")
table.cell(maTable, 1, Cell, text = swing_structure_4h, bgcolor = swing_structure_4h_color, text_size = h3_size)
Cell += 1
table.cell(maTable, 0, Cell, text = "15m Swing Structure")
table.cell(maTable, 1, Cell, text = swing_structure_15m, bgcolor = swing_structure_15m_color, text_size = h3_size)
//table.merge_cells(maTable, 0, Cell, 1, Cell)
//General Infos
Cell += 1
table.cell(maTable, 0, Cell, text = General_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = General_Infos, text_size = h3_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
// Market Structure
Cell += 1
table.cell(maTable, 0, Cell, text = Market_Structure_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = Market_Structure_Info, text_size = h3_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//Supply and Demand
Cell += 1
table.cell(maTable, 0, Cell, text = SnD_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = SnD_Info, text_size = h3_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//Liquidity
Cell += 1
table.cell(maTable, 0, Cell, text = Liquidity_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = Liquidity_Info, text_size = h3_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//More Confluences
Cell += 1
table.cell(maTable, 0, Cell, text = more_confluences_title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = more_confluences_info, text_size = h3_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//Before you take a trade, please, for the love of god, read this!
Cell += 1
table.cell(maTable, 0, Cell, text = before_trade_title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = before_trade_info, text_size = h3_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//Inside Bar Section
inside_bar_color = input.color(color.white, "Inside Bar Color", group = "Inside Bar")
if inside_bar_show == false
inside_bar_color := na
Inside(position) => high <= high[position] and low >= low[position]
secLast = 1
barcolor(Inside(secLast)? inside_bar_color: na)
// ********* //
// ********* //
// Trading Session //
// ********* //
// ********* //
fr_group = "session_fr"
lnd_group = "session_lnd"
ny_group = "session_ny"
asia_group = "session_asia"
style_group = "Trading Session Box Style"
// Show & Styles
i_sess_border_style = input.string(line.style_dotted, 'Style', options=[line.style_solid, line.style_dotted, line.style_dashed], group=style_group)
i_sess_border_width = input.int(1, 'Thickness', minval=0, group=style_group)
i_sess_bgopacity = input.int(100, 'Transp', minval=0, maxval=100, step=1, group=style_group, tooltip='Setting the 100 is no background color')
i_tz = input.string('GMT+2', title='Timezone', options=['GMT-11', 'GMT-10', 'GMT-9', 'GMT-8', 'GMT-7', 'GMT-6', 'GMT-5', 'GMT-4', 'GMT-3', 'GMT-2', 'GMT-1', 'GMT', 'GMT+1', 'GMT+2', 'GMT+3', 'GMT+4', 'GMT+5', 'GMT+6', 'GMT+7', 'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12'], tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group="General")
trading_session_group = "Trading Session"
outside_session_color = input.color(color.red, 'Bar Color', group=trading_session_group)
text_color = input.color(color.white, 'Text Color', group=trading_session_group)
label_color = input.color(color.new(color.green, 100), 'Label Color', group=trading_session_group)
label_position = str.lower(input.string('Bottom', '', options=['Top', 'Bottom'], group=trading_session_group))
label_style = label.style_label_center
icon_separator = ' • '
fr_Session = input.session(title="Frankfurt", defval="0700-1100", inline=fr_group)
show_fr = input.bool(true, title="", inline=fr_group)
fr_color = input.color(color.new(color.teal, 0), '', inline=fr_group)
lnd_Session = input.session(title="London", defval="0800-1200", inline=lnd_group)
show_ln = input.bool(true, title="", inline=lnd_group)
ln_color = input.color(color.new(color.blue, 0), '', inline=lnd_group)
ny_Session = input.session(title="New York", defval="1300-1700", inline=ny_group)
show_ny = input.bool(true, title="", inline=ny_group)
ny_color = input.color(color.new(color.orange, 0), '', inline=ny_group)
asia_Session= input.session(title="Asia", defval="0100-0700", inline=asia_group)
show_as = input.bool(true, title="", inline=asia_group)
as_color = input.color(color.new(color.purple, 0), '', inline=asia_group)
//Pip calculation
i_lookback = 12 * 60
f_get_started (_session) => na(_session[1]) and _session
f_get_ended (_session) => na(_session) and _session[1]
f_get_period (_session, _start, _lookback) =>
result = math.max(_start, 1)
for i = result to _lookback
if na(_session[i+1]) and _session[i]
result := i+1
break
result
get_min_max(_session) =>
max = f_get_period(_session, 1, i_lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)
[top, bottom]
get_pips(_top, _bottom) =>
pips = (_top - _bottom) * 10000
pips
//draw_line(lnd_Session, f_get_started(sess_ln), sess_ln)
draw_line(_is_session, _is_started, _session) =>
open_session = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
line my_line = na
if _is_started
my_line := line.new(bar_index-1, open_session, bar_index, open_session)
if _is_session
line.set_y1(my_line, open_session)
line.set_y2(my_line, open_session)
draw_label(_is_started, _is_session, session_string, active_session, _top, _bottom, _textcolor) =>
pips = get_pips(_top, _bottom)
label my_label = na
if _is_started
my_label := label.new(time, _bottom, str.tostring(pips), textcolor=_textcolor, color=label_color, size=size.normal, style=label_style, xloc=xloc.bar_time)
//label.delete(my_label[1])
if show_pips_history == false
label.delete(my_label[1])
label_seperator = (high * syminfo.mintick * 100)
if _is_session
if session_string == "Frankfurt "
label.set_y(my_label, _bottom - label_seperator)
else
label.set_y(my_label, _bottom - label_seperator - label_seperator)
label.set_text(my_label, session_string + icon_separator + str.tostring(pips))
draw_market (_show, _session, _is_started, _is_ended, _color, _top, _bottom) =>
var box my_box = na
x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
var x1 = 0
var x2 = 0
var v_session_open = 0.0
var v_session_high = 0.0
var v_session_low = 0.0
if _show
if _is_started
x1 := bar_index
x2 := bar_index + math.abs(x0_2 - x0_1)
my_box := box.new(x1, _top, x2, _bottom)
box.set_border_style(my_box, i_sess_border_style)
box.set_border_width(my_box, i_sess_border_width)
box.set_border_color(my_box, _color)
box.set_bgcolor(my_box, color.new(_color, i_sess_bgopacity))
v_session_open := open
v_session_high := _top
v_session_low := _bottom
if show_box_history == false
box.delete(my_box[1])
// Proccesing
else if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
v_session_high := _top
v_session_low := _bottom
else if _is_ended
v_session_open := na
box.set_right(my_box, bar_index)
[x1, x2, v_session_open, v_session_high, v_session_low]
///////////////////
// Calculating
///////////////////
string tz = (i_tz == "No" or i_tz == '') ? na : i_tz
int sess_fr = time(timeframe.period, fr_Session, tz)
int sess_as = time(timeframe.period, asia_Session, tz)
int sess_ln = time(timeframe.period, lnd_Session, tz)
int sess_ny = time(timeframe.period, ny_Session, tz)
[fr_top, fr_bottom] = get_min_max(sess_fr)
[ln_top, ln_bottom] = get_min_max(sess_ln)
[ny_top, ny_bottom] = get_min_max(sess_ny)
[as_top, as_bottom] = get_min_max(sess_as)
if show_fr
if show_pips
draw_label(f_get_started(sess_fr), sess_fr, "Frankfurt ", fr_Session, fr_top, fr_bottom, fr_color)
draw_market(show_box, sess_fr, f_get_started(sess_fr), f_get_ended(sess_fr), fr_color, fr_top, fr_bottom)
if show_ln
if show_pips
draw_label(f_get_started(sess_ln), sess_ln, "London ", lnd_Session, ln_top, ln_bottom, ln_color)
draw_market(show_box, sess_ln, f_get_started(sess_ln), f_get_ended(sess_ln), ln_color, ln_top, ln_bottom)
if show_lines
draw_line(sess_ln, f_get_started(sess_ln), sess_ln)
if show_ny
if show_pips
draw_label(f_get_started(sess_ny), sess_ny, "New York ", ny_Session, ny_top, ny_bottom, ny_color)
draw_market(show_box, sess_ny, f_get_started(sess_ny), f_get_ended(sess_ny), ny_color, ny_top, ny_bottom)
if show_as
if show_pips
draw_label(f_get_started(sess_as), sess_as, "Asia ", asia_Session, as_top, as_bottom, as_color)
draw_market(show_box, sess_as, f_get_started(sess_as), f_get_ended(sess_as), as_color, as_top, as_bottom)
if show_session == false
outside_session_color := na
InSession(sess) => na(time(timeframe.period, sess, tz)) == false
barcolor(color=(InSession(fr_Session)[1] and show_fr) or (InSession(lnd_Session)[1] and show_ln) or (InSession(ny_Session)[1] and show_ny ) or (InSession(asia_Session)[1] and show_as) ? na : outside_session_color, title="Frankfurt")
////////////////////
// Alerts
////////////////////
// Alerts
i_alert1_show = input.bool(false, 'Alerts - Sessions stard/end', group='Alerts visualized')
i_alert2_show = input.bool(false, 'Alerts - Opening range breakouts', group='Alerts visualized')
i_alert3_show = input.bool(false, 'Alerts - Price crossed session\s High/Low after session closed', group='Alerts visualized')
//Session alerts
bool sess_frankfurt_started = sess_fr and not sess_fr[1]
bool sess_frankfurt_ended = not sess_fr and sess_fr[1]
bool sess_london_started = sess_ln and not sess_ln[1]
bool sess_london_ended = not sess_ln and sess_ln[1]
bool sess_new_york_started = sess_ny and not sess_ny[1]
bool sess_new_york_ended = not sess_ny and sess_ny[1]
bool sess_asia_started = sess_as and not sess_as[1]
bool sess_asia_ended = not sess_as and sess_as[1]
alertcondition(sess_frankfurt_started, 'Frankfurt session started')
alertcondition(sess_frankfurt_ended, 'Frankfurt session ended')
alertcondition(sess_london_started, 'London session started')
alertcondition(sess_london_ended, 'London session ended')
alertcondition(sess_new_york_started, 'New York session started')
alertcondition(sess_new_york_ended, 'New York session ended')
alertcondition(sess_asia_started, 'Asia session started')
alertcondition(sess_asia_ended, 'Asia session ended')
alertcondition((not sess_fr) and ta.crossover(close, fr_top), 'Frankfurt session High crossed (after session closed)')
alertcondition((not sess_fr) and ta.crossunder(close, fr_bottom), 'Frankfurt session Low crossed (after session closed)')
alertcondition((not sess_ln) and ta.crossover(close, ln_top), 'London session High crossed (after session closed)')
alertcondition((not sess_ln) and ta.crossunder(close, ln_bottom), 'London session Low crossed (after session closed)')
alertcondition((not sess_ny) and ta.crossover(close, ny_top), 'New York session High crossed (after session closed)')
alertcondition((not sess_ny) and ta.crossunder(close, ny_bottom), 'New York session Low crossed (after session closed)')
alertcondition((not sess_as) and ta.crossover(close, as_top), 'Asia session High crossed (after session closed)')
alertcondition((not sess_as) and ta.crossunder(close, as_bottom), 'Asia session Low crossed (after session closed)')
// ********* //
// ********* //
// Imbalance //
// ********* //
// ********* //
color gray0 = color.new(color.gray, 0)
color yellow0 = color.new(#FFF700, 0)
bool showgreydiamond = input(defval=false, title='Show Diamond For Back Testing' ,group='=== Information ===')
Imbcol = input.color(yellow0, 'Imbalance Colour', inline="1" ,group='=== Information ===')
Dimcol = input.color(gray0, 'Imbalance Colour', inline="1" ,group='=== Information ===')
TopImbalance = low[2] <= open[1] and high[0] >= close[1]
TopImbalancesize = low[2] - high[0]
if TopImbalance and TopImbalancesize > 0 and show_imbalance
BOX1 = box.new(left=bar_index[1], top=low[2], right=bar_index[0], bottom=high[0])
box.set_bgcolor(BOX1, Imbcol )
box.set_border_color(BOX1, Imbcol )
BottomImbalance = high[2] >= open[1] and low[0] <= close[1]
BottomImbalancesize = low[0] - high[2]
if BottomImbalance and BottomImbalancesize > 0 and show_imbalance
BOX2 = box.new(left=bar_index[1], top=low[0], right=bar_index[0], bottom=high[2])
box.set_bgcolor(BOX2, Imbcol )
box.set_border_color(BOX2, Imbcol )
DownImbalance = TopImbalance and TopImbalancesize > 0
if show_imbalance == false
DownImbalance := false
showgreydiamond := false
plotshape(DownImbalance[0] and showgreydiamond, style=shape.diamond, location=location.abovebar, color=Dimcol, size=size.tiny)
UpImbalance = BottomImbalance and BottomImbalancesize > 0
if show_imbalance
UpImbalance := false
showgreydiamond := false
plotshape(UpImbalance[0] and showgreydiamond, style=shape.diamond, location=location.belowbar, color=Dimcol, size=size.tiny)
alertcondition(DownImbalance , title='Down Imbalance', message='Down Imbalance')
alertcondition(UpImbalance , title='Up Imbalance', message='Up Imbalance')
alertcondition(DownImbalance or UpImbalance , title='Imbalance Present ', message='Imbalance Present') |
Pi Cycle Bottom Indicator | https://www.tradingview.com/script/IFf6VobP-Pi-Cycle-Bottom-Indicator/ | Doncic | https://www.tradingview.com/u/Doncic/ | 554 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Doncic on TradingView
//@version=5
indicator('Pi Cycle Bottom Indicator', shorttitle=' Pi Cycle Bottom', overlay=true)
ln_ma_bottomlong = input.int(471, minval=1, title='Long SMA')
ln_ma_bottomshort = input.int(150, minval=1, title='Short EMA')
long_multiple = input(0.745, title='Long MA Multiple')
short_multiple = input(1.0, title='Short MA Multiple')
resolution = input('D', title='Time interval')
is_show_ma = input(true, title='Display Moving Averages')
is_show_diff = input(false, title='Display Difference between MAs')
is_alert = input(false, title='Send an alert at Pi Cycle Bottom')
ma_bottomlong = request.security(syminfo.tickerid, resolution, ta.sma(close, ln_ma_bottomlong) * long_multiple)
ma_bottomshort = request.security(syminfo.tickerid, resolution, ta.ema(close, ln_ma_bottomshort) * short_multiple)
ma_diff = ma_bottomshort - ma_bottomlong
src = request.security(syminfo.tickerid, resolution, close)
plot(is_show_ma ? ma_bottomlong : na, color=color.new(color.red, 0), title='Long MA')
plot(is_show_ma ? ma_bottomshort : na, color=color.new(color.green, 0), title='Short MA')
plot(is_show_diff ? ma_diff : na, color=color.new(color.white, 0), title='MA Difference')
PiCycleBottom = ta.crossunder(ma_bottomshort, ma_bottomlong) ? src + src / 100 * 10 : na
plotshape(PiCycleBottom, style=shape.triangleup, size=size.small, text='Pi Cycle Bottom', color=color.new(color.green, 0), textcolor=color.new(color.white, 0), location=location.belowbar)
|
Jurik Volty Adaptive EMA [Loxx] | https://www.tradingview.com/script/nYFtwUZp-Jurik-Volty-Adaptive-EMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 51 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Jurik Volty Adaptive EMA [Loxx]", shorttitle = "JVAEMA [Loxx]", overlay = true, timeframe="", timeframe_gaps = true, max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
EMA(x, t) =>
_ema = x
_ema := na(_ema[1]) ? x : (x - nz(_ema[1])) * (2 / (t + 1)) + nz(_ema[1])
_ema
_a_jurik_filt(src, len) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
_temp= vsum != 0 ? avolty / vsum: 1
_temp
src = input.source(close, "Source", group = "Basic Settings")
len = input.int(40, "EMA Length", group = "Basic Settings")
colorbars = input.bool(true, title='Color bars?', group = "UI Options")
emaout = EMA(src, len * math.ceil(_a_jurik_filt(src, len)))
plot(emaout, color = src >= emaout ? greencolor : redcolor, linewidth = 3)
barcolor(color = src >= emaout ? greencolor : redcolor)
|
Jurik CFB Adaptive QQE [Loxx] | https://www.tradingview.com/script/FS2ctCcJ-Jurik-CFB-Adaptive-QQE-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 119 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Jurik CFB Adaptive QQE [Loxx]",
shorttitle = "JCFBAQQE [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true,
max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
RMA(x, t) =>
_rma = x
_rma := na(_rma[1]) ? x : (x - nz(_rma[1])) * (1/t) + nz(_rma[1])
_rma
EMA(x, t, a) =>
_ema = x
_ema := na(_ema[1]) ? x : (x - nz(_ema[1])) * a + nz(_ema[1])
_ema
_a_jurik_filt(src, len, phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jma = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
_jcfbaux(src, depth)=>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = depth - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
_jcfb(src, len, smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, _jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
_rsx_rsi(src, len)=>
src_out = 100 * src
mom0 = ta.change(src_out)
moa0 = math.abs(mom0)
Kg = 3 / (len + 2)
Hg = 1 - Kg
//mom
f28 = 0.0, f30 = 0.0
f28 := Kg * mom0 + Hg * nz(f28[1])
f30 := Hg * nz(f30[1]) + Kg * f28
mom1 = f28 * 1.5 - f30 * 0.5
f38 = 0.0, f40 = 0.0
f38 := Hg * nz(f38[1]) + Kg * mom1
f40 := Kg * f38 + Hg * nz(f40[1])
mom2 = f38 * 1.5 - f40 * 0.5
f48 = 0.0, f50 = 0.0
f48 := Hg * nz(f48[1]) + Kg * mom2
f50 := Kg * f48 + Hg * nz(f50[1])
mom_out = f48 * 1.5 - f50 * 0.5
//moa
f58 = 0.0, f60 = 0.0
f58 := Hg * nz(f58[1]) + Kg * moa0
f60 := Kg * f58 + Hg * nz(f60[1])
moa1 = f58 * 1.5 - f60 * 0.5
f68 = 0.0, f70 = 0.0
f68 := Hg * nz(f68[1]) + Kg * moa1
f70 := Kg * f68 + Hg * nz(f70[1])
moa2 = f68 * 1.5 - f70 * 0.5
f78 = 0.0, f80 = 0.0
f78 := Hg * nz(f78[1]) + Kg * moa2
f80 := Kg * f78 + Hg * nz(f80[1])
moa_out = f78 * 1.5 - f80 * 0.5
rsx = math.max(math.min((mom_out / moa_out + 1.0) * 50.0, 100.00), 0.00)
rsx
_wilders_rsi(x, y) =>
u = math.max(x - x[1], 0)
d = math.max(x[1] - x, 0)
rs = RMA(u, y) / RMA(d, y)
res = 100 - 100 / (1 + rs)
res
_rapid_rsi(src, len)=>
upSum = math.sum(math.max(ta.change(src), 0), len)
dnSum = math.sum(math.max(-ta.change(src), 0), len)
rrsi = dnSum == 0 ? 100 : upSum == 0 ? 0 : 100 - 100 / (1 + upSum / dnSum)
rrsi
rsiType = input.string("RSX", "RSI Type", options =["Wilders", "RSX", "Rapid"], group = "Basic Settings")
adaptOn = input.string("CFB Adaptive", "RSI Calculation Type", options = ["Fixed", "CFB Adaptive"], group = "Basic Settings")
src = input.source(close, "Source", group = "Basic Settings")
rsiPeriodIn = input.int(14, title='RSI Period', minval = 1, group = "Basic Settings")
RsiSmoothingFactor = input.int(5, title='Smoothing Factor', group = "Basic Settings")
RsiPriceSmoothing = input.int(1, "Source Smoothing Period", minval = 1, group = "Basic Settings")
WPFast = input.float(2.618, "WP Fast Coeffient", group = "Basic Settings")
WPSlow = input.float(4.236, "WP Slow Coeffient", group = "Basic Settings")
overbought = input.int(80, "Overbought Level", group = "Basic Settings")
oversold = input.int(20, "Oversold Level", group = "Basic Settings")
cfb_src = input.source(hlcc4, "CFB Source", group = "CFB Ingest Settings")
nlen = input.int(50, "CFB Normal Length", minval = 1, group = "CFB Ingest Settings")
cfb_len = input.int(10, "CFB Depth", maxval = 10, group = "CFB Ingest Settings")
smth = input.int(8, "CFB Smooth Length", minval = 1, group = "CFB Ingest Settings")
slim = input.int(10, "CFB Short Limit", minval = 1, group = "CFB Ingest Settings")
llim = input.int(20, "CFB Long Limit", minval = 1, group = "CFB Ingest Settings")
jcfbsmlen = input.int(10, "CFB Jurik Smooth Length", minval = 1, group = "CFB Ingest Settings")
jcfbsmph = input.float(0, "CFB Jurik Smooth Phase", group = "CFB Ingest Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
cfb_draft = _jcfb(cfb_src, cfb_len, smth)
cfb_pre = _a_jurik_filt(_a_jurik_filt(cfb_draft, jcfbsmlen, jcfbsmph), jcfbsmlen, jcfbsmph)
max = ta.highest(cfb_pre, nlen)
min = ta.lowest(cfb_pre, nlen)
denom = max - min
ratio = (denom > 0) ? (cfb_pre - min) / denom : 0.5
len_out_cfb = math.ceil(slim + ratio * (llim - slim))
len_out_cfb := math.ceil(len_out_cfb) < 1 ? 1 : math.ceil(len_out_cfb)
rsiPeriod = adaptOn == "Fixed" ? rsiPeriodIn : len_out_cfb
rsiPeriod := nz(rsiPeriod) < 1 ? 1 : nz(rsiPeriod)
closer = ta.sma(src, RsiPriceSmoothing)
rsi = rsiType == "Wilders" ? _wilders_rsi(closer, rsiPeriod) : rsiType == "Rapid" ? _rapid_rsi(closer, rsiPeriod) : _rsx_rsi(closer, rsiPeriod)
alpha1 = 2.0/(RsiSmoothingFactor+1.0)
alpha2 = 1.0/(math.max(rsiPeriod, 1))
rsiMA = EMA(rsi, RsiSmoothingFactor, alpha1)
MaAtrRsi = EMA(math.abs(rsiMA[1] - rsiMA), rsiPeriodIn, alpha2)
outer = EMA(MaAtrRsi, rsiPeriodIn, alpha2)
emaf = outer * WPFast
emas = outer * WPSlow
TrendSlow = 0.0
tr = nz(TrendSlow[1])
dv = tr
if (rsiMA < tr)
tr := rsiMA + emas
if ((nz(rsiMA[1]) < dv and tr > dv))
tr := dv
if (rsiMA > tr)
tr := rsiMA - emas
if ((nz(rsiMA[1]) > dv) and (tr < dv))
tr := dv
TrendSlow := tr
TrendFast = 0.0
tr := nz(TrendFast[1])
dv := tr
if (rsiMA < tr)
tr := rsiMA + emaf
if ((nz(rsiMA[1]) < dv and tr > dv))
tr := dv
if (rsiMA > tr)
tr := rsiMA - emaf
if ((nz(rsiMA[1]) > dv) and (tr < dv))
tr := dv
TrendFast := tr
plot(TrendSlow, "Slow Trend", color=color.new(color.yellow, 0),linewidth = 1, style=plot.style_circles)
plot(TrendFast, "Fast Trend", color=color.new(color.white, 0), linewidth = 1)
colout =
rsiMA > TrendSlow and rsiMA > TrendFast ? greencolor :
rsiMA < TrendSlow and rsiMA < TrendFast ? redcolor :
color.gray
plot(rsiMA,"RSIMA", color = colout, linewidth = 3)
plot(50, color=color.new(color.gray, 30), linewidth=1, style=plot.style_circles, title = "Zero line")
tl = plot(overbought, color=color.rgb(0, 255, 255, 100), style=plot.style_line, title = "Overbought Level 2")
tl1 = plot(overbought-5, color=color.rgb(0, 255, 255, 100), style=plot.style_line, title = "Overbought Level 1")
bl1 = plot(oversold, color=color.rgb(255, 255, 255, 100), style=plot.style_line, title = "Overbought Level 1")
bl = plot(oversold+5, color=color.rgb(255, 255, 255, 100), style=plot.style_line, title = "Overbought Level 2")
fill(tl, tl1, color=color.new(color.gray, 85), title = "Top Boundary Fill Color")
fill(bl, bl1, color=color.new(color.gray, 85), title = "Bottom Boundary Fill Color")
barcolor(colorbars ? colout : na)
|
BTC Pi Multiple | https://www.tradingview.com/script/D82eIDV7-BTC-Pi-Multiple/ | cryptoonchain | https://www.tradingview.com/u/cryptoonchain/ | 132 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MJShahsavar
//@version=5
indicator("BTC Pi Multiple", timeframe = "D")
a = ta.sma(close, 350)
b=2*a
c = ta.sma(close, 111)
d=b/c
e=1-d
h1= hline (- 0.2)
h2= hline (1)
h3= hline (-3)
h4=hline (-2)
h5= hline (-1, linewidth=2)
fill (h1,h2, color.red, transp = 60)
fill (h3,h4, color.blue, transp = 60)
plot (e, color= color.blue , linewidth=1) |
Trend Trigger Factor w/ Discontinued Signal Lines [Loxx] | https://www.tradingview.com/script/Am9zze2V-Trend-Trigger-Factor-w-Discontinued-Signal-Lines-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 239 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Trend Trigger Factor w/ Discontinued Signal Lines [Loxx]",
shorttitle = "TTFDSL [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
len = input.int(15, "Period", group = "Basic Settings")
avglen = input.int(5, "Pre-smoothing Period", group = "Basic Settings")
siglen = input.int(10, "Discontinued Signal Lines (DSL) Period", group = "Basic Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
hhRecent = 0.
llRecent = 0.
hhOlder = 0.
llOlder = 0.
levu = 0., levd = 0., fdn = 0.
mah = ta.ema(high, avglen)
mal = ta.ema(low, avglen)
start = len * 2 - 1
hhOlder := nz(ta.lowest(mah, len)[start])
llOlder := nz(ta.lowest(mal, len)[start])
hhRecent := nz(ta.lowest(mah, len-1)[start])
llRecent := nz(ta.lowest(mal, len-1)[start])
BuyPower = (mah > hhRecent ? mah : hhRecent) - llOlder
SellPower = hhOlder - (mal < llRecent ? mal : llRecent)
val = (BuyPower + SellPower != 0) ? 100.0 * (BuyPower - SellPower) / (0.5 * (BuyPower + SellPower)) : 0
dslAlpha = 2.0 / (1.0 + siglen)
levu := (val > 0) ? nz(levu[1]) + dslAlpha * (val - nz(levu[1])) : nz(levu[1])
levd := (val < 0) ? nz(levd[1]) + dslAlpha * (val - nz(levd[1])) : nz(levd[1])
lmid = (levu + levd)/2
colorout = val >= levu ? darkGreenColor : val <= levd ? darkRedColor : color.gray
lu = plot(levu, color = bar_index % 2 ? color.gray : na)
ld = plot(levd, color = bar_index % 2 ? color.gray : na)
lm = plot(val, color = colorout, linewidth = 3)
plot(lmid, color = bar_index % 2 ? color.gray : na)
fill(lu, lm, val >= levu ? greencolor : na)
fill(ld, lm, val <= levd ? redcolor : na)
coloroutb = val >= levu ? greencolor : val <= levd ? redcolor : color.gray
barcolor(colorbars ? coloroutb : na)
|
Crude Oil: Backwardation Vs Contango | https://www.tradingview.com/script/QQTxa4wh-Crude-Oil-Backwardation-Vs-Contango/ | twingall | https://www.tradingview.com/u/twingall/ | 68 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//Crude Oil: CL
// Plots Futures contracts prices over the next 3.5 years; to easily visualize Backwardation Vs Contango (carrying charge) markets.
// Carrying charge (contract prices increasing into the future) = normal, representing the costs of carrying/storage of a commodity. When this is flipped to Backwardation (contract prices decreasing into the future): its a bullish sign: Buyers want this commodity, and they want it NOW.
// Note: indicator does not map to time axis in the same way as price; it simply plots the progression of contract months out into the future; left to right; so timeframe doesn't matter for this plot
// There's likely some more efficient way to write this; e.g. when plotting for Gold (GC); 21 of the security requests are redundant; but they are still made; and can make this slower to load
// TO UPDATE: in REQUEST CONTRACTS section, delete old contracts (top) and add new ones (bottom). Then in PLOTTING section, Delete old [expired] contract labels (bottom); add new [distant future] contract labels (top); adjust the X in 'bar_index-(X+_historical)' numbers accordingly
// This is one of several similar indicators: Meats | Metals | Grains | VIX | Crude Oil
// -If you want to build from this; to work on other commodities; be aware that Tradingview limits the number of contract calls to 40 (hence the multiple indicators)
// Tips:
// -Right click and reset chart if you can't see the plot; or if you have trouble with the scaling.
// -Right click and add to new scale if you prefer this not to overlay directly on price. Or move to new pane below.
// -If this takes too long to load; comment out the more distant future half of the contracts; and their respective labels. Or comment out every other contract and every other label.
// --Added historical input: input days back in time; to see the historical shape of the Futures curve via selecting 'days back' snapshot
//updated to work on WTI (MATBAROFEX): Plots CL (NYMEX) futures curve when selected asset is WTI (3rd July 2022)
// updated 1st Feb 2023
// © twingall
indicator("Crude Oil: Backwardation Vs Contango", overlay = true, scale = scale.right)
_historical = input(0, "time travel back; days")
_adr = ta.atr(5)
_root = syminfo.root== "WTI"? "CL": syminfo.root
colorNone= color.new(color.white, 100)
//Function to test if contract is expired
int oneWeek = 5*24*60*60*1000 // 5 or more days since last reported closing price => expired
isExp (int _timeClose)=>
expired = _timeClose <= (last_bar_time-oneWeek)
///REQUEST CONTRACTS---
//Crude Oil Contracts. Add the commented out ones if you prefer, but they may cause slower loading
[jul22,jul22t]= request.security("NYMEX:" + _root + "N2022", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[aug22,aug22t]= request.security("NYMEX:" + _root + "Q2022", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[sept22,sept22t]=request.security("NYMEX:" + _root + "U2022", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[oct22,oct22t]= request.security("NYMEX:" + _root + "V2022", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[nov22,nov22t]= request.security("NYMEX:" + _root + "X2022", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[dec22,dec22t]= request.security("NYMEX:" + _root + "Z2022", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[jan23,jan23t]= request.security("NYMEX:" + _root + "F2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[feb23,feb23t]= request.security("NYMEX:" + _root + "G2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[mar23,mar23t]= request.security("NYMEX:" + _root + "H2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[apr23,apr23t]= request.security("NYMEX:" + _root + "J2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[may23,may23t]= request.security("NYMEX:" + _root + "K2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[jun23,jun23t]= request.security("NYMEX:" + _root + "M2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[jul23,jul23t]= request.security("NYMEX:" + _root + "N2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[aug23,aug23t]= request.security("NYMEX:" + _root + "Q2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[sept23,sept23t]=request.security("NYMEX:" + _root + "U2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[oct23,oct23t]= request.security("NYMEX:" + _root + "V2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[nov23,nov23t]= request.security("NYMEX:" + _root + "X2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[dec23,dec23t]= request.security("NYMEX:" + _root + "Z2023", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[jan24,jan24t]= request.security("NYMEX:" + _root + "f2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[feb24,feb24t]= request.security("NYMEX:" + _root + "G2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[mar24,mar24t]= request.security("NYMEX:" + _root + "H2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[apr24,apr24t]= request.security("NYMEX:" + _root + "J2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[may24,may24t]= request.security("NYMEX:" + _root + "K2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[jun24,jun24t]= request.security("NYMEX:" + _root + "M2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[jul24,jul24t]= request.security("NYMEX:" + _root + "N2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[aug24,aug24t]= request.security("NYMEX:" + _root + "Q2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[sept24,sept24t]=request.security("NYMEX:" + _root + "U2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[oct24,oct24t]= request.security("NYMEX:" + _root + "V2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[nov24,nov24t]= request.security("NYMEX:" + _root + "X2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
[dec24,dec24t]= request.security("NYMEX:" + _root + "Z2024", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [jan25,jan25t]= request.security("NYMEX:" + _root + "F2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [feb25,feb25t]= request.security("NYMEX:" + _root + "G2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [mar25,mar25t]= request.security("NYMEX:" + _root + "H2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [apr25,apr25t]= request.security("NYMEX:" + _root + "J2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [may25,may25t]= request.security("NYMEX:" + _root + "K2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [jun25,jun25t]= request.security("NYMEX:" + _root + "M2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [jul25,jul25t]= request.security("NYMEX:" + _root + "N2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [aug25,aug25t]= request.security("NYMEX:" + _root + "Q2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [sept25,sept25t]=request.security("NYMEX:" + _root + "U2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
// [oct25,oct25t]= request.security("NYMEX:" + _root + "V2025", "D",[close[_historical], time_close], ignore_invalid_symbol=true)
//PLOTTING----
//if you've uncommented the contracts above; comment-out lines 80-97, then uncomment lines 99-138
if barstate.islastconfirmedhistory and _root=='CL'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(aug24t)?0:aug24, text = 'Aug24', textcolor =isExp(aug24t)?colorNone: color.red, style=isExp(aug24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(jul24t)?0:jul24, text = 'Jul24', textcolor = isExp(jul24t)?colorNone:color.red, style=isExp(jul24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(jun24t)?0:jun24, text = 'Jun24', textcolor =isExp(jun24t)?colorNone: color.red, style=isExp(jun24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(may24t)?0:may24, text = 'May24', textcolor =isExp(may24t)?colorNone: color.red, style=isExp(may24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(apr24t)?0:apr24, text = 'Apr24', textcolor =isExp(apr24t)?colorNone: color.red, style=isExp(apr24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(mar24t)?0:mar24, text = 'Mar24', textcolor =isExp(mar24t)?colorNone: color.red, style=isExp(mar24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(feb24t)?0:feb24, text = 'Feb24', textcolor =isExp(feb24t)?colorNone: color.red, style=isExp(feb24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(jan24t)?0:jan24, text = 'Jan24', textcolor =isExp(jan24t)?colorNone: color.red, style=isExp(jan24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(dec23t)?0:dec23, text = 'Dec23', textcolor =isExp(dec23t)?colorNone: color.red, style=isExp(dec23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(20+_historical), isExp(nov23t)?0:nov23, text = 'Nov23', textcolor =isExp(nov23t)?colorNone: color.red, style=isExp(nov23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(22+_historical), isExp(oct23t)?0:oct23, text = 'Oct23', textcolor =isExp(oct23t)?colorNone: color.red, style=isExp(oct23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(24+_historical), isExp(sept23t)?0:sept23, text = 'Sept23', textcolor =isExp(sept23t)?colorNone: color.red, style=isExp(sept23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(26+_historical), isExp(aug23t)?0:aug23, text = 'Aug23', textcolor = isExp(aug23t)?colorNone:color.red, style=isExp(aug23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(28+_historical), isExp(jul23t)?0:jul23, text = 'Jul23', textcolor = isExp(jul23t)?colorNone:color.red, style=isExp(jul23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(30+_historical), isExp(jun23t)?0:jun23, text = 'Jun23', textcolor = isExp(jun23t)?colorNone: color.red, style= isExp(jun23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(32+_historical), isExp(may23t)?0:may23, text = 'May23', textcolor =isExp(may23t)?colorNone: color.red, style=isExp(may23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(34+_historical), isExp(apr23t)?0:apr23, text = 'Apr23', textcolor =isExp(apr23t)?colorNone: color.red, style=isExp(apr23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(36+_historical), isExp(mar23t)?0:mar23, text = 'Mar23', textcolor =isExp(mar23t)?colorNone: color.red, style=isExp(mar23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(38+_historical), isExp(feb23t)?0:feb23, text = 'Feb23', textcolor =isExp(feb23t)?colorNone: color.red, style=isExp(feb23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(40+_historical), isExp(jan23t)?0:jan23, text = 'Jan23', textcolor =isExp(jan23t)?colorNone: color.red, style=isExp(jan23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(42+_historical), isExp(dec22t)?0:dec22, text = 'Dec22', textcolor =isExp(dec22t)?colorNone: color.red, style=isExp(dec22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(44+_historical), isExp(nov22t)?0:nov22, text = 'Nov22', textcolor =isExp(nov22t)?colorNone: color.red, style=isExp(nov22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(46+_historical), isExp(oct22t)?0:oct22, text = 'Oct22', textcolor =isExp(oct22t)?colorNone: color.red, style=isExp(oct22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(48+_historical), isExp(sept22t)?0:sept22, text = 'Sept22', textcolor =isExp(sept22t)?colorNone: color.red, style=isExp(sept22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(50+_historical), isExp(aug22t)?0:aug22, text = 'Aug22', textcolor =isExp(aug22t)?colorNone: color.red, style=isExp(aug22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(52+_historical), isExp(jul22t)?0:jul22, text = 'Jul22', textcolor =isExp(jul22t)?colorNone: color.red, style=isExp(jul22t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(2+_historical), isExp(oct25t)?0:oct25, text = 'Oct25', textcolor = isExp(oct25t)?colorNone: color.red, style= isExp(oct25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(4+_historical), isExp(sept25t)?0:sept25, text = 'Sept25', textcolor =isExp(sept25t)?colorNone: color.red, style=isExp(sept25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(6+_historical), isExp(aug25t)?0:aug25, text = 'Aug25', textcolor = isExp(aug25t)?colorNone:color.red, style=isExp(aug25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(8+_historical), isExp(jul25t)?0:jul25, text = 'Jul25', textcolor =isExp(jul25t)?colorNone: color.red, style=isExp(jul25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(10+_historical), isExp(jun25t)?0:jun25, text = 'Jun25', textcolor =isExp(jun25t)?colorNone: color.red, style=isExp(jun25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(12+_historical), isExp(may25t)?0:may25, text = 'May25', textcolor =isExp(may25t)?colorNone: color.red, style=isExp(may25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(14+_historical), isExp(apr25t)?0:apr25, text = 'Apr25', textcolor = isExp(apr25t)?colorNone: color.red, style= isExp(apr25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(16+_historical), isExp(mar25t)?0:mar25, text = 'Mar25', textcolor = isExp(mar25t)?colorNone: color.red, style= isExp(mar25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(18+_historical), isExp(feb25t)?0:feb25, text = 'Feb25', textcolor =isExp(feb25t)?colorNone: color.red, style=isExp(feb25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(20+_historical), isExp(jan25t)?0:jan25, text = 'Jan25', textcolor = isExp(jan25t)?colorNone: color.red, style= isExp(jan25t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(22+_historical), isExp(dec24t)?0:dec24, text = 'Dec24', textcolor =isExp(dec24t)?colorNone: color.red, style=isExp(dec24t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(24+_historical), isExp(nov24t)?0:nov24, text = 'Nov24', textcolor =isExp(nov24t)?colorNone: color.red, style=isExp(nov24t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(26+_historical), isExp(oct24t)?0:oct24, text = 'Oct24', textcolor =isExp(oct24t)?colorNone: color.red, style=isExp(oct24t)?label.style_none:label.style_diamond, size = size.tiny)
// label.new(bar_index-(28+_historical), isExp(sept24t)?0:sept24, text = 'Sept24', textcolor =isExp(sept24t)?colorNone: color.red, style=isExp(sept24t)?label.style_none:label.style_diamond, size = size.tiny)
|
Jurik Filtered, Composite Fractal Behavior (CFB) Channels [Loxx] | https://www.tradingview.com/script/bq79NJVr-Jurik-Filtered-Composite-Fractal-Behavior-CFB-Channels-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Jurik Filtered, Composite Fractal Behavior (CFB) Channels [Loxx]",
shorttitle = "JFCFBC [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true,
max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
_a_jurik_filt(src, len, phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jma = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
_jcfbaux(src, depth)=>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = depth - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
_jcfb(src, len, smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, _jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
cfb_src = input.source(hlcc4, "CFB Source", group = "CFB Ingest Settings")
nlen = input.int(50, "CFB Normal Length", minval = 1, group = "CFB Ingest Settings")
cfb_len = input.int(10, "CFB Depth", maxval = 10, group = "CFB Ingest Settings")
smth = input.int(8, "CFB Smooth Length", minval = 1, group = "CFB Ingest Settings")
slim = input.int(10, "CFB Short Limit", minval = 1, group = "CFB Ingest Settings")
llim = input.int(20, "CFB Long Limit", minval = 1, group = "CFB Ingest Settings")
jcfbsmlen = input.int(10, "CFB Jurik Smooth Length", minval = 1, group = "CFB Ingest Settings")
jcfbsmph = input.float(0, "CFB Jurik Smooth Phase", group = "CFB Ingest Settings")
colorbars = input.bool(false, "Fill channels?", group = "UI Options")
cfb_draft = _jcfb(cfb_src, cfb_len, smth)
cfb_pre = _a_jurik_filt(_a_jurik_filt(cfb_draft, jcfbsmlen, jcfbsmph), jcfbsmlen, jcfbsmph)
max = ta.highest(cfb_pre, nlen)
min = ta.lowest(cfb_pre, nlen)
denom = max - min
ratio = (denom > 0) ? (cfb_pre - min) / denom : 0.5
len_out_cfb = math.ceil(slim + ratio * (llim - slim))
hi = 0.0
mid = 0.0
lo = 0.0
temph = ta.highest(high, nz(len_out_cfb, 1))
templ = ta.lowest(low, nz(len_out_cfb, 1))
hi := high > nz(hi[1]) ? high : (temph + nz(hi[1])) / 2.0
lo := low < nz(lo[1]) ? low : (templ + nz(lo[1])) / 2.0
mid := (hi + lo)/2.0
pb1 = plot(hi, color = greencolor, linewidth = 2, style = plot.style_line)
pb2 = plot(mid, color = color.white, linewidth = 1, style = plot.style_line)
pb3 = plot(lo, color = redcolor, linewidth = 2, style = plot.style_line)
fill(pb1, pb2, color = colorbars ? color.new(greencolor, 90) : na)
fill(pb2, pb3, color = colorbars ? color.new(redcolor, 90) : na)
|
Reverse Stoch [BApig Gift] - on Panel | https://www.tradingview.com/script/JyhJff31-Reverse-Stoch-BApig-Gift-on-Panel/ | TraderHalai | https://www.tradingview.com/u/TraderHalai/ | 55 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// First off, want to give massive credit to Motgench, Balipour and Wugamlo for this script. This script is all of their good work.
//
// This script is basically just the non-on chart version which I've slightly tweaked off their script. This can be useful to reduce the clutter on the chart itself.
//@author = Motgench, balipour and Wugamlo (modified by TraderHalai)
//@version=5
indicator('Reverse Stoch [BApig Gift] - on Panel', 'BA🐷 Reverse Stoch - PANEL 🎄', overlay=false, precision=2)
len = input.int(14, 'K', minval=2)
D = input.int(3, 'D', minval=1)
E = input.string('Forecasted KD', 'KD Estimation', options=['Current Dynamic KD', 'Current Static KD', 'Forecasted KD'])
smooth = input.int(6, 'Smooth', minval=1)
ures = input(true, 'Use Multi Time Frame')
reso = input.string('1 day', ' Multi Time Frame Resolution 🕐', options=['5 min', '10 min', '15 min', '30 min', '45 min', '1 hour', '2 hours', '3 hours', '4 hours', '6 hours', '8 hours', '10 hours', '12 hours', '1 day', '2 days', '3 days', '1 week', '1 month'])
p = input(true, 'Show Stoch Cross Value Panel📋')
bs = input(false, 'Show OverBought OverSold Panel📜')
BL = input.string('Line Levels', '▼▼▼ Overbought Oversold Style ▼▼▼', options=['Line Levels', 'Bands'])
plb = input(false, 'Plot OverBought Price')
ob = input.float(80, ' OverBought Level', minval=50, maxval=100)
pls = input(false, 'Plot Oversold Price')
os = input.float(20, ' OverSold Level', minval=0, maxval=50)
sm = input(false, '====== Stoch Cross Smoothing ======')
slen = input(8, ' Smoothing Length')
ib = input(true, 'Dark Background ⬛')
dec = input.int(1, 'Decimals🔢', minval=0, maxval=10)
ss(Series, Period) => // Super Smoother Function
// period = input(8, "Super Smoother Period", input.float, minval=2.0, step=0.5)
var PI = 2.0 * math.asin(1.0)
var SQRT2 = math.sqrt(2.0)
lambda = PI * SQRT2 / Period
a1 = math.exp(-lambda)
coeff2 = 2.0 * a1 * math.cos(lambda)
coeff3 = -math.pow(a1, 2.0)
coeff1 = 1.0 - coeff2 - coeff3
filt1 = 0.0
filt1 := coeff1 * (Series + nz(Series[1])) * 0.5 + coeff2 * nz(filt1[1]) + coeff3 * nz(filt1[2])
filt1
getRez(intval) =>
iff_1 = intval == '1 month' ? 'M' : 'D'
iff_2 = intval == '1 week' ? 'W' : iff_1
iff_3 = intval == '3 days' ? '3D' : iff_2
iff_4 = intval == '2 days' ? '2D' : iff_3
iff_5 = intval == '1 day' ? 'D' : iff_4
iff_6 = intval == '12 hours' ? '720' : iff_5
iff_7 = intval == '10 hours' ? '600' : iff_6
iff_8 = intval == '8 hours' ? '480' : iff_7
iff_9 = intval == '6 hours' ? '360' : iff_8
iff_10 = intval == '4 hours' ? '240' : iff_9
iff_11 = intval == '3 hours' ? '180' : iff_10
iff_12 = intval == '2 hours' ? '120' : iff_11
iff_13 = intval == '1 hour' ? '60' : iff_12
iff_14 = intval == '45 min' ? '45' : iff_13
iff_15 = intval == '30 min' ? '30' : iff_14
iff_16 = intval == '15 min' ? '15' : iff_15
iff_17 = intval == '10 min' ? '10' : iff_16
int_1 = intval == '5 min' ? '5' : iff_17
int_1
res = ures ? getRez(reso) : timeframe.period
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
_resInMinutes
// ————— Returns the float minutes value of the string _res.
f_tfResInMinutes(_res) =>
// _res: resolution of any TF (in "timeframe.period" string format).
// Dependency: f_resInMinutes().
request.security(syminfo.tickerid, _res, f_resInMinutes())
// —————————— Determine if current timeframe is smaller that higher timeframe selected in Inputs.
// Get higher timeframe in minutes.
higherTfInMinutes = f_tfResInMinutes(res)
// Get current timeframe in minutes.
currentTfInMinutes = f_resInMinutes()
// Compare current TF to higher TF to make sure it is smaller, otherwise our plots don't make sense.
chartOnLowerTf = currentTfInMinutes <= higherTfInMinutes
mtf(data) =>
chartOnLowerTf ? request.security(syminfo.tickerid, res, data) : data
st(len) =>
(close - ta.lowest(low, len)) / (ta.highest(high, len) - ta.lowest(low, len))
x = ta.stoch(close, high, low, len) * 0.01
x2 = ta.sma(x, smooth)
x3 = ta.sma(x2, D)
C(level, len, smooth) =>
if smooth == 1
C = (ta.highest(high, len) - ta.lowest(low, len)) * level + ta.lowest(low, len)
C
else
sum = 0.0
for i = 1 to smooth - 1 by 1
sum := x[i] + sum
sum
a = smooth * level - sum
C = a * (ta.highest(high, len) - ta.lowest(low, len)) + ta.lowest(low, len)
C
C2(len, smooth) =>
float sumK = 0
for i = 1 to smooth - 1 by 1
sumK += x[i]
sumK
float sumKS = 0
for i = 1 to D - 1 by 1
sumKS += x2[i]
sumKS
C2 = (sumKS * smooth + sumK - sumK * D) * (ta.highest(high, len) - ta.lowest(low, len)) / (D - 1) + ta.lowest(low, len)
C2
Cf(level, len, smooth) =>
if smooth == 1
Cf = (ta.highest(high, len) - ta.lowest(low, len)) * level + ta.lowest(low, len)
Cf
else
sum = 0.0
for i = 0 to smooth - 2 by 1
sum := x[i] + sum
sum
a = smooth * level - sum
Cf = a * (ta.highest(high, len - 1) - ta.lowest(low, len - 1)) + ta.lowest(low, len - 1)
Cf
stp(len) =>
(close - ta.lowest(low, len - 1)) / (ta.highest(high, len - 1) - ta.lowest(low, len - 1))
kk = ta.stoch(close, high, low, len) * 0.01
X = stp(len)
xk = 100 * ta.sma(kk, smooth)
k1(len) =>
sum = 0.0
for i = 0 to len - 2 by 1
sum := kk[i] + sum
mean = (sum + X) / len
mean
X2 = 100 * k1(smooth)
d1(len) =>
sum = 0.0
for i = 0 to len - 2 by 1
sum := xk[i] + sum
sum
mean = (sum + X2) / len
mean
x3p = d1(D) * 0.01
ccks = mtf(ss(C(x3, len, smooth), slen))
cck = mtf(C(x3, len, smooth))
ccks2 = mtf(ss(C2(len, smooth), slen))
cck2 = mtf(C2(len, smooth))
cfks = mtf(ss(Cf(x3p, len, smooth), slen))
cfk = mtf(Cf(x3p, len, smooth))
stochk = mtf(x)
stochks = mtf(x2)
stochd = mtf(x3)
highmtf = mtf(ta.highest(high, len))
lowmtf = mtf(ta.lowest(low, len))
//Highest and Lowest K you can get on current Bar
sumk = 0.0
for i = 1 to smooth - 1 by 1
sumk := stochk[i] + sumk
sumk
hk = (1 + sumk) / smooth
lk = sumk / smooth
//Highest D and Lowest D you can get on current Bar
sumd = 0.0
for i = 1 to D - 1 by 1
sumd := stochks[i] + sumd
sumd
hd = (hk + sumd) / D
ld = (lk + sumd) / D
//Impossible Cross Situation
ip = stochks < stochd and cck2 > highmtf and hd > hk or stochks > stochd and cck2 < lowmtf and hd < hk ? 1 : 0
float Cross = na
if E == 'Current Dynamic KD' // Close one day ago
Cross := sm ? ccks : cck
Cross
if E == 'Current Static KD'
Cross := sm ? ccks2 : cck2
Cross
if E == 'Forecasted KD'
Cross := sm ? cfks : cfk
Cross
Round(_val, _decimals) =>
// Rounds _val to _decimals places.
_p = math.pow(10, _decimals)
math.round(math.abs(_val) * _p) / _p * math.sign(_val)
cob = mtf(C(0.01 * ob, len, smooth))
fob = mtf(Cf(0.01 * ob, len, smooth))
cos = mtf(C(0.01 * os, len, smooth))
fos = mtf(Cf(0.01 * os, len, smooth))
float obp = na
if E == 'Current Dynamic KD' or E == 'Current Static KD'
obp := cob
obp
if E == 'Forecasted KD'
obp := fob
obp
float osp = na
if E == 'Current Dynamic KD' or E == 'Current Static KD'
osp := cos
osp
if E == 'Forecasted KD'
osp := fos
osp
Co = close[1] > Cross[1] ? color.aqua : color.fuchsia
US = close > Cross and close[1] < Cross[1] ? Cross : na
UD = close < Cross and close[1] > Cross[1] ? Cross : na
lable(P, T, s, color_PnL) => // show_panel
label PnL_Label = na
PnL_Label := label.new(bar_index, 50, text=T, color=color_PnL, textcolor=color.white, style=s, yloc=yloc.price, xloc=xloc.bar_index, size=size.small)
PnL_Label
lable1(P, T, s, color_PnL) => // show_panel
label PnL_Label = na
PnL_Label := label.new(bar_index, 50, text=T, color=color_PnL, textcolor=color.white, style=s, yloc=yloc.price, xloc=xloc.bar_index, size=size.normal)
label.delete(PnL_Label[1])
ab = Cross > close
labelstyle = label.style_label_left
lbg = ib ? color.new(#000000, 45) : color.new(#000000, 99)
ud() =>
if mtf(x3) > mtf(x2)
'UP'
else
'DOWN'
bslabel() =>
bs ? '\n' + '\n' + 'OverBought : ' + str.tostring(Round(obp, dec)) + '\n' + '\n' + 'OverSold : ' + str.tostring(Round(osp, dec)) : na
float obl = na
if BL == 'Line Levels'
obl := obp
obl
else
na
float osl = na
if BL == 'Line Levels'
osl := osp
osl
else
na
float obb = na
if BL == 'Bands'
obb := obp
obb
else
na
float osb = na
if BL == 'Bands'
osb := osp
osb
else
na
lb() =>
float lb = na
if barstate.islast
lb := obl
lb
else
na
ls() =>
float ls = na
if barstate.islast
ls := osl
ls
else
na
tf() =>
if not ures or not chartOnLowerTf
''
else
reso
if p
lable1(Cross, tf() + ' Stoch Crossing ' + ud() + ' Price: ' + str.tostring(Round(Cross, dec)) + bslabel(), labelstyle, lbg)
if plb and BL == 'Line Levels'
B = line.new(nz(bar_index[1], 0), obl, bar_index, obl, extend=extend.both, width=1, color=color.new(#00C0FFff, 0), style=line.style_dotted)
line.delete(B[1])
if pls and BL == 'Line Levels'
S = line.new(nz(bar_index[1], 0), osl, bar_index, osl, extend=extend.both, width=1, color=color.new(#FF0080ff, 0), style=line.style_dotted)
line.delete(S[1])
k = ta.sma(ta.stoch(mtf(close), mtf(high), mtf(low), len), smooth)
d = ta.sma(k, D)
plot(k, title='%K', color=color.new(#2962FF, 0))
plot(d, title='%D', color=color.new(#FF6D00, 0))
h0 = hline(80, 'Upper Band', color=#787B86)
h1 = hline(20, 'Lower Band', color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title='Background')
|
Kabalistic 36/72 SMA | https://www.tradingview.com/script/SLV8bqIE-Kabalistic-36-72-SMA/ | Daimonik | https://www.tradingview.com/u/Daimonik/ | 18 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Daimonik
//@version=5
indicator("Kabalistic 36/72 SMA", overlay=true)
averageData = input.source (close, title= "Average data source")
shortlength = input.int (36, title= "Short Average Length")
longlength= input.int (72, title= "Long Average Length")
shortAverage = ta.sma(averageData, shortlength)
longAverage = ta.sma(averageData, longlength)
plot(shortAverage, color= color.blue, title= "Short SMA")
plot(longAverage, color= color.yellow, title= "Long SMA" )
crossAbove = ta.crossover(shortAverage, longAverage)
crossUnder = ta.crossunder(shortAverage, longAverage)
crossColour = if crossUnder
color.new(color.red, 70)
else if crossAbove
color.new(color.green, 70)
bgcolor(crossColour, title= "Crosses Background")
|
Adaptivity: Measures of Dominant Cycles and Price Trend [Loxx] | https://www.tradingview.com/script/55t2itvF-Adaptivity-Measures-of-Dominant-Cycles-and-Price-Trend-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 81 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator('Adaptivity: Measures of Dominant Cycles and Price Trend [Loxx]', shorttitle = "AMDCPT [Loxx]", overlay = false, max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
bluecolor = #042dd2
purplecolor = #a904d2
auto_src = input.source(close, title='Auto Source', group = "Dominant Cycle: Autocorrelation Periodogram")
auto_min = input.int(8, minval = 1, title='Auto Min Length', group = "Dominant Cycle: Autocorrelation Periodogram")
auto_max = input.int(48, minval = 1, title='Auto Max Length', group = "Dominant Cycle: Autocorrelation Periodogram")
auto_avg = input.int(3, minval = 1, title='Auto Average Length', group = "Dominant Cycle: Autocorrelation Periodogram")
hilbert_src = input.source(hl2, title='Hilbert Source', group = "Dominant Cycle: Hilbert Period")
hilbert_len = input.int(7, title='Hilbert Length', minval=1, group = "Dominant Cycle: Hilbert Period")
hilbert_alpha = input.float(0.07, title = "Hilbert Alpha", step = 0.01, group = "Dominant Cycle: Hilbert Period")
instant_src = input.source(hl2, title='Instant Source', group = "Dominant Cycle: Instantaneous")
instant_min_len = input.int(8, title='Instant Min Length', minval=1, group = "Dominant Cycle: Instantaneous")
instant_max_len = input.int(48, title='Instant Max Length', minval=1, group = "Dominant Cycle: Instantaneous")
bp_period = input.int(20, "Band-pass Period", minval = 1, group = "Dominant Cycle: Band-pass")
Bandwidth = input.float(0.70, "Band-pass Width", step = 0.1, group = "Dominant Cycle: Band-pass")
LPPeriod = input(20, title='LP Period', group = "Dominant Cycle: Hilbert Dual Differentiator")
min_len_input = input.int(8, title='Min Length', group = "Dominant Cycle: Hilbert Dual Differentiator")
max_len_input = input.int(48, title='Max Length', group = "Dominant Cycle: Hilbert Dual Differentiator")
cfb_src = input.source(hlcc4, "Source", group = "Price Trend Adaptive: Composite Fractal Behavior Settings")
cfb_len = input.int(10, "CFB Depth", maxval = 10, group = "Price Trend Adaptive: Composite Fractal Behavior Settings")
cfb_smth = input.int(8, "CFB Smooth Length", group = "Price Trend Adaptive: Composite Fractal Behavior Settings")
cfb_jper = input.int(5, "Juirk Fitler Smoothing Period", group = "Price Trend Adaptive: Composite Fractal Behavior Settings")
cfb_phs = input.float(0.0, "Jurik Filter Phase", group = "Price Trend Adaptive: Composite Fractal Behavior Settings")
_a_jurik_filt(src, len, phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jma = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
_jcfbaux(src, depth)=>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = depth - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
_jcfb(src, len, smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, _jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
_hilber_dual(len_in, min_len, max_len) =>
alpha1 = 0.00
HP = 0.00
a1 = 0.00
b1 = 0.00
c1 = 0.00
c2 = 0.00
c3 = 0.00
Filt = 0.00
QFilt = 0.00
Real = 0.00
Quad = 0.00
Imag = 0.00
IPeak = 0.00
QPeak = 0.00
IDot = 0.00
QDot = 0.00
Period = 0.00
DomCycle = 0.00
alpha1 := (math.cos(0.707 * 2 * math.pi / max_len) + math.sin(0.707 * 2 * math.pi / max_len) - 1) / math.cos(0.707 * 2 * math.pi / max_len)
HP := (1 - alpha1 / 2) * (1 - alpha1 / 2) * (close - 2 * close[1] + close[2]) + 2 * (1 - alpha1) * nz(HP[1]) - (1 - alpha1) * (1 - alpha1) * nz(HP[2])
a1 := math.exp(-math.sqrt(2) * math.pi / LPPeriod)
b1 := 2 * a1 * math.cos(math.sqrt(2) * math.pi / LPPeriod)
c2 := b1
c3 := -a1 * a1
c1 := 1 - c2 - c3
Filt := c1 * (HP + nz(HP[1])) / 2 + c2 * nz(Filt[1]) + c3 * nz(Filt[2])
IPeak := 0.991 * nz(IPeak[1])
IPeak := math.abs(Filt) > IPeak ? math.abs(Filt) : IPeak
Real := Filt / IPeak
Quad := Real - nz(Real[1])
QPeak := 0.991 * nz(QPeak[1])
QPeak := math.abs(Quad) > QPeak ? math.abs(Quad) : QPeak
Imag := Quad / QPeak
IDot := Real - nz(Real[1])
QDot := Imag - nz(Imag[1])
Period := Real * QDot - Imag * IDot != 0 ? 2 * math.pi * (Real * Real + Imag * Imag) / (-Real * QDot + Imag * IDot) : Period
Period := math.min(math.max(Period, min_len), max_len)
DomCycle := c1 * (Period + nz(Period[1])) / 2 + c2 * nz(DomCycle[1]) + c3 * nz(DomCycle[2])
DomCycle
_corrrelation(x, y, len) =>
lenMinusOne = len - 1
meanx = 0.0, meany = 0.0
for i=0.0 to lenMinusOne
meanx := meanx + nz(x[i])
meany := meany + nz(y[i])
meanx := meanx / len
meany := meany / len
sumxy=0.0, sumx=0.0, sumy=0.0
for i=0 to lenMinusOne
sumxy := sumxy + (nz(x[i]) - meanx) * (nz(y[i]) - meany)
sumx := sumx + math.pow(nz(x[i]) - meanx, 2)
sumy := sumy + math.pow(nz(y[i]) - meany, 2)
sumxy / math.sqrt(sumy * sumx)
_cycleit(src, len, alpha) =>
instPeriod = 0.0
smooth = (src + 2 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 6
cycle = 0.0
cycle := bar_index < 7 ? (src - 2 * nz(src[1]) + nz(src[2])) / 4 :
(1 - .5*alpha)*(1 - .5*alpha)*(smooth - 2*smooth[1] + smooth[2]) + 2*(1 - alpha)*cycle[1] - (1 - alpha)*(1 - alpha)*cycle[2]
q1 = (0.0962 * cycle + 0.5769 * nz(cycle[2]) - 0.5769 * nz(cycle[4]) - 0.0962 * nz(cycle[6])) * (0.5 + 0.08 * nz(instPeriod[1]))
i1 = nz(cycle[3])
deltaPhase = q1 != 0 and nz(q1[1]) != 0 ? (i1 / q1 - nz(i1[1]) / nz(q1[1])) / (1 + i1 * nz(i1[1]) / (q1 * nz(q1[1]))) : 0
deltaPhase := math.min(math.max(deltaPhase, 0.1), 1.1)
medianDelta = ta.percentile_nearest_rank(deltaPhase, len, 50)
dc = medianDelta != 0 ? math.pi*2 / medianDelta + 0.5 : 15
instPeriod := 0.33 * dc + 0.67 * nz(instPeriod[1])
period = 0.0
period := 0.15 * instPeriod + 0.85 * nz(period[1])
number = math.round(math.floor(ta.wma(period, 4)))
number
_f_hp(_src, max_len) =>
var c = 360 * math.pi / 180
_alpha = (1 - math.sin(c / max_len)) / math.cos(c / max_len)
_hp = 0.0
_hp := 0.5 * (1 + _alpha) * (_src - nz(_src[1])) + _alpha * nz(_hp[1])
_hp
_f_ess(_src, _len) =>
var s = math.sqrt(2)
_a = math.exp(-s * math.pi / _len)
_b = 2 * _a * math.cos(s * math.pi / _len)
_c2 = _b
_c3 = -_a * _a
_c1 = 1 - _c2 - _c3
_out = 0.0
_out := _c1 * (_src + nz(_src[1])) / 2 + _c2 * nz(_out[1], nz(_src[1], _src)) + _c3 * nz(_out[2], nz(_src[2], nz(_src[1], _src)))
_out
_auto_dom(src, min_len, max_len, ave_len) =>
var c = 2 * math.pi
var s = math.sqrt(2)
avglen = ave_len
filt = _f_ess(_f_hp(src, max_len), min_len)
arr_size = max_len * 2
var corr = array.new_float(arr_size, initial_value=0)
var cospart = array.new_float(arr_size, initial_value=0)
var sinpart = array.new_float(arr_size, initial_value=0)
var sqsum = array.new_float(arr_size, initial_value=0)
var r1 = array.new_float(arr_size, initial_value=0)
var r2 = array.new_float(arr_size, initial_value=0)
var pwr = array.new_float(arr_size, initial_value=0)
for lag = 0 to max_len by 1
m = avglen == 0 ? lag : avglen
Sx = 0.0
Sy = 0.0
Sxx = 0.0
Syy = 0.0
Sxy = 0.0
for i = 0 to m - 1 by 1
x = nz(filt[i])
y = nz(filt[lag + i])
Sx += x
Sy += y
Sxx += x * x
Sxy += x * y
Syy += y * y
Syy
if (m * Sxx - Sx * Sx) * (m * Syy - Sy * Sy) > 0
array.set(corr, lag, (m * Sxy - Sx * Sy) / math.sqrt((m * Sxx - Sx * Sx) * (m * Syy - Sy * Sy)))
for period = min_len to max_len by 1
array.set(cospart, period, 0)
array.set(sinpart, period, 0)
for n = ave_len to max_len by 1
array.set(cospart, period, nz(array.get(cospart, period)) + nz(array.get(corr, n)) * math.cos(c * n / period))
array.set(sinpart, period, nz(array.get(sinpart, period)) + nz(array.get(corr, n)) * math.sin(c * n / period))
array.set(sqsum, period, math.pow(nz(array.get(cospart, period)), 2) + math.pow(nz(array.get(sinpart, period)), 2))
for period = min_len to max_len by 1
array.set(r2, period, nz(array.get(r1, period)))
array.set(r1, period, 0.2 * math.pow(nz(array.get(sqsum, period)), 2) + 0.8 * nz(array.get(r2, period)))
maxpwr = 0.0
for period = min_len to max_len by 1
if nz(array.get(r1, period)) > maxpwr
maxpwr := nz(array.get(r1, period))
for period = ave_len to max_len by 1
array.set(pwr, period, nz(array.get(r1, period)) / maxpwr)
dominantcycle = 0.0
peakpwr = 0.0
for period = min_len to max_len by 1
if nz(array.get(pwr, period)) > peakpwr
peakpwr := nz(array.get(pwr, period))
spx = 0.0
sp = 0.0
for period = min_len to max_len by 1
if peakpwr >= 0.25 and nz(array.get(pwr, period)) >= 0.25
spx += period * nz(array.get(pwr, period))
sp += nz(array.get(pwr, period))
if sp != 0
dominantcycle := spx / sp
if sp < 0.25
dominantcycle := dominantcycle[1]
if dominantcycle < 1
dominantcycle := 1
dom_in = math.min(math.max(dominantcycle, min_len), max_len)
dom_in
_instant_cycle(src, llen, hlen) =>
v1 = src - nz(src[llen])
ip = 0.0
ip := 1.25 * (nz(v1[4]) - 0.635 * nz(v1[2])) + 0.635 * nz(ip[3])
qu = 0.0
qu := nz(v1[2]) - 0.338 * v1 + 0.338 * nz(qu[2])
phase = math.abs(ip + nz(ip[1])) > 0 ? math.atan(math.abs((qu + nz(qu[1])) / (ip + nz(ip[1])))) * 180 / math.pi : 0
phase := ip < 0 and qu > 0 ? 180 - phase : phase
phase := ip < 0 and qu < 0 ? 180 + phase : phase
phase := ip > 0 and qu < 0 ? 360 - phase : phase
dPhase = nz(phase[1]) - phase
dPhase := nz(phase[1]) < 90 and phase > 270 ? 360 + nz(phase[1]) - phase : dPhase
dPhase := math.max(math.min(60, dPhase), 1)
instPeriod = 0.0
v4 = 0.0
for i = 0 to hlen by 1
v4 += nz(dPhase[i])
if v4 > 360 and instPeriod == 0
instPeriod := i
instPeriod
dcPeriod = 0.0
dcPeriod := 0.25 * instPeriod + 0.75 * nz(dcPeriod[1])
dom_in = math.min(math.max(dcPeriod, llen), hlen)
dom_in
_bpDom(len, bpw) =>
HP = 0.0
BP = 0.0
Peak = 0.0
Real = 0.0
counter = 0.0
DC = 0.0
alpha2 = (math.cos(0.25 * bpw * 2 * math.pi / len) + math.sin(0.25 * bpw * 2 * math.pi / len) - 1) / math.cos(0.25 * bpw * 2 * math.pi / len)
HP := (1 + alpha2 / 2) * (close - nz(close[1])) + (1 - alpha2) * nz(HP[1])
beta1 = math.cos(2 * math.pi / len)
gamma1 = 1 / math.cos(2 * math.pi * bpw / len)
alpha1 = gamma1 - math.sqrt(gamma1 * gamma1 - 1)
BP := 0.5 * (1 - alpha1) * (HP - nz(HP[2])) + beta1 * (1 + alpha1) * nz(BP[1]) - alpha1 * nz(BP[2])
BP := bar_index == 1 or bar_index == 2 ? 0 : BP
Peak := 0.991 * Peak
Peak := math.abs(BP) > Peak ? math.abs(BP) : Peak
Real := Peak != 0 ? BP / Peak : Real
DC := nz(DC[1])
DC := DC < 6 ? 6 : DC
counter := counter[1] + 1
if ta.crossover(Real, 0) or ta.crossunder(Real, 0)
DC := 2 * counter
if 2 * counter > 1.25 * nz(DC[1])
DC := 1.25 * DC[1]
if 2 * counter < 0.8 * nz(DC[1])
DC := 0.8 * nz(DC[1])
counter := 0
DC
auto = _auto_dom(auto_src, auto_min, auto_max, auto_avg)
auto := math.floor(auto) < 1 ? 1 : math.floor(auto)
instant = _instant_cycle(instant_src, instant_min_len, instant_max_len)
instant := math.floor(instant) < 1 ? 1 : math.floor(instant)
hilbert = _cycleit(hilbert_src, hilbert_len, hilbert_alpha)
hilbert := math.floor(hilbert) < 1 ? 1 : math.floor(hilbert)
band = _bpDom(bp_period, Bandwidth)
band := math.floor(band) < 1 ? 1 : math.floor(band)
hilbert_dd = _hilber_dual(LPPeriod, min_len_input, max_len_input)
hilbert_dd := math.floor(hilbert_dd) < 1 ? 1 : math.floor(hilbert_dd)
cfb_out = _a_jurik_filt(_a_jurik_filt(_jcfb(cfb_src, cfb_len, cfb_smth), cfb_jper, cfb_phs), cfb_jper, cfb_phs)
cfb_out := math.ceil(cfb_out) < 1 ? 1 : math.ceil(cfb_out)
plot(auto, "Ehlers - Autocorrelation Periodogram Cycle", color = greencolor, linewidth = 2)
plot(instant, "Ehlers - Instantaneous Cycle", color = redcolor, linewidth = 2)
plot(hilbert, "Ehlers - Hilbert Cycle", color = bluecolor, linewidth = 2)
plot(band, "Ehlers - Band-pass Cycle", color = color.yellow, linewidth = 2)
plot(hilbert_dd, "Ehlers - Hilber Dual Differentiator Cycle", color = purplecolor, linewidth = 2)
plot(cfb_out, "Jurik - Composite Fractal Behavior PA Timeframe", color = color.orange, linewidth = 2)
|
Jurik CFB Adaptive, Elder Force Index w/ ATR Channels [Loxx] | https://www.tradingview.com/script/vr0yG3GI-Jurik-CFB-Adaptive-Elder-Force-Index-w-ATR-Channels-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 102 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator(title='Jurik CFB Adaptive, Elder Force Index w/ ATR Channels [Loxx]', shorttitle='JCFAEFIATR [Loxx]', format=format.volume, timeframe="", timeframe_gaps=true, max_bars_back = 5000)
RMA(src,p) =>
ema = 0.
sf = 1/p
ema := nz(ema[1] + sf*(src - ema[1]),src)
EMA(src,p) =>
ema = 0.
sf = 2/(p+1)
ema := nz(ema[1] + sf*(src - ema[1]),src)
_a_jurik_filt(src, len, phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jma = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
_jcfbaux(src, depth)=>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = depth - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
_jcfb(src, len, smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, _jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
//inputs
src = input.source(close, title = "Source", group = "Basic Settings")
calc_type = input.string("Fixed", title = "Calculation Type", options =["Fixed", "Composite Fractal Behavior Adaptive"], group = "Basic Settings")
len = input.int(13, title = "Fixed EFI Period", group = "Fixed Settings")
slen = input.int(21, title='Fixed Signal Period', group = "Fixed Settings")
atr_sm = input.int(21, title ="Fixed ATR Smoothing Length", group = "Fixed Settings")
cfb_src = input.source(hlcc4, "CFB Source", group = "Basic CFB Ingest Settings")
fast_nlen = input.int(25, "Fast CFB Normal Length", minval = 1, group = "Fast CFB Ingest Settings")
fast_cfb_len = input.int(10, "Fast CFB Depth", maxval = 10, group = "Fast CFB Ingest Settings")
fast_smth = input.int(7, "Fast CFB Smooth Length", minval = 1, group = "Fast CFB Ingest Settings")
fast_slim = input.int(4, "Fast CFB Short Limit", minval = 1, group = "Fast CFB Ingest Settings")
fast_llim = input.int(15, "Fast CFB Long Limit", minval = 1, group = "Fast CFB Ingest Settings")
fast_jcfbsmlen = input.int(7, "Fast CFB Jurik Smooth Length", minval = 1, group = "Fast CFB Ingest Settings")
fast_jcfbsmph = input.float(0, "Fast CFB Jurik Smooth Phase", group = "Fast CFB Ingest Settings")
slow_nlen = input.int(25, "Slow CFB Normal Length", minval = 1, group = "Slow CFB Ingest Settings")
slow_cfb_len = input.int(10, "Slow CFB Depth", maxval = 10, group = "Slow CFB Ingest Settings")
slow_smth = input.int(7, "Slow CFB Smooth Length", minval = 1, group = "Slow CFB Ingest Settings")
slow_slim = input.int(15, "Slow CFB Short Limit", minval = 1, group = "Slow CFB Ingest Settings")
slow_llim = input.int(30, "Slow CFB Long Limit", minval = 1, group = "Slow CFB Ingest Settings")
slow_jcfbsmlen = input.int(7, "Slow CFB Jurik Smooth Length", minval = 1, group = "Slow CFB Ingest Settings")
slow_jcfbsmph = input.float(0, "Slow CFB Jurik Smooth Phase", group = "Slow CFB Ingest Settings")
fast_cfb_draft = _jcfb(cfb_src, fast_cfb_len, fast_smth)
fast_cfb_pre = _a_jurik_filt(_a_jurik_filt(fast_cfb_draft, fast_jcfbsmlen, fast_jcfbsmph), fast_jcfbsmlen, fast_jcfbsmph)
fast_max = ta.highest(fast_cfb_pre, fast_nlen)
fast_min = ta.lowest(fast_cfb_pre, fast_nlen)
fast_denom = fast_max - fast_min
fast_ratio = (fast_denom > 0) ? (fast_cfb_pre - fast_min) / fast_denom : 0.5
fast_len_out_cfb = math.ceil(fast_slim + fast_ratio * (fast_llim - fast_slim))
slow_cfb_draft = _jcfb(cfb_src, slow_cfb_len, slow_smth)
slow_cfb_pre = _a_jurik_filt(_a_jurik_filt(slow_cfb_draft, slow_jcfbsmlen, slow_jcfbsmph), slow_jcfbsmlen, slow_jcfbsmph)
slow_max = ta.highest(slow_cfb_pre, slow_nlen)
slow_min = ta.lowest(slow_cfb_pre, slow_nlen)
slow_denom = slow_max - slow_min
slow_ratio = (slow_denom > 0) ? (slow_cfb_pre - slow_min) / slow_denom : 0.5
slow_len_out_cfb = math.ceil(slow_slim + slow_ratio * (slow_llim - slow_slim))
len_out_fast = int(fast_len_out_cfb) < 1 ? 1 : int(fast_len_out_cfb)
len_out_slow = int(slow_len_out_cfb) < 1 ? 1 : int(slow_len_out_cfb)
atr_mult1 = input.int(1, title = "ATR Mult Level 1", group = "ATR Multipliers")
atr_mult2 = input.int(2, title = "ATR Mult Level 2", group = "ATR Multipliers")
atr_mult3 = input.int(3, title = "ATR Mult Level 3", group = "ATR Multipliers")
trunc_atr = input.bool(true, title = "Truncate over ATR Mult Level 4?", group = "UI Options")
efi = EMA(ta.change(close) * volume, calc_type == "Fixed" ? len : len_out_fast)
sig = EMA(efi, calc_type == "Fixed" ? len : len_out_slow)
atr_ema = math.abs(efi[1] - efi)
atr_out = RMA(atr_ema, calc_type == "Fixed" ? len : len_out_slow)
//atr channel calc
atr_high1 = sig + atr_out * atr_mult1
atr_low1 = sig - atr_out * atr_mult1
atr_high2= sig + atr_out * atr_mult2
atr_low2 = sig - atr_out * atr_mult2
atr_high3 = sig + atr_out * atr_mult3
atr_low3 = sig - atr_out * atr_mult3
atr_obhigh = sig + atr_out * (atr_mult3 + 1)
atr_oblow = sig - atr_out * (atr_mult3 + 1)
efi_out = trunc_atr ? efi > atr_obhigh ? atr_high3 : efi < atr_oblow ? atr_low3 : efi : efi
//plot atr channels
plot(atr_high1, color = bar_index % 2 == 0 ? na : color.new(color.gray, 30), linewidth = 1, title = "ATR1 High")
plot(atr_high2, color = bar_index % 4 == 0 ? na : color.new(color.gray, 30), linewidth = 1, title = "ATR2 High")
plot(atr_high3, color = color.new(color.gray, 30), linewidth = 2, title = "ATR3 High")
plot(atr_low1, color = bar_index % 2 == 0 ? na : color.new(color.gray, 30), linewidth = 1, title = "ATR1 Low")
plot(atr_low2, color = bar_index % 4 == 0 ? na : color.new(color.gray, 30), linewidth = 1, title = "ATR2 Low")
plot(atr_low3, color = color.new(color.gray, 30), linewidth = 2, title = "ATR3 Low")
//plot main
plot(0, color=color.gray, style = plot.style_circles, title='Zero Line', linewidth = 2)
plot(sig, color=color.new(color.white, 0), title='Signal', linewidth = 2)
plot(efi_out, color = #4f6cdf, title='EFI', linewidth = 2)
//plot shapes
plot(efi_out >= atr_high3 ? efi_out : na, style = plot.style_circles, linewidth = 3, color = #D2042D, title = "Over ATR4 High")
plot(efi_out <= atr_low3 ? efi_out : na, style = plot.style_circles, linewidth = 3, color = #2DD204, title = "Over ATR4 Low")
|
Adaptive, One More Moving Average (OMA) [Loxx] | https://www.tradingview.com/script/fOPPg0kz-Adaptive-One-More-Moving-Average-OMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 61 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Adaptive, One More Moving Average (OMA) [Loxx]", shorttitle="AOMA [Loxx]", timeframe="", timeframe_gaps=true, overlay = true)
greencolor = #2DD204
redcolor = #D2042D
//speed 0.5 - T3 (0.618 Tilson)
//sspeed 2.5 - T3 (0.618 Fulks/Matulich)
//sspeed 1 - SMA, harmonic mean
//sspeed 2 - LWMA
//sspeed 7 - very similar to Hull and TEMA
//sspeed 8 - very similar to LSMA and Linear regression value
src = input.source(close, "Source")
len = input.int(26, "Average Period", minval = 1)
const = input.float(1.0, "Speed", step = .01)
adapt = input.bool(true, "Make it adapotive?")
colorbars = input.bool(false, "Color bars?")
_oma(src, len, const, adapt) =>
e1 = nz(src[1]), e2 = nz(src[1]), e3 = nz(src[1])
e4 = nz(src[1]), e5 = nz(src[1]), e6 = nz(src[1])
averagePeriod = len
noise = 0.00000000001
minPeriod = averagePeriod/2.0
maxPeriod = minPeriod*5.0
endPeriod = math.ceil(maxPeriod)
signal = math.abs(src - nz(src[endPeriod]))
if adapt
for k = 1 to endPeriod
noise += math.abs(src - nz(src[k]))
averagePeriod := math.ceil(((signal / noise) * (maxPeriod - minPeriod)) + minPeriod)
alpha = (2.0 + const) / (1.0 + const + averagePeriod)
e1 := nz(e1[1] + alpha * (src - e1[1]), src)
e2 := nz(e2[1] + alpha * (e1 - e2[1]), e1)
v1 = 1.5 * e1 - 0.5 * e2
e3 := nz(e3[1] + alpha * (v1 - e3[1]), v1)
e4 := nz(e4[1] + alpha * (e3 - e4[1]), e3)
v2 = 1.5 * e3 - 0.5 * e4
e5 := nz(e5[1] + alpha * (v2 - e5[1]), v2)
e6 := nz(e6[1] + alpha * (e5 - e6[1]), e5)
v3 = 1.5 * e5 - 0.5 * e6
v3
out = _oma(src, len, const, adapt)
plot(out, color = src >= out ? greencolor : redcolor, linewidth = 3)
barcolor(colorbars ? src >= out ? greencolor : redcolor : na)
|
swami_money_flow | https://www.tradingview.com/script/1QxaqrRj-swami-money-flow/ | palitoj_endthen | https://www.tradingview.com/u/palitoj_endthen/ | 93 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © palitoj_endthen
//@version=5
indicator(title= 'swami_chart_money_flow', shorttitle = 'swami_money_flow', format = format.price, precision = 2, overlay = false)
// Money flow
var cum_vol = 0.0
cum_vol += nz(volume)
if barstate.islast and cum_vol == 0
runtime.error('No volume is provided by the data vendor')
mf(length)=>
average_day = close == high and close == low or high == low ? 0 : ((((close - low) - (high - close)) / (high - low))*volume)
cmf = math.sum(average_day, length)/math.sum(volume, length)
smooth = (4*cmf + 3*cmf[1] + 2*cmf[2] + cmf[3])/10
mf1 = mf(1)
mf2 = mf(2)
mf3 = mf(3)
mf4 = mf(4)
mf5 = mf(5)
mf6 = mf(6)
mf7 = mf(7)
mf8 = mf(8)
mf9 = mf(9)
mf10 = mf(10)
mf11 = mf(11)
mf12 = mf(12)
mf13 = mf(13)
mf14 = mf(14)
mf15 = mf(15)
mf16 = mf(16)
mf17 = mf(17)
mf18 = mf(18)
mf19 = mf(19)
mf20 = mf(20)
mf21 = mf(21)
mf22 = mf(22)
mf23 = mf(23)
mf24 = mf(24)
mf25 = mf(25)
mf26 = mf(26)
mf27 = mf(27)
mf28 = mf(28)
mf29 = mf(29)
mf30 = mf(30)
// Color
col(x) => x < -0.6 ? #680000 :
x > -0.6 and x < -0.56 ? #750000 :
x > -0.56 and x < -0.52 ? #840000 :
x > -0.52 and x < -0.48 ? #9B0000 :
x > -0.48 and x < -0.44 ? #B70000 :
x > -0.44 and x < -0.4 ? #CB0000 :
x > -0.4 and x < -0.36 ? #DB0000 :
x > -0.36 and x < -0.32 ? #EC0000 :
x > -0.32 and x < -0.28 ? #FA0000 :
x > -0.28 and x < -0.24 ? #DA3300 :
x > -0.24 and x < -0.2 ? #E83600 :
x > -0.2 and x < -0.16 ? #F23800 :
x > -0.16 and x < -0.12 ? #FF3C00 :
x > -0.12 and x < -0.08 ? #E45300 :
x > -0.08 and x < -0.04 ? #EE5700 :
x > -0.04 and x < 0 ? #FF5E00 :
x > 0 and x < 0.04 ? #FF9A00 :
x > 0.04 and x < 0.08 ? #FFCD00 :
x > 0.08 and x < 0.12 ? #D5FF00 :
x > 0.12 and x < 0.16 ? #ABFF00 :
x > 0.16 and x < 0.2 ? #66FF00 :
x > 0.2 and x < 0.24 ? #33FF00 :
x > 0.24 and x < 0.28 ? #00FF00 :
x > 0.28 and x < 0.32 ? #00E92F :
x > 0.32 and x < 0.36 ? #00D72B :
x > 0.36 and x < 0.4 ? #009C1F :
x > 0.4 and x < 0.44 ? #008A1C :
x > 0.44 and x < 0.48 ? #007918 :
x > 0.48 and x < 0.52 ? #006614 :
x > 0.52 and x < 0.56 ? #005210 :
#003F0D
// Visualize
p1 = plot(1, color = col(mf1), linewidth = 22)
p2 = plot(2, color = col(mf2), linewidth = 22)
p3 = plot(3, color = col(mf3), linewidth = 22)
p4 = plot(4, color = col(mf4), linewidth = 22)
p5 = plot(5, color = col(mf5), linewidth = 22)
p6 = plot(6, color = col(mf6), linewidth = 22)
p7 = plot(7, color = col(mf7), linewidth = 22)
p8 = plot(8, color = col(mf8), linewidth = 22)
p9 = plot(9, color = col(mf9), linewidth = 22)
p10 = plot(10, color = col(mf10), linewidth = 22)
p11 = plot(11, color = col(mf11), linewidth = 22)
p12 = plot(12, color = col(mf12), linewidth = 22)
p13 = plot(13, color = col(mf13), linewidth = 22)
p14 = plot(14, color = col(mf14), linewidth = 22)
p15 = plot(15, color = col(mf15), linewidth = 22)
p16 = plot(16, color = col(mf16), linewidth = 22)
p17 = plot(17, color = col(mf17), linewidth = 22)
p18 = plot(18, color = col(mf18), linewidth = 22)
p19 = plot(19, color = col(mf19), linewidth = 22)
p20 = plot(20, color = col(mf20), linewidth = 22)
p21 = plot(21, color = col(mf21), linewidth = 22)
p22 = plot(22, color = col(mf22), linewidth = 22)
p23 = plot(23, color = col(mf23), linewidth = 22)
p24 = plot(24, color = col(mf24), linewidth = 22)
p25 = plot(25, color = col(mf25), linewidth = 22)
p26 = plot(26, color = col(mf26), linewidth = 22)
p27 = plot(27, color = col(mf27), linewidth = 22)
p28 = plot(28, color = col(mf28), linewidth = 22)
p29 = plot(29, color = col(mf29), linewidth = 22)
p30 = plot(30, color = col(mf30), linewidth = 22) |
Market Structure Break & Order Block by EmreKb | https://www.tradingview.com/script/DkE7UniD/ | EmreKb | https://www.tradingview.com/u/EmreKb/ | 12,985 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EmreKb
//@version=5
indicator("Market Structure Break & Order Block", "MSB-OB", overlay=true, max_lines_count=500, max_bars_back=4900, max_boxes_count=500)
settings = "Settings"
zigzag_len = input.int(9, "ZigZag Length", group=settings)
show_zigzag = input.bool(true, "Show Zigzag", group=settings)
fib_factor = input.float(0.33, "Fib Factor for breakout confirmation", 0, 1, 0.01, group=settings)
text_size = input.string(size.tiny, "Text Size", [size.tiny, size.small, size.normal, size.large, size.huge], group=settings)
delete_boxes = input.bool(true, "Delete Old/Broken Boxes", group=settings)
bu_ob_inline_color = "Bu-OB Colors"
be_ob_inline_color = "Be-OB Colors"
bu_bb_inline_color = "Bu-BB Colors"
be_bb_inline_color = "Be-BB Colors"
bu_ob_display_settings = "Bu-OB Display Settings"
bu_ob_color = input.color(color.new(color.green, 70), "Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_border_color = input.color(color.green, "Border Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_text_color = input.color(color.green, "Text Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
be_ob_display_settings = "Be-OB Display Settings"
be_ob_color = input.color(color.new(color.red, 70), "Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_border_color = input.color(color.red, "Border Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_text_color = input.color(color.red, "Text Color", group=be_ob_display_settings, inline=be_ob_inline_color)
bu_bb_display_settings = "Bu-BB & Bu-MB Display Settings"
bu_bb_color = input.color(color.new(color.green, 70), "Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_border_color = input.color(color.green, "Border Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_text_color = input.color(color.green, "Text Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
be_bb_display_settings = "Be-BB & Be-MB Display Settings"
be_bb_color = input.color(color.new(color.red, 70), "Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_border_color = input.color(color.red, "Border Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_text_color = input.color(color.red, "Text Color", group=be_bb_display_settings, inline=be_bb_inline_color)
var float[] high_points_arr = array.new_float(5)
var int[] high_index_arr = array.new_int(5)
var float[] low_points_arr = array.new_float(5)
var int[] low_index_arr = array.new_int(5)
var box[] bu_ob_boxes = array.new_box(5)
var box[] be_ob_boxes = array.new_box(5)
var box[] bu_bb_boxes = array.new_box(5)
var box[] be_bb_boxes = array.new_box(5)
to_up = high >= ta.highest(zigzag_len)
to_down = low <= ta.lowest(zigzag_len)
trend = 1
trend := nz(trend[1], 1)
trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend
last_trend_up_since = ta.barssince(to_up[1])
low_val = ta.lowest(nz(last_trend_up_since > 0 ? last_trend_up_since : 1, 1))
low_index = bar_index - ta.barssince(low_val == low)
last_trend_down_since = ta.barssince(to_down[1])
high_val = ta.highest(nz(last_trend_down_since > 0 ? last_trend_down_since : 1, 1))
high_index = bar_index - ta.barssince(high_val == high)
if ta.change(trend) != 0
if trend == 1
array.push(low_points_arr, low_val)
array.push(low_index_arr, low_index)
if trend == -1
array.push(high_points_arr, high_val)
array.push(high_index_arr, high_index)
f_get_high(ind) =>
[array.get(high_points_arr, array.size(high_points_arr) - 1 - ind), array.get(high_index_arr, array.size(high_index_arr) - 1 - ind)]
f_get_low(ind) =>
[array.get(low_points_arr, array.size(low_points_arr) - 1 - ind), array.get(low_index_arr, array.size(low_index_arr) - 1 - ind)]
f_delete_box(box_arr) =>
if delete_boxes
box.delete(array.shift(box_arr))
else
array.shift(box_arr)
0
[h0, h0i] = f_get_high(0)
[h1, h1i] = f_get_high(1)
[l0, l0i] = f_get_low(0)
[l1, l1i] = f_get_low(1)
if ta.change(trend) != 0 and show_zigzag
if trend == 1
line.new(h0i, h0, l0i, l0)
if trend == -1
line.new(l0i, l0, h0i, h0)
market = 1
market := nz(market[1], 1)
// market := market == 1 and close < l0 and low < l0 - math.abs(h0 - l0) * fib_factor ? -1 : market == -1 and close > h0 and high > h0 + math.abs(h0 - l0) * fib_factor ? 1 : market
last_l0 = ta.valuewhen(ta.change(market) != 0, l0, 0)
last_h0 = ta.valuewhen(ta.change(market) != 0, h0, 0)
market := last_l0 == l0 or last_h0 == h0 ? market : market == 1 and l0 < l1 and l0 < l1 - math.abs(h0 - l1) * fib_factor ? -1 : market == -1 and h0 > h1 and h0 > h1 + math.abs(h1 - l0) * fib_factor ? 1 : market
bu_ob_index = bar_index
bu_ob_index := nz(bu_ob_index[1], bar_index)
for i=h1i to l0i[zigzag_len]
index = bar_index - i
if open[index] > close[index]
bu_ob_index := bar_index[index]
bu_ob_since = bar_index - bu_ob_index
be_ob_index = bar_index
be_ob_index := nz(be_ob_index[1], bar_index)
for i=l1i to h0i[zigzag_len]
index = bar_index - i
if open[index] < close[index]
be_ob_index := bar_index[index]
be_ob_since = bar_index - be_ob_index
be_bb_index = bar_index
be_bb_index := nz(be_bb_index[1], bar_index)
for i=h1i - zigzag_len to l1i
index = bar_index - i
if open[index] > close[index]
be_bb_index := bar_index[index]
be_bb_since = bar_index - be_bb_index
bu_bb_index = bar_index
bu_bb_index := nz(bu_bb_index[1], bar_index)
for i=l1i - zigzag_len to h1i
index = bar_index - i
if open[index] < close[index]
bu_bb_index := bar_index[index]
bu_bb_since = bar_index - bu_bb_index
if ta.change(market) != 0
if market == 1
line.new(h1i, h1, h0i, h1, color=color.green, width=2)
label.new(int(math.avg(h1i, l0i)), h1, "MSB", color=color.new(color.black, 100), style=label.style_label_down, textcolor=color.green, size=size.small)
bu_ob = box.new(bu_ob_index, high[bu_ob_since], bar_index + 10, low[bu_ob_since], bgcolor=bu_ob_color, border_color=bu_ob_border_color, text="Bu-OB", text_color=bu_ob_text_color, text_halign=text.align_right, text_size=text_size)
bu_bb = box.new(bu_bb_index, high[bu_bb_since], bar_index + 10, low[bu_bb_since], bgcolor=bu_bb_color, border_color=bu_bb_border_color, text=l0 < l1 ? "Bu-BB" : "Bu-MB", text_color=bu_bb_text_color, text_halign=text.align_right, text_size=text_size)
array.push(bu_ob_boxes, bu_ob)
array.push(bu_bb_boxes, bu_bb)
if market == -1
line.new(l1i, l1, l0i, l1, color=color.red, width=2)
label.new(int(math.avg(l1i, h0i)), l1, "MSB", color=color.new(color.black, 100), style=label.style_label_up, textcolor=color.red, size=size.small)
be_ob = box.new(be_ob_index, high[be_ob_since], bar_index + 10, low[be_ob_since], bgcolor=be_ob_color, border_color=be_ob_border_color, text="Be-OB", text_color=be_ob_text_color, text_halign=text.align_right, text_size=text_size)
be_bb = box.new(be_bb_index, high[be_bb_since], bar_index + 10, low[be_bb_since], bgcolor=be_bb_color, border_color=be_bb_border_color, text=h0 > h1 ? "Be-BB" : "Be-MB", text_color=be_bb_text_color, text_halign=text.align_right, text_size=text_size)
array.push(be_ob_boxes, be_ob)
array.push(be_bb_boxes, be_bb)
for bull_ob in bu_ob_boxes
bottom = box.get_bottom(bull_ob)
top = box.get_top(bull_ob)
if close < bottom
f_delete_box(bu_ob_boxes)
else if close < top
alert("Price in the BU-OB zone")
else
box.set_right(bull_ob, bar_index + 10)
for bear_ob in be_ob_boxes
top = box.get_top(bear_ob)
bottom = box.get_bottom((bear_ob))
if close > top
f_delete_box(be_ob_boxes)
if close > bottom
alert("Price in the BE-OB zone")
else
box.set_right(bear_ob, bar_index + 10)
for bear_bb in be_bb_boxes
top = box.get_top(bear_bb)
bottom = box.get_bottom(bear_bb)
if close > top
f_delete_box(be_bb_boxes)
else if close > bottom
alert("Price in the BE-BB zone")
else
box.set_right(bear_bb, bar_index + 10)
for bull_bb in bu_bb_boxes
bottom = box.get_bottom(bull_bb)
top = box.get_top(bull_bb)
if close < bottom
f_delete_box(bu_bb_boxes)
else if close < top
alert("Price in the BU-BB zone")
else
box.set_right(bull_bb, bar_index + 10)
alertcondition(ta.change(market) != 0, "MSB", "MSB")
|
No-lose trading targets (Based on MFI) By Mustafa ÖZVER | https://www.tradingview.com/script/JBTGDpDI/ | Mustafaozver | https://www.tradingview.com/u/Mustafaozver/ | 312 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mustafaozver
//@version=5
indicator('No-lose trading targets (Based on MFI) By Mustafa ÖZVER', 'NLTT_MFI', overlay=true)
ref = input(hlc3)
var line U_AREA_LINE = na
var line D_AREA_LINE = na
counter_succ = 0
counter_fail = 0
counter_succ := nz(counter_succ[1],0)
counter_fail := nz(counter_fail[1],0)
BUY__AREA = 0
SELL_AREA = 0
// mfi
FPrice = ta.wma(ref, 3)
FVolume = ta.wma(volume, 3)
len = input(17, 'Length')
limit = input(10, 'Limit')
// filteren price and volume calculation
change = ta.change(FPrice) * (FVolume > 0 ? FVolume : 1)
gain = change >= 0 ? change : 0.0
loss = change < 0 ? -1 * change : 0.0
avgGain = ta.rma(gain, len)
avgLoss = ta.rma(loss, len)
rs = avgGain / avgLoss
rsi = 100 - 100 / (1 + rs)
//rsi = mfi(ref)
higherpoint = ta.highest(high, len * 2)
lowerpoint = ta.lowest(low, len * 2)
Rational = (FPrice - lowerpoint) / (higherpoint - lowerpoint)
BUY__SIGNAL = rsi < limit and ta.change(rsi) > 0 and Rational < 0.4 ? 1 : 0
SELL_SIGNAL = rsi > 100 - limit and ta.change(rsi) > 0 and Rational > 0.6 ? 1 : 0
U_AREA_ = math.min(ohlc4, hlc3, hl2)//, open, close)
D_AREA_ = math.max(ohlc4, hlc3, hl2)//, open, close)
U_AREA = U_AREA_
D_AREA = D_AREA_
maxLine = high
minLine = low
BUY__AREA := nz(BUY__SIGNAL[1], 0) == 1 ? 1 : nz(BUY__AREA[1], 0) == 1 ? 1 : 0
SELL_AREA := nz(SELL_SIGNAL[1], 0) == 1 ? 1 : nz(SELL_AREA[1], 0) == 1 ? 1 : 0
U_AREA := SELL_AREA == 1 ? nz(U_AREA[1], U_AREA_) : U_AREA_
D_AREA := BUY__AREA == 1 ? nz(D_AREA[1], D_AREA_) : D_AREA_
maxLine := SELL_AREA == 1 ? math.max(nz(maxLine[1], 0), high) : high
minLine := BUY__AREA == 1 ? math.min(nz(minLine[1], 0), low) : low
refLine = plot(ref, color=#00000000, display=display.none, offset=1)
D_Line = plot(D_AREA, color=BUY__AREA == 1 ? #00FF00A0 : #00000000, linewidth=2, offset=2)
U_Line = plot(U_AREA, color=SELL_AREA == 1 ? #FF0000A0 : #00000000, linewidth=2, offset=2)
fibo_0236 = 0.23606797749979
fibo_0381 = 0.38196601125011
fibo_0500 = 0.5
fibo_0618 = 0.61803398874990
fibo_0763 = 0.76393202250021
fibo_1618 = 1.61803398874990
SelllineforBuying = fibo_0763 * (D_AREA - minLine) + minLine
BuylineforSelling = fibo_0236 * (maxLine - U_AREA) + U_AREA
//if (U_AREA < close)
// line.set_x2(U_AREA_LINE,bar_index)
//if (D_AREA > close)
// line.set_x2(D_AREA_LINE,bar_index)
if BUY__SIGNAL == 1 or nz(BuylineforSelling[1], low) > low or ta.barssince(SELL_AREA == 1) > 20
SELL_AREA := 0
counter_fail := counter_fail + 1
if SELL_SIGNAL == 1 or nz(SelllineforBuying[1], high) < high or ta.barssince(BUY__AREA == 1) > 20
BUY__AREA := 0
counter_fail := counter_fail + 1
if SELL_AREA == 0 and SELL_SIGNAL == 1
U_AREA_LINE := line.new(bar_index, U_AREA, bar_index + 10, U_AREA, xloc.bar_index, extend.none, #FF0000A0, line.style_solid, 3)
U_AREA_LINE
if BUY__AREA == 0 and BUY__SIGNAL == 1
D_AREA_LINE := line.new(bar_index, D_AREA, bar_index + 10, D_AREA, xloc.bar_index, extend.none, #00FF00A0, line.style_solid, 3)
D_AREA_LINE
//fill(D_Line, refLine, color=BUY__AREA==1?#00FF0020:#00000000)
//fill(U_Line, refLine, color=SELL_AREA==1?#FF000020:#00000000)
// draw fibonacci
max_ = BUY__AREA == 1 ? D_AREA : SELL_AREA == 1 ? maxLine : ref
min_ = SELL_AREA == 1 ? U_AREA : BUY__AREA == 1 ? minLine : ref
tolerance = input(0.003)
verify_Revision = ta.change(max_ + min_) == 0 and max_ / min_ > tolerance + 1
verify_Draw = (BUY__AREA == 1 or SELL_AREA == 1) and verify_Revision
Target_line_slope = 1.0 + tolerance
HMCiOH = math.min(86400000 / ta.change(time), 50)
fibo_0000_line = plot(min_, color=BUY__AREA == 1 and verify_Revision ? #FFFFFF80 : #00000000, linewidth=2, editable=false, display=display.none)
fibo_1000_line = plot(max_, color=SELL_AREA == 1 and verify_Revision ? #FFFFFF80 : #00000000, linewidth=2, editable=false, display=display.none)
fibo_1618_line1 = plot((max_ - min_) * fibo_1618 + min_, color=verify_Draw ? #FF000050 : #00000000, linewidth=2, editable=false, display=display.none)
fibo_1618_line2 = plot(-(max_ - min_) * fibo_1618 + min_, color=verify_Draw ? #00FF0050 : #00000000, linewidth=2, editable=false, display=display.none)
fibo_0236_line = plot((max_ - min_) * fibo_0236 + min_, color=verify_Draw ? #FFFFFF50 : #00000000, linewidth=1, editable=false, display=display.none)
fibo_0381_line = plot((max_ - min_) * fibo_0381 + min_, color=verify_Draw ? #00FF0080 : #00000000, linewidth=1, editable=false, display=display.none)
fibo_0500_line = plot((max_ - min_) * fibo_0500 + min_, color=verify_Draw ? #FFFFFF50 : #00000000, linewidth=1, editable=false, display=display.none)
fibo_0618_line = plot((max_ - min_) * fibo_0618 + min_, color=verify_Draw ? #FF000080 : #00000000, linewidth=1, editable=false, display=display.none)
fibo_0763_line = plot((max_ - min_) * fibo_0763 + min_, color=verify_Draw ? #FFFFFF50 : #00000000, linewidth=1, editable=false, display=display.none)
fill(fibo_0236_line, fibo_0381_line, color=verify_Draw == 1 ? #00FF0020 : #00000000)
fill(fibo_0763_line, fibo_0618_line, color=verify_Draw == 1 ? #FF000020 : #00000000)
//min_Line = plot(SelllineforBuying,color=BUY__AREA==1?#FF000080:#00000000,linewidth=2)
//max_Line = plot(BuylineforSelling,color=SELL_AREA==1?#00FF0080:#00000000,linewidth=2)
plotshape(BUY__SIGNAL == 1 and BUY__AREA == 0, style=shape.triangledown, location=location.abovebar, color=#00FF00FF, size=size.auto)
plotshape(SELL_SIGNAL == 1 and SELL_AREA == 0, style=shape.triangleup, location=location.belowbar, color=#FF0000FF, size=size.auto)
// Report
var label lbl = na
label.delete(lbl)
if verify_Draw
var string reports = ''
reports += (BUY__AREA == 1 ? 'LONG' : '')
reports += (SELL_AREA == 1 ? 'SHORT' : '')
reports += '\n SETUP => % ' + str.tostring(math.round((max_ - min_) * 0.5 / close * 10000) / 100)
lbl := label.new(x=barstate.islast ? time : na, y=max_, text=reports, xloc=xloc.bar_time, color=#2020AA, textcolor=#FFFFFF)
reports := ''
reports
alertcondition(condition=verify_Draw, title='Trading Setup from NLTTa_MFI', message='Trading setup action from NLTTa based on MFI')
|
Time Anchored Intraday High/Low Trendline | https://www.tradingview.com/script/JKLE9yDa-Time-Anchored-Intraday-High-Low-Trendline/ | schroederjoa | https://www.tradingview.com/u/schroederjoa/ | 136 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © schroederjoa
// Oftentimes, intraday trendlines that are started at specific times, e.g. 8:00am or market open 9:30am, are well respected throughout the trading day.
// This indicator draws up tp 3 intraday trendlines that are anchored at user defined times, respectively at the corresponding candle's high and low points.
// From there, the line*s xy2 are connected in a way that all following candles are enclosed.
//@version=5
indicator("Time Anchored Intraday High/Low Trendline", shorttitle="Intra Trend", overlay=true)
start_hour_01 = input.int(4, "Trendline 01 Start Hour ", minval=-1, maxval=23, step=1, inline = "01", tooltip="Enter hour/minute to anchor trendline point x1. Use -1 to disable.")
line_width_01 = input.int(2, title="Line Width", inline = "01")
start_minute_01 = input.int(0, " Start Minute", minval=-1, maxval=59, step=1, inline = "01_1")
line_color_01 = input.color(color.new(color.orange,40), title="Line Color ", inline = "01_1")
start_hour_02 = input.int(8, "Trendline 02 Start Hour ", minval=-1, maxval=23, step=1, inline = "02")
line_width_02 = input.int(2, title="Line Width", inline = "02")
start_minute_02 = input.int(0, " Start Minute", minval=-1, maxval=59, step=1, inline = "02_1")
line_color_02 = input.color(color.new(color.orange,40), title="Line Color ", inline = "02_1")
start_hour_03 = input.int(9, "Trendline 03 Start Hour ", minval=-1, maxval=23, step=1, inline = "03")
line_width_03 = input.int(2, title="Line Width", inline = "03")
start_minute_03 = input.int(30, " Start Minute", minval=-1, maxval=59, step=1, inline = "03_1")
line_color_03 = input.color(color.new(color.orange,40), title="Line Color ", inline = "03_1")
update_close = input.bool(true, "Await Candle Close before updating Trendline")
var line_high_01 = line.new(na,na,na,na, xloc=xloc.bar_index, style=line.style_solid, color=line_color_01, width=line_width_01, extend=extend.right)
var line_low_01 = line.new(na,na,na,na, xloc=xloc.bar_index, style=line.style_solid, color=line_color_01, width=line_width_01, extend=extend.right)
var line_high_02 = line.new(na,na,na,na, xloc=xloc.bar_index, style=line.style_solid, color=line_color_02, width=line_width_02, extend=extend.right)
var line_low_02 = line.new(na,na,na,na, xloc=xloc.bar_index, style=line.style_solid, color=line_color_02, width=line_width_02, extend=extend.right)
var line_high_03 = line.new(na,na,na,na, xloc=xloc.bar_index, style=line.style_solid, color=line_color_03, width=line_width_03, extend=extend.right)
var line_low_03 = line.new(na,na,na,na, xloc=xloc.bar_index, style=line.style_solid, color=line_color_03, width=line_width_03, extend=extend.right)
t_01 = (hour*100 + minute >= start_hour_01*100 + start_minute_01) and ((hour[1]*100 + minute[1] < start_hour_01*100 + start_minute_01) or (dayofmonth[1] != dayofmonth)) and start_hour_01 != -1 and start_minute_01 != -1
t_02 = (hour*100 + minute >= start_hour_02*100 + start_minute_02) and ((hour[1]*100 + minute[1] < start_hour_02*100 + start_minute_02) or (dayofmonth[1] != dayofmonth)) and start_hour_02 != -1 and start_minute_02 != -1
t_03 = (hour*100 + minute >= start_hour_03*100 + start_minute_03) and ((hour[1]*100 + minute[1] < start_hour_03*100 + start_minute_03) or (dayofmonth[1] != dayofmonth)) and start_hour_03 != -1 and start_minute_03 != -1
if t_01[1] and not t_01
line.set_xy1(line_high_01, bar_index[1], high[1])
line.set_xy2(line_high_01, bar_index, high)
line.set_xy1(line_low_01, bar_index[1], low[1])
line.set_xy2(line_low_01, bar_index, low)
if t_02[1] and not t_02
line.set_xy1(line_high_02, bar_index[1], high[1])
line.set_xy2(line_high_02, bar_index, high)
line.set_xy1(line_low_02, bar_index[1], low[1])
line.set_xy2(line_low_02, bar_index, low)
if t_03[1] and not t_03
line.set_xy1(line_high_03, bar_index[1], high[1])
line.set_xy2(line_high_03, bar_index, high)
line.set_xy1(line_low_03, bar_index[1], low[1])
line.set_xy2(line_low_03, bar_index, low)
update = update_close ? barstate.isconfirmed : true
if update
if line.get_price(line_high_01, bar_index) < high
line.set_xy2(line_high_01, bar_index, high)
if line.get_price(line_low_01, bar_index) > low
line.set_xy2(line_low_01, bar_index, low)
if line.get_price(line_high_02, bar_index) < high
line.set_xy2(line_high_02, bar_index, high)
if line.get_price(line_low_02, bar_index) > low
line.set_xy2(line_low_02, bar_index, low)
if line.get_price(line_high_03, bar_index) < high
line.set_xy2(line_high_03, bar_index, high)
if line.get_price(line_low_03, bar_index) > low
line.set_xy2(line_low_03, bar_index, low)
|
PuetzUWS [time, price] multiFractal mirrors, SPX 1872-2020 | https://www.tradingview.com/script/xMrv9RMv-PuetzUWS-time-price-multiFractal-mirrors-SPX-1872-2020/ | Bill_Howell | https://www.tradingview.com/u/Bill_Howell/ | 24 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bill_Howell
//@version=5
indicator(title="PuetzUWS [time, price] multiFractal mirrors, SPX 1872-2020", shorttitle="PuetzUWS 1872-2020 fractal mirrors", overlay=true)
// 24************************24
// Table of Contents :
// Quick notes
// Descriptions of [constant, function] symbols used in this PineScript
// Key [setup, parameters to adjust]
// Setup - timeframe.period, n_bars, [min, max] of tracked main price series in chart
// Symbols' pricing semi-log {[trend, relStdDev], priceRsd[Min, Max, Spread]Idx}
// PriceFractals [Fibonacci, Liebnitz, Puetz]
// Fibonnacci PriceFractals
// Leibnitz PriceFractals (Gottfried Wilhelm Leibnitz), 19May2022 not coded yet (text pulled out)
// Puetz PriceFractals (Stephen J. Puetz), 19May2022 not coded yet (text pulled out)
// Plot PriceFractals
// TimeFractals
// Puetz TimeFractals (Stephen J. Puetz) - used for ALL [Fibonacci, Liebnitz, Puetz] timeFractals
// as I know of no common timeFractals for [Fibonacci, Liebnitz]
// however, the levels are different for each
// plot Time Fractals (spikes or verticalLines)
// 24************************24
// 24************************24
// Quick notes
// For [intro, concept, reference, TradingView's Pine Script language, [challenge, problem, debug]s] of this script, webSearch my name and this script?
// Make sure that the overlay output "PeutzUWS 1872-2020 fractal mirrors" is on a separate axis!
// right click on detrended SPX, select "pin to new right scale"
// Select "seetings for each axis (except TVC: TNX 10yT-bond rate) and select "logaritmic"
// There is a great deal of [vestigial, anachronistic] code here, as I kept going back & forth to different
// approaches to find solutions. Not entirely successfully...
// cannot do fractals with [hline, plot] - not accepted in local [function, for, if]
// can use line.new [vertical, multiple of a base line, etc]
// Don't use libraries!! it's too much of a mess...
// 04Jun2022 I was finally able to publish the library but it doesn't seem to import? no action
// 24************************24
// Descriptions of [constant, function] symbols used in this PineScript
// priceFractal | timeFractal
// ---------------|---------------
// flagSpike | flagSpike boolean -whether to output a [line, spike]
// lambdaPuetzUWS | lambdaPuetzUWS PuetzUWS (Universal Wave Series), period = cycle lengths (years)
// rsdPuetzUWS | timeLambda PuetzUWS converted to relStdDev [time, price]
// midIdx | n/a [PuetzUWS, rsdPuetzUWS] index, such that rsdPuetzUWS = 1.000
// p_cycle | t_cycle current cycle length in [drawPriceFrac, drawTimeFrac]
// priceRsdMax? | t_now .
// priceRsdMax? | timenow .
// p_mod | t_mod modulus (leftover) iUWS p_cycles from basLevel to rsdLevel
// priceRsdCum | t_spike .
// n_spikes | n_spikes number of iUWS [line, spike]s to show on chart
// n/a | t_lengthUnix chart's time duration (t_lengthYear) converted to Unix (milliseconds)
// n/a | timenow Unix current time UTC (milliseconds since 01Jan1970)
// n_bars | ?can't get starting [bar, time] - sloppy guess
// y_offset | y_offset price offset, typically from a [line, spike] on chart, for labels
// 24************************24
// Basic [constant, function]s used in rest of library
// lambdaPuetzUWS - used for timeFractals, all of which are positive!
lambdaPuetzUWS = array.from(0.0001072980, 0.0003218942, 0.0009656826, 0.002897047, 0.008691143, 0.02607343, 0.07822029, 0.2346608, 0.7039826, 2.111947, 6.335843, 19.00753, 57.02259, 171.0677, 513.2033)
// rsdPuetzUWS - used for priceFractals, which are both [posit, negat]ive!
// rsdPuetzUWS = lambdaPuetzUWS / 0.2346608 (mid-range value)
// full sequence reversal
// this shorter rsdPuetzUWS sequence - will NOT accomodate cypto and other extremely high growth! nor negatives
rsdPuetzUWS = array.from(-9., -3., -1., -0.333333, -0.111111, -0.037037, -0.0123457, -0.00411523, -0.00137174, -0.000457247, 0.000, 0.000457247, 0.00137174, 0.00411523, 0.0123457, 0.037037, 0.111111, 0.333333, 1., 3., 9.)
// 21 elements, (0 - 20) midIdx == 10
lastRsdIdx = array.size(rsdPuetzUWS) - 1
midIdx = math.floor(array.size(rsdPuetzUWS) / 2)
// 09Jun2022 not used yet :
string fracTyp = "Fibonacci" // had to rip out to revert to old code, still want in future
float t_lagYears = 0.05 // shifts all time spikes
// Find the highest and lowest values for the entire dataset
// 20Mar2021 Howell - adapt this for viewable data
// 11Jun2022 old approach very inefficient, don't use these normally!
biggest(series,size) =>
max = 0.0
for j = 0 to size
if series[j] > max
max := series[j]
max
smalest(series,size) =>
min = 100000.
for j = 0 to size
if series[j] < min
min := series[j]
min
// 24************************24
// Time - timeframe.period, n_bars, [min, max] of tracked main price series in chart (once stable, generalised)
// 03Jun2022 Much of this should go into a library to use across my PineScript code (once stable, generalised)
// but I couldn't get a library to work
// User must turn OFF : SP500 axis menu -> Labels -> Indicators and financials name labels (no checkmark)
// time conversions
var float t_year_to_millisecs = 365.25*24*60*60*1000
var float year_to_minutes = 365.25*24*60
var float year_to_hours = 365.25*24
var float year_to_days = 365.25
var float year_to_weeks = 52.1786
var float year_to_months = 12.0
// timeIdx = index to ary_t_length, the active chart timeSpan
// visual = "1D" "5D" "1M" "3M" "6M" "1Y" "5Y" "All" "All, 01Feb1871"
// actual = 1 1 30 120 D W 30? or 20? 20?
//qnial> (1/365.25) (5/365.25) (1/12) (3/12) (1/2) (1.0) (5.0) (20) (20)
// .00273785 0.0136893 0.0833333 0.25 0.5 1. 5. 20. 150.
// set to true to go back to 01Feb1871
flag_1871 = true
timeIdx = 0 // index to UWS constants
if (timeframe.period == "1")
timeIdx := 0
else if (timeframe.period == "5")
timeIdx := 1
else if (timeframe.period == "30")
timeIdx := 2
else if (timeframe.period == "60")
timeIdx := 3
else if (timeframe.period == "120")
timeIdx := 4
else if (timeframe.period == "D")
timeIdx := 5
else if (timeframe.period == "W")
timeIdx := 6
else if (timeframe.period == "M") and flag_1871
timeIdx := 8
else if (timeframe.period == "M")
timeIdx := 7
// does "1" n_bars (1 hour timeframe.period, 1 day t_length) change over course of day?
// t_lengthYear = duration of graph timescale for each timeperiod
// 1Jun2022 this did NOT work when declared as t_lenghtYear = 0.0, then
// t_lengthYear := array.get(ary_t_length, timeIdx) Whyy!!!? very frustrating!!!
ary_t_length = array.from(0.00273785, 0.0136893, 0.0833333, 0.25, 0.5, 1.0, 5.0, 20.0, 150.0)
// declaring these as float, or "var float" won't work???!!!???
t_lengthYear = array.get(ary_t_length, timeIdx) // duration of graph timescale (years)
t_lengthUnix = math.floor(t_lengthYear * t_year_to_millisecs) // duration of graph timescale (milliseconds)
year_fraction = time / t_year_to_millisecs + 1970
// strange shift 01Mar1922 to 01Aug1929
t_unix01Jan1970_to_unix01Jul1929(t_unix01Jan1970) =>
math.floor(t_unix01Jan1970 + (1929.5833 - 7.25)*t_year_to_millisecs)
// ary_n_bar -> can cause scrunching of outputs!!!
// 27May2022 PineScript provides no bug-free means of getting n_bars.
// see '0_PineScript notes.txt' :
// I did it by trial & error for each time period and even then...
// std TradingView timeScales ( 1D 5D 1M 3M 6M 1Y 5Y All "All, 01Feb1871")
// last_bar_index (24924, 21257, 28294, 20055, 22804, 4951, 1000, 230, ????) these vary a bit
ary_n_bars = array.new<int>(8, 0)
ary_n_bars := array.from( 1300, 1300, 1100, 1500, 1500, 240, 240, 250, 1500) // 15Jun2022
n_bars = 2500 // number of datapoints on time axis
n_bars := array.get(ary_n_bars, timeIdx)
bar_2_3rds = last_bar_index - math.round(n_bars*2/3)
bar_1_half = last_bar_index - math.round(n_bars /2)
bar_3_8ths = last_bar_index - math.round(n_bars*3/8)
bar_1_qrtr = last_bar_index - math.round(n_bars /4)
bar_1_8ths = last_bar_index - math.round(n_bars /8)
// 24************************24
// Labels
// 03Jun2022 Much of this should go into a library to use across my PineScript code (once stable, generalised)
// but I couldn't get a library to work
simple_label(int bar_index, float price, string txt) =>
label.new(bar_index, price, txt, textcolor = color.black, color = na, style=label.style_label_left, size=size.large)
barLast_label(float price, string txt) =>
label.new(bar_index, price, txt, textcolor = color.black, color = na, style=label.style_label_left)
// priceOffsets are : + = upward; - = downward
barFirst_label(float barFractionFrmRight, float serPrice, float priceOffset, string txt) =>
label.new(last_bar_index-math.round(n_bars*barFractionFrmRight), serPrice + priceOffset, txt, textcolor = color.black, color = na, style=label.style_label_left)
// 14Jun2022 doesn't work - need a series to et price level?
// 04Jun2022 Used for timeSpikes, can't get priceOffset to work, doesn't seem work with label.new...
time_label(int timer, float serPrice, float priceOffset, string txt) =>
label.new(timer, serPrice + priceOffset, txt, xloc = xloc.bar_time, textcolor = color.black, color = na, style=label.style_label_left)
// didn't work - dumVar not typed?
//time_label(int timer, float serPrice, float priceOffset, string txt) =>
// dummyVar = priceOffset
// label.new(timer, serPrice + priceOffset, txt, xloc = xloc.bar_time, textcolor = color.black, color = na, style=label.style_label_left)
// 03Jun2022 I should use "table" functions - maybe later
mat_write(string matTitle, matrix<float> matSymbol, int n_bars, int barRightShift, float serPrice, float txtLineHeight) =>
rows = matrix.rows(matSymbol)
cols = matrix.columns(matSymbol)
rowStr = ""
num = 10.0
y_offset = 0.0
y_offset := -6*txtLineHeight
// barFirst_label(float barFractionFrmRight, float serPrice, float priceOffset, string txt) =>
barFirst_label(0.75, serPrice, y_offset, matTitle)
for iRow = 0 to (rows - 1)
rowStr := ""
for iCol = 0 to (cols - 1)
num := matrix.get(matSymbol, iRow, iCol)
rowStr := rowStr + str.tostring(num, '#.000') + " "
y_offset := float(-(iRow + 7)*txtLineHeight)
barFirst_label(0.75, serPrice, y_offset, rowStr)
// 24************************24
// price[Min, Max] over full length of t_timelength, txtLineHeight
// Do not put in an if statement yet - needed by draw_spikes
// Note : the y_axis may not be a price, it could be [volume, other], but the "price" term used here
// 23May2022 do NOT declare with 'var'!!! :
// 11Jun2022 old approach very inefficient, not necessary :
priceMin = smalest(close, n_bars)
priceMax = biggest(close, n_bars)
// 12Jun2022 this approach did NOT work - it was an attempt to improve efficiency [memory, computation]s
//float priceMin = 1.0E6
//float priceMax = 0
//
//if close < priceMin
// priceMin := close
//
//if close > priceMax
// priceMax := close
// 24************************24
// 24************************24
// Symbols' pricing semi-log {[trend, relStdDev], priceRsd[Min, Max, Spread]Idx, etc}
// priceFractals - are hard-bound to the SP500USD 1926-2020 semi-log trend line and
// its standard deviation. (fib = number of relStdDev)
// So they are tied to the SPXUSD over the last 83+ years, but are NOT related to current market specifics.
// Wilhelm Abel ?1937?, David Fischer 1996, I ve used the following split :
// price equilibrium (stable prices) 1871-1926
// price revolution 1926-2020
// calculate trendline for [1926.25-2020.???, 1872-1926.25] too lzy to get 2020 exact endDate of regression fit
calc_SP500Trend(y_fraction) =>
expnt = 0.0
if y_fraction >= 1926.25
expnt := 0.792392+0.0289587*(y_fraction - 1926.25)
else
expnt := 0.784617+1.40925E-04 *(y_fraction - 1871.08)
SP500base = math.pow(10,expnt)
lin0000 = calc_SP500Trend(year_fraction)
//lin0000_[start, end] : don't need, its just lin0000 at barstate.islast (horizontal lines)
// The "relative standard deviation" (relStdDev or rsd) of the 83y trend is from the data 1926-2020
// calculated in LibreOffice Calc spreadsheet =STDEV(SP500_detrend_1926_2020), i.e on semi-log detrend basis
// see "$d_webRawe"'economics, markets/SP500/multi-fractal/SP500 1872-2020 TradingView, 1928-2020 yahoo
// WARNING!!! Redo this yourself!!! I made so many changes of a period of two years, weird things could have happened.
// keep coming back like zombies. examples :
// fib0236Hi = (1 + 0.236*relStdDev/2) should be relStdDev (should be no "/2")
// I don't trust this
relStdDev = 0.4308
price_to_rsd(price) =>
(price / lin0000 - 1) / relStdDev
rsd_to_price(rsd) =>
lin0000 * (rsd * relStdDev + 1)
// rsd = relative standard deviation series, with respect to 1926-2020 SP500 semilog [trend, relStdDev]
priceRsd = price_to_rsd(close) // 25May2022 probably WRONG!! - consider semi-log
plot(priceRsd, color=color.aqua, linewidth=2)
// priceRsd[Min, Max] over full length of t_timelength
float priceRsdMin = 5.0
float priceRsdMax = -5.0
float txtLineHeight = 0.0
// 11Jun2022 old approach very inefficient, not necessary :
priceRsdMin := smalest(priceRsd, n_bars)
priceRsdMax := biggest(priceRsd, n_bars)
// 11Jun2022 new approach, trying to get simple floats to work (does not work!)
//if priceRsd < priceRsdMin
// priceRsdMin := priceRsd
//
//if priceRsd > priceRsdMax
// priceRsdMax := priceRsd
priceRsdMin_to_lambdaIdx() =>
idxMin = 0
for j = 0 to lastRsdIdx
if array.get(rsdPuetzUWS, j) < priceRsdMin
idxMin := j
idxMin
priceRsdMax_to_lambdaIdx() =>
idxMax = 0
for j = lastRsdIdx to 0
if array.get(rsdPuetzUWS, j) > priceRsdMax
idxMax := j
idxMax
// priceRsd[Min, Max, Bas] to indexs
float priceRsdBas = 0.0
int priceRsdMinIdx = 0
int priceRsdMaxIdx = 0
int priceRsdBasIdx = 0
int priceRsdLesIdx = 0
int priceRsdBelowIdx = midIdx
int priceRsdAboveIdx = midIdx
int priceRsdBelowStopIdx = midIdx
int priceRsdAboveStopIdx = midIdx
if barstate.islast
txtLineHeight := (priceRsdMax - priceRsdMin)/10
//
priceRsdMinIdx := priceRsdMin_to_lambdaIdx()
priceRsdMaxIdx := priceRsdMax_to_lambdaIdx()
//
// set iUWS ranges to provide common fractal levels [below, above] rsd = 1.000
if priceRsdMinIdx <= midIdx and priceRsdMaxIdx <= midIdx
priceRsdBelowIdx := priceRsdMinIdx
priceRsdBelowStopIdx := priceRsdBelowIdx + 2
if priceRsdBelowStopIdx > midIdx
priceRsdBelowStopIdx := midIdx
else if priceRsdMinIdx >= midIdx and priceRsdMaxIdx >= midIdx
priceRsdAboveIdx := priceRsdMaxIdx
priceRsdAboveStopIdx := priceRsdAboveIdx - 2
if priceRsdAboveStopIdx < midIdx
priceRsdAboveStopIdx := midIdx
else
// adjust +1 because off midIdx
if math.abs(priceRsdMinIdx - midIdx) > math.abs(priceRsdMaxIdx - midIdx)
priceRsdBasIdx := math.abs(priceRsdMinIdx - midIdx) - 1
else
priceRsdBasIdx := math.abs(priceRsdMaxIdx - midIdx) - 1
//
if priceRsdBasIdx < 2
priceRsdLesIdx := midIdx
else
priceRsdLesIdx := priceRsdBasIdx - 2
//
priceRsdBelowIdx := midIdx - priceRsdBasIdx
priceRsdAboveIdx := midIdx + priceRsdBasIdx
priceRsdBelowStopIdx := midIdx - priceRsdLesIdx
priceRsdAboveStopIdx := midIdx + priceRsdLesIdx
// Bug check - output variables on chart
simple_label_prices() =>
float priceLabel = 0.0
// bar_[2_3rds, 1_half, 1_qrtr] are defined above in section "Time - timeframe.period, n_bars, [min, max]"
//
priceLabel := priceRsdMax - 2*txtLineHeight
simple_label(bar_2_3rds, priceLabel, "priceMin = " + str.tostring(priceMin))
simple_label(bar_1_half, priceLabel, "priceMax = " + str.tostring(priceMax))
simple_label(bar_1_qrtr, priceLabel, "midIdx = " + str.tostring(midIdx))
//
priceLabel := priceRsdMax - 3*txtLineHeight
simple_label(bar_2_3rds, priceLabel, "priceRsdMin = " + str.tostring(priceRsdMin, '#.000'))
simple_label(bar_1_half, priceLabel, "priceRsdMax = " + str.tostring(priceRsdMax, '#.000'))
simple_label(bar_1_qrtr, priceLabel, "lastRsdIdx = " + str.tostring(lastRsdIdx))
//
priceLabel := priceRsdMax - 4*txtLineHeight
simple_label(bar_2_3rds, priceLabel, "priceRsdMinIdx = " + str.tostring(priceRsdMinIdx))
simple_label(bar_1_half, priceLabel, "priceRsdMaxIdx = " + str.tostring(priceRsdMaxIdx))
simple_label(bar_1_qrtr, priceLabel, "priceRsdBasIdx = " + str.tostring(priceRsdBasIdx))
//
priceLabel := priceRsdMax - 5*txtLineHeight
simple_label(bar_2_3rds, priceLabel, "priceRsdBelowIdx = " + str.tostring(priceRsdBelowIdx))
simple_label(bar_1_half, priceLabel, "priceRsdBelowStopIdx = " + str.tostring(priceRsdBelowStopIdx))
//
priceLabel := priceRsdMax - 6*txtLineHeight
simple_label(bar_2_3rds, priceLabel, "priceRsdAboveStopIdx = " + str.tostring(priceRsdAboveStopIdx))
simple_label(bar_1_half, priceLabel, "priceRsdAboveIdx = " + str.tostring(priceRsdAboveIdx))
//
simple_label(bar_1_qrtr, priceRsdMin, "n_bars = " + str.tostring(n_bars))
//if barstate.islast
// simple_label_prices()
//if barstate.islast
// priceLabel = priceRsdMax - 1*txtLineHeight
// simple_label(bar_2_3rds, priceLabel, "timeframe.period = " + timeframe.period)
// 24************************24
// 24************************24
// [Puetz, Fibonacci] priceFractals - are hard-bound to the SP500USD 1926-2020 semi-log trend line and
// its standard deviation. (fib = number of relStdDev)
// So they are tied to the SPXUSD over the last 83+ years, but are NOT related to current market specifics.
// [lambdaPuetzUWS, rsdPuetzUWS] defined in setup section above
// note that the "plot" function cannot be a local : ie in [function, for, if, etc]
// for price, key fractal measure is rsdPrice, preferably with 1.0 in set rsdPuetzUWS?
// wanted to have options on type of priceFractals : Puetz framework, Fibonacci lowest level?
// drawPriceFrac() - for now only nests 2 levels below topLevel
// 08Jun2022 need to do [above, below] lin0000 (fractal = 1.000) - currently just above
drawPriceFrac() =>
bool flagSpike = true
int iStop = 0
int widthr = 1
float y_offset = 0.0
float priceRsdBelow = 0.0
float priceRsdAbove = 0.0
float priceRsdBelowStop = 0.0
float priceRsdAboveStop = 0.0
float priceRsdNow = 0.0
float priceRsdStep = 0.0
float priceLabel = 0.0
//
// do levels below priceRsd = 1.000, if they are present
if priceRsdMin < 0.000
iStop := 0
widthr := 0
priceRsdBelow := array.get(rsdPuetzUWS, priceRsdBelowIdx)
priceRsdBelowStop := array.get(rsdPuetzUWS, priceRsdBelowStopIdx)
//priceLabel := priceRsdMax - 7*txtLineHeight
//simple_label(bar_2_3rds, priceLabel, "priceRsdBelowStop = " + str.tostring(priceRsdBelowStop))
//simple_label(bar_1_half, priceLabel, "priceRsdBelow = " + str.tostring(priceRsdBelow))
for iRSD = priceRsdBelowStopIdx to priceRsdBelowIdx
widthr := widthr + 1
priceRsdStep := array.get(rsdPuetzUWS, iRSD)
priceRsdNow := 0.0
while (priceRsdMin <= priceRsdNow) and (iStop < 300)
if priceRsdMax >= priceRsdNow
line.new(last_bar_index - n_bars, priceRsdNow, last_bar_index, priceRsdNow, color=color.black, width=widthr)
barLast_label(priceRsdNow, " " + str.tostring(rsd_to_price(priceRsdNow), '#'))
priceRsdNow := priceRsdNow + priceRsdStep
iStop := iStop + 1
//
// do levels above priceRsd = 1.000, if they are present
if priceRsdMax >= 0.000
iStop := 0
widthr := 0
priceRsdAbove := array.get(rsdPuetzUWS, priceRsdAboveIdx)
priceRsdAboveStop := array.get(rsdPuetzUWS, priceRsdAboveStopIdx)
//priceLabel := priceRsdMax - 8*txtLineHeight
//simple_label(bar_2_3rds, priceLabel, "priceRsdAboveStop = " + str.tostring(priceRsdAboveStop))
//simple_label(bar_1_half, priceLabel, "priceRsdAbove = " + str.tostring(priceRsdAbove))
for iRSD = priceRsdAboveStopIdx to priceRsdAboveIdx
widthr := widthr + 1
priceRsdNow := 0.0
priceRsdStep := array.get(rsdPuetzUWS, iRSD)
while (priceRsdNow <= priceRsdMax) and (iStop < 300)
if priceRsdMin <= priceRsdNow
line.new(last_bar_index - n_bars, priceRsdNow, last_bar_index, priceRsdNow, color=color.black, width=widthr)
barLast_label(priceRsdNow, " " + str.tostring(rsd_to_price(priceRsdNow), '#'))
priceRsdNow := priceRsdNow + priceRsdStep
iStop := iStop + 1
if barstate.islast
drawPriceFrac()
// line.new(last_bar_index - n_bars, priceRsdNow, last_bar_index, priceRsdNow, color=color.black, width=iRSD + 1)
// 24************************24
// 24************************24
// TimeFractals
//+-----+
// Puetz TimeFractals (Stephen J. Puetz) - used for ALL [Fibonacci, Liebnitz, Puetz] timeFractals
// as I know of no common timeFractals for [Fibonacci, Liebnitz]
// However, the levels are different for each
// 12May2022 initial
// SP500 multi-fractal : 1926-2020 semi-log trend; Puetz "Universal Wave Series" temporal nested cycles
// UWS wavelengths (cycle times in years) that I will use for the 1926-2020 SP500 semi-log trend are (rounded to 6 digits), but these NEED CORRECTION for trading hours etc (a project for the future - not likely for me). As TradingView typically plots trading days only, there won't be a good time-fit, especially for lower timescales. More sophisticated calculations could fix this, but that's for another day if ever. TradingView has "cyclic lines" to easily show temporal cycles on charts.
// Fourier series analysis - might be a good starting spectral analysis to pick out relevant periods.
// again, missing multiple n (HUWS)
// While the ratios of UWS sequential periods are fixed to a factor of 3, the "anchor time" and perhaps more importantly the phase angles, depend on the application.
// set UWS series parameters (not yet HUWS)
// 16Mar2015 Howell adapted from "TradingView auto fib extension" standard PineScript library
// 25May2022 oops still had erroneous "/2" :
// 26May2022 these are NOT nested, as with the Puetz timeFractals below.
// I couldn't get [line.new, nested [for, if] expressions] to work (see a previous section above)
// NOTE : as per the reference in section "" above, Puetz has recently used :
// P(0,0) is a base cycle with a period of 2.82894367327307 solar years.
// In comparison, above I have UWS[09] = 2.111947 years. But I do not have a complete updated table of USW [lambda, phi] to go by, so I simply used 2011 lambda rather than the 2014 numbers.
// However, since the initial list of lamda in Puetz's 2011 book, the assigned values have been updated as many new time series have qualified for the Puetz UWS. Note that phi angles are specific to each application of each time series, and must be optimized for the problem at hand. 12May2022 THIS NEEDS TO BE UPDATED!!
// Also not that the Half-UWS harmonics bring the UWS-HUWS cmbination much closer to a Fourier series! :
// n is one of eight period-halving harmonics where n ∈ {0, 1, 2, 3, 4, 5, 6, 7}
// Rather than show all of the above cycles on a graph, I will reduce the cycles according to the timescale of the chart
// lamda (cycle periods)
// years months days hours
// 1.072980E-04 0.940574
// 3.218942E-04 0.117572 2.82173
// 9.656826E-04 0.352716 8.46518
// 2.897047E-03 1.05815 25.3956
// 8.691143E-03 0.104294 3.17444 76.1866
// 2.607343E-02 0.312881 9.52332 228.56
// 7.822029E-02 0.938643 28.57
// 2.346608E-01 2.81593 85.7099
// 7.039826E-01 8.44779 257.13
// 2.111947E+00 25.3434 771.389
// 6.335843E+00 76.0301
// 1.900753E+01 228.09
// 5.702259E+01
// 1.710677E+02
// 5.132033E+02
// "anchor time" NYET -not used!! - just use the pure UWS times?? But how to adjust?
// I will simply take the somewhat arbitrary date of the 1926 start of the SP500 series that I used : 1926.25. Fudging and excuses will follow later. Note that all UWS cycles align with the largest of the series, and hence with one another, so the choice of the start time is "universal" in a sense (but coud be wrong, obviously).
// [lambdaPuetzUWS, rsdPuetzUWS] defined in setup section above
// find the lambdaPuetzUWS index of the largest ary_t_length fits into the chart timescale
t_lengthMaxFitIdx() =>
max = 0
for j = 0 to 14
if array.get(lambdaPuetzUWS, j) < t_lengthYear
max := j
max
// timeLambdaYearL - active lambdaPuetzUWS for the current timescale [D, 5D, W, M, ...]
timeLambdaYearL = array.new_float(5, 0.0)
timeLambdaUnixL = array.new_int(5, 0)
int timeLamdaMaxIdx = 0
init_timeLambdaL() =>
lambdaYear = 0.0
for j = 0 to 4
lambdaYear := array.get(lambdaPuetzUWS, timeLamdaMaxIdx - 2 + j)
array.set(timeLambdaYearL, j, lambdaYear)
array.set(timeLambdaUnixL, j, math.round(lambdaYear * t_year_to_millisecs))
// Jun2022 timePhi - not used yet.I am actually reluctant to going astray with optimization,
// when I don't understand the results, and I'm fighting to better understand Pine Script.
// phi = time [lag, phase angle], not currently implemented
// these are simply fit to each of the data series
// 13May2022 simple set phase angles to zero for initial coding.
// UWS_phi = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
//timePhi = array.new_float(5, 0.0)
//init_timePhi() =>
// for j = 0 to 4
// array.set(timePhi, j, array.get(UWS_phi, timeLamdaMaxIdx - 2))
// 14Jun2022 if statement didn't work
//if barstate.isfirst
// timeLamdaMaxIdx := t_lengthMaxFitIdx()
// init_timeLambdaL()
// //init_timePhi()
timeLamdaMaxIdx := t_lengthMaxFitIdx()
init_timeLambdaL()
//init_timePhi()
// write debug information to chart :
//debugTimeFrac() =>
// priceLabel := priceRsdMax - 3*txtLineHeight
// simple_label(bar_2_3rds, priceLabel, "timeIdx = " + str.tostring(timeIdx))
// simple_label(bar_1_half, priceLabel, "timeLamdaMaxIdx = " + str.tostring(timeLamdaMaxIdx))
// priceLabel := priceRsdMax - 4*txtLineHeight
// simple_label(bar_2_3rds, priceLabel, "t_lengthYear = " + str.tostring(t_lengthYear))
// simple_label(bar_1_half, priceLabel, "t_lengthUnix = " + str.tostring(t_lengthUnix))
// priceLabel := priceRsdMax - 5*txtLineHeight
// simple_label(bar_2_3rds, priceLabel, "t_cycle = " + str.tostring(t_cycle))
// simple_label(bar_1_half, priceLabel, "t_mod = " + str.tostring(t_mod))
// find last, closest] spike in t_lengthUnix
//+--+
// drawTimeFrac [spikes, label]s (spikes = verticalLines)
// 12May2022 initial, 19May2022 generalized for [Fibonacci, Liebnitz, Puetz]
// 19May2022 Half-UWS pike is NOT provided yet
// inputs tab - cannot find anywhere for :
// fracTyp = input.string(defval="Fibonacci", title="fracTyp", options= ["Fibonacci", "Liebnitz", "Puetz"])
// skip daily chart, as SP500 [t_lengthUnix, n_bars] seem messed up
// (maybe not available by minute or whatever)
// plot the UWS cycle times (not yet the HUWS)
// from Setup (reminder) :
// float t_year_to_millisecs = 1000*60*60*24*365.25
float t_shiftYears = 0.05
drawTimeFrac() =>
bool flagSpike = true
int t_cycle = 0
int time_now = 0
int t_mod = 0
int t_spike = 0
int n_spikes = 0
float y_offBase = 0.0
float y_offset = 0.0
float priceLabel = 0.0
for iUWS = 0 to 4
flagSpike := true
t_cycle := array.get(timeLambdaUnixL, iUWS)
if flag_1871
time_now := t_unix01Jan1970_to_unix01Jul1929(timenow)
else
time_now := timenow
t_mod := math.floor(((time_now / t_cycle) % 1) * t_cycle)
//if iUWS == 2
// debugTimeFrac()
if t_mod < t_lengthUnix
t_spike := timenow - t_mod
n_spikes := math.floor(((t_lengthUnix - t_mod) / t_cycle))
else if t_mod == 0.0
t_spike := timenow
n_spikes := math.floor(((t_lengthUnix - t_mod) / t_cycle)) + 1
else if t_mod > t_lengthUnix
flagSpike := false
if flagSpike
for i_spike = 0 to (n_spikes - 1)
line.new(t_spike, priceRsdMin, t_spike, priceRsdMax, xloc = xloc.bar_time, color=color.black, width=iUWS + 1)
y_offset := (y_offBase - 1 - iUWS)*txtLineHeight/2
time_label(t_spike, priceRsdMax, y_offset, " " + str.tostring(iUWS))
t_spike := t_spike - t_cycle
if barstate.islast
drawTimeFrac()
// remi - defined earlier
//bar_2_3rds = last_bar_index - math.round(n_bars*2/3)
//bar_1_half = last_bar_index - math.round(n_bars /2)
//bar_3_8ths = last_bar_index - math.round(n_bars*3/8)
//bar_1_qrtr = last_bar_index - math.round(n_bars /4)
//bar_1_8ths = last_bar_index - math.round(n_bars /8)
// simple_label(bar_2_3rds, priceLabel, "timeframe.period = " + timeframe.period)
// y_offset := (y_offBase - 1 - i_spike)*txtLineHeight
// Create a legend showing periods for fractal depths
if barstate.islast
periodLabel = "error"
period = 0.0
y_offBase = -3.0
y_offset = 0.0
//
y_offset := y_offBase*txtLineHeight
// barFirst_label(float barFractionFrmRight, float serPrice, float priceOffset, string txt) =>
barFirst_label(0.85, priceRsdMax, y_offset, "Puetz timeFractal [depth, period]s")
for iUWS = 0 to 4
period := array.get(timeLambdaYearL, iUWS)
if period < 60/year_to_minutes
period := period * year_to_minutes
periodLabel := "minutes"
else if period < 24/year_to_hours
period := period * year_to_hours
periodLabel := "hours "
else if period < 7/year_to_days
period := period * year_to_days
periodLabel := "days "
else if period < 4.1/year_to_weeks
period := period * year_to_weeks
periodLabel := "weeks "
else if period < 1
period := period * year_to_months
periodLabel := "months "
else
periodLabel := "years "
// timeBarOffsets are backwards from a specified bar_index
// priceOffsets are : + = upward; - = downward
y_offset := (y_offBase - 1 - iUWS)*txtLineHeight
// 27May2022 cannot use parenthesis in labels?
barFirst_label(0.85, priceRsdMax, y_offset, str.tostring(iUWS) + ". " + str.tostring(period, '#.000') + " " + periodLabel)
// endcode
|
OmidCapitalCal | https://www.tradingview.com/script/pJ5mqKcJ-OmidCapitalCal/ | OMIDCAPITAL | https://www.tradingview.com/u/OMIDCAPITAL/ | 11 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OmidCapital
//@version=5
// ------ Settings Inputs -----------------------------------------------------------------------------------------------------
// "Capital" -- enter your portfolio balance
// "Risk" -- enter the percent of your portfolio you are willing to lose if the stop loss is hit
// "Entry" -- enter the price at which you will enter the trade
// "Stop" -- enter the price at which your stop loss will be set
// "Target" -- enter the price at which your take profit will be set
// ----------------------------------------------------------------------------------------------------------------------------
// ------ Outputs -------------------------------------------------------------------------------------------------------------
// "Capital" -- displays the portfolio balance entered in settings
// "Risk" -- displays the % loss entered in settings and the corresponding amount of your portfolio
// "Entry" -- displays the entry price entered in settings
// "Stop" -- displays the stop loss price entered in settings
// "Stop %" -- displays the calculated percentage loss from the entry price
// "Target" -- displays the take profit price entered in settings
// "Target %" -- displays the calculated percentage profit from the entry price
// "Leverage" -- displays the calculated leverage based on your max loss and stop loss settings
indicator('OmidCapitalCal', overlay=true, max_bars_back = 500)
dicimals = input.bool(defval= false, title= "Display decimals up to 8 digits")
// Get inputs
Capital = input.float(title='Capital', defval=1000, minval=.001)
Risk = input.float(title='Risk%', defval=1, minval=0.01, maxval=100, step=0.1) * 0.01
Entry = input.price(defval=0, title="Entry$", confirm=true)
Stop = input.price(defval=0, title="Stop$", confirm=true)
Target = input.price(defval=0, title="Target$", confirm=true)
Entry_Line = plot(Entry, title="Entry", color=#ffb74d, linewidth=1, offset= 100, show_last= 150)
Target_Line = plot(Target, title="Target", color=#5b9cf6, linewidth=1, offset= 100, show_last= 150)
Stop_Line = plot(Stop, title="Stop", color=#f77c80, linewidth=1, offset= 100, show_last= 150)
// Calculations for risk
amt_Risk = Capital * Risk
Reward = math.abs((Target - Entry) / (Entry - Stop))
Reward := math.round(Reward * 1000) / 1000
Profit = math.abs((Reward * amt_Risk))
Profit := math.round(Profit * 1000) / 1000
Stop_pct = math.abs((Stop / Entry - 1) * 100)
Stop_pct := math.round(Stop_pct * 1000) / 1000
Target_pct = math.abs((Target / Entry - 1) * 100)
Target_pct := math.round(Target_pct * 1000) / 1000
Leverage = Risk / Stop_pct * 100
Leverage := math.round(Leverage * 100) / 100
if Entry == 0 or Stop == 0
Leverage := 0
Leverage
// Create and populate table
var theTable= table.new(position=position.bottom_left, columns=3, rows=3, bgcolor=color.white, border_width=0)
if barstate.islast
table.set_border_color(theTable, color.white)
table.cell(theTable, 0, 0, text='Capital = $' + str.tostring(Capital))
table.cell(theTable, 1, 0, text='Risk = $' + str.tostring(amt_Risk))
table.cell(theTable, 2, 0, text='Leverage = ' + str.tostring(Leverage))
table.cell(theTable, 0, 1, text='Entry = $' + str.tostring(Entry))
table.cell(theTable, 1, 1, text='Stop = $' + str.tostring(Stop))
table.cell(theTable, 2, 1, text='Target = $' + str.tostring(Target))
table.cell(theTable, 0, 2, text='Profit = $' + str.tostring(Profit))
table.cell(theTable, 1, 2, text='Stop% = ' + str.tostring(Stop_pct) + '%')
table.cell(theTable, 2, 2, text='Reward = ' + str.tostring(Reward))
// Alerts
alertcondition(ta.cross(close,Entry),
title="Entry", message="Price hit entry point ➜ \n" + "{{ticker}}, price = {{close}}")
alertcondition(ta.cross(close,Stop),
title="Stop", message="Price hit Stop ➜ \n" + "{{ticker}}, price = {{close}}")
alertcondition(ta.cross(close,Target),
title="Target", message="Price hit Target ➜ \n" + "{{ticker}}, price = {{close}}")
|
MTF High Low | https://www.tradingview.com/script/dyTEaZ5T-MTF-High-Low/ | Mohit_Kakkar08 | https://www.tradingview.com/u/Mohit_Kakkar08/ | 149 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mohit_Kakkar08
//@version=5
indicator(title="MTF High Low", shorttitle="MTF HIGH LOW", overlay=true)
length = input.int(6, minval=1)
lower = ta.lowest(low[1], length)
upper = ta.highest(high[1], length)
basis = math.avg(upper, lower)
htf = input(title="Higher Time Frame", defval="D")
htf_lower = request.security(syminfo.tickerid, htf, ta.lowest(low[1], length))
htf_upper = request.security(syminfo.tickerid, htf, ta.highest(high[1], length))
htf_basis = math.avg(htf_upper, htf_lower)
k1 = plot(upper, "High", color=color.red, offset = 0, style=plot.style_line, show_last=1, linewidth=2, trackprice=true, display=display.all)
k2 = plot(lower, "Low", color=color.green, offset = 0, style=plot.style_line, show_last=1, linewidth=2, trackprice=true, display=display.all)
k3 = plot(basis, "Mid", color=color.black, offset = 0, style=plot.style_line, show_last=1, linewidth=2, trackprice=true, display=display.none)
H1 = plot(htf_upper, "High_HTF", color=color.red, offset = 0, style=plot.style_line, show_last=1, linewidth=4, trackprice=true, display=display.all)
H2 = plot(htf_lower, "Low_HTF", color=color.green, offset = 0, style=plot.style_line, show_last=1, linewidth=4, trackprice=true, display=display.all)
H3 = plot(htf_basis, "Mid_HTF", color=color.black, offset = 0, style=plot.style_line, show_last=1, linewidth=4, trackprice=true, display=display.none)
show_table = input(true, "Show Table?")
tableposition=input.string("top_right",title="Table position", options=["top_left", "top_center", "top_right", "middle_left", "middle_center", "middle_right", "bottom_left", "bottom_center", "bottom_right"])
tabpos= tableposition== "top_left"? position.top_left:tableposition== "top_center"?position.top_center : tableposition== "top_right"? position.top_right : tableposition== "middle_left"? position.middle_left : tableposition== "middle_center"? position.middle_center : tableposition== "middle_right"? position.middle_right : tableposition== "bottom_left"? position.bottom_left : tableposition== "bottom_center"? position.bottom_center: tableposition== "bottom_right"? position.bottom_right: position.top_right
t0=timeframe.period
var table indicatorTable = table.new(tabpos, 10, 10, border_width=1)
if show_table and (barstate.islast or not barstate.islast)
// symbols
table.cell(indicatorTable, 0, 0, text='TF' + ' ' + '=' + ' '+ t0, bgcolor=color.black, text_color=color.white, text_size=size.normal)
table.cell(indicatorTable, 0, 1, text='High', text_halign=text.align_center, bgcolor=color.silver, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 0, 2, text='Low', text_halign=text.align_center, bgcolor=color.silver, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 0, 3, text='View', text_halign=text.align_center, bgcolor=color.silver, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 1, 1, str.tostring(math.round(upper,0)), text_halign=text.align_center, bgcolor=close < upper ? color.red : color.green, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 1, 2, str.tostring(math.round(lower,0)), text_halign=text.align_center, bgcolor=close < lower ? color.red : color.green, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 1, 3, close<basis?"Bearish":"Bullish", text_halign=text.align_center, bgcolor=close < basis ? color.red : color.green, text_color=color.black, text_size=size.normal)
table.merge_cells(indicatorTable, 0, 0, 1, 0)
table.cell(indicatorTable, 2, 0, text='TF' + ' ' + '=' + ' '+ htf, bgcolor=color.black, text_color=color.white, text_size=size.normal)
table.cell(indicatorTable, 2, 1, text='High', text_halign=text.align_center, bgcolor=color.silver, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 2, 2, text='Low', text_halign=text.align_center, bgcolor=color.silver, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 2, 3, text='View', text_halign=text.align_center, bgcolor=color.silver, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 3, 1, str.tostring(math.round(htf_upper,0)), text_halign=text.align_center, bgcolor=close < htf_upper ? color.red : color.green, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 3, 2, str.tostring(math.round(htf_lower,0)), text_halign=text.align_center, bgcolor=close < htf_lower ? color.red : color.green, text_color=color.black, text_size=size.normal)
table.cell(indicatorTable, 3, 3, close<htf_basis?"Bearish":"Bullish", text_halign=text.align_center, bgcolor=close < htf_basis ? color.red : color.green, text_color=color.black, text_size=size.normal)
table.merge_cells(indicatorTable, 2, 0, 3, 0)
|
Jurik Composite Fractal Behavior (CFB) on EMA [Loxx] | https://www.tradingview.com/script/7QJg35wB-Jurik-Composite-Fractal-Behavior-CFB-on-EMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 141 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Jurik Composite Fractal Behavior (CFB) on EMA [Loxx]", shorttitle = "JCFBEMA [Loxx]", overlay = true, timeframe="", timeframe_gaps = true, max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
EMA(x, t) =>
_ema = x
_ema := na(_ema[1]) ? x : (x - nz(_ema[1])) * (2 / (t + 1)) + nz(_ema[1])
_ema
_jcfbaux(src, depth)=>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = depth - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
_jcfb(src, len, smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, _jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
_a_jurik_filt(src, len, phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jma = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
src = input.source(hlcc4, "Source", group = "Basic Settings")
cfb_src = input.source(hlcc4, "CFB Source", group = "CFB Ingest Settings")
// backsamping period for highs/lows
nlen = input.int(50, "CFB Normal Length", minval = 1, group = "CFB Ingest Settings")
// cfb depth, max 10 since that's around 5000 bars
cfb_len = input.int(10, "CFB Depth", maxval = 10, group = "CFB Ingest Settings")
// internal cfb calc smoothing
smth = input.int(8, "CFB Smooth Length", minval = 1, group = "CFB Ingest Settings")
// lower bound of samples returned from the nlen rolling window
slim = input.int(10, "CFB Short Limit", minval = 1, group = "CFB Ingest Settings")
// upper bound of samples returned from the nlen rolling window
llim = input.int(20, "CFB Long Limit", minval = 1, group = "CFB Ingest Settings")
// for jurik filter post cfb calcuation smoothing length
jcfbsmlen = input.int(10, "CFB Jurik Smooth Length", minval = 1, group = "CFB Ingest Settings")
// for jurik filter post cfb calcuation smoothing phase, generall a number between -100 and 100
jcfbsmph = input.float(0, "CFB Jurik Smooth Phase", group = "CFB Ingest Settings")
colorbars = input.bool(true, title='Color bars?', group = "UI Options")
cfb_draft = _jcfb(cfb_src, cfb_len, smth)
cfb_pre = _a_jurik_filt(_a_jurik_filt(cfb_draft, jcfbsmlen, jcfbsmph), jcfbsmlen, jcfbsmph)
max = ta.highest(cfb_pre, nlen)
min = ta.lowest(cfb_pre, nlen)
denom = max - min
ratio = (denom > 0) ? (cfb_pre - min) / denom : 0.5
len_out_cfb = math.ceil(slim + ratio * (llim - slim))
emaout = EMA(src, int(len_out_cfb))
plot(emaout, color = src >= emaout ? greencolor : redcolor, linewidth = 3)
barcolor(color = src >= emaout ? greencolor : redcolor)
|
Current Trend [KPM] - Buy / Sell | https://www.tradingview.com/script/r1jPKx7c-Current-Trend-KPM-Buy-Sell/ | pm2022 | https://www.tradingview.com/u/pm2022/ | 137 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kpm
//@version=5
indicator(title="Current Trend [KPM] - Buy / Sell", shorttitle="CT-KPM",timeframe="180", timeframe_gaps=false)
linewidth = input.int(title="EMA Width", defval=3, maxval=10, minval=2)
rsi = ta.rsi(close,14)
ema = ta.ema(high,1)
emacol = rsi > 55 ? color.lime : rsi < 45 ? color.red : color.black
plot(ema, title="Histogram",style=plot.style_histogram, color = emacol, linewidth=linewidth, offset=0)
plot(ema, title="Top EMA", color = emacol, linewidth=linewidth, offset=0) |
Order Flow Imbalance Finder By Turk | https://www.tradingview.com/script/kEPvBsWe-Order-Flow-Imbalance-Finder-By-Turk/ | turk_shariq | https://www.tradingview.com/u/turk_shariq/ | 895 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © turk_shariq
//@version=5
indicator("Order Flow Imbalance Finder By Turk", "OFIF BY TURK", true, max_lines_count = 500)
// Inputs {
adboxcount = input.int (50, "Maximum Imb Displayed", 1, group = "Chart Customization")
boxcolor = input.color(color.new(color.gray, 65), "Imbalance Box Color", inline = "customcolor", group = "Chart Customization Box")
// }
// Box Variables {
var box[] imbboxarray = array.new_box()
topimbalance = low[2] <= open[1] and high[0] >= close[1]
topimbalancesize = low[2] - high[0]
bottomimbalance = high[2] >= open[1] and low[0] <= close[1]
bottomimbalancesize = low[0] - high[2]
//}
// Box Calc {
f_choppedoffimb(imbboxarray) =>
if array.size(imbboxarray) > 0
for i = array.size(imbboxarray) - 1 to 0 by 1
cutbox = array.get(imbboxarray, i)
boxhighzone = box.get_top(cutbox)
boxlowzone = box.get_bottom(cutbox)
boxrightzone = box.get_right(cutbox)
if na or bar_index - 1 == boxrightzone and not(high > boxlowzone and low < boxlowzone or high > boxhighzone and low < boxhighzone)
box.set_right(array.get(imbboxarray, i), bar_index)
// }
// Box Draw {
if topimbalance and topimbalancesize > 0 or bottomimbalance and bottomimbalancesize > 0
boxhighzone = topimbalance and topimbalancesize > 0 ? low[2] : low[0]
boxlowzone = topimbalance and topimbalancesize > 0 ? high[0] : high[2]
imbbox = box.new(bar_index, boxhighzone, bar_index, boxlowzone, boxcolor, border_style = line.style_dashed, bgcolor = boxcolor)
if array.size(imbboxarray) > adboxcount
box.delete(array.shift(imbboxarray))
array.push(imbboxarray, imbbox)
f_choppedoffimb(imbboxarray)
// } |
Bollinger Bands Breakout Oscillator [LuxAlgo] | https://www.tradingview.com/script/YaniRMVC-Bollinger-Bands-Breakout-Oscillator-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,736 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Bollinger Bands Breakout Oscillator [LUX]", "BBands BO [LuxAlgo]")
//------------------------------------------------------------------------------
//Settings
//------------------------------------------------------------------------------
length = input(14)
mult = input(1.)
src = input(close)
//Style
bull_css = input(#089981, 'Bullish Color'
, group = 'Style')
bear_css = input(#f23645, 'Bearish Color'
, group = 'Style')
//------------------------------------------------------------------------------
//Calculation
//------------------------------------------------------------------------------
stdev = ta.stdev(src, length) * mult
ema = ta.ema(src, length)
upper = ema + stdev
lower = ema - stdev
bull = 0.
bear = 0.
bull_den = 0.
bear_den = 0.
for i = 0 to length-1
bull += math.max(src[i] - upper[i], 0)
bear += math.max(lower[i] - src[i], 0)
bull_den += math.abs(src[i] - upper[i])
bear_den += math.abs(lower[i] - src[i])
bull := bull/bull_den*100
bear := bear/bear_den*100
//------------------------------------------------------------------------------
//Plots
//------------------------------------------------------------------------------
bull_grad = color.from_gradient(bull, 0, 100
, color.new(bull_css, 100)
, color.new(bull_css, 50))
bear_grad = color.from_gradient(bear, 0, 100
, color.new(bear_css, 100)
, color.new(bear_css, 50))
plot0 = plot(bull
, color = bull == 0 ? na : bull_css)
plot1 = plot(bear
, color = bear == 0 ? na : bear_css)
plot2 = plot(0
, color = na
, editable = false)
hline(50, 'Midline')
fill(plot0, plot2
, color = bull_grad)
fill(plot1, plot2
, color = bear_grad) |
Jurik Filter [Loxx] | https://www.tradingview.com/script/tfuf2UPB-Jurik-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 67 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Jurik Filter [Loxx]", overlay = true, shorttitle='JF [Loxx]', timeframe="", timeframe_gaps=true)
greencolor = #2DD204
redcolor = #D2042D
_a_jurik_filt(src, len, phase) =>
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
pow1 = math.max(len1 - 2.0, 0.5)
volty = 7.0, avolty = 9.0, vsum = 8.0, bsmax = 5.0, bsmin = 6.0, avgLen = 65
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
temp_avg = ta.sma(vsum, avgLen)
y = bar_index + 1
if(y <= avgLen + 1)
avolty := nz(avolty[1]) + 2.0 * (vsum - nz(avolty[1])) / (avgLen + 1)
else
avolty := temp_avg
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := dVolty > math.pow(len1, 1.0/pow1) ? math.pow(len1, 1.0/pow1) : dVolty
dVolty := dVolty < 1 ? 1 : dVolty
pow2 = math.pow(dVolty, pow1)
len2 = math.sqrt(0.5 * (len - 1)) * len1
Kv = math.pow(len2 / (len2 + 1), math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
alpha = math.pow(beta, pow2)
jma1 = 0.0, e0 = 0.0, e1 = 0.0, e2 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 := (e0 + phaseRatio * e1 - nz(jma1[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma1 := e2 + nz(jma1[1])
jma1
_filt(src, len, filter)=>
price = src
filtdev = filter * ta.stdev(src, len)
price := math.abs(price - price[1]) < filtdev ? price[1] : price
price
_hlcc4 = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
filterop = input.string("Both", "Filter Options", options = ["Price", "Jurik MA", "Both"], group= "Basic Settings")
src = _hlcc4
len = input.int(15, "Length", group= "Basic Settings")
filter = input.int(0, "Filter devaitions", minval = 0, group= "Basic Settings")
phase = input.float(0, "Jurik Phase", group= "Basic Settings")
double = input.bool(false, "Double Smooth?", group= "Basic Settings")
colorbars = input.bool(false, "Color bars?", group= "UI Options")
price = filterop == "Both" or filterop == "Price" ? _filt(src, len, filter) : src
jmaout = double ? _a_jurik_filt(_a_jurik_filt(price, len, phase), len, phase) : _a_jurik_filt(price, len, phase)
out = filterop == "Both" or filterop == "Jurik MA" ? _filt(jmaout, len, filter) : jmaout
plot(out,"Jurik Filter", color = src >= out ? greencolor : redcolor, linewidth = 3)
barcolor(colorbars ? src >= out ? greencolor : redcolor : na)
|
Composite Fractal Behavior (CFB) [Loxx] | https://www.tradingview.com/script/tSCDF0CI-Composite-Fractal-Behavior-CFB-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Composite Fractal Behavior (CFB) [Loxx]", shorttitle = "CFB [Loxx]", overlay = false, timeframe="", timeframe_gaps = true, max_bars_back = 2000)
greencolor = #2DD204
redcolor = #D2042D
_a_jurik_filt(src, len, phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jma = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
_jcfbaux(src, depth)=>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = depth - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
_jcfb(src, len, smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, _jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
src = input.source(hlcc4, "Source", group = "Basic Settings")
//max value is 10 so we since above 10 requests over 5K bars of history
len = input.int(10, "CFB Depth", maxval = 10, group = "Ingest Settings")
smth = input.int(8, "CFB Smooth Length", group = "Ingest Settings")
jper = input.int(5, "Juirk Fitler Smoothing Period", group = "Jurik Filter Settings")
phs = input.float(0.0, "Jurik Filter Phase", group = "Jurik Filter Settings")
out = _a_jurik_filt(_a_jurik_filt(_jcfb(src, len, smth), jper, phs), jper, phs)
out := math.ceil(out) < 1 ? 1 : math.ceil(out)
plot(out, "CFB", color = greencolor, linewidth = 2)
|
Grains:Backwardation/Contango | https://www.tradingview.com/script/77um2nrx-Grains-Backwardation-Contango/ | twingall | https://www.tradingview.com/u/twingall/ | 25 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// Wheat, Soybeans, Corn (ZW, ZS, ZC)
// Quickly visualize carrying charge market vs backwardized market by comparing the price of the next 2 years of futures contracts.
// Carrying charge (contract prices increasing into the future) = normal, representing the costs of carrying/storage of a commodity. When this is flipped to Backwardation (contract prices decreasing into the future): it's a bullish sign: Buyers want this commodity, and they want it NOW.
// Note: indicator does not map to time axis in the same way as price; it simply plots the progression of contract months out into the future; left to right; so timeframe doesn't matter for this plot
// There's likely some more efficient way to write this; e.g. when plotting for ZW; 15 of the security requests are redundant; but they are still made; and can make this slower to load
// TO UPDATE: in REQUEST CONTRACTS section, delete old contracts (top) and add new ones (bottom). Then in PLOTTING section, Delete old [expired] contract labels (bottom); add new [distant future] contract labels (top); adjust the X in 'bar_index-(X+_historical)' numbers accordingly
// This is one of three similar indicators: Meats | Metals | Grains
// -If you want to build from this; to work on other commodities; be aware that Tradingview limits the number of contract calls to 40 (hence the 3 seperate indicators)
// Tips:
// -Right click and reset chart if you can't see the plot; or if you have trouble with the scaling.
// -Right click and add to new scale if you prefer this not to overlay directly on price. Or move to new pane below.
// --Added historical input: input days back in time; to see the historical shape of the Futures curve via selecting 'days back' snapshot
// updated 15th June 2022
// updated 29th Jan 2023
// © twingall
indicator("Grains:Backwardation/Contango", overlay = true) //, scale = scale.right)
_historical = input(0, "time travel back; days")
_adr = ta.atr(5)
colorNone= color.new(color.white, 100)
//Function to test if contract is expired
int oneWeek = 5*24*60*60*1000 // 5 or more days since last reported closing price => expired
isExp (int _timeClose)=>
expired = _timeClose <= (last_bar_time-oneWeek)
///REQUEST CONTRACTS---
//shared contracts and/or All wheat contracts.
cash=request.security(syminfo.root + "1!", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jul22,jul22t]= request.security(syminfo.root + "N2022", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[sept22,sept22t]= request.security(syminfo.root + "U2022", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[dec22,dec22t]= request.security(syminfo.root + "Z2022", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[mar23,mar23t]= request.security(syminfo.root + "H2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[may23,may23t]= request.security(syminfo.root + "K2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jul23,jul23t]= request.security(syminfo.root + "N2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[sept23,sept23t]= request.security(syminfo.root + "U2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[dec23,dec23t]= request.security(syminfo.root + "Z2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[mar24,mar24t]=request.security(syminfo.root + "H2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[may24,may24t]=request.security(syminfo.root + "K2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jul24,jul24t]=request.security(syminfo.root + "N2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[sept24,sept24t]=request.security(syminfo.root + "U2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[dec24,dec24t] =request.security(syminfo.root + "Z2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[mar25,mar25t]=request.security(syminfo.root + "H2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[may25,may25t]=request.security(syminfo.root + "K2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jul25,jul25t]=request.security(syminfo.root + "N2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
//additional contracts for soybeans
[aug22,aug22t]=request.security(syminfo.root + "Q2022", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[nov22,nov22t]=request.security(syminfo.root + "X2022", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jan23,jan23t]=request.security(syminfo.root + "F2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[aug23,aug23t]=request.security(syminfo.root + "Q2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[nov23,nov23t]=request.security(syminfo.root + "X2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jan24,jan24t]=request.security(syminfo.root + "F2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[aug24,aug24t]=request.security(syminfo.root + "Q2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[nov24,nov24t]=request.security(syminfo.root + "X2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jan25,jan25t]=request.security(syminfo.root + "F2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[aug25,aug25t]=request.security(syminfo.root + "Q2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[sept25,sept25t]=request.security(syminfo.root + "U2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[nov25,nov25t]=request.security(syminfo.root + "X2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jul26,jul26t]=request.security(syminfo.root + "N2026", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[nov26,nov26t]=request.security(syminfo.root + "X2026", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
//additional contracts for Corn
[dec25,dec25t]=request.security(syminfo.root + "Z2025", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[dec26,dec26t]=request.security(syminfo.root + "Z2026", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
//---PLOTTING----
//
//Wheat plotting
if barstate.islast and syminfo.root=='ZW'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(jul25t)?0:jul25, text = 'Jul25', textcolor =isExp(jul25t)?colorNone: color.red, style=isExp(jul25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(may25t)?0:may25, text = 'May25', textcolor =isExp(may25t)?colorNone: color.red, style=isExp(may25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(mar25t)?0:mar25, text = 'Mar25', textcolor =isExp(mar25t)?colorNone: color.red, style=isExp(mar25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(dec24t)?0:dec24, text = 'Dec24', textcolor =isExp(dec24t)?colorNone: color.red, style=isExp(dec24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(sept24t)?0:sept24, text = 'Sept24', textcolor =isExp(sept24t)?colorNone: color.red, style=isExp(sept24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(jul24t)?0:jul24, text = 'Jul24', textcolor =isExp(jul24t)?colorNone: color.red, style=isExp(jul24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(may24t)?0:may24, text = 'May24', textcolor =isExp(may24t)?colorNone: color.red, style=isExp(may24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(mar24t)?0:mar24, text = 'Mar24', textcolor =isExp(mar24t)?colorNone: color.red, style=isExp(mar24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(dec23t)?0:dec23, text = 'Dec23', textcolor =isExp(dec23t)?colorNone: color.red, style=isExp(dec23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(20+_historical), isExp(sept23t)?0:sept23, text = 'Sept23', textcolor =isExp(sept23t)?colorNone: color.red, style=isExp(sept23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(22+_historical), isExp(jul23t)?0:jul23, text = 'Jul23', textcolor =isExp(jul23t)?colorNone: color.red, style=isExp(jul23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(24+_historical), isExp(may23t)?0:may23, text = 'May23', textcolor =isExp(may23t)?colorNone: color.red, style=isExp(may23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(26+_historical), isExp(mar23t)?0:mar23, text = 'Mar23', textcolor =isExp(mar23t)?colorNone: color.red, style=isExp(mar23t)?label.style_none:label.style_diamond, size = size.tiny)
//historical (3rd Feb 2023)
label.new(bar_index-(28+_historical), isExp(dec22t)?0:dec22, text = 'Dec22', textcolor =isExp(dec22t)?colorNone: color.red, style=isExp(dec22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(30+_historical), isExp(sept22t)?0:sept22, text = 'Sept22', textcolor =isExp(sept22t)?colorNone: color.red, style=isExp(sept22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(32+_historical), isExp(jul22t)?0:jul22, text = 'Jul22', textcolor =isExp(jul22t)?colorNone: color.red, style=isExp(jul22t)?label.style_none:label.style_diamond, size = size.tiny)
//Soybeans plotting
if barstate.islast and syminfo.root == 'ZS'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(nov26t)?0:nov26, text = 'Nov26', textcolor =isExp(nov26t)?colorNone: color.red, style=isExp(nov26t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(jul26t)?0:jul26, text = 'Jul26', textcolor =isExp(jul26t)?colorNone: color.red, style=isExp(jul26t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(nov25t)?0:nov25, text = 'Nov25', textcolor =isExp(nov25t)?colorNone: color.red, style=isExp(nov25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(sept25t)?0:sept25, text = 'Sept25', textcolor =isExp(sept25t)?colorNone: color.red, style=isExp(sept25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(aug25t)?0:aug25, text = 'Aug25', textcolor =isExp(aug25t)?colorNone: color.red, style=isExp(aug25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(jul25t)?0:jul25, text = 'July25', textcolor =isExp(jul25t)?colorNone: color.red, style=isExp(jul25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(may25t)?0:may25, text = 'May25', textcolor =isExp(may25t)?colorNone: color.red, style=isExp(may25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(mar25t)?0:mar25, text = 'Mar25', textcolor =isExp(mar25t)?colorNone: color.red, style=isExp(mar25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(jan25t)?0:jan25, text = 'Jan25', textcolor =isExp(jan25t)?colorNone: color.red, style=isExp(jan25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(20+_historical), isExp(nov24t)?0:nov24, text = 'Nov24', textcolor =isExp(nov24t)?colorNone: color.red, style=isExp(nov24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(22+_historical), isExp(sept24t)?0:sept24, text = 'Sept24', textcolor =isExp(sept24t)?colorNone: color.red, style=isExp(sept24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(24+_historical), isExp(aug24t)?0:aug24, text = 'Aug24', textcolor =isExp(aug24t)?colorNone: color.red, style=isExp(aug24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(26+_historical), isExp(jul24t)?0:jul24, text = 'Jul24', textcolor =isExp(jul24t)?colorNone: color.red, style=isExp(jul24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(28+_historical), isExp(may24t)?0:may24, text = 'May24', textcolor =isExp(may24t)?colorNone: color.red, style=isExp(may24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(30+_historical), isExp(mar24t)?0:mar24, text = 'Mar24', textcolor =isExp(mar24t)?colorNone: color.red, style=isExp(mar24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(32+_historical), isExp(jan24t)?0:jan24, text = 'Jan24', textcolor =isExp(jan24t)?colorNone: color.red, style=isExp(jan24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(34+_historical), isExp(nov23t)?0:nov23, text = 'Nov23', textcolor =isExp(nov23t)?colorNone: color.red, style=isExp(nov23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(36+_historical), isExp(sept23t)?0:sept23, text = 'Sept23', textcolor =isExp(sept23t)?colorNone: color.red, style=isExp(sept23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(38+_historical), isExp(aug23t)?0:aug23, text = 'Aug23', textcolor =isExp(aug23t)?colorNone: color.red, style=isExp(aug23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(40+_historical), isExp(jul23t)?0:jul23, text = 'July23', textcolor =isExp(jul23t)?colorNone: color.red, style=isExp(jul23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(42+_historical), isExp(may23t)?0:may23, text = 'May23', textcolor =isExp(may23t)?colorNone: color.red, style=isExp(may23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(44+_historical), isExp(mar23t)?0:mar23, text = 'Mar23', textcolor =isExp(mar23t)?colorNone: color.red, style=isExp(mar23t)?label.style_none:label.style_diamond, size = size.tiny)
//historical
label.new(bar_index-(46+_historical), isExp(jan23t)?0:jan23, text = 'Jan23', textcolor =isExp(jan23t)?colorNone: color.red, style=isExp(jan23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(48+_historical), isExp(nov22t)?0:nov22, text = 'Nov22', textcolor =isExp(nov22t)?colorNone: color.red, style=isExp(nov22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(50+_historical), isExp(sept22t)?0:sept22, text = 'Sept22', textcolor =isExp(sept22t)?colorNone: color.red, style=isExp(sept22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(52+_historical), isExp(aug22t)?0:aug22, text = 'Aug22', textcolor =isExp(aug22t)?colorNone: color.red, style=isExp(aug22t)?label.style_none:label.style_diamond, size = size.tiny)
//Corn plotting
if barstate.islast and syminfo.root == 'ZC'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(dec26t)?0:dec26 , text = 'Dec26', textcolor =isExp(dec26t)?colorNone: color.red, style=isExp(dec26t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(jul26t)?0:jul26, text = 'Jul26', textcolor =isExp(jul26t)?colorNone: color.red, style=isExp(jul26t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(dec25t)?0:dec25 , text = 'Dec25', textcolor =isExp(dec25t)?colorNone: color.red, style=isExp(dec25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(sept25t)?0:sept25, text = 'Sept25', textcolor =isExp(sept25t)?colorNone: color.red, style=isExp(sept25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(jul25t)?0:jul25, text = 'Jul25', textcolor =isExp(jul25t)?colorNone: color.red, style=isExp(jul25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(may25t)?0:may25, text = 'May25', textcolor =isExp(may25t)?colorNone: color.red, style=isExp(may25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(mar25t)?0:mar25, text = 'Mar25', textcolor =isExp(mar25t)?colorNone: color.red, style=isExp(mar25t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(dec24t)?0:dec24, text = 'Dec24', textcolor =isExp(dec24t)?colorNone: color.red, style=isExp(dec24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(sept24t)?0:sept24, text = 'Sept24', textcolor =isExp(sept24t)?colorNone: color.red, style=isExp(sept24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(20+_historical), isExp(jul24t)?0:jul24, text = 'Jul24', textcolor = isExp(jul24t)?colorNone: color.red, style= isExp(jul24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(22+_historical), isExp(may24t)?0:may24, text = 'May24', textcolor =isExp(may24t)?colorNone: color.red, style=isExp(may24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(24+_historical), isExp(mar24t)?0:mar24, text = 'Mar24', textcolor =isExp(mar24t)?colorNone: color.red, style=isExp(mar24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(26+_historical), isExp(dec23t)?0:dec23, text = 'Dec23', textcolor =isExp(dec23t)?colorNone: color.red, style=isExp(dec23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(28+_historical), isExp(sept23t)?0:sept23, text = 'Sept23', textcolor =isExp(sept23t)?colorNone: color.red, style=isExp(sept23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(30+_historical), isExp(jul23t)?0:jul23, text = 'Jul23', textcolor =isExp(jul23t)?colorNone: color.red, style=isExp(jul23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(32+_historical), isExp(may23t)?0:may23, text = 'May23', textcolor =isExp(may23t)?colorNone: color.red, style=isExp(may23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(34+_historical), isExp(mar23t)?0:mar23, text = 'Mar23', textcolor =isExp(mar23t)?colorNone: color.red, style=isExp(mar23t)?label.style_none:label.style_diamond, size = size.tiny)
//historical
label.new(bar_index-(36+_historical), isExp(dec22t)?0:dec22, text = 'Dec22', textcolor =isExp(dec22t)?colorNone: color.red, style=isExp(dec22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(38+_historical), isExp(sept22t)?0:sept22, text = 'Sept22', textcolor =isExp(sept22t)?colorNone: color.red, style=isExp(sept22t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(40+_historical), isExp(jul22t)?0:jul22, text = 'Jul22', textcolor =isExp(jul22t)?colorNone: color.red, style=isExp(jul22t)?label.style_none:label.style_diamond, size = size.tiny)
|
Meats: Backwardation/Cantango | https://www.tradingview.com/script/vQbtZA6d-Meats-Backwardation-Cantango/ | twingall | https://www.tradingview.com/u/twingall/ | 22 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// MEATS: Live Cattle; Feeder Cattle; Lean Hogs (LE, GF, HE)
// Quickly visualize carrying charge market vs backwardized market by comparing the price of the next 2 years of futures contracts.
// Carrying charge (contract prices increasing into the future) = normal, representing the costs of carrying/storage of a commodity. When this is flipped to Backwardation (contract prices decreasing into the future): it's a bullish sign: Buyers want this commodity, and they want it NOW.
// Note: indicator does NOT map to time axis in the same way as price; it simply plots the progression of contract months out into the future; left to right; so timeframe doesn't matter for this plot
// There's likely some more efficient way to write this; e.g. when plotting for Live Cattle (LE); 8 of the security requests are redundant; but they are still made; and can make this slower to load
// TO UPDATE: in REQUEST CONTRACTS section, delete old contracts (top) and add new ones (bottom). Then in PLOTTING section, Delete old [expired] contract labels (bottom); add new [distant future] contract labels (top); adjust the X in 'bar_index-(X+_historical)' numbers accordingly
// This is one of three similar indicators: Meats | Metals | Grains
// -If you want to build from this; to work on other commodities; be aware that Tradingview limits the number of contract calls to 40 (hence the 3 seperate indicators)
// Tips:
// -Right click and reset chart if you can't see the plot; or if you have trouble with the scaling.
// -Right click and add to new scale if you prefer this not to overlay directly on price. Or move to new pane below.
// --Added historical input: input days back in time; to see the historical shape of the Futures curve via selecting 'days back' snapshot
// updated contracts 30th Jan 2023
// © twingall
indicator("Meats: Backwardation/Cantango", overlay = true, scale = scale.right)
_historical = input(0, "time travel back; days")
_adr = ta.atr(5)
colorNone= color.new(color.white, 100)
//Function to test if contract is expired
int oneWeek = 5*24*60*60*1000 // 5 or more days since last reported closing price => expired
isExp (int _timeClose)=>
expired = _timeClose <= (last_bar_time-oneWeek)
///REQUEST CONTRACTS---
//shared contracts and/or All Live Cattle Contracts.
[dec22, dec22t]= request.security(syminfo.root + "Z2022", "D", [close[_historical], time_close], ignore_invalid_symbol=true)
[feb23, feb23t]= request.security(syminfo.root + "G2023", "D", [close[_historical], time_close], ignore_invalid_symbol=true)
[apr23, apr23t]= request.security(syminfo.root + "J2023", "D", [close[_historical], time_close], ignore_invalid_symbol=true)
[jun23,jun23t]= request.security(syminfo.root + "M2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[aug23,aug23t]= request.security(syminfo.root + "Q2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[oct23,oct23t]=request.security(syminfo.root + "V2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[dec23,dec23t]= request.security(syminfo.root + "Z2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[feb24,feb24t]=request.security(syminfo.root + "G2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[apr24,apr24t]=request.security(syminfo.root + "J2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jun24,jun24t]=request.security(syminfo.root + "M2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
//additional contracts for Feeder Cattle
[jan23,jan23t]=request.security(syminfo.root + "F2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[mar23,mar23t]=request.security(syminfo.root + "H2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[may23,may23t]=request.security(syminfo.root + "K2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[sept23,sept23t]=request.security(syminfo.root + "U2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[nov23,nov23t]=request.security(syminfo.root + "X2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[jan24,jan24t]=request.security(syminfo.root + "F2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
//additional contracts for Lean Hogs
[jul23,jul23t]=request.security(syminfo.root + "N2023", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
[may24,may24t]=request.security(syminfo.root + "K2024", "D", [close[_historical],time_close], ignore_invalid_symbol=true)
//PLOTTING----
//
//Live Cattle plotting
if barstate.islast and syminfo.root=='LE'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(jun24t)?0:jun24, text = 'Jun24', textcolor =isExp(jun24t)?colorNone: color.red, style=isExp(jun24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(apr24t)?0:apr24, text = 'Apr24', textcolor =isExp(apr24t)?colorNone: color.red, style=isExp(apr24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(feb24t)?0:feb24, text = 'Feb24', textcolor =isExp(feb24t)?colorNone: color.red, style=isExp(feb24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(dec23t)?0:dec23, text = 'Dec23', textcolor =isExp(dec23t)?colorNone: color.red, style=isExp(dec23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(oct23t)?0:oct23, text = 'Oct23', textcolor =isExp(oct23t)?colorNone: color.red, style=isExp(oct23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(aug23t)?0:aug23, text = 'Aug23', textcolor =isExp(aug23t)?colorNone: color.red, style=isExp(aug23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(jun23t)?0:jun23, text = 'Jun23', textcolor = isExp(jun23t)?colorNone:color.red, style=isExp(jun23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(apr23t)?0:apr23, text = 'Apr23', textcolor = isExp(apr23t)?colorNone:color.red, style=isExp(apr23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(feb23t)?0:feb23, text = 'Feb23', textcolor =isExp(feb23t)?colorNone: color.red, style=isExp(feb23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(20+_historical), isExp(dec22t)?0:dec22, text = 'Dec22', textcolor =isExp(dec22t)?colorNone: color.red, style=isExp(dec22t)?label.style_none:label.style_diamond, size = size.tiny)
//Feeder Cattle plotting
if barstate.islast and syminfo.root == 'GF'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(jan24t)?0:jan24, text = 'Jan24', textcolor = isExp(jan24t)?colorNone:color.red, style=isExp(jan24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(nov23t)?0:nov23, text = 'Nov23', textcolor =isExp(nov23t)?colorNone: color.red, style=isExp(nov23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(oct23t)?0:oct23, text = 'Oct23', textcolor =isExp(oct23t)?colorNone: color.red, style=isExp(oct23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(sept23t)?0:sept23,text ='Sept23',textcolor =isExp(sept23t)?colorNone: color.red, style=isExp(sept23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(aug23t)?0:aug23, text = 'Aug23', textcolor =isExp(aug23t)?colorNone: color.red, style=isExp(aug23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(may23t)?0:may23, text = 'May23', textcolor =isExp(may23t)?colorNone: color.red, style=isExp(may23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(apr23t)?0:apr23, text = 'Apr23', textcolor =isExp(apr23t)?colorNone: color.red, style= isExp(apr23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(mar23t)?0:mar23, text = 'Mar23', textcolor = isExp(mar23t)?colorNone:color.red, style=isExp(mar23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(jan23t)?0:jan23, text = 'Jan23', textcolor = isExp(jan23t)?colorNone:color.red, style=isExp(jan23t)?label.style_none:label.style_diamond, size = size.tiny)
//Lean Hogs plotting
if barstate.islast and syminfo.root == 'HE'
label.new(bar_index-(_historical), close[_historical]+ 2*_adr, text = 'S\nN\nA\nP\nS\nH\nO\nT', textcolor = color.red, style=label.style_arrowdown, color= color.red, size = size.tiny)
label.new(bar_index-(2+_historical), isExp(jun24t)?0:jun24, text = 'Jun24', textcolor =isExp(jun24t)?colorNone: color.red, style=isExp(jun24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(4+_historical), isExp(may24t)?0:may24, text = 'May24', textcolor =isExp(may24t)?colorNone: color.red, style=isExp(may24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(6+_historical), isExp(apr24t)?0:apr24, text = 'Apr24', textcolor =isExp(apr24t)?colorNone: color.red, style=isExp(apr24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(8+_historical), isExp(feb24t)?0:feb24, text = 'Feb24', textcolor =isExp(feb24t)?colorNone: color.red, style=isExp(feb24t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(10+_historical), isExp(dec23t)?0:dec23 , text = 'Dec23', textcolor =isExp(dec23t)?colorNone: color.red, style=isExp(dec23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(12+_historical), isExp(oct23t)?0:oct23, text = 'Oct23', textcolor = isExp(oct23t)?colorNone:color.red, style=isExp(oct23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(14+_historical), isExp(aug23t)?0:aug23, text = 'Aug23', textcolor =isExp(aug23t)?colorNone:color.red, style=isExp(aug23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(16+_historical), isExp(jul23t)?0:jul23, text = 'Jul23', textcolor =isExp(jul23t)?colorNone: color.red, style=isExp(jul23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(18+_historical), isExp(jun23t)?0:jun23, text = 'Jun23', textcolor = isExp(jun23t)?colorNone:color.red, style=isExp(jun23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(20+_historical), isExp(may23t)?0:may23, text = 'May23', textcolor = isExp(may23t)?colorNone:color.red, style=isExp(may23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(22+_historical), isExp(apr23t)?0:apr23, text = 'Apr23', textcolor =isExp(apr23t)?colorNone: color.red, style=isExp(apr23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(24+_historical), isExp(feb23t)?0:feb23, text = 'Feb23', textcolor =isExp(feb23t)?colorNone: color.red, style=isExp(apr23t)?label.style_none:label.style_diamond, size = size.tiny)
label.new(bar_index-(26+_historical), isExp(dec22t)?0:dec22, text = 'Dec22', textcolor =isExp(dec22t)?colorNone: color.red, style=isExp(dec22t)?label.style_none:label.style_diamond, size = size.tiny)
|
Sherry on crypto | https://www.tradingview.com/script/Ftfhmhif-Sherry-on-crypto/ | kshadabshayir | https://www.tradingview.com/u/kshadabshayir/ | 324 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kshadabshayir
//@version=5
// Indicator to combines:
// Trend Channel[Gu5] (SMA 200) +
// EMA's cross (26, 50 ) +
// Golden Cross (50, 200)
// Author: Sherry
// v2.3.6, 2022.02.18
// Trend Channel [Gu5] // Author: Sherry
//
// This source code is subject to these terms:
// Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)
// https://www.safecreative.org/work/2202190517452-Sherry on crypto
// You are free to:
// Share, copy and redistribute this script
// Adapt, transform and build on this script
// Under the following terms:
// Non-commercial: You cannot sell my indicator. You can't sell my work.
// Attribution: If you post part of my code, you must give me proper credit
//
// I am using part of this code published by @SOC and Public Library
// Disclaimer: I am not a financial advisor.
// For purpose educate only. Use at your own risk.
indicator(title = 'Sherry on crypto', shorttitle = 'SOC', overlay = true)
// --------- Inputs "==============================" |
i_maSrc = input.source (close, 'MA Source' , group = 'EMAs')
i_maFast1 = input.int (26, 'EMA Fast' , group = 'EMAs')
i_maFast2 = input.int (50, 'EMA Medium' , group = 'EMAs')
i_maLen = input.int (200, 'MA Trend' , group = 'Trend Channel')
o_maLen1 = 'EMA'
o_maLen2 = 'SMA'
i_maLenSel = input.string (o_maLen2, 'MA Type' , group = 'Trend Channel',
options = [o_maLen1, o_maLen2],
tooltip = "EMA or SMA")
i_htf = input.timeframe ('', 'Select Higher Timeframe' , tooltip = 'Only for MA Trend' , group = 'Trend Channel')
i_rangeLen = input.float (0.618, 'Channel Range Length' , tooltip = 'ATR of the MA Trend', group = 'Trend Channel')
i_slOn = input.bool (false, '■ Stop Loss On/Off' , group = 'Stop Loss')
i_sl = input.float (2.618, 'SL %' , step = 0.1, group = 'Stop Loss')
i_periodSw = input.bool (false, '■ Period On/Off' , group = 'Period')
o_start = timestamp ( '2020-01-01 00:00 GMT-3' )
o_end = timestamp ( '2099-12-31 00:00 GMT-3' )
i_periodStar = input.time (o_start, 'Start Time' , group = 'Period')
i_periodEnd = input.time (o_end, 'End Time' , group = 'Period')
o_posSel1 = 'Only Long'
o_posSel2 = 'Only Short'
o_posSel3 = 'Both'
i_posSel = input.string (o_posSel3, 'Position Type' , group = 'Strategy',
options = [o_posSel1, o_posSel2, o_posSel3],
tooltip = "Only Long, Only short or Both")
o_typeS1 = 'Strategy 1'
o_typeS2 = 'Strategy 2'
i_typeS = input.string (o_typeS2, 'Strategy Type' , group = 'Strategy',
options = [o_typeS1, o_typeS2],
tooltip = "Strategy 1:\nLong, when the price (close) crosses the ema.\nStrategy 2:\nLong, only when ema goes up")
i_barColOn = input.bool (true, '■ Bar Color On/Off' , group = 'Display')
i_alertOn = input.bool (true, '■ Alert On/Off' , group = 'Display')
i_channelOn = input.bool (false, '■ Channel Range On/Off' , tooltip = 'If the price (close) is over than the channel, the trend is bullish. If the price is under, bearish. And if the price is in the channel, it is in range', group = 'Display')
i_goldenOn = input.bool (false, '■ Golden Cross On/Off' )
// --------- Calculations
maFast1 = ta.ema(i_maSrc, i_maFast1)
maFast2 = ta.ema(i_maSrc, i_maFast2)
maDir = maFast1 > maFast2 ? 1 : -1
maTrend = request.security(syminfo.tickerid, i_htf,
i_maLenSel == "SMA" ? ta.sma(close, i_maLen)[1] : ta.ema(close, i_maLen)[1],
lookahead = barmerge.lookahead_on) //No repaint
maTrendDir = i_maSrc >= maTrend ? 1 : -1
rangeAtr = ta.atr(i_maLen) * i_rangeLen
rangeTop = maTrend + rangeAtr
rangeBot = maTrend - rangeAtr
rangeCh = (open <= rangeTop or close <= rangeTop) and
(open >= rangeBot or close >= rangeBot)
trendDir = i_typeS == 'Strategy 1' ?
rangeCh ? 0 :
maTrendDir == 1 and maDir == 1 and maTrend > maFast2 ? 0 :
maTrendDir == -1 and maDir == -1 and maTrend < maFast2 ? 0 :
maTrendDir == 1 and maDir == 1 ? 1 :
maTrendDir == -1 and maDir == -1 ? -1 : 0 :
rangeCh ? 0 :
maTrendDir == 1 and maDir == 1 ? 1 :
maTrendDir == -1 and maDir == -1 ? -1 : 0
GCross = i_goldenOn ? ta.crossover (maFast2, maTrend) : na
DCross = i_goldenOn ? ta.crossunder(maFast2, maTrend) : na
period = time >= i_periodStar and time <= i_periodEnd
// Set initial values
condition = 0.0
entryLong = trendDir == 1 and
i_posSel != 'Only Short' and
(i_periodSw ? period : true)
entryShort = trendDir == -1 and
i_posSel != 'Only Long' and
(i_periodSw ? period : true)
exitLong = (trendDir != 1 or maDir == -1) and
condition[1] == 1 and
i_posSel != 'Only Short' and
(i_periodSw ? period : true)
exitShort = (trendDir != -1 or maDir == 1) and
condition[1] == -1 and
i_posSel != 'Only Long' and
(i_periodSw ? period : true)
closeCond = exitLong or exitShort
// Stop Loss (sl)
slEntry = close * i_sl / 100
slTop = close + slEntry
slBot = close - slEntry
slTopBuff = ta.valuewhen(condition[1] != 1 and entryLong, slBot, 0)
slBotBuff = ta.valuewhen(condition[1] != -1 and entryShort, slTop, 0)
slLine = condition[1] == -1 and entryLong ? slTopBuff :
condition[1] == 1 and entryShort ? slBotBuff :
condition[1] == 1 or entryLong ? slTopBuff :
condition[1] == -1 or entryShort ? slBotBuff : na
slTopCross = condition[1] == 1 and ta.crossunder(close, slLine) or high > slLine and low < slLine
slBotCross = condition[1] == -1 and ta.crossover (close, slLine) or high > slLine and low < slLine
slExit = i_slOn ? slTopCross or slBotCross : na
// Conditions
condition := condition[1] != 1 and entryLong ? 1 :
condition[1] != -1 and entryShort ? -1 :
condition[1] != 0 and slExit ? 0 :
condition[1] != 0 and exitLong ? 0 :
condition[1] != 0 and exitShort ? 0 : nz(condition[1])
long = condition[1] != 1 and condition == 1
short = condition[1] != -1 and condition == -1
xl = condition[1] == 1 and exitLong and not slExit
xs = condition[1] == -1 and exitShort and not slExit
sl = condition[1] != 0 and slExit
// --------- Colors
c_green = #006400 //Green
c_greenLight = #388e3c //Green Light
c_red = #8B0000 //Red
c_redLight = #b71c1c //Red Light
c_emas = xl ? color.new(color.fuchsia, 99) :
xs ? color.new(color.fuchsia, 99) :
trendDir == 1 and maDir == 1 ? color.new(c_green, 99) :
trendDir == -1 and maDir == -1 ? color.new(c_red, 99) :
color.new(color.fuchsia, 99)
c_maFill = xl ? color.new(color.fuchsia, 70) :
xs ? color.new(color.fuchsia, 70) :
trendDir == 1 and maDir == 1 ? color.new(c_green, 70) :
trendDir == -1 and maDir == -1 ? color.new(c_red, 70) :
color.new(color.fuchsia, 70)
c_maTrend = trendDir == 0 ? color.new(color.fuchsia, 0) :
trendDir == 1 and maTrend[1] < maTrend ? color.new(c_green, 0) :
trendDir == 1 and maTrend[1] >= maTrend ? color.new(c_greenLight, 0) :
trendDir == -1 and maTrend[1] < maTrend ? color.new(c_redLight, 0) :
trendDir == -1 and maTrend[1] >= maTrend ? color.new(c_red, 0) : na
c_ch = trendDir == 0 ? color.new(color.fuchsia, 75) :
trendDir == 1 ? color.new(c_green, 75) :
trendDir == -1 ? color.new(c_red, 75) : na
c_slLineUp = ta.rising (slLine, 1)
c_slLineDn = ta.falling(slLine, 1)
c_slLine = c_slLineUp ? na :
c_slLineDn ? na : color.red
c_barCol = trendDir == 0 ? color.new(color.fuchsia, 0) :
trendDir == 1 and open <= close ? color.new(c_green, 0) :
trendDir == 1 and open > close ? color.new(c_greenLight, 0) :
trendDir == -1 and open >= close ? color.new(c_red, 0) :
trendDir == -1 and open < close ? color.new(c_redLight, 0) :
color.new(color.orange, 0)
// --------- Plots
p_maFast1 = plot(
maFast1,
title = 'EMA Fast 1',
color = c_emas,
linewidth = 1)
p_maFast2 = plot(
maFast2,
title = 'EMA Fast 2',
color = c_emas,
linewidth = 2)
fill(
p_maFast1, p_maFast2,
title = 'EMAs Fill',
color = c_maFill)
plot(
maTrend,
title = 'SMA Trend',
color = c_maTrend,
linewidth = 3)
p_chTop = plot(
i_channelOn ? rangeTop : na,
title = 'Top Channel',
color = c_maTrend,
linewidth = 1)
p_chBot = plot(
i_channelOn ? rangeBot : na,
title = 'Bottom Channel',
color = c_maTrend,
linewidth = 1)
fill(
p_chTop, p_chBot,
title = 'Channel',
color = c_ch)
plot(
i_slOn and condition != 0 ? slLine : na,
title = 'Stop Loss Line',
color = c_slLine,
linewidth = 1,
style = plot.style_linebr)
// --------- Alerts
barcolor(i_barColOn ? c_barCol : na)
plotshape(
i_alertOn and long ? high : na,
title = 'Buy Label',
text = 'Buy',
textcolor = color.white,
color = color.new(c_green, 0),
style = shape.labelup,
size = size.normal,
location = location.belowbar)
plotshape(
i_alertOn and short ? low : na,
title = 'Sell Label',
text = 'Sell',
textcolor = color.white,
color = color.new(c_red, 0),
style = shape.labeldown,
size = size.normal,
location = location.abovebar)
plotshape(
i_alertOn and (xl or xs) ? close : na,
title = '. Label',
text = '.',
textcolor = color.yellow,
color = color.new(color.orange, 0),
style = shape.triangleup,
size = size.small,
location = location.absolute)
plotshape(
i_alertOn and sl ? slLine : na,
title = 'Stop Loss',
text = 'Stop\nLoss',
textcolor = color.orange,
color = color.new(color.orange, 0),
style = shape.triangleup,
size = size.small,
location = location.absolute)
plotshape(
i_alertOn and i_goldenOn and GCross ? maTrend : na,
title = 'Golden Cross Label',
text = 'Golden\nCross',
textcolor = color.white,
color = color.new(color.orange, 0),
style = shape.labelup,
size = size.normal,
location = location.absolute)
plotshape(
i_alertOn and i_goldenOn and DCross ? maTrend : na,
title = 'Death Cross Label',
text = 'Death\nCross',
textcolor = color.white,
color = color.new(color.orange, 0),
style = shape.labeldown,
size = size.normal,
location = location.absolute)
bgcolor(
i_periodSw and not period ? color.new(color.gray, 90) : na,
title = 'Session')
alertcondition(
long or short or xl or xs or sl,
title = "Any Alert",
message = "Any Alert")
alertcondition(
long,
title = "Buy Alert",
message = "Buy Alert")
alertcondition(
short,
title = "Sell Alert",
message = "Sell Alert")
alertcondition(
xl,
title = "Buy Close Alert",
message = "Buy Close Alert")
alertcondition(
xs,
title = "Sell Close Alert",
message = "Sell Close Alert")
alertcondition(
sl,
title = "Stop Loss Alert",
message = "Stop Loss Alert") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.