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
|
---|---|---|---|---|---|---|---|---|
WaveTrend 3D | https://www.tradingview.com/script/clUzC70G-WaveTrend-3D/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 2,625 | 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/
// © jdehorty
// @version=5
indicator("WaveTrend 3D", max_lines_count=500, explicit_plot_zorder=true, timeframe="")
import jdehorty/KernelFunctions/2 as kernels
// ==================
// ==== Overview ====
// ==================
// WaveTrend 3D (WT3D) is a novel implementation of the famous WaveTrend (WT) indicator and has been completely redesigned from the ground up to address some
// of the inherent shortcomings associated with the traditional WT algorithm, including:
// (1) unbounded extremes
// (2) susceptibility to whipsaw
// (3) lack of insight into other timeframes
// Furthermore, WT3D expands upon the original functionality of WT by providing:
// (1) first-class support for multi-timeframe (MTF) analysis
// (2) kernel-based regression for trend reversal confirmation
// (3) various options for signal smoothing and transformation
// (4) a unique mode for visualizing an input series as a symmetrical, three-dimensional waveform useful for pattern identification and cycle-related analysis
// Fundamental Assumptions:
// (1) There exists a probability density function that describes the relative likelihood for a price to visit a given value.
// (2) The probability density function for price is a function of time.
// (3) The probability density function can approximate a Gaussian distribution (shown below).
// ___
// .::~!:.. |
// :ΞΞΞΞ~!ΞΞΞ!. |
// .ΞJΞΞΞΞ~!ΞΞΞ?J^ |
// :J?ΞΞΞΞΞ~!ΞΞΞΞΞJ^ |
// :J?ΞΞΞΞΞΞ~!ΞΞΞΞΞΞ??. |
// :JΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞ?J^ |
// :JΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞ?J^ [ PRICE ]
// .:~ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!!~ |
// :?~^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^Ξ! |
// ~:^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^!Ξ. |
// .Ξ!^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^~Ξ~ |
// .~Ξ~^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^!Ξ: |
// .~Ξ~^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^~!!^. |
// ....::^^!~~^^^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^^^^~!^^::...... |
// ..:::^^^^^^^::::::::::::::ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!::::::::::::^^^^^^^^:::.. |
//
// -------------------------------- [ TIME ] -------------------------------|
// How to use this indicator:
// - The basic usage of WT3D is similar to how one would use the traditional WT indicator.
// - Divergences can be spotted by finding "trigger waves", which are small waves that immediately follow a larger wave. These can also be thought of as Lower-Highs and Higher-Lows in the oscillator.
// - Instead of the SMA-cross in the original WT, the primary mechanism for identifying potential pivots are the crossovers of the fast/normal speed oscillators, denoted by the small red/green circles.
// - The larger red/green circles represent points where there could be a potential trigger wave for a Divergence. Settings related to Divergence detection can be configured in the "Divergence" section.
// - For overbought/oversold conditions, the 0.5 and -0.5 levels are convenient since the normal-speed oscillator will only exceed this level ~25% of the time.
// - For less experienced users, focusing on the three oscillators is recommended since they give critical information from multiple timeframes that can help to identify trends and spot potential divergences.
// - For more experienced users, this indicator also has many other valuable features, such as Center of Gravity (CoG) smoothing, Kernel Estimate Crossovers, a mirrored mode for cycle analysis, and more.
// - Note: Additional resources for learning/using the more advanced features of this indicator are a work in progress, but in the meantime, I am happy to answer any questions.
// ================
// ==== Inputs ====
// ================
// Signal Settings
src = input.source(close, title="Source", group="Signal Settings", inline='00')
useMirror = input.bool(false, "Use Mirror", group="Signal Settings", inline='00', tooltip="Displays the input series as a symmetrical, three-dimensional waveform useful for pattern identification and cycle-related analysis.")
useEma = input.bool(false, "Use EMA", group="Signal Settings", inline='ema')
emaLength = input.int(3, minval=1, title="Length", tooltip="The number of bars used to calculate the EMA smoothing.", group="Signal Settings", inline='ema')
useCog = input.bool(false, "Use CoG", tooltip="Use the center of gravity of the price distribution as the signal.", group="Signal Settings", inline="smoothing")
cogLength = input.int(6, minval=1, title="Length", tooltip="Add CoG smoothing to the signal", group="Signal Settings", inline="smoothing")
oscillatorLookback = input.int(20, "Lookback", minval=2, tooltip="The number of bars to use for signal smoothing. This lookback is scaled so that multiple frequencies can be examined concurrently.", group="Signal Settings", inline="osc")
quadraticMeanLength = input.int(50, "Quadratic Mean", minval=2, tooltip="The Quadratic Mean is the square root of the average of the squares of the values. It is used in the normalization of the price's rate of change.", group="Signal Settings", inline="osc")
src := useEma ? ta.ema(src, emaLength) : src
src := useCog ? ta.cog(src, cogLength) : src
speedToEmphasize = input.string('Slow', 'Speed to Emphasize', options=['Slow', 'Normal', 'Fast', 'None'], tooltip='Length to emphasize. This is like a timeframe within a timeframe.', inline="emphasis", group="Signal Settings")
emphasisWidth = input.int(2, "Width", tooltip="Width of the emphasized line.", inline="emphasis", group="Signal Settings")
useKernelMA = input.bool(false, "Display Kernel Moving Average", group="Signal Settings", tooltip="Display the Kernel Moving Average of the signal. This is a smoothed version of the signal that is more robust to noise.", inline="kernel")
useKernelEmphasis = input.bool(false, "Display Kernel Signal", group="Signal Settings", tooltip="Display the Kernel Estimator for the emphasized line. This is a smoothed version of the emphasized line that is more robust to noise.", inline="kernel")
// Oscillator Settings
offset = input.int(0, "Oscillator Separation Distance", group="Oscillators", tooltip="Separates the signal from the source by the specified number of bars. Useful for examining an oscillator in isolation and directly comparing to other timeframes.", inline="toggleOsc")
showOsc = input.bool(true, "Show Oscillator Lines", group="Oscillators", inline="toggleOsc")
showOsc := showOsc
f_length = input.float(0.75, "Fast Length:", step=0.05, tooltip="Length scale factor for the fast oscillator.", inline="fast", group="Oscillators")
f_smoothing = input.float(0.45, "Smoothing:", step=0.05, tooltip="Smoothing scale factor for the fast oscillator.", inline="fast", group="Oscillators")
n_length = input.float(1.0, "Normal Length:", step=0.05, tooltip="Length scale factor for the normal oscillator.", inline="normal", group="Oscillators")
n_smoothing = input.float(1.0, "Smoothing:", step=0.05, tooltip="Smoothing scale factor for the normal frequency.", inline="normal", group="Oscillators")
s_length = input.float(1.75, "Slow Length:", step=0.05, tooltip="Length scale factor for the slow oscillator.", inline="slow", group="Oscillators")
s_smoothing = input.float(2.5, "Smoothing:", step=0.05, tooltip="Smoothing scale factor for the slow frequency.", inline="slow", group="Oscillators")
// Divergence Detection
divThreshold = input.int(30, "Divergence Distance", minval=1, tooltip="The amount of bars for the divergence to be considered significant.", group="Divergence Detection", inline="divergence")
sizePercent = input.int(40, "Percent Size", tooltip="How big the current wave should be relative to the previous wave. A smaller waves immediately following a larger wave is often a trigger wave for a divergence.", group="Divergence Detection", inline="divergence")
// Overbought/Oversold Zones (Reversal Zones)
showObOs = input.bool(false, "Show OB/OS Zones", tooltip="Show the overbought/oversold zones for the normal-speed oscillator. These zones are useful for identifying potential reversal points since price will only exceed the ±0.5 level ~25% of the time.", group="Overbought/Oversold Zones", inline="zones")
invertObOsColors = input.bool(false, "Invert Colors", tooltip="Changes the colors of the overbought/oversold regions to be the inverse.", group="Overbought/Oversold Zones", inline="zones")
ob1 = input.float(0.5, "Overbought Primary", minval=0, maxval=1, step=0.05, group="Overbought/Oversold Zones", inline="ob")
ob2 = input.float(0.75, "Overbought Secondary", minval=0, maxval=1, step=0.05, group="Overbought/Oversold Zones", inline="ob")
os1 = input.float(-0.5, "Oversold Primary", minval=-1, maxval=0, step=0.05, group="Overbought/Oversold Zones", inline="os")
os2 = input.float(-0.75, "Oversold Secondary", minval=-1, maxval=0, step=0.05, group="Overbought/Oversold Zones", inline="os")
// Transparencies and Gradients
areaBackgroundTrans = input.float(128., "Background Area Transparency Factor", minval=0., step=1, tooltip="Transparency factor for the background area.", group="Transparencies and Gradients")
areaForegroundTrans = input.float(64., "Foreground Area Transparency Factor", minval=0., step=1, tooltip="Transparency factor for the foreground area.", group="Transparencies and Gradients")
lineBackgroundTrans = input.float(2.6, "Background Line Transparency Factor", minval=0., step=1, tooltip="Transparency factor for the background line.", group="Transparencies and Gradients")
lineForegroundTrans = input.float(2., "Foreground Line Transparency Factor", minval=0., step=1, tooltip="Transparency factor for the foreground line.", group="Transparencies and Gradients")
customTransparency = input.int(30, 'Custom Transparency', minval=0, maxval=100, step=5, tooltip="Transparency of the custom colors.", group="Transparencies and Gradients")
maxStepsForGradient = input.int(8, 'Total Gradient Steps', minval=2, maxval=256, tooltip='The maximum amount of steps supported for a gradient calculation is 256.', group="Transparencies and Gradients")
// The defaults are colors that Google uses for its Data Science libraries (e.g. TensorFlow). They are considered to be colorblind-safe.
var color fastBullishColor = input.color(color.new(#009988, 30), 'Fast Bullish Color', group="Colors", inline="fast")
var color normalBullishColor = input.color(color.new(#009988, 60), 'Normal Bullish Color', group="Colors", inline="normal")
var color slowBullishColor = input.color(color.new(#009988, 70), 'Slow Bullish Color', group="Colors", inline="slow")
var color fastBearishColor = input.color(color.new(#CC3311, 30), 'Fast Bearish Color', group="Colors", inline="fast")
var color normalBearishColor = input.color(color.new(#CC3311, 60), 'Normal Bearish Color', group="Colors", inline="normal")
var color slowBearishColor = input.color(color.new(#CC3311, 70), 'Slow Bearish Color', group="Colors", inline="slow")
var color c_bullish = input.color(#009988, "Bullish Divergence Signals", group="Colors", inline="divergence")
var color c_bearish = input.color(#CC3311, "Bearish Divergence Signals", group="Colors", inline="divergence")
lineBackgroundTrans := lineBackgroundTrans * customTransparency
areaBackgroundTrans := areaBackgroundTrans * customTransparency
lineForegroundTrans := lineForegroundTrans * customTransparency
areaForegroundTrans := areaForegroundTrans * customTransparency
areaFastTrans = areaBackgroundTrans
lineFastTrans = lineBackgroundTrans
areaNormalTrans = areaBackgroundTrans
lineNormalTrans = lineBackgroundTrans
areaSlowTrans = areaForegroundTrans
lineSlowTrans = lineForegroundTrans
switch speedToEmphasize
"Slow" =>
areaFastTrans := areaBackgroundTrans
lineFastTrans := lineBackgroundTrans
areaNormalTrans := areaBackgroundTrans
lineNormalTrans := lineBackgroundTrans
areaSlowTrans := areaForegroundTrans
lineSlowTrans := lineForegroundTrans
"Normal" =>
areaFastTrans := areaBackgroundTrans
lineFastTrans := lineBackgroundTrans
areaNormalTrans := areaForegroundTrans
lineNormalTrans := lineForegroundTrans
areaSlowTrans := areaBackgroundTrans
lineSlowTrans := lineBackgroundTrans
"Fast" =>
areaFastTrans := areaForegroundTrans
lineFastTrans := lineForegroundTrans
areaNormalTrans := areaBackgroundTrans
lineNormalTrans := lineBackgroundTrans
areaSlowTrans := areaBackgroundTrans
lineSlowTrans := lineBackgroundTrans
"None" =>
areaFastTrans := areaBackgroundTrans
lineFastTrans := lineBackgroundTrans
areaNormalTrans := areaBackgroundTrans
lineNormalTrans := lineBackgroundTrans
areaSlowTrans := areaBackgroundTrans
lineSlowTrans := lineBackgroundTrans
// =================================
// ==== Color Helper Functions =====
// =================================
getPlotColor(signal, bullColor, bearColor) =>
signal >= 0.0 ? bullColor : bearColor
getAreaColor(signal, useMomentum, bullColor, bearColor) =>
if useMomentum
ta.rising(signal, 1) ? bullColor : bearColor
else
signal >= 0.0 ? bullColor : bearColor
getColorGradientFromSteps(_source, _center, _steps, weakColor, strongColor) =>
var float _qtyAdvDec = 0.
var float _maxSteps = math.max(1, _steps)
bool _xUp = ta.crossover(_source, _center)
bool _xDn = ta.crossunder(_source, _center)
float _chg = ta.change(_source)
bool _up = _chg > 0
bool _dn = _chg < 0
bool _srcBull = _source > _center
bool _srcBear = _source < _center
_qtyAdvDec := _srcBull ? _xUp ? 1 : _up ? math.min(_maxSteps, _qtyAdvDec + 1) : _dn ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _srcBear ? _xDn ? 1 : _dn ? math.min(_maxSteps, _qtyAdvDec + 1) : _up ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _qtyAdvDec
color colorGradient = color.from_gradient(_qtyAdvDec, 1, _maxSteps, weakColor, strongColor)
colorGradient
getColorGradientFromSource(series, _min, _max, weakColor, strongColor) =>
var float baseLineSeries = _min + (_max - _min) / 2
color colorGradient = series >= baseLineSeries ? color.from_gradient(value=series, bottom_value=baseLineSeries, top_value=_max, bottom_color=weakColor, top_color=strongColor) : color.from_gradient(series, _min, baseLineSeries, strongColor, weakColor)
colorGradient
// ================================
// ==== Main Helper Functions =====
// ================================
normalizeDeriv(_src, _quadraticMeanLength) =>
float derivative = _src - _src[2]
quadraticMean = math.sqrt(nz(math.sum(math.pow(derivative, 2), _quadraticMeanLength) / _quadraticMeanLength))
derivative/quadraticMean
tanh(series float _src) =>
-1 + 2/(1 + math.exp(-2*_src))
dualPoleFilter(float _src, float _lookback) =>
float _omega = -99 * math.pi / (70 * _lookback)
float _alpha = math.exp(_omega)
float _beta = -math.pow(_alpha, 2)
float _gamma = math.cos(_omega) * 2 * _alpha
float _delta = 1 - _gamma - _beta
float _slidingAvg = 0.5 * (_src + nz(_src[1], _src))
float _filter = na
_filter := (_delta*_slidingAvg) + _gamma*nz(_filter[1]) + _beta*nz(_filter[2])
_filter
getOscillator(float src, float smoothingFrequency, int quadraticMeanLength) =>
nDeriv = normalizeDeriv(src, quadraticMeanLength)
hyperbolicTangent = tanh(nDeriv)
result = dualPoleFilter(hyperbolicTangent, smoothingFrequency)
// =================================
// ==== Oscillator Calculations ====
// =================================
// Fast Oscillator + Mirror
offsetFast = offset
f_lookback = f_smoothing * oscillatorLookback
signalFast = getOscillator(src, f_lookback, quadraticMeanLength)
seriesFast = f_length*signalFast+offsetFast
seriesFastMirror = useMirror ? -seriesFast + 2*offsetFast : na
// Normal Oscillator + Mirror
offsetNormal = 0
n_lookback = n_smoothing * oscillatorLookback
signalNormal = getOscillator(src, n_lookback, quadraticMeanLength)
seriesNormal = n_length*signalNormal+offsetNormal
seriesNormalMirror = useMirror ? -seriesNormal + 2*offsetNormal : na
// Slow Oscillator + Mirror
offsetSlow = -offset
s_lookback = s_smoothing * oscillatorLookback
signalSlow = getOscillator(src, s_lookback, quadraticMeanLength)
seriesSlow = s_length*signalSlow+offsetSlow
seriesSlowMirror = useMirror ? -seriesSlow + 2*offsetSlow : na
// =====================================
// ==== Color Gradient Calculations ====
// =====================================
// Fast Color Gradients (Areas and Lines)
fastBaseColor = getPlotColor(signalFast, fastBullishColor, fastBearishColor)
fastBaseColorInverse = getPlotColor(signalFast, fastBearishColor, fastBullishColor)
fastAreaGradientFromSource = getColorGradientFromSource(seriesFast, -1.+offsetFast, 1+offsetFast, color.new(fastBaseColor, areaFastTrans), fastBaseColor)
fastAreaGradientFromSteps = getColorGradientFromSteps(seriesFast, offsetFast, maxStepsForGradient, color.new(fastBaseColor, areaFastTrans), fastBaseColor)
fastLineGradientFromSource = getColorGradientFromSource(seriesFast, -1+offsetFast, 1+offsetFast, color.new(fastBaseColor, lineFastTrans), fastBaseColor)
fastLineGradientFromSteps = getColorGradientFromSteps(seriesFast, offsetFast, maxStepsForGradient, color.new(fastBaseColor, lineFastTrans), fastBaseColor)
fastAreaGradientFromSourceInverse = getColorGradientFromSource(seriesFast, -1.+offsetFast, 1+offsetFast, color.new(fastBaseColorInverse, areaFastTrans), fastBaseColorInverse)
fastAreaGradientFromStepsInverse = getColorGradientFromSteps(seriesFast, offsetFast, maxStepsForGradient, color.new(fastBaseColorInverse, areaFastTrans), fastBaseColorInverse)
// Normal Color Gradients (Areas and Lines)
normalBaseColor = getPlotColor(signalNormal, normalBullishColor, normalBearishColor)
normalBaseColorInverse = getPlotColor(signalNormal, normalBearishColor, normalBullishColor)
normalAreaGradientFromSource = getColorGradientFromSource(seriesNormal, -1.+offsetNormal, 1.+offsetNormal, color.new(normalBaseColor, areaNormalTrans), normalBaseColor)
normalAreaGradientFromSteps = getColorGradientFromSteps(seriesNormal, offsetNormal, maxStepsForGradient, color.new(normalBaseColor, areaNormalTrans), normalBaseColor)
normalLineGradientFromSource = getColorGradientFromSource(seriesNormal, -1+offsetNormal, 1+offsetNormal, color.new(normalBaseColor, lineNormalTrans), normalBaseColor)
normalLineGradientFromSteps = getColorGradientFromSteps(seriesNormal, offsetNormal, maxStepsForGradient, color.new(normalBaseColor, lineNormalTrans), normalBaseColor)
normalAreaGradientFromSourceInverse = getColorGradientFromSource(seriesNormal, -1.+offsetNormal, 1.+offsetNormal, color.new(normalBaseColorInverse, areaNormalTrans), normalBaseColorInverse)
normalAreaGradientFromStepsInverse = getColorGradientFromSteps(seriesNormal, offsetNormal, maxStepsForGradient, color.new(normalBaseColorInverse, areaNormalTrans), normalBaseColorInverse)
// Slow Color Gradients (Areas and Lines)
slowBaseColor = getPlotColor(signalSlow, slowBullishColor, slowBearishColor)
slowBaseColorInverse = getPlotColor(signalSlow, slowBearishColor, slowBullishColor)
slowAreaGradientFromSource = getColorGradientFromSource(seriesSlow, -1.75+offsetSlow, 1.75+offsetSlow, color.new(slowBaseColor, areaSlowTrans), slowBaseColor)
slowAreaGradientFromSteps = getColorGradientFromSteps(seriesSlow, offsetSlow, maxStepsForGradient, color.new(slowBaseColor, areaSlowTrans), slowBaseColor)
slowLineGradientFromSource = getColorGradientFromSource(seriesSlow, -1.75+offsetSlow, 1.75+offsetSlow, color.new(slowBaseColor, lineSlowTrans), slowBaseColor)
slowLineGradientFromSteps = getColorGradientFromSteps(seriesSlow, offsetSlow, maxStepsForGradient, color.new(slowBaseColor, lineSlowTrans), slowBaseColor)
slowAreaGradientFromSourceInverse = getColorGradientFromSource(seriesSlow, -1.75+offsetSlow, 1.75+offsetSlow, color.new(slowBaseColorInverse, areaSlowTrans), slowBaseColorInverse)
slowAreaGradientFromStepsInverse = getColorGradientFromSteps(seriesSlow, offsetSlow, maxStepsForGradient, color.new(slowBaseColorInverse, areaSlowTrans), slowBaseColorInverse)
// =========================================
// ==== Plot Parameters and Logic Gates ====
// =========================================
// Speed Booleans
isSlow = speedToEmphasize == "Slow"
isNormal = speedToEmphasize == "Normal"
isFast = speedToEmphasize == "Fast"
// Series Colors
seriesSlowColor = showOsc or isSlow ? color.new(slowLineGradientFromSource, lineSlowTrans) : na
seriesNormalColor = showOsc or isNormal ? color.new(normalLineGradientFromSource, lineNormalTrans) : na
seriesFastColor = showOsc or isFast ? color.new(fastLineGradientFromSource, lineFastTrans) : na
seriesSlowMirrorColor = useMirror ? seriesSlowColor : na
seriesNormalMirrorColor = useMirror ? seriesNormalColor : na
seriesFastMirrorColor = useMirror ? seriesFastColor : na
// Series Line Widths
seriesSlowWidth = isSlow ? emphasisWidth : 1
seriesNormalWidth = isNormal ? emphasisWidth : 1
seriesFastWidth = isFast ? emphasisWidth : 1
seriesSlowMirrorWidth = useMirror ? seriesSlowWidth : na
seriesNormalMirrorWidth = useMirror ? seriesNormalWidth : na
seriesFastMirrorWidth = useMirror ? seriesFastWidth : na
// Speed Related Switches
seriesEmphasis = switch
isFast => seriesFast
isNormal => seriesNormal
isSlow => seriesSlow
=> na
colorLineEmphasis = switch
isFast => fastLineGradientFromSource
isNormal => normalLineGradientFromSource
isSlow => slowLineGradientFromSource
=> na
colorAreaEmphasis = switch
isFast => fastAreaGradientFromSource
isNormal => normalAreaGradientFromSource
isSlow => slowAreaGradientFromSource
=> na
// Crossover Signals
bearishCross = ta.crossunder(seriesFast, seriesNormal) and seriesNormal > 0
bullishCross = ta.crossover(seriesFast, seriesNormal) and seriesNormal < 0
slowBearishMedianCross = ta.crossunder(seriesSlow, 0)
slowBullishMedianCross = ta.crossover(seriesSlow, 0)
normalBearishMedianCross = ta.crossunder(seriesNormal, 0)
normalBullishMedianCross = ta.crossover(seriesNormal, 0)
fastBearishMedianCross = ta.crossunder(seriesFast, 0)
fastBullishMedianCross = ta.crossover(seriesFast, 0)
// Last Crossover Values
lastBearishCrossValue = ta.valuewhen(condition=bearishCross, source=seriesNormal, occurrence=1)
lastBullishCrossValue = ta.valuewhen(condition=bullishCross , source=seriesNormal, occurrence=1)
// Trigger Wave Size Comparison
triggerWaveFactor = sizePercent/100
isSmallerBearishCross = bearishCross and seriesNormal < lastBearishCrossValue * triggerWaveFactor
isSmallerBullishCross = bullishCross and seriesNormal > lastBullishCrossValue * triggerWaveFactor
// ===========================
// ==== Kernel Estimators ====
// ===========================
// The following kernel estimators are based on the Gaussian Kernel.
// They are used for:
// (1) Confirming directional changes in the slow oscillator (i.e. a type of trend filter)
// (2) Visualizing directional changes as a dynamic ribbon (i.e. an additional oscillator that can crossover with the user specified oscillator of interest)
// (3) Visualizing transient directional changes while in the midst of a larger uptrend or downtrend (i.e. via color changes on the ribbon)
// Gaussian Kernel with a lookback of 6 bars, starting on bar 6 of the chart (medium fit)
yhat0 = kernels.gaussian(seriesEmphasis, 6, 6)
// Gaussian Kernel with a lookback of 3 bars, starting on bar 2 of the chart (tight fit)
yhat1 = kernels.gaussian(seriesEmphasis, 3, 2)
// Trend Assessment based on the relative position of the medium fit kernel to the slow oscillator
isBearishKernelTrend = yhat0 < seriesSlow
isBullishKernelTrend = yhat0 > seriesSlow
// Plots of the Kernel Estimators
p = plot(seriesEmphasis, title="Series Emphasis", color=color.new(color.white, 100))
p0 = plot(useKernelMA ? yhat0 : na, "Kernel Estimate for Trend", color=colorLineEmphasis)
p1 = plot(useKernelEmphasis ? yhat1 : na, "Kernel Estimate for Emphasis", color=colorLineEmphasis)
// By assigning the color of a faster gradient, we can create a dynamic ribbon that changes color even amid a more significant trend. Since this is essentially a projection
// of the rate of change of a lower frequency component to a higher frequency component, this can be seen as analogous to "Principal Component Analysis" (PCA), an unsupervised
// machine learning technique used to reduce the dimensionality of a dataset by projecting multi-dimensional data onto a single component. In this scenario, we are essentially
// reducing the dimensions from 3 to 2, allowing the user to focus exclusively on the ribbon, while the background oscillators are used to confirm the color changes of the ribbon.
// Fills for the Kernel Ribbon Colors
fill(p, p0, color=fastLineGradientFromSource)
fill(p, p1, color=fastLineGradientFromSource)
// Divergence Signals
isBearishDivZone = ta.barssince(bearishCross[1]) < divThreshold
isBullishDivZone = ta.barssince(bullishCross[1]) < divThreshold
// Crossover Detection
isBearishTriggerWave = isSmallerBearishCross and isBearishDivZone and isBearishKernelTrend
isBullishTriggerWave = isSmallerBullishCross and isBullishDivZone and isBullishKernelTrend
// =======================
// ==== Plots & Fills ====
// =======================
// Overbought/Oversold Zones
obPlot1 = plot(ob1, "Overbought Primary", color=na)
obPlot2 = plot(ob2, "Overbought Secondary", color=na)
osPlot1 = plot(os1, "Oversold Primary", color=na)
osPlot2 = plot(os2, "Oversold Secondary", color=na)
fill(obPlot1, obPlot2, offset == 0 and showObOs ? invertObOsColors ? normalAreaGradientFromStepsInverse : normalAreaGradientFromSteps : na)
fill(osPlot1, osPlot2, offset == 0 and showObOs ? invertObOsColors ? normalAreaGradientFromStepsInverse : normalAreaGradientFromSteps : na)
// Slow Plots with Fills
slowOscPlot = plot(seriesSlow, "Slow Oscillator", color=seriesSlowColor, linewidth=seriesSlowWidth)
slowOscPlotMirror = plot(seriesSlowMirror, "Slow Oscillator Mirror", color=seriesSlowMirrorColor, linewidth=seriesSlowMirrorWidth)
baseLineSlow = plot(offsetSlow, "Baseline Slow", slowLineGradientFromSteps, style=plot.style_line, linewidth=1)
fill(baseLineSlow, slowOscPlot, slowAreaGradientFromSource)
fill(baseLineSlow, slowOscPlotMirror, slowAreaGradientFromSource)
// Normal Plots with Fills
normalOscPlot = plot(seriesNormal, "Normal Oscillator", color=seriesNormalColor, linewidth=seriesNormalWidth)
normalOscPlotMirror = plot(seriesNormalMirror, "Normal Oscillator Mirror", color=seriesNormalMirrorColor, linewidth=seriesNormalMirrorWidth)
baseLineNormal = plot(offsetNormal, "Baseline Normal", normalLineGradientFromSteps, style=plot.style_line, linewidth=1)
fill(baseLineNormal, normalOscPlot, normalAreaGradientFromSource)
fill(baseLineNormal, normalOscPlotMirror, normalAreaGradientFromSource)
// Fast Plots with Fills
fastOscPlot = plot(seriesFast, "Fast Oscillator", color=seriesFastColor, linewidth=seriesFastWidth)
fastOscPlotMirror = plot(seriesFastMirror, "Fast Oscillator Mirror", color=seriesFastMirrorColor, linewidth=seriesFastMirrorWidth)
baseLineFast = plot(offsetFast, "Baseline Fast", color=fastLineGradientFromSteps, style=plot.style_line, linewidth=1)
fill(baseLineFast, fastOscPlot, fastAreaGradientFromSource)
fill(baseLineFast, fastOscPlotMirror, fastAreaGradientFromSource)
// Signal Plots
plot(bearishCross ? useMirror ? 0 : seriesNormal : na, title="Bearish Cross", style=plot.style_circles, linewidth=1, color=c_bearish, offset=-1)
plot(isBearishTriggerWave ? useMirror ? 0 : seriesNormal : na, title="Bearish Trigger Cross", style=plot.style_circles, linewidth=3, color=c_bearish, offset=-1)
plot(bullishCross ? useMirror ? 0 : seriesNormal : na, title="Bullish Cross", style=plot.style_circles, linewidth=1, color=c_bullish, offset=-1)
plot(isBullishTriggerWave ? useMirror ? 0 : seriesNormal : na, title="Bullish Trigger Cross", style=plot.style_circles, linewidth=3, color=c_bullish, offset=-1)
// ================
// ==== Alerts ====
// ================
alertcondition(bearishCross, title='Bearish Cross', message='WT3D: {{ticker}} ({{interval}}) Bearish Cross ▼ [{{close}}]')
alertcondition(bullishCross, title='Bullish Cross', message='WT3D: {{ticker}} ({{interval}}) Bullish Cross ▲ [{{close}}]')
alertcondition(isBearishTriggerWave, title='Bearish Divergence', message='WT3D: {{ticker}} ({{interval}}) Bearish Divergence ▼ [{{close}}]')
alertcondition(isBullishTriggerWave, title='Bullish Divergence', message='WT3D: {{ticker}} ({{interval}}) Bullish Divergence ▲ [{{close}}]')
alertcondition(slowBearishMedianCross, title='Slow Bearish Median Cross', message='WT3D: {{ticker}} ({{interval}}) Slow Bearish Median Cross ▼ [{{close}}]')
alertcondition(slowBullishMedianCross, title='Slow Bullish Median Cross', message='WT3D: {{ticker}} ({{interval}}) Slow Bullish Median Cross ▲ [{{close}}]')
alertcondition(normalBearishMedianCross, title='Normal Bearish Median Cross', message='WT3D: {{ticker}} ({{interval}}) Normal Bearish Median Cross ▼ [{{close}}]')
alertcondition(normalBullishMedianCross, title='Normal Bullish Median Cross', message='WT3D: {{ticker}} ({{interval}}) Normal Bullish Median Cross ▲ [{{close}}]')
alertcondition(fastBearishMedianCross, title='Fast Bearish Median Cross', message='WT3D: {{ticker}} ({{interval}}) Fast Bearish Median Cross ▼ [{{close}}]')
alertcondition(fastBullishMedianCross, title='Fast Bullish Median Cross', message='WT3D: {{ticker}} ({{interval}}) Fast Bullish Median Cross ▲ [{{close}}]')
// =====================
// ==== Backtesting ====
// =====================
condition = switch
bearishCross => 1
bullishCross => 2
isBearishTriggerWave => 3
isBullishTriggerWave => 4
slowBearishMedianCross => 5
slowBullishMedianCross => 6
normalBearishMedianCross => 7
normalBullishMedianCross => 8
fastBearishMedianCross => 9
fastBullishMedianCross => 10
plot(condition, "Alert Stream", display=display.none) |
VWMA Fibonacci Bands (VFIBs) | https://www.tradingview.com/script/9qWQd9z6-VWMA-Fibonacci-Bands-VFIBs/ | jpwall | https://www.tradingview.com/u/jpwall/ | 13 | 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/
// © jpwall
//@version=5
indicator("VWMA Fibonacci Bands (VFIBs)", overlay=true)
bars_vwma_st = input(title="VWMA (Short Term) Bars Back", defval = 20)
bars_vwma_1 = input(title="VWMA #1 Bars Back", defval=50)
bars_vwma_2 = input(title="VWMA #2 Bars Back", defval=200)
bars_vwma_lt = input(title="VWMA (Long Term) Bars Back", defval=500)
bars_atr = input(title="ATR Bars Back", defval=14)
fib_vwma1 = input(title="Outer Fibonacci (VWMA #1)", defval=6.18)
fib_vwma2 = input(title="Outer Fibonacci (VWMA #2)", defval=6.18)
vwma_st_base_color = input.color(title="VWMA (Short Term) Color", defval=color.white)
vwma1_base_color = input.color(title="VWMA #1 Main Color", defval=color.yellow)
vwma1_outer_color = input.color(title="VWMA #1 Outer Color", defval=color.yellow)
vwma2_base_color = input.color(title="VWMA #2 Main Color", defval=color.teal)
vwma2_outer_color = input.color(title="VWMA #2 Outer Color", defval=color.teal)
vwma_lt_base_color = input.color(title="VWMA (Long Term) Color", defval=color.red)
mid_2 = ta.vwma(math.avg(high, low, close), bars_vwma_2)
mid_1 = ta.vwma(math.avg(high, low, close), bars_vwma_1)
atr = ta.atr(bars_atr)
tf_vwma1 = (atr * fib_vwma1) + mid_1
bf_vwma1 = mid_1 - (atr * fib_vwma1)
tf_vwma2 = (atr * fib_vwma2) + mid_2
bf_vwma2 = mid_2 - (atr * fib_vwma2)
plot(mid_1, color=vwma1_base_color, linewidth=2)
plot(tf_vwma1, color=vwma1_outer_color)
plot(bf_vwma1, color=vwma1_outer_color)
plot(mid_2, color=vwma2_base_color, linewidth=2)
plot(tf_vwma2, color=vwma2_outer_color)
plot(bf_vwma2, color=vwma2_outer_color)
plot(ta.vwma(math.avg(high,low,close), bars_vwma_lt), color=vwma_lt_base_color)
plot(ta.vwma(math.avg(high,low,close), bars_vwma_st), color=vwma_st_base_color) |
Z Score Band | https://www.tradingview.com/script/Y9voSg8G-Z-Score-Band/ | tista | https://www.tradingview.com/u/tista/ | 167 | 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/
// © tista
//@version=5
indicator("Z Score Band", overlay=true)
Length = input(247)
stddevs = input(1.69)
src = close
basis = ta.ema(src, Length)
zscore = (src-basis)/ta.stdev(src, Length)
diff = math.abs(src - basis)
absZscore = math.abs(zscore)
bounds = diff / absZscore * stddevs
upper = basis + bounds
lower = basis - bounds
zscoreColor = zscore > 0.0 ? zscore >= zscore[1] ? zscore >= stddevs ? color.blue : color.green : color.new(color.green, 70) : zscore <= zscore[1] ? zscore <= -stddevs ? color.blue : color.red : color.new(color.red, 70)
plot(ta.ema(upper, 5), title="Upper Bound", linewidth=2)
plot(ta.ema(basis, 5), title="Median", color=color.new(color.white, 60), linewidth=2)
plot(ta.ema(lower, 5), title="Lower Bound", linewidth=2)
|
Smooth Slow RSI | https://www.tradingview.com/script/mVwKUslJ-Smooth-Slow-RSI/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 21 | 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/
// © peacefulLizard50262
//@version=5
indicator("Smooth Slow RSI")
rsi(src, len) =>
rsi = ta.rsi(src, 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
rsia = if rsi > 50
f + 50
else
-f + 50
rsia
rsi_len = input.int(140, "RSI Length", group = "RSI")
smoothing = input.int(20, "Smoothing Length", group = "RSI")
rsi = rsi(ta.hma(close, smoothing), rsi_len)
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)
maEnable = input.bool(false, "Enable MA", group="MA 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")
rsiMA = maEnable ? ma(rsi, maLengthInput, maTypeInput) : na
isBB = maTypeInput == "Bollinger Bands"
plot(rsi, "RSI", color=#7E57C2)
plot(rsiMA, "RSI-based MA", color=color.yellow)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "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")
|
TT Killzones | https://www.tradingview.com/script/MfAueA8o-TT-Killzones/ | Chill00r | https://www.tradingview.com/u/Chill00r/ | 173 | 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/
// © Chill00r
//@version=5
indicator('TT Killzones', overlay= true)
// INFO: Trading Days for Sessions: 1 = Sunday, 7 = Saturday
//**************************************************************************************************************
// INPUTS{
//**************************************************************************************************************
bool showAsia = input.bool(true , 'Asia' , inline = 'Asia')
color AsiaColor = input(#ffcc00 , ' ' , inline = 'Asia')
bool showEU = input.bool(true , 'London' , inline = 'EU')
color EUColor = input(#00b386 , ' ' , inline = 'EU')
bool showUS = input.bool(true , 'New York' , inline = 'US')
color USColor = input(#0077b3 , '' , inline = 'US')
bool showHighVol = input.bool(false , 'High Trading Volume' , inline = 'highVol')
string highVol = input.session("1300-1700" , '' , inline = 'highVol')
color highVolColor = input.color(color.red , '' , inline = 'highVol')
bool showCME = input.bool(true , 'CME open/close' , inline = 'CME')
color CMEColor = input(#0077b3 , '' , inline = 'CME')
//}
//**************************************************************************************************************
// FUNCTION{
//**************************************************************************************************************
var tf_is_below_1h = timeframe.isminutes and timeframe.multiplier < 60 ? true : false
f_session(_session, _days) =>
session = _session + ":" + _days
if not na(time(timeframe.period, session)) and tf_is_below_1h
true
//}
//**************************************************************************************************************
// PLOTTING{
//**************************************************************************************************************
//Asia
plotshape(showAsia ? f_session("0000-0900", "23456"): na , location = location.bottom, style = shape.square, size = size.tiny, color = AsiaColor)
plotshape(showAsia ? f_session("0000-0001", "23456"): na , location = location.bottom, style = shape.square, size = size.tiny, color = AsiaColor, textcolor = AsiaColor, text='Asia')
//London
plotshape(showEU ? f_session("0700-1600", "23456"): na , location = location.bottom, style = shape.square, size = size.tiny, color = EUColor)
plotshape(showEU ? f_session("0700-0701", "23456"): na , location = location.bottom, style = shape.square, size = size.tiny, color = EUColor, textcolor = EUColor, text='London')
//New York
plotshape(showUS ? f_session("1300-2200", "23456"): na , location = location.bottom, style = shape.square, size = size.tiny, color = USColor)
plotshape(showUS ? f_session("1300-1301", "23456"): na , location = location.bottom, style = shape.square, size = size.tiny, color = USColor, textcolor = USColor, text='New York')
//High Volume
plotshape(showEU and showUS and showHighVol ? f_session(highVol, "23456") : na , location = location.bottom, style = shape.square, size = size.tiny, color = highVolColor)
//CME
plotshape(showCME ? f_session("2300-0000", "1") : na , location = location.top, style = shape.square, size = size.tiny, color = CMEColor)
plotshape(showCME ? f_session("2300-2301", "1") : na , location = location.top, style = shape.square, size = size.tiny, color = CMEColor, textcolor = CMEColor, text='CME Open')
plotshape(showCME ? f_session("2100-2200", "6") : na , location = location.top, style = shape.square, size = size.tiny, color = CMEColor)
plotshape(showCME ? f_session("2100-2101", "6") : na , location = location.top, style = shape.square, size = size.tiny, color = CMEColor, textcolor = CMEColor, text='CME Close')
//} |
Volume RSI | https://www.tradingview.com/script/w3Ijuuer-Volume-RSI/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 142 | 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/
// © peacefulLizard50262
//@version=5
indicator("Volume RSI")
ema(src, len) => //{
alpha = 2 / (len + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
tma(src, int len) => //{
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
tma = 3 * (ema1 - ema2) + ema3
back = input.int(14, 'Length')
smooth = input.bool(true, "Smoothing")
cum = ta.cum(open > close ? -float(volume) : float(volume))
rsi = ta.rsi(smooth ? (cum + (cum[1] * 2) + (cum[2] * 2) + cum[3])/6 : cum, back)
plot(rsi, "RSI", color=#7E57C2)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
|
Turtle Money Management | https://www.tradingview.com/script/hUuFMjoY/ | miraalgo | https://www.tradingview.com/u/miraalgo/ | 62 | 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/
// © miraalgo
//@version=5
indicator("Turtle Money Management",overlay=true)
cap = input(10000,title="Capital")
risk = input.float(2,step=1,title="Risk % ")/100
mlt = input.float(2,step=0.1,title="ATR Multiplier",tooltip = "for stop-loss")
len = input.int(20,step=1,title="ATR Length")
direction = input.string(defval="Long",options=["Long","Short"],title="Direction")
b_daily = input.bool(defval=true,title="Use daily ATR")
////////////////////////////////////////////////
atr_daily= request.security(syminfo.tickerid, "1D", ta.atr(len))
voltly = b_daily ? atr_daily/close : ta.atr(len)/close
d = direction=="Long"? 1:-1
stopl = math.round_to_mintick((1-(d*(voltly*mlt)))*close)
invest = cap*(risk/(voltly*mlt))
plot(invest,display=display.none,title="Position ₵")
plot(stopl,color=color.yellow,title="Stop-loss",style=plot.style_circles)
var risktable = table.new(position = position.top_right, columns = 2, rows = 4, bgcolor = color.rgb(204, 230, 255), border_width = 2, frame_color= color.black, frame_width = 2)
table.set_border_color(risktable, color.black)
if barstate.islast
table.cell(table_id = risktable, column = 0, row = 0 , text = "Capital ₵")
table.cell(table_id = risktable, column = 1, row = 0,width = 15, text = str.tostring( cap))
table.cell(table_id = risktable, column = 0, row = 1, text = "Position ₵")
table.cell(table_id = risktable, column = 1, row = 1,width = 15, text =str.tostring(math.round(invest)) )
table.cell(table_id = risktable, column = 0, row = 2, text = "Volatility %")
table.cell(table_id = risktable, column = 1, row = 2,width = 15, text =str.tostring(math.round(voltly*100,2)))
table.cell(table_id = risktable, column = 0, row = 3, text = "Stop-Loss")
table.cell(table_id = risktable, column = 1, row = 3,width = 15, text =str.tostring(stopl) )
|
Next Pivot Projection [Trendoscope] | https://www.tradingview.com/script/dkSaWOLA-Next-Pivot-Projection-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 2,842 | 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/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
indicator("Next Pivot Projection [Trendoscope]", "NPP[Trendoscope]", overlay=true, max_lines_count = 500, max_labels_count = 500)
import HeWhoMustNotBeNamed/mZigzag/12 as zg
import HeWhoMustNotBeNamed/enhanced_ta/14 as eta
import HeWhoMustNotBeNamed/arrays/1 as pa
length = input.int(8, 'Length', group='Zigzag', display = display.none)
oscillatorType = input.string("rsi", title="Oscillator", inline="osc", options=["cci", "cmo", "cog", "mfi", "roc", "rsi"],
group='Oscillator', display = display.none)
oscLength = input.int(14, title="", inline="osc", group='Oscillator', display = display.none)
supertrendLength = input.int(5, 'History', inline='st', group='Supertrend', display = display.none)
drawSupertrend = input.bool(false, "Draw Zigzag Supertrend", inline='st2', group='Supertrend', display = display.none)
showTable = input.bool(false, 'Detailed Stats', inline='txt', group = 'Stats and Display', display = display.none)
txtSize = input.string(size.tiny, '', [size.tiny, size.small, size.normal, size.large, size.huge],
inline='txt', group = 'Stats and Display', display = display.none)
txtColor = input.color(color.white, '', inline='txt', group = 'Stats and Display', display = display.none)
showPivotLines = input.bool(true, 'Pivot Lines', inline='pli', group = 'Stats and Display', display = display.none)
showPivotLabel = input.bool(false, 'Pivot Label', inline='pla', group = 'Stats and Display', display = display.none)
fillAreas = input.bool(true, 'Fill Bullish/Bearish Sentiments', inline='fil', group = 'Stats and Display', display = display.none)
increment(mtx, row, col, val=1)=>matrix.set(mtx, row, col, matrix.get(mtx, row, col)+val)
gettrendindex(int price, int osc, int trend)=>
trendFactor = trend > 0 ? 0 : 1
priceFactor = math.abs(price) > 1? 1 : 0
oscFactor = math.abs(osc) > 1? 1 : 0
trendFactor*4 + priceFactor*2 + oscFactor
getSentimentDetails(pDir, oDir, sDir) =>
sentiment = pDir == oDir ? sDir == pDir or sDir * 2 == -pDir ? -sDir : sDir * 4 : sDir == pDir or sDir == -oDir ? 0 : (math.abs(oDir) > math.abs(pDir) ? sDir : -sDir) * (sDir == oDir ? 2 : 3)
sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣'
sentimentColor = sentiment == 4 ? color.green : sentiment == -4 ? color.red : sentiment == 3 ? color.lime : sentiment == -3 ? color.orange : sentiment == 2 ? color.rgb(202, 224, 13, 0) : sentiment == -2 ? color.rgb(250, 128, 114, 0) : color.silver
sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I'
[sentimentSymbol, sentimentLabel, sentimentColor]
getStatus(int trendIndex, int pivotDir)=>
trendFactor = int(trendIndex/4)
remainder = trendIndex % 4
priceFactor = int(remainder/2)+1
oscFactor = (remainder % 2)+1
trendChar = (trendFactor == 0)? 'U' : 'D'
priceChar = pivotDir > 0? (priceFactor == 2? 'HH' : 'LH') : (priceFactor == 2? 'LL' : 'HL')
oscChar = pivotDir > 0? (oscFactor == 2? 'HH' : 'LH') : (oscFactor == 2? 'LL' : 'HL')
trendChar + ' - ' + priceChar + '/'+oscChar
draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix,
barArray, trendArray, lineColor, lineWidth, lineStyle) =>
if matrix.rows(valueMatrix) > 2
idxLen1 = matrix.rows(valueMatrix)-idx1
idxLen2 = matrix.rows(valueMatrix)-idx2
lastValues = matrix.row(valueMatrix, idxLen1)
llastValues = matrix.row(valueMatrix, idxLen2)
lastDirections = matrix.row(directionMatrix, idxLen1)
lastRatios = matrix.row(ratioMatrix, idxLen1)
lastDivergence = matrix.row(divergenceMatrix, idxLen1)
lastDoubleDivergence = matrix.row(doubleDivergenceMatrix, idxLen1)
y1 = array.get(lastValues, 0)
y2 = array.get(llastValues, 0)
x1 = array.get(barArray, idxLen1)
x2 = array.get(barArray, idxLen2)
zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=lineColor, width=lineWidth, style=lineStyle)
currentDir = y1 > y2? 1 : -1
priceDir = array.get(lastDirections, 0)
oscDir = array.get(lastDirections, 1)
trendDir = array.get(trendArray, idxLen1)
trendIndex = gettrendindex(priceDir, oscDir, trendDir)
trendLabel = getStatus(trendIndex, currentDir)
[sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(priceDir, oscDir, trendDir)
labelStyle = currentDir > 0? label.style_label_down : label.style_label_up
zlabel = showPivotLabel ? label.new(x=x1, y=y1, yloc=yloc.price, color=sentimentColor, style=labelStyle, text=sentimentSymbol + ' ' + trendLabel,
textcolor=color.black, size = size.small, tooltip=sentimentLabel) : na
if array.size(zigzaglines) > 0
lastLine = array.get(zigzaglines, array.size(zigzaglines)-1)
if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1
pa.pop(zigzaglines)
pa.pop(zigzaglabels)
pa.push(zigzaglines, zline, 500)
pa.push(zigzaglabels, zlabel, 500)
draw(matrix<float> valueMatrix, matrix<int> directionMatrix, matrix<float> ratioMatrix, matrix<int> divergenceMatrix, matrix<int> doubleDivergenceMatrix, array<int> barArray, array<int> trendArray,
bool newZG, bool doubleZG, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid)=>
var zigzaglines = array.new_line(0)
var zigzaglabels = array.new_label(0)
if(newZG)
if doubleZG
draw_zg_line(2, 3, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
lineColor, lineWidth, lineStyle)
if matrix.rows(valueMatrix) >= 2
draw_zg_line(1, 2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
lineColor, lineWidth, lineStyle)
[valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, zigzaglines, zigzaglabels]
indicatorHigh = array.new_float()
indicatorLow = array.new_float()
indicatorLabels = array.new_string()
[oscHigh, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, high)
[oscLow, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, low)
array.push(indicatorHigh, math.round(oscHigh,2))
array.push(indicatorLow, math.round(oscLow,2))
array.push(indicatorLabels, oscillatorType+str.tostring(oscLength))
[valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, supertrendDir, supertrend, newZG, doubleZG] =
zg.calculate(length, array.from(high, low), indicatorHigh, indicatorLow, supertrendLength = supertrendLength)
nextDirection = matrix.rows(directionMatrix) > 0? matrix.row(directionMatrix, matrix.rows(directionMatrix)-1) : array.new_int()
lastDirection = matrix.rows(directionMatrix) > 1? matrix.row(directionMatrix, matrix.rows(directionMatrix)-2) : array.new_int()
llastDirection = matrix.rows(directionMatrix) > 2? matrix.row(directionMatrix, matrix.rows(directionMatrix)-3) : array.new_int()
lllastDirection = matrix.rows(directionMatrix) > 3? matrix.row(directionMatrix, matrix.rows(directionMatrix)-4) : array.new_int()
var pivotHighStats = matrix.new<int>(64, 3, 0)
var pivotLowStats = matrix.new<int>(64, 3, 0)
var pivotHighRatios = matrix.new<float>(64, 3, 0)
var pivotLowRatios = matrix.new<float>(64, 3, 0)
var pivotHighBars = matrix.new<float>(64, 3, 0)
var pivotLowBars = matrix.new<float>(64, 3, 0)
currentTotalTrendIndex = 0
nextTotalTrendIndex = 0
currentDir = matrix.rows(directionMatrix) > 0? matrix.get(directionMatrix, matrix.rows(directionMatrix)-1, 0) : 0
currentPDir = lastDirection.size() > 0 ? lastDirection.first() : na
changePriceDirection = ta.change(math.sign(currentPDir))
if(array.size(lllastDirection) > 0)
priceDirection = array.get(lastDirection, 0)
priceRatio = matrix.get(ratioMatrix, matrix.rows(ratioMatrix)-2, 0)
numberOfBars = array.get(barArray, array.size(barArray)-2) - array.get(barArray, array.size(barArray)-3)
currentPriceDirection = array.get(lastDirection, 0)
currentOscDirection = array.get(lastDirection, 1)
currentTrend = array.get(trendArray, array.size(trendArray)-2)
nextPriceDirection = array.get(nextDirection, 0)
nextOscDirection = array.get(nextDirection, 1)
nextTrend = array.get(trendArray, array.size(trendArray)-1)
lastPriceDirection = array.get(llastDirection, 0)
lastOscDirection = array.get(llastDirection, 1)
lastTrend = array.get(trendArray, array.size(trendArray)-3)
llastPriceDirection = array.get(lllastDirection, 0)
llastOscDirection = array.get(lllastDirection, 1)
llastTrend = array.get(trendArray, array.size(trendArray)-4)
colLast = math.abs(priceDirection) %2
nextTrendIndex = gettrendindex(nextPriceDirection, nextOscDirection, nextTrend)
currentTrendIndex = gettrendindex(currentPriceDirection, currentOscDirection, currentTrend)
lastTrendIndex = gettrendindex(lastPriceDirection, lastOscDirection, lastTrend)
llastTrendIndex = gettrendindex(llastPriceDirection, llastOscDirection, llastTrend)
totalIndex = lastTrendIndex*8 + llastTrendIndex
currentTotalTrendIndex := currentTrendIndex*8 + lastTrendIndex
nextTotalTrendIndex := nextTrendIndex*8 + currentTrendIndex
matrixToSet = math.sign(priceDirection) > 0? pivotHighStats : pivotLowStats
ratioMatrixToSet = math.sign(priceDirection) > 0? pivotHighRatios : pivotLowRatios
barMatrixToSet = math.sign(priceDirection) > 0? pivotHighBars : pivotLowBars
if(not na(currentPDir) and changePriceDirection != 0)
increment(matrixToSet, totalIndex, colLast)
increment(ratioMatrixToSet, totalIndex, colLast, priceRatio)
increment(barMatrixToSet, totalIndex, colLast, numberOfBars)
increment(matrixToSet, totalIndex, 2)
increment(ratioMatrixToSet, totalIndex, 2, priceRatio)
increment(barMatrixToSet, totalIndex, 2, numberOfBars)
var float hhValue = na
var float lhValue = na
var float llValue = na
var float hlValue = na
var float hhProbability = na
var float llProbability = na
var float htRatio = na
var float ltRatio = na
if(array.size(barArray) > 10)
currentBar = array.get(barArray, array.size(barArray)-1)
lastBar = array.get(barArray, array.size(barArray)-2)
currentPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-1, 0)
lastPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-2, 0)
llastPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-3, 0)
startRow = 2
var statsTable = showTable ? table.new(position=position.top_right, columns=10, rows=64+startRow, border_color = color.black, border_width = 2) : na
phSortIndices = array.sort_indices(matrix.col(pivotHighStats, 2), order.descending)
phColStart = currentDir > 0 ? 0 : 5
if(showTable)
table.clear(statsTable, 0, 0, 9, 64+startRow-1)
table.cell(statsTable, phColStart, 0, 'Pivot High Projection', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart, 1, 'Last Two Pivots', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart+2, 1, 'HH', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart+3, 1, 'LH', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart+4, 1, 'T', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.merge_cells(statsTable, phColStart, 0, phColStart+4, 0)
table.merge_cells(statsTable, phColStart, 1, phColStart+1, 1)
hlr = startRow
for i=0 to 63
si = array.get(phSortIndices, i)
lastTrendIndex = int(si/8)
llastTrendIndex = si%8
lastPivotStatus = getStatus(lastTrendIndex, -1)
llastPivotStatus = getStatus(llastTrendIndex, 1)
hhStats = matrix.get(pivotHighStats, si, 0)
lhStats = matrix.get(pivotHighStats, si, 1)
tStats = matrix.get(pivotHighStats, si, 2)
hhRatio = math.round(matrix.get(pivotHighRatios, si, 0)/hhStats, 3)
lhRatio = math.round(matrix.get(pivotHighRatios, si, 1)/lhStats, 3)
tRatio = math.round(matrix.get(pivotHighRatios, si, 2)/tStats, 3)
hhBars = math.round(matrix.get(pivotHighBars, si, 0)/hhStats)
lhBars = math.round(matrix.get(pivotHighBars, si, 1)/lhStats)
tBars = math.round(matrix.get(pivotHighBars, si, 2)/tStats)
highlight = math.sign(currentDir) < 0 ? nextTotalTrendIndex == si : currentTotalTrendIndex == si
hhTooltip = 'Average Ratio - '+str.tostring(hhRatio)+'\n'+'Average Bars - '+str.tostring(hhBars)
lhTooltip = 'Average Ratio - '+str.tostring(lhRatio)+'\n'+'Average Bars - '+str.tostring(lhBars)
tTooltip = 'Average Ratio - '+str.tostring(tRatio)+'\n'+'Average Bars - '+str.tostring(tBars)
if(highlight)
var line hhLine = na
var line lhLine = na
var line tLine = na
var label hhLabel = na
var label lhLabel = na
var label tLabel = na
line.delete(hhLine)
line.delete(lhLine)
line.delete(tLine)
label.delete(hhLabel)
label.delete(lhLabel)
label.delete(tLabel)
x1 = math.sign(currentDir) < 0 ? currentBar : lastBar
hhX2 = x1 + hhBars
lhX2 = x1 + lhBars
tX2 = x1 + tBars
y1 = math.sign(currentDir) < 0 ? currentPrice : lastPrice
prev = math.sign(currentDir) < 0 ? lastPrice : llastPrice
hhY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*hhRatio)
lhY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*lhRatio)
tY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*tRatio)
hhLine := line.new(x1, y1, hhX2, hhY2, xloc=xloc.bar_index, color=color.green, style=line.style_arrow_right)
lhLine := line.new(x1, y1, lhX2, lhY2, xloc=xloc.bar_index, color=color.lime, style=line.style_arrow_right)
tLine := line.new(x1, y1, tX2, tY2, xloc=xloc.bar_index, color=color.yellow, style=line.style_arrow_right)
hhPercent = str.tostring(hhStats*100/tStats, format.percent)
lhPercent = str.tostring(lhStats*100/tStats, format.percent)
hhText = 'Number of Historical References :'+str.tostring(hhStats)+'/'+str.tostring(tStats)+
'\nProbability of Higher High :'+hhPercent+
'\nAverage Higher High Ratio :'+str.tostring(hhRatio) +
'\nAverage Higher High Bars :'+str.tostring(hhBars)
lhText = 'Number of Historical References :'+str.tostring(lhStats)+'/'+str.tostring(tStats)+
'\nProbability of Lower High :'+lhPercent+
'\nAverage Lower High Ratio :'+str.tostring(lhRatio) +
'\nAverage Lower High Bars :'+str.tostring(lhBars)
tText = 'Number of Historical References :'+str.tostring(tStats)+
'\nAverage Fib Ratio :'+str.tostring(tRatio)+
'\nAverage Bars :'+str.tostring(tBars)
hhLabel := label.new(hhX2, hhY2, str.tostring(hhY2)+ ' - ' +hhPercent, style=label.style_label_lower_left, color=color.new(color.green, 70), textcolor = color.white, size=size.small, tooltip=hhText)
lhLabel := label.new(lhX2, lhY2, str.tostring(lhY2)+ ' - ' +lhPercent, style=label.style_label_upper_left, color=color.new(color.lime, 70), textcolor = color.white, size=size.small, tooltip=lhText)
tLabel := label.new(tX2, tY2, str.tostring(tY2)+ '@'+str.tostring(tRatio), style=label.style_label_left, color=color.new(color.yellow, 70), textcolor = color.white, size=size.small, tooltip=tText)
hhValue := hhY2
lhValue := lhY2
hhProbability := hhStats*100/tStats
htRatio := tRatio
if(hhStats != 0 and lhStats != 0) and showTable
table.cell(statsTable, phColStart, hlr, llastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.lime, 60))
table.cell(statsTable, phColStart+1, hlr, lastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.orange, 60))
table.cell(statsTable, phColStart+2, hlr, str.tostring(hhStats)+' - '+str.tostring(hhRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.green, highlight ? 50 : 90), tooltip = hhTooltip)
table.cell(statsTable, phColStart+3, hlr, str.tostring(lhStats)+' - '+str.tostring(lhRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.red, highlight? 50 : 90), tooltip = lhTooltip)
table.cell(statsTable, phColStart+4, hlr, str.tostring(tStats)+' - '+str.tostring(tRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.from_gradient(hhStats/tStats, 0, 1, color.red, color.green), tooltip = tTooltip)
hlr+=1
plColStart = currentDir < 0 ? 0 : 5
if(showTable)
table.cell(statsTable, plColStart, 0, 'Pivot Low Projection', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart, 1, 'Last Two Pivots', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart+2, 1, 'LL', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart+3, 1, 'HL', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart+4, 1, 'T', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.merge_cells(statsTable, plColStart, 0, plColStart+4, 0)
table.merge_cells(statsTable, plColStart, 1, plColStart+1, 1)
plSortIndices = array.sort_indices(matrix.col(pivotLowStats, 2), order.descending)
llr = startRow
for i=0 to 63
si = array.get(plSortIndices, i)
lastTrendIndex = int(si/8)
llastTrendIndex = si%8
lastPivotStatus = getStatus(lastTrendIndex, 1)
llastPivotStatus = getStatus(llastTrendIndex, -1)
llStats = matrix.get(pivotLowStats, si, 0)
hlStats = matrix.get(pivotLowStats, si, 1)
tStats = matrix.get(pivotLowStats, si, 2)
llRatio = math.round(matrix.get(pivotLowRatios, si, 0)/llStats, 3)
hlRatio = math.round(matrix.get(pivotLowRatios, si, 1)/hlStats, 3)
tRatio = math.round(matrix.get(pivotLowRatios, si, 2)/tStats, 3)
llBars = math.round(matrix.get(pivotLowBars, si, 0)/llStats)
hlBars = math.round(matrix.get(pivotLowBars, si, 1)/hlStats)
tBars = math.round(matrix.get(pivotLowBars, si, 2)/tStats)
highlight = math.sign(currentDir) > 0 ? nextTotalTrendIndex== si : currentTotalTrendIndex == si
llTooltip = 'Average Ratio - '+str.tostring(llRatio)+'\n'+'Average Bars - '+str.tostring(llBars)
hlTooltip = 'Average Ratio - '+str.tostring(hlRatio)+'\n'+'Average Bars - '+str.tostring(hlBars)
tTooltip = 'Average Ratio - '+str.tostring(tRatio)+'\n'+'Average Bars - '+str.tostring(tBars)
if(highlight)
var line llLine = na
var line hlLine = na
var line tLine = na
var label llLabel = na
var label hlLabel = na
var label tLabel = na
line.delete(llLine)
line.delete(hlLine)
line.delete(tLine)
label.delete(llLabel)
label.delete(hlLabel)
label.delete(tLabel)
x1 = math.sign(currentDir) > 0 ? currentBar : lastBar
llX2 = x1 + llBars
hlX2 = x1 + hlBars
tX2 = x1 + tBars
y1 = math.sign(currentDir) > 0 ? currentPrice : lastPrice
prev = math.sign(currentDir) > 0 ? lastPrice : llastPrice
llY2 = math.round_to_mintick(y1 - math.abs(y1-prev)*llRatio)
hlY2 = math.round_to_mintick(y1 - math.abs(y1-prev)*hlRatio)
tY2 = math.round_to_mintick(y1 - math.abs(y1-prev)*tRatio)
llLine := line.new(x1, y1, llX2, llY2, xloc=xloc.bar_index, color=color.red, style=line.style_arrow_right)
hlLine := line.new(x1, y1, hlX2, hlY2, xloc=xloc.bar_index, color=color.orange, style=line.style_arrow_right)
tLine := line.new(x1, y1, tX2, tY2, xloc=xloc.bar_index, color=color.yellow, style=line.style_arrow_right)
llPercent = str.tostring(llStats*100/tStats, format.percent)
hlPercent = str.tostring(hlStats*100/tStats, format.percent)
llText = 'Number of Historical References :'+str.tostring(llStats)+'/'+str.tostring(tStats)+
'\nProbability of Lower Low :'+llPercent+
'\nAverage Lower Low Ratio :'+str.tostring(llRatio) +
'\nAverage Lower Low Bars :'+str.tostring(llBars)
hlText = 'Number of Historical References :'+str.tostring(hlStats)+'/'+str.tostring(tStats)+
'\nProbability of Higher Low :'+hlPercent+
'\nAverage Higher Low Ratio :'+str.tostring(hlRatio) +
'\nAverage Higher Low Bars :'+str.tostring(hlBars)
tText = 'Number of Historical References :'+str.tostring(tStats)+
'\nAverage Fib Ratio :'+str.tostring(tRatio)+
'\nAverage Bars :'+str.tostring(tBars)
llLabel := label.new(llX2, llY2, str.tostring(llY2)+ ' - ' +llPercent, style=label.style_label_upper_left, color=color.new(color.red, 70), textcolor = color.white, size=size.small, tooltip=llText)
hlLabel := label.new(hlX2, hlY2, str.tostring(hlY2)+ ' - ' +hlPercent, style=label.style_label_lower_left, color=color.new(color.orange, 70), textcolor = color.white, size=size.small, tooltip=hlText)
tLabel := label.new(tX2, tY2, str.tostring(tY2)+ '@'+str.tostring(tRatio), style=label.style_label_left, color=color.new(color.yellow, 70), textcolor = color.white, size=size.small, tooltip=tText)
llValue := llY2
hlValue := hlY2
llProbability := llStats*100/tStats
ltRatio := tRatio
if(llStats != 0 and hlStats != 0) and showTable
table.cell(statsTable, plColStart, llr, llastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.orange, 60))
table.cell(statsTable, plColStart+1, llr, lastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.lime, 60))
table.cell(statsTable, plColStart+2, llr, str.tostring(llStats)+' - '+str.tostring(llRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.red, highlight? 50 : 90), tooltip=llTooltip)
table.cell(statsTable, plColStart+3, llr, str.tostring(hlStats)+' - '+str.tostring(hlRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.green, highlight? 50 : 90), tooltip = hlTooltip)
table.cell(statsTable, plColStart+4, llr, str.tostring(tStats)+' - '+str.tostring(tRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.from_gradient(llStats/tStats, 0, 1, color.green, color.red), tooltip = tTooltip)
llr+=1
if showPivotLines
draw(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, newZG, doubleZG)
plot(drawSupertrend? supertrend:na, color=supertrendDir>0? color.green:color.red, style=plot.style_linebr)
hhp = plot(fillAreas?hhValue:na, 'Higher High Range', color.new(color.green, 100), 1)
lhp = plot(fillAreas?lhValue:na, 'Lower High Range', color.new(color.lime, 100), 1)
llp = plot(fillAreas?llValue:na, 'Lower Low Range', color.new(color.red, 100), 1)
hlp = plot(fillAreas?hlValue:na, 'Higher Low Range', color.new(color.orange, 100), 1)
fill(hhp, lhp, color=color.new(hhProbability > 50 ? color.green : hhProbability < 50? color.red : color.silver, 90))
fill(llp, hlp, color=color.new(llProbability > 50 ? color.red : llProbability < 50? color.green : color.silver, 90))
|
RSI adjusted SuperTrend | https://www.tradingview.com/script/C7bB6qvJ-RSI-adjusted-SuperTrend/ | fikira | https://www.tradingview.com/u/fikira/ | 542 | 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/
// © fikira
//@version=5
indicator("RSI adjusted SuperTrend", overlay=true)
fct = input.float ( 2 , 'factor' )
lenATR = input.int ( 20 , 'length ATR' )
lenRSI = input.int ( 14 , 'Length RSI' )
toggle = input.string('100', 'Divide RSI value by', options=['100', '50'])
regST = input.bool (false, 'show Regular ST' )
rsi = ta.rsi (close, lenRSI)
aRsi = math.abs (rsi - 50 ) / (toggle == '100' ? 100 : 50)
// 90 or 10 -> 40 -> 0.4
// 80 or 20 -> 30 -> 0.3
// 60 or 40 -> 10 -> 0.1
// 50 -> 0
//plot(aRsi)
rsiAdjustedSupertrend(fct, ATRper) =>
src = hl2
atr = ta.atr(ATRper)
upper = src + fct * atr, upper2 = src + fct * atr
lower = src - fct * atr, lower2 = src - fct * atr
prevLower = nz(lower [1]), prevLower2 = nz(lower2[1])
prevUpper = nz(upper [1]), prevUpper2 = nz(upper2[1])
//
lower := lower > prevLower or close[1] < prevLower ? lower : prevLower
upper := upper < prevUpper or close[1] > prevUpper ? upper : prevUpper
//
lower2 -= lower2 * aRsi
upper2 += upper2 * aRsi
//
lower2 := lower2 > prevLower2 or close[1] < prevLower2 ? lower2 : prevLower2
upper2 := upper2 < prevUpper2 or close[1] > prevUpper2 ? upper2 : prevUpper2
//
int direction = na, int direction2 = na
float superdir = na, float superdir2 = na
prevSuperdir = superdir [1]
prevSuperdir2 = superdir2[1]
//
if na(atr[1])
direction := 1
direction2 := 1
else
if prevSuperdir == prevUpper
direction := close > upper ? -1 : 1
else
direction := close < lower ? 1 : -1
if prevSuperdir2 == prevUpper2
direction2 := close > upper2 ? -1 : 1
else
direction2 := close < lower2 ? 1 : -1
//
superdir := direction == -1 ? lower : upper
superdir2 := direction2 == -1 ? lower2 : upper2
//
[superdir, direction, superdir2, direction2]
[st, dir, st2, dir2] = rsiAdjustedSupertrend(fct, lenATR)
plot(regST ? st : na, 'regular SuperTrend' , linewidth=1, color=dir < 0 ? color.green : color.red)
plot( st2 , 'RSI adjusted SuperTrend', linewidth=2, color=dir2 < 0 ? color.lime : #FF0000 )
|
[HM] Fibonacci Fractals Absolute Auto v20221114 | https://www.tradingview.com/script/MDXk5A5R/ | HelionMelion | https://www.tradingview.com/u/HelionMelion/ | 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/
// © HelionMelion
//@version=5
indicator('[HM] Fibonacci Fractals Absolute Auto v20230608', shorttitle='FFAA', overlay=true)
calctype = input.string(title='CALCULUS TYPE', defval='⅓', options=['⅓','Φ', 'fibonaccing'], tooltip='Φ: default 0.382 and 0.618 levels \n ⅓: not fibo but 1/3 and 2/3 levels (based on chessmaster Hindenburg Melao article hint - give a try) \n fibonaccing: 0.236 and 0.764 levels (based on trader Marco Antonio Rossi method hint - give a try)') //, 'Φ3', 'Φ2', ])
float third = float(2) / 3
float phix = math.rphi
float phix2 = math.pow(phix, 2)
float phix3 = math.pow(phix, 3) //0.236
float fibonaccing = 1-phix3 //0.764
float phi = calctype == '⅓' ? third : calctype == 'Φ' ? phix : calctype == 'fibonaccing'? fibonaccing: na
n = input.int(defval=3, title='CALCULATION FOR MIN RANGE', minval=1)
highest_high() =>
var float h = 0.0
h := math.max(h, high)
h
lowest_low() =>
var float l = 10e10
l := math.min(l, low)
l
[low_12M, high_12M, yatr] = request.security(syminfo.tickerid, '12M', [lowest_low(), highest_high(), ta.atr(n)], lookahead=barmerge.lookahead_off)
[low_1M, high_1M, matr] = request.security(syminfo.tickerid, '1M', [lowest_low(), highest_high(), ta.atr(n)], lookahead=barmerge.lookahead_off)
[low_1W, high_1W, watr] = request.security(syminfo.tickerid, '1W', [lowest_low(), highest_high(), ta.atr(n)], lookahead=barmerge.lookahead_off)
[low_1D, high_1D, datr] = request.security(syminfo.tickerid, '1D', [lowest_low(), highest_high(), ta.atr(n)], lookahead=barmerge.lookahead_off)
var ATH = nz(high_12M, nz(high_1M, nz(high_1W, nz(high_1D, high))))
//ATH := high_12M //math.max(high, nz(ATH[1], ATH))
ATH := math.max(high, nz(ATH[1], ATH))
var ATL = nz(low_12M, nz(low_1M, nz(low_1W, nz(low_1D, low))))
//ATL := low_12M //math.min(low, nz(ATL[1], ATL))
ATL := math.min(low, nz(ATL[1], ATL))
//free = input(title="USE FREE ATR OR LOCKED", type=input.bool, defval=true)
//atrcount = input(defval=200, title="bars to consider", type=input.integer, minval=1)
//datrpercent = free? atr(atrcount) : (datr/ATH)*100
datrpercent = datr / ATH * 100
r1 = input.string(title='MIN RANGE INTRADAY CALC', defval='DAY ATR', options=['DAY ATR', 'WEEK ATR', 'MONTH ATR', 'YEAR ATR'])
r2 = input.string(title='MIN RANGE DAY CALC', defval='WEEK ATR', options=['DAY ATR', 'WEEK ATR', 'MONTH ATR', 'YEAR ATR'])
r3 = input.string(title='MIN RANGE MONTH CALC', defval='MONTH ATR', options=['DAY ATR', 'WEEK ATR', 'MONTH ATR', 'YEAR ATR'])
r4 = input.string(title='MIN RANGE YEAR CALC', defval='YEAR ATR', options=['DAY ATR', 'WEEK ATR', 'MONTH ATR', 'YEAR ATR'])
r = timeframe.isintraday ? r1 : timeframe.isdaily ? r2 : timeframe.isweekly ? r3 : timeframe.ismonthly ? r4 : na
rmultiplier = input.float(defval=2, title='DEPTH FOR MIN RANGE', minval=0.01)
range_1 = r == 'DAY ATR' ? datr * rmultiplier : r == 'WEEK ATR' ? watr * rmultiplier : r == 'MONTH ATR' ? matr * rmultiplier : r == 'YEAR ATR' ? yatr * rmultiplier : na
minrange(x, y) =>
m = x - y >= range_1 ? 1 : 0
m
//color2 = color.new(#1976d2,0)
//color3 = color.new(color.orange,0)
color1 = color.new(color.orange, 50)
color2 = color.new(color.orange, 50)
color3 = color.new(color.orange, 0)
//input(defval="red",type=input.string,options=[black,gray,white,red,fuchsia,lime,orange,aqua,yellow])
showhist = input(defval=true, title='SHOW HISTORY')
iSHOWlast = input(title='SHOW LAST N BARS', defval=500)
showlvlchange = input(defval=false, title='SHOW HISTORY LEVELS CHANGE') //and timeframe.isdwm
showline = input(defval=false, title='SHOW LINE')
showlabeldef = input(defval=true, title='SHOW LABEL def')
showlabelprice = input(defval=false, title='SHOW LABEL price')
//showlabelfibo = input(defval=true, title="SHOW LABEL fibonacci lvl", type=input.bool)
lwidth = input.int(defval=1, title='LINE WIDTH', minval=1)
ahead = input(defval=10, title='BAR AHEAD') //, minval=1)
multi = 0.0 //ahead*timeframe.multiplier * (timeframe.isintraday ? 1000*60 : timeframe.isdaily ? 1000*60*60*24 : timeframe.isweekly ? 1000*60*60*24*7 : timeframe.ismonthly ? 1000*60*60*24*30 : na)
space0 = ''
space = ' '
//space = ' '
space1 = space + space0
space2 = space1 + space
space3 = space2 + space
space4 = space3 + space
space5 = space4 + space
autofibo(UP, DOWN, EUP, CAP1, CAP2, CAP3, COLOR1, COLOR2, COLOR3) =>
for _j = 0 to 55 by 1
line.new(bar_index, open, bar_index, open)
//label.new(bar_index, open, "", color=#ffffffff)
a = minrange(UP, DOWN) ? (UP - DOWN) * phi + DOWN : na
b = minrange(UP, DOWN) ? (UP - DOWN) * (1 - phi) + DOWN : na
extt = input.string(title='EXTENSION TYPE', defval='less', options=['less', 'more'])
c = minrange(UP, DOWN) ? extt == 'less' ? (UP - DOWN) * (1 - phi) + UP : (UP - DOWN) * phi + UP : na
c := na
//space=" "
string texta1 = showlabelprice ? '' + str.tostring(a, '#.##') + '' : na
string textb1 = showlabelprice ? '' + str.tostring(b, '#.##') + '' : na
string textc1 = showlabelprice ? '' + str.tostring(c, '#.##') + '' : na
string texta2 = showlabeldef ? CAP1 + ' ' : na
string textb2 = showlabeldef ? CAP2 + ' ' : na
string textc2 = showlabeldef ? CAP3 + ' ' : na
string texta = space2 + texta2 + texta1
string textb = space2 + textb2 + textb1
string textc = space2 + textc2 + textc1
alabel = a and barstate.islast ? label.new(time, a, text=texta, style=label.style_none, xloc=xloc.bar_time, textcolor=COLOR1, size=size.normal, textalign=text.align_right) : na
label.delete(alabel[1])
blabel = b and barstate.islast ? label.new(time, b, text=textb, style=label.style_none, xloc=xloc.bar_time, textcolor=COLOR2, size=size.normal, textalign=text.align_right) : na
label.delete(blabel[1])
clabel = c and barstate.islast ? label.new(time, c, text=textc, style=label.style_none, xloc=xloc.bar_time, textcolor=COLOR3, size=size.normal, textalign=text.align_right) : na
label.delete(clabel[1])
aline = a and showline and barstate.islast ? showhist ? line.new(time, a, time + 1, a, xloc=xloc.bar_time, color=COLOR1, style=line.style_dotted, extend=extend.right) : line.new(time, a, time + 1, a, xloc=xloc.bar_time, color=COLOR1, style=line.style_dotted, extend=extend.both) : na
line.delete(aline[1])
bline = b and showline and barstate.islast ? showhist ? line.new(time, b, time + 1, b, xloc=xloc.bar_time, color=COLOR2, style=line.style_dotted, extend=extend.right) : line.new(time, b, time + 1, b, xloc=xloc.bar_time, color=COLOR2, style=line.style_dotted, extend=extend.both) : na
line.delete(bline[1])
cline = c and showline and barstate.islast ? showhist ? line.new(time, c, time + 1, c, xloc=xloc.bar_time, color=COLOR3, style=line.style_dotted, extend=extend.right) : line.new(time, c, time + 1, c, xloc=xloc.bar_time, color=COLOR3, style=line.style_dotted, extend=extend.both) : na
line.delete(cline[1])
[a, b, c, UP, DOWN, CAP1, CAP2, CAP3, COLOR1, COLOR2, COLOR3]
autotier(PHI1, PHI2, PHI3, UP, DOWN, CAP1, CAP2, CAP3, COLOR1, COLOR2, COLOR3) =>
if close > PHI1
up = UP
down = PHI1
eup = PHI3
//cap1 = "A"+CAP1//+"⬆"上中下
//cap2 = "A"+CAP2//+"⬆"上中下
cap1 = CAP1 + 'a' //"∾"//"→"//+CAP2//+"⬆"
cap2 = CAP2 + 'a' //"∾"//"→"//+CAP2//+"⬆"
cap3 = CAP3 + 'a' //"∾"//"→"//+CAP2//+"⬆"
colour1 = COLOR1
colour2 = COLOR2
colour3 = COLOR3
[phi1, phi2, phi3, xx1, xx2, xx3, xx4, xx5, xx6, xx7, xx8] = autofibo(up, down, eup, cap1, cap2, cap3, colour1, colour2, colour3)
[phi1, phi2, phi3, up, down, cap1, cap2, cap3, colour1, colour2, colour3]
else if close < PHI2
up = PHI2
down = DOWN
eup = PHI3
//cap1 = "E"+CAP1//+"⬇"上中下
//cap2 = "E"+CAP2//+"⬇"上中下
cap1 = CAP1 + 'c' //"≋"//↯"//"⇶"//+CAP2//+"⬆
cap2 = CAP2 + 'c' //"≋"//↯"//"⇶"//+CAP2//+"⬆
cap3 = CAP3 + 'c' //"≋"//↯"//"⇶"//+CAP2//+"⬆
colour1 = COLOR1
colour2 = COLOR2
colour3 = COLOR3
[phi1, phi2, phi3, xx1, xx2, xx3, xx4, xx5, xx6, xx7, xx8] = autofibo(up, down, eup, cap1, cap2, cap3, colour1, colour2, colour3)
[phi1, phi2, phi3, up, down, cap1, cap2, cap3, colour1, colour2, colour3]
else if close >= PHI2 and close <= PHI1
up = PHI1
down = PHI2
eup = PHI3
//cap1 = "Æ"+CAP1//+"♱"上中下±
//cap2 = "Æ"+CAP2//+"♱"ÆÆAE±
cap1 = CAP1 + 'b' //"≍"//"⇉"//+CAP2//+"⬆"
cap2 = CAP2 + 'b' //"≍"//"⇉"//+CAP2//+"⬆"
cap3 = CAP3 + 'b' //"≋"//↯"//"⇶"//+CAP2//+"⬆
colour1 = COLOR1
colour2 = COLOR2
colour3 = COLOR3
[phi1, phi2, phi3, xx1, xx2, xx3, xx4, xx5, xx6, xx7, xx8] = autofibo(up, down, eup, cap1, cap2, cap3, colour1, colour2, colour3)
[phi1, phi2, phi3, up, down, cap1, cap2, cap3, colour1, colour2, colour3]
fx(X) =>
showhist ? ta.change(X) and not showlvlchange ? na : X : na
show_labels = input(title='Show labels ATH ATL?', defval=true)
var ATL_label = show_labels ? label.new(bar_index, low, 'ATL', color=color.black, textcolor=color.orange, style=label.style_label_upper_right, size=size.small, tooltip='ALL TIME HIGH') : na
var ATH_label = show_labels ? label.new(bar_index, high, 'ATH', color=color.black, textcolor=color.orange, style=label.style_label_lower_right, size=size.small, tooltip='ALL TIME LOW') : na
if ATL < ATL[1] and show_labels
label.set_xy(ATL_label, bar_index, ATL * 1.00)
if ATH > ATH[1] and show_labels
label.set_xy(ATH_label, bar_index, ATH * 1.00)
char1 = input(defval='↥', title="character for higher segment separator") //"↥↥"//⬆"//⬆
char2 = input(defval='↧', title="character for lower segment separator") //"↧"//⬇"//"
char3 = '+' //"↧"//⬇"//"
up = ATH
down = 0.0
down := input(title='use ZERO for down point instead ALL TIME LOW?', defval=true , tooltip='This is my insight, never seen before, give a try') ? 0 : ATL
eup = 0.0
//eup := (up-down)*(phi)+up
[a, b, c, d, e, f, g, h, i, j, k] = autofibo(up, down, eup, char1, char2, char3, color1, color2, color3)
[a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1] = autotier(a, b, c, d, e, f, g, h, i, j, k)
[a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2] = autotier(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1)
[a3, b3, c3, d3, e3, f3, g3, h3, i3, j3, k3] = autotier(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2)
[a4, b4, c4, d4, e4, f4, g4, h4, i4, j4, k4] = autotier(a3, b3, c3, d3, e3, f3, g3, h3, i3, j3, k3)
[a5, b5, c5, d5, e5, f5, g5, h5, i5, j5, k5] = autotier(a4, b4, c4, d4, e4, f4, g4, h4, i4, j4, k4)
[a6, b6, c6, d6, e6, f6, g6, h6, i6, j6, k6] = autotier(a5, b5, c5, d5, e5, f5, g5, h5, i5, j5, k5)
[a7, b7, c7, d7, e7, f7, g7, h7, i7, j7, k7] = autotier(a6, b6, c6, d6, e6, f6, g6, h6, i6, j6, k6)
[a8, b8, c8, d8, e8, f8, g8, h8, i8, j8, k8] = autotier(a7, b7, c7, d7, e7, f7, g7, h7, i7, j7, k7)
[a9, b9, c9, d9, e9, f9, g9, h9, i9, j9, k9] = autotier(a8, b8, c8, d8, e8, f8, g8, h8, i8, j8, k8)
[a10, b10, c10, d10, e10, f10, g10, h10, i10, j10, k10] = autotier(a9, b9, c9, d9, e9, f9, g9, h9, i9, j9, k9)
showup = input(title='Show up point?', defval=true)
showdown = input(title='Show down point?', defval=true)
plot(showup ? fx(up) : na, color=color1, linewidth=lwidth * 2, style=plot.style_linebr, show_last=iSHOWlast)
plot(showdown ? fx(down) : na, color=color2, linewidth=lwidth * 2, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a), color=color1, linewidth=lwidth * 1, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b), color=color2, linewidth=lwidth * 1, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c),color=color3,linewidth=lwidth*1,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a1), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b1), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c1),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a2), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b2), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c2),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a3), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b3), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c3),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a4), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b4), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c4),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a5), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b5), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c5),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a6), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b6), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c6),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a7), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b7), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c7),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a8), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b8), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c8),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a9), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b9), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c9),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(a10), color=color1, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
plot(fx(b10), color=color2, linewidth=lwidth, style=plot.style_linebr, show_last=iSHOWlast)
//plot(fx(c10),color=color3,linewidth=lwidth,style=plot.style_linebr, show_last=iSHOWlast)
|
Adaptive Fisherized Trend Intensity Index | https://www.tradingview.com/script/3EvHwE49-Adaptive-Fisherized-Trend-Intensity-Index/ | simwai | https://www.tradingview.com/u/simwai/ | 107 | 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/
// © simwai
//@version=5
indicator('Adaptive Fisherized Trend Intensity Index', 'AF_TII', precision=2)
// -- Input --
float source = input.source(title='Source', defval=close, group='TII', inline='1')
string resolution = input.timeframe(defval='', title='Choose Resolution', group='TII', inline='1')
string maType = input.string(defval='KAMA', title='Choose MA', options=['SMA', 'SMMA', 'EMA', 'ZLEMA', 'DEMA', 'TEMA', 'HMA', 'EHMA', 'RMA', 'WMA', 'VWMA', 'KAMA'], group='TII', inline='2')
int maLength = input.int(title='MA Length', defval=200, group='TII', inline='3', tooltip='When adaptive mode is enabled, this value is used as the maximum length.')
int min = input.int(title='Min MA Length', defval=50, group='TII', inline='4', tooltip='When adaptive mode is enabled, this value is used as the minimum length.')
float upperLevel = input.float(title='Upper Level', defval=0.8, group='TII', inline='5')
float lowerLevel = input.float(title='Lower Level', defval=-0.8, group='TII', inline='5')
string adaptiveMode = input.string('None', 'Choose Adaptive Mode', options=['Hilbert Transform', 'Inphase-Quadrature Transform', 'Median', 'Homodyne Discriminator', 'None'], group='TII', inline='6')
bool isHighlighted = input.bool(defval=true, title='Enable Trend Highlightning', group='TII', inline='7')
bool isFisherized = input.bool(defval=false, title='Enable Fisherization', group='TII', inline='8')
bool isHannEnabled = input.bool(true, 'Enable Hann Window Smoothing', group='TII', inline='9')
int hannLength = input.int(2, 'Hann Window Length', minval=2, tooltip='Smoothing Length', group='TII', inline='9')
// -- Colors --
color maximumYellowRed = color.rgb(255, 203, 98) // yellow
color rajah = color.rgb(242, 166, 84) // orange
color magicMint = color.rgb(171, 237, 198)
color lightPurple = color.rgb(193, 133, 243)
color languidLavender = color.rgb(232, 215, 255)
color maximumBluePurple = color.rgb(181, 161, 226)
color skyBlue = color.rgb(144, 226, 244)
color lightGray = color.rgb(214, 214, 214)
color quickSilver = color.rgb(163, 163, 163)
color mediumAquamarine = color.rgb(104, 223, 153)
color lightOrange = color.rgb(241, 205, 167)
color peachPuff = color.rgb(244, 215, 184)
color transpLightGray = color.new(lightGray, 50)
color transpMagicMint = color.new(magicMint, 45)
color transpRajah = color.new(rajah, 45)
color sidetrendColor = color.new(peachPuff, 45)
// -- Global States --
[_src, _close, _high, _low, _volume] = request.security(syminfo.tickerid, resolution, [source[1], close[1], high[1], low[1], volume[1]], barmerge.gaps_off, barmerge.lookahead_on)
// -- Functions --
// Apply normalization
normalize(float _src, int _min, int _max) =>
var float _historicMin = 1.0
var float _historicMax = -1.0
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 1)
// Inverse Fisher Transformation (IFT)
fisherize(float _value) => (math.exp(2 * _value) - 1) / (math.exp(2 * _value) + 1)
// Convert length to alpha
getAlpha(float _length) => 2 / (_length + 1)
// Get dominant cyber cycle – Median – Credits to @blackcat1402
getMedianDc(float Price, float alpha=0.07, simple float CycPart=0.5) =>
Smooth = 0.00
Cycle = 0.00
Q1 = 0.00
I1 = 0.00
DeltaPhase = 0.00
MedianDelta = 0.00
DC = 0.00
InstPeriod = 0.00
Period = 0.00
I2 = 0.00
Q2 = 0.00
IntPeriod = 0
Smooth := (Price + 2 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 6
Cycle := (1 - .5 * alpha) * (1 - .5 * alpha) * (Smooth - 2 * nz(Smooth[1]) + nz(Smooth[2])) + 2 * (1 - alpha) * nz(Cycle[1]) - (1 - alpha) * (1 - alpha) * nz(Cycle[2])
Cycle := bar_index < 7 ? (Price - 2 * nz(Price[1]) + nz(Price[2])) / 4 : Cycle
Q1 := (.0962 * Cycle + .5769 * nz(Cycle[2]) - .5769 * nz(Cycle[4]) - .0962 * nz(Cycle[6])) * (.5 + .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]))) : DeltaPhase
DeltaPhase := DeltaPhase < 0.1 ? 0.1 : DeltaPhase
DeltaPhase := DeltaPhase > 1.1 ? 1.1 : DeltaPhase
MedianDelta := ta.median(DeltaPhase, 5)
DC := MedianDelta == 0.00 ? 15.00 : 6.28318 / MedianDelta + .5
InstPeriod := .33 * DC + .67 * nz(InstPeriod[1])
Period := .15 * InstPeriod + .85 * nz(Period[1])
//it can add filter to Period here
//IntPeriod := round((4*Period + 3*nz(Period[1]) + 2*nz(Period[3]) + nz(Period[4])) / 20)
IntPeriod := math.round(Period * CycPart) > 34 ? 34 : math.round(Period * CycPart) < 1 ? 1 : math.round(Period * CycPart)
IntPeriod
// Get dominant cyber cycle – Inphase-Quadrature -- Credits to @DasanC
getIqDc(float src, int min, int max) =>
PI = 3.14159265359
P = src - src[7]
lenIQ = 0.0
lenC = 0.0
imult = 0.635
qmult = 0.338
inphase = 0.0
quadrature = 0.0
re = 0.0
im = 0.0
deltaIQ = 0.0
instIQ = 0.0
V = 0.0
inphase := 1.25 * (P[4] - imult * P[2]) + imult * nz(inphase[3])
quadrature := P[2] - qmult * P + qmult * nz(quadrature[2])
re := 0.2 * (inphase * inphase[1] + quadrature * quadrature[1]) + 0.8 * nz(re[1])
im := 0.2 * (inphase * quadrature[1] - inphase[1] * quadrature) + 0.8 * nz(im[1])
if re != 0.0
deltaIQ := math.atan(im / re)
deltaIQ
for i = 0 to max by 1
V += deltaIQ[i]
if V > 2 * PI and instIQ == 0.0
instIQ := i
instIQ
if instIQ == 0.0
instIQ := nz(instIQ[1])
instIQ
lenIQ := 0.25 * instIQ + 0.75 * nz(lenIQ[1], 1)
length = lenIQ < min ? min : lenIQ
math.round(length)
// Get dominant cyber cycle – Hilbert Transform -- Credits to @DasanC
getHtDc(float src) =>
Imult = .635
Qmult = .338
PI = 3.14159
InPhase = 0.0
Quadrature = 0.0
Phase = 0.0
DeltaPhase = 0.0
InstPeriod = 0.0
Period = 0.0
Value4 = 0.0
if bar_index > 5
// Detrend src
Value3 = src - src[7]
// Compute InPhase and Quadrature components
InPhase := 1.25 * (Value3[4] - Imult * Value3[2]) + Imult * nz(InPhase[3])
Quadrature := Value3[2] - Qmult * Value3 + Qmult * nz(Quadrature[2])
// Use ArcTangent to compute the current phase
if math.abs(InPhase + InPhase[1]) > 0
Phase := 180 / PI * math.atan(math.abs((Quadrature + Quadrature[1]) / (InPhase + InPhase[1])))
Phase
// Resolve the ArcTangent ambiguity
if InPhase < 0 and Quadrature > 0
Phase := 180 - Phase
Phase
if InPhase < 0 and Quadrature < 0
Phase := 180 + Phase
Phase
if InPhase > 0 and Quadrature < 0
Phase := 360 - Phase
Phase
// Compute a differential phase, resolve phase wraparound, and limit delta phase errors
DeltaPhase := Phase[1] - Phase
if Phase[1] < 90 and Phase > 270
DeltaPhase := 360 + Phase[1] - Phase
DeltaPhase
if DeltaPhase < 1
DeltaPhase := 1
DeltaPhase
if DeltaPhase > 60
DeltaPhase := 60
DeltaPhase
// Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous period.
for i = 0 to 50 by 1
Value4 += DeltaPhase[i]
if Value4 > 360 and InstPeriod == 0
InstPeriod := i
InstPeriod
// Resolve Instantaneous Period errors and smooth
if InstPeriod == 0
nz(InstPeriod[1])
Period := .25 * InstPeriod + .75 * Period[1]
math.round(Period)
// Get Dominant Cyber Cycle - Homodyne Discriminator With Hilbert Dominant Cycle – Credits to @blackcat1402
getHdDc(float Price, int min, int max, simple float CycPart=0.5) =>
Smooth = 0.00
Detrender = 0.00
I1 = 0.00
Q1 = 0.00
jI = 0.00
jQ = 0.00
I2 = 0.00
Q2 = 0.00
Re = 0.00
Im = 0.00
Period = 0.00
SmoothPeriod = 0.00
pi = 2 * math.asin(1)
DomCycle = 0.0
//Hilbert Transform
Smooth := bar_index > 7 ? (4 * Price + 3 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 10 : Smooth
Detrender := bar_index > 7 ? (.0962 * Smooth + .5769 * nz(Smooth[2]) - .5769 * nz(Smooth[4]) - .0962 * nz(Smooth[6])) * (.075 * nz(Period[1]) + .54) : Detrender
//Compute InPhase and Quadrature components
Q1 := bar_index > 7 ? (.0962 * Detrender + .5769 * nz(Detrender[2]) - .5769 * nz(Detrender[4]) - .0962 * nz(Detrender[6])) * (.075 * nz(Period[1]) + .54) : Q1
I1 := bar_index > 7 ? nz(Detrender[3]) : I1
//Advance the phase of I1 and Q1 by 90 degrees
jI := (.0962 * I1 + .5769 * nz(I1[2]) - .5769 * nz(I1[4]) - .0962 * nz(I1[6])) * (.075 * nz(Period[1]) + .54)
jQ := (.0962 * Q1 + .5769 * nz(Q1[2]) - .5769 * nz(Q1[4]) - .0962 * nz(Q1[6])) * (.075 * nz(Period[1]) + .54)
//Phasor addition for 3 bar averaging
I2 := I1 - jQ
Q2 := Q1 + jI
//Smooth the I and Q components before applying the discriminator
I2 := .2 * I2 + .8 * nz(I2[1])
Q2 := .2 * Q2 + .8 * nz(Q2[1])
//Homodyne Discriminator
Re := I2 * nz(I2[1]) + Q2 * nz(Q2[1])
Im := I2 * nz(Q2[1]) - Q2 * nz(I2[1])
Re := .2 * Re + .8 * nz(Re[1])
Im := .2 * Im + .8 * nz(Im[1])
Period := Im != 0 and Re != 0 ? 2 * pi / math.atan(Im / Re) : Period
Period := Period > 1.5 * nz(Period[1]) ? 1.5 * nz(Period[1]) : Period
Period := Period < .67 * nz(Period[1]) ? .67 * nz(Period[1]) : Period
Period := Period < min ? min : Period
Period := Period > max ? max : Period
Period := .2 * Period + .8 * nz(Period[1])
SmoothPeriod := .33 * Period + .67 * nz(SmoothPeriod[1])
//it can add filter to Period here
DomCycle := math.ceil(CycPart * SmoothPeriod) > 34 ? 34 : math.ceil(CycPart * SmoothPeriod) < 1 ? 1 : math.ceil(CycPart * SmoothPeriod)
// Limit dominant cycle
DomCycle := DomCycle < min ? min : DomCycle
DomCycle := DomCycle > max ? max : DomCycle
// Hann Window Smoothing – Credits to @cheatcountry
doHannWindow(float _series, float _hannWindowLength) =>
sum = 0.0, coef = 0.0
for i = 1 to _hannWindowLength
cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1))
sum := sum + (cosine * nz(_series[i - 1]))
coef := coef + cosine
h = coef != 0 ? sum / coef : 0
// Simple Moving Average (SMA)
sma(float _src, int _period) =>
sum = 0.0
for i = 0 to _period - 1
sum := sum + _src[i] / _period
sum
// Standard Deviation
isZero(val, eps) => math.abs(val) <= eps
sum(fst, snd) =>
EPS = 1e-10
res = fst + snd
if isZero(res, EPS)
res := 0
else
if not isZero(res, 1e-4)
res := res
else
15
stdev(src, length) =>
avg = sma(src, length)
sumOfSquareDeviations = 0.0
for i = 0 to length - 1
sum = sum(src[i], - avg)
sumOfSquareDeviations := sumOfSquareDeviations + sum * sum
stdev = math.sqrt(sumOfSquareDeviations / length)
// Measure of difference between the series and it's ma
dev(float source, int length, float ma) =>
mean = sma(source, length)
sum = 0.0
for i = 0 to length - 1
val = source[i]
sum := sum + math.abs(val - mean)
dev = sum/length
// Exponential Moving Average (EMA)
ema(float _src, int _period) =>
alpha = 2 / (_period + 1)
sum = 0.0
sum := na(sum[1]) ? sma(_src, _period) : alpha * _src + (1 - alpha) * nz(sum[1])
// Zero-lag Exponential Moving Average (ZLEMA)
zlema(float _src, int _period) =>
lag = math.round((_period - 1) / 2)
ema_data = _src + (_src - _src[lag])
zl= ema(ema_data, _period)
// Smoothed Moving Average (SMMA)
smma(float _src, int _period) =>
tmpSMA = sma(_src, _period)
tmpVal = 0.0
tmpVal := na(tmpVal[1]) ? tmpSMA : (tmpVal[1] * (_period - 1) + _src) / _period
// Double Expotential Moving Average (DEMA)
dema(float _src, int _period) =>
(2 * ema(_src, _period) - ema(ema(_src, _period), _period))
// Exponential Hull Moving Average (EHMA)
ehma(float _src, int _period) =>
tmpVal = math.max(2, _period)
ema(2 * ema(_src, tmpVal / 2) - ema(_src, tmpVal), math.round(math.sqrt(tmpVal)))
// Kaufman's Adaptive Moving Average (KAMA)
kama(float _src, int _period) =>
if (bar_index > _period)
tmpVal = 0.0
tmpVal := nz(tmpVal[1]) + math.pow(((math.sum(math.abs(_src - _src[1]), _period) != 0) ? (math.abs(_src - _src[_period]) / math.sum(math.abs(_src - _src[1]), _period)) : 0) * (0.666 - 0.0645) + 0.0645, 2) * (_src - nz(tmpVal[1]))
tmpVal
// Chandelier Momentum Oscillator (CMO)
f1(m) => m >= 0.0 ? m : 0.0
f2(m) => m >= 0.0 ? 0.0 : -m
percent(nom, div) => 100 * nom / div
cmo(_src, _cmoLength) =>
if (bar_index > _cmoLength)
float mommOut = ta.change(_src)
float m1 = f1(mommOut)
float m2 = f2(mommOut)
float sm1 = math.sum(m1, _cmoLength)
float sm2 = math.sum(m2, _cmoLength)
float cmo = percent(sm1 - sm2, sm1 + sm2)
// Variable Index Dynamic Average (VIDYA)
vidya(float _src, int _period) =>
if (bar_index > _period)
float cmo = math.abs(cmo(_src, _period))
float alpha = 2 / (_period + 1)
float vidya = 0.0
vidya := _src * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
// Tripple Exponential Moving Average (TEMA)
tema(float _src, int _period) =>
ema1 = ema(_src, _period)
ema2 = ema(ema1, _period)
ema3 = ema(ema2, _period)
(3 * ema1) - (3 * ema2) + ema3
// Rolling Moving Average (RMA)
rma(float _src, int _period) =>
rmaAlpha = 1 / _period
sum = 0.0
sum := na(sum[1]) ? sma(_src, _period) : rmaAlpha * _src + (1 - rmaAlpha) * nz(sum[1])
// Weighted Moving Average (WMA)
wma(float _src, int _period) =>
norm = 0.0
sum = 0.0
for i = 0 to _period - 1
weight = (_period - i) * _period
norm := norm + weight
sum := sum + _src[i] * weight
sum / norm
// Hull Moving Average (HMA)
hma(float _src, int _period) =>
tmpVal = math.max(2, _period)
wma((2 * wma(_src, tmpVal / 2)) - wma(_src, tmpVal), math.round(math.sqrt(tmpVal)))
// Volume Weighted Moving Averga (VWMA)
vwma(float _src, int _period) =>
sma(_src * _volume, _period) / sma(_volume, _period)
ma(float source, int length, string type) =>
float ma = switch type
'SMA' => sma(source, length)
'EMA' => ema(source, length)
'ZLEMA' => zlema(source, length)
'EHMA' => ehma(source, length)
'DEMA' => dema(source, length)
'KAMA' => kama(source, length)
'SMMA' => smma(source, length)
'RMA' => rma(source, length)
'WMA' => wma(source, length)
'VWMA' => vwma(source, length)
'HMA' => hma(source, length)
'TEMA' => tema(source, length)
// -- Calculation --
// Trend Intensity Index Calculation
int _maLength = maLength
if (isHannEnabled)
_src := doHannWindow(_src, hannLength)
if (adaptiveMode == 'Inphase-Quadrature Transform')
_maLength := math.round(getIqDc(_close, min, maLength) * 4)
if (adaptiveMode == 'Homodyne Discriminator')
_maLength := math.round(getHdDc(_close, min, maLength) * 2)
if (adaptiveMode == 'Median')
_maLength := math.round(getMedianDc(_close, min, maLength) * 2)
if (adaptiveMode == 'Hilbert Transform')
_maLength := math.round(getHtDc(_close) * 2)
if (_maLength < min)
_maLength := min
ma = ma(_src, _maLength, maType)
positiveSum = 0.0
negativeSum = 0.0
for i = 0 to min - 1 by 1
price = nz(_src[i])
avg = nz(ma[i])
positiveSum := positiveSum + (price > avg ? price - avg : 0)
negativeSum := negativeSum + (price > avg ? 0 : avg - price)
negativeSum
float tii = 100 * positiveSum / (positiveSum + negativeSum)
if (isFisherized)
tii := fisherize(0.1 * (tii - 50))
else
tii := normalize(tii, -1, 1)
tiiColor = tii > upperLevel ? transpMagicMint : tii < lowerLevel ? transpRajah : (tii < upperLevel and tii > lowerLevel) ? sidetrendColor : na
plot(tii, title='TII', linewidth=2, color=tiiColor)
topBand = plot(1, 'Top Band', color=transpLightGray)
upperBand = plot(upperLevel, 'Upper Band', color=transpLightGray)
zeroLine = plot(0, 'Zero Line', color=transpLightGray)
lowerBand = plot(lowerLevel, 'Lower Band', color=transpLightGray)
bottomBand = plot(-1, 'Bottom Band', color=transpLightGray)
plot = plot(tii, title='TII', color=languidLavender)
fill(upperBand, topBand, color=tii > upperLevel ? tiiColor : na)
fill(lowerBand, bottomBand, color=tii < lowerLevel ? tiiColor : na)
fill(lowerBand, upperBand, color=(tii < upperLevel and tii > lowerLevel) ? tiiColor : na)
|
Custom XABCD Validation and Backtesting Tool | https://www.tradingview.com/script/NqGUd3e4-Custom-XABCD-Validation-and-Backtesting-Tool/ | reees | https://www.tradingview.com/u/reees/ | 1,185 | 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/
// © reees
//@version=5
indicator("Custom XABCD Validation and Backtesting Tool","CustomXABCD",overlay=true,max_lines_count=500,max_labels_count=500,max_bars_back=500)
import reees/TA/66 as t
import reees/Draw/22 as draw
import reees/Utilities/2 as u
//-----------------------------------------
// inputs and vars
//-----------------------------------------
// Pattern Type Inputs
var i_bullOn = input.bool(true, "Bullish", inline="type_b", group="Types")
var i_bearOn = input.bool(true, "Bearish", inline="type_b", group="Types")
var i_incOn = input.bool(true, "Potential/Incomplete", inline="type_b", group="Types")
var i_pOn = input.bool(true, "Pattern 1", group="Types", inline="type_b2")
var i_pOn2 = input.bool(true, "Pattern 2", group="Types", inline="type_b2")
var i_pOn3 = input.bool(true, "Pattern 3", group="Types", inline="type_b2", tooltip="Define retracement values and targets for up to 3 custom patterns.\n\nTips:\n\n
(1) Assign a unique Pattern ID to each pattern, used for identification on the pattern label and in the results table.\n\n
(2) Enter '0' if you don't want a retracement value defined for a given leg/ratio. The only requirement is that you have a value defined for at least one of the 3 CD retracements.\n\n
(3) Adjust a pattern's entry/stop/target configuration and see how it affects the pattern's results.\n\n
(4) Adjust the weights of pattern score components (% error, PRZ confluence, Point D/PRZ confluence), along with the entry minimum score requirements ('If score is above'), and see how it affects the patterns' results.")
//
var i_pid = input.string("🐪","Pat ID", group="Types", inline="pid")
var i_xab = input.float(0.618, "AB/XA", minval=0, group="Types", inline="xab")
var i_abc = input.float(0.886, "BC/AB", minval=0, group="Types", inline="abc")
var i_bcd = input.float(1.618, "CD/BC", minval=0, group="Types", inline="bcd")
var i_xad = input.float(0.786, "AD/XA", minval=0, group="Types", inline="xad")
var i_xcd = input.float(0.0, "CD/XC", minval=0, group="Types", inline="xcd")
var i_t1 = input.string(".618 AD", "Target 1", group="Types", inline="t1", options=[".382 AD",".5 AD",".618 AD",".382 XA",".5 XA",".618 XA","1.272 XA","1.618 XA",".382 CD",".5 CD",".618 CD","1.272 CD","1.618 CD","A","B","C"])
var i_t2 = input.string("1.272 AD", "Target 2", group="Types", inline="t2", options=[".618 AD","1.272 AD","1.618 AD",".618 XA","1.272 XA","1.618 XA",".618 CD","1.272 CD","1.618 CD","A","B","C"])
var i_pid2 = input.string("🦄","", group="Types", inline="pid")
var i_xab2 = input.float(0.618, "", minval=0, group="Types", inline="xab")
var i_abc2 = input.float(1.414, "", minval=0, group="Types", inline="abc")
var i_bcd2 = input.float(0.0, "", minval=0, group="Types", inline="bcd")
var i_xad2 = input.float(0.0, "", minval=0, group="Types", inline="xad")
var i_xcd2 = input.float(0.786, "", minval=0, group="Types", inline="xcd")
var i_t12 = input.string(".618 AD", "", group="Types", inline="t1", options=[".382 AD",".5 AD",".618 AD",".382 XA",".5 XA",".618 XA","1.272 XA","1.618 XA",".382 CD",".5 CD",".618 CD","1.272 CD","1.618 CD","A","B","C"])
var i_t22 = input.string("1.272 AD", "", group="Types", inline="t2", options=[".618 AD","1.272 AD","1.618 AD",".618 XA","1.272 XA","1.618 XA",".618 CD","1.272 CD","1.618 CD","A","B","C"])
var i_pid3 = input.string("🐉","", group="Types", inline="pid")
var i_xab3 = input.float(0.786, "", minval=0, group="Types", inline="xab")
var i_abc3 = input.float(1.0, "", minval=0, group="Types", inline="abc")
var i_bcd3 = input.float(2.0, "", minval=0, group="Types", inline="bcd")
var i_xad3 = input.float(1.618, "", minval=0, group="Types", inline="xad")
var i_xcd3 = input.float(0.0, "", minval=0, group="Types", inline="xcd")
var i_t13 = input.string(".618 AD", "", group="Types", inline="t1", options=[".382 AD",".5 AD",".618 AD",".382 XA",".5 XA",".618 XA","1.272 XA","1.618 XA",".382 CD",".5 CD",".618 CD","1.272 CD","1.618 CD","A","B","C"])
var i_t23 = input.string("1.272 AD", "", group="Types", inline="t2", options=[".618 AD","1.272 AD","1.618 AD",".618 XA","1.272 XA","1.618 XA",".618 CD","1.272 CD","1.618 CD","A","B","C"])
// Entry/Stop Inputs
var e_afterC = input.bool(true,"Enter after Point C",group="Entry/Stop")
var e_lvlc = input.string("Nearest confluent PRZ level"," ==> Enter at",options=["Nearest confluent PRZ level","Farthest confluent PRZ level","Between the two confluent PRZ levels","Nearest PRZ level","Farthest PRZ level"],group="Entry/Stop")
var e_aboveC = input.float(90," ==> If score is above",group="Entry/Stop",tooltip="A trade will only be entered if the pattern's score is above the specified value. Note that when entering a trade after Point C, we have an incomplete score because we can't yet measure Point D's confluence with the PRZ. Therefore the final pattern score may differ from the incomplete score at the time of entry. Set this to 0 if you wish to enter a trade on every pattern.")
var e_afterD = input.bool(true,"Enter after Point D",group="Entry/Stop")
var e_lvldPct = input.float(1.0," ==> Enter at limit % away from D",minval=0.0,step=.1,group="Entry/Stop",tooltip="Enter the trade after a valid point D has been confirmed, up to the limit of this % away from Point D. E.g. for a bullish pattern (long entry), if this value is set to 5%, an entry will be placed at the best possible price up to 5% above point D. If 'Entry after Point C' is also set, the entry will be at whichever level is reached first. \n\nIf the entry level is not reached, the pattern will not be included in the Success Rate and Return % statistics.")
var e_aboveD = input.float(90," ==> If score is above",group="Entry/Stop",tooltip="A trade will only be entered if the pattern's score is above the specified value. Set this to 0 if you wish to enter a trade on every pattern.")
var e_tLimit = input.float(.5," ==> Entry window (time limit)",group="Entry/Stop",tooltip="Time limit for order entry, specified in pattern lengths (e.g. '0.5' means half the total pattern length). If the time limit expires before the order is filled, it will be cancelled and no trade will be entered for the pattern.")
var stopPct = input.float(75,"Stop",step=1.0,minval=0.0,group="Entry/Stop",inline="stop")
var stopB = input.string("% of distance to target 1, beyond entry","",options=["% beyond X or D","% beyond Farthest PRZ level","% beyond Point D","% beyond entry","% of distance to target 1, beyond entry"],group="Entry/Stop",inline="stop",tooltip="Set stop-loss % beyond the specified level. If price reaches this level before the first target is hit, or before the target timeout period expires, the pattern will be considered a failure.\n\n'% beyond X or D' = percentage below Point X or Point D, whichever is farther from entry\n\n'% of distance to target 1' = a percentage of the distance from the entry level to target 1. \n\n'% beyond entry' = percentage above/below the entry level. \n\n'% beyond Point D' = percentage above/below Point D. \n\n'beyond Farthest PRZ level' = percentage above/below the Farthest PRZ level")
// Pattern Inputs
var t_b = input.int(1,"Pattern validation length (# trailing bars)",minval=1,group="Pattern",tooltip="The number of bars after pivot point D (or point C for incomplete patterns) before a pattern is considered valid. This affects how soon patterns will be drawn and entries can be placed.")
var pctErr = input.float(15.0,"Allowed ratio error %",step=1.0,minval=0.0,maxval=50.0,group="Pattern",inline="err")
var pctAsym = input.float(250.0,"Allowed leg length asymmetry %",step=1.0,minval=0.0,maxval=1000.0,group="Pattern")
var w_e = input.float(4.0,"Weight",step=.1,minval=0.0,group="Pattern",inline="err",tooltip="A leg is considered valid if its retracement (ΔY) ratio is within this % of the harmonic ratio. Weight determines the weight of retracement % error in the total score calculation for a pattern.")
var tLimitMult = input.float(3,"Pattern time limit",group="Pattern",step=.1,minval=.1,tooltip="Time limit for a completed pattern to reach the projected targets. Value is specified in terms of total pattern length (point X to point D), i.e. a value of 1 will allow one pattern length to elapse before the pattern times out and can no longer be considered successful. Patterns that time out will not count towards the success rates in the results table.")
var w_p = input.float(2.0,"Weight of PRZ level confluence",step=.1,minval=0.0,group="Pattern",tooltip="Weight applied to Potential Reversal Zone fib level confluence in the total score calculation for a pattern. The closer together the two closest PRZ fib levels are, the higher the score.")
var w_d = input.float(3.0,"Weight of point D / PRZ level confluence",step=.1,minval=0.0,group="Pattern",tooltip="Weight applied to the confluence of point D with the Potential Reversal Zone levels in the total score calculation for a pattern. The closer point D is to either of the two confluent PRZ fib levels, the higher the score. ")
// Alert Inputs
var a_on = input.bool(true, "Alert", inline="alert", group="Alerts")
var a_type = input.string("Both", "for", options=["Potential patterns","Complete patterns","Both"], inline="alert", group="Alerts")
// Display Inputs
var c_bline = input.color(color.new(color.green,20), "Bullish lines", group="Display")
var c_beline = input.color(color.new(color.red,20), "Bearish lines", group="Display")
var c_blab = input.color(color.new(color.green,75), "Bullish labels", group="Display")
var c_belab = input.color(color.new(color.red,75), "Bearish labels", group="Display")
var l_txt = input.color(color.new(color.white,20), "Label text", group="Display")
var i_tbl = input.bool(true,"",group="Display",inline="tbl")
var i_tblLoc = input.string("Bottom left","Results table location",group="Display",inline="tbl",options=["Top left","Top center","Top right","Middle left","Middle center","Middle right","Bottom left","Bottom center","Bottom right"])
// Completed pattern structures
var string[] pat = array.new_string(0)
var int[] pTypes = array.new_int(0)
if barstate.isfirst // initialize selected patterns
if i_pOn
array.push(pTypes,1)
array.push(pat,"a1")
array.push(pat,"b1")
if i_pOn2
array.push(pTypes,2)
array.push(pat,"a2")
array.push(pat,"b2")
if i_pOn3
array.push(pTypes,3)
array.push(pat,"a3")
array.push(pat,"b3")
var bull1 = matrix.new<string>(0)
var bull2 = matrix.new<string>(0)
var bull3 = matrix.new<string>(0)
var bear1 = matrix.new<string>(0)
var bear2 = matrix.new<string>(0)
var bear3 = matrix.new<string>(0)
// Corresponding drawing structures (1:1 map)
var label[] bull1L = array.new_label(0)
var label[] bull2L = array.new_label(0)
var label[] bull3L = array.new_label(0)
var label[] bear1L = array.new_label(0)
var label[] bear2L = array.new_label(0)
var label[] bear3L = array.new_label(0)
var bull1Ln = matrix.new<line>(0)
var bull2Ln = matrix.new<line>(0)
var bull3Ln = matrix.new<line>(0)
var bear1Ln = matrix.new<line>(0)
var bear2Ln = matrix.new<line>(0)
var bear3Ln = matrix.new<line>(0)
// temp/last pattern structures
var pending = matrix.new<string>(0)
var label[] fullIpL = array.new_label(0)
var line[] fullIpLn = array.new_line(0)
var linefill[] fullIpLf = array.new_linefill(0)
// Incomplete pattern arrays
var inc = matrix.new<string>(0)
var label[] incL = array.new_label(0)
var incLn = matrix.new<line>(0)
// Stat totals
var int[] pTot = array.new_int(0)
var int[] tTot = array.new_int(0)
var float[] t1Tot = array.new_float(0)
var float[] t2Tot = array.new_float(0)
var float[] arTot = array.new_float(0)
var float[] trTot = array.new_float(0)
//-----------------------------------------
// functions
//-----------------------------------------
nToMatrix(n) =>
switch n
"a1" => bull1
"a2" => bull2
"a3" => bull3
"b1" => bear1
"b2" => bear2
"b3" => bear3
nToArrayL(n) =>
switch n
"a1" => bull1L
"a2" => bull2L
"a3" => bull3L
"b1" => bear1L
"b2" => bear2L
"b3" => bear3L
typeToMatrix(t,tp) =>
n = (t ? "a" : "b") + str.tostring(tp)
nToMatrix(n)
typeToArrayL(t,tp) =>
n = (t ? "a" : "b") + str.tostring(tp)
nToArrayL(n)
nToMatrixLn(n) =>
switch n
"a1" => bull1Ln
"a2" => bull2Ln
"a3" => bull3Ln
"b1" => bear1Ln
"b2" => bear2Ln
"b3" => bear3Ln
typeToMatrixLn(t,tp) =>
n = (t ? "a" : "b") + str.tostring(tp)
nToMatrixLn(n)
id(tp) =>
switch tp
1 => i_pid
2 => i_pid2
3 => i_pid3
xab(tp) =>
v = switch tp
1 => i_xab
2 => i_xab2
3 => i_xab3
v == 0 ? na : v
abc(tp) =>
v = switch tp
1 => i_abc
2 => i_abc2
3 => i_abc3
v == 0 ? na : v
bcd(tp) =>
v = switch tp
1 => i_bcd
2 => i_bcd2
3 => i_bcd3
v == 0 ? na : v
xad(tp) =>
v = switch tp
1 => i_xad
2 => i_xad2
3 => i_xad3
v == 0 ? na : v
xcd(tp) =>
v = switch tp
1 => i_xcd
2 => i_xcd2
3 => i_xcd3
v == 0 ? na : v
t1(tp) =>
switch tp
1 => i_t1
2 => i_t12
3 => i_t13
t2(tp) =>
switch tp
1 => i_t2
2 => i_t22
3 => i_t23
// get target
harmonic_xabcd_targets(tp,xY,aY,bY,cY,dY) =>
tgt1 = t1(tp)
tgt2 = t2(tp)
[t1,t2,_] = t.harmonic_xabcd_targets(xY,aY,bY,cY,dY,tgt1,tgt2)
[t1,t2]
// Timeout period
tLimit(xX,dX) =>
int((dX - xX)*tLimitMult)
incTLimit(xX,cX) =>
avg = (cX-xX)/3
int(avg * (1 + pctAsym/100)) // time out after max possible bars based on asymmetry parameter
// Entry has timed out
eTimeout(xX,dX) =>
bar_index - dX > int((dX - xX)*e_tLimit)
// Pattern still active within timeout period
stillActive(xX,dX) =>
bar_index - tLimit(xX,dX) <= dX and eTimeout(xX,dX) == false
// Get/Set functions (can map array indices in the future if necessary)
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// [t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1Hit,t2Hit,eHit,eX,eY,score]
setEntry(s,eH,eX,eY) =>
a = s
seH = if na(eH)
"na"
else if eH
"1"
else
"0"
seX = na(eX) ? "na" : str.tostring(eX)
seY = na(eY) ? "na" : str.tostring(eY)
array.set(a,19,seH)
array.set(a,20,seX)
array.set(a,21,seY)
a
getScore(s) =>
str.tonumber(array.get(s,22))
//----------------------------
// make sure score is high enough to enter a trade
noEntry(d,string[] s=na,float score=na) =>
sc = not na(score) ? score : getScore(s)
d ? sc < (e_aboveD/100) : sc < (e_aboveC/100)
entry(t,tp,xY,aY,bY,cY,float dY=na,score) =>
if noEntry(not na(dY),score=score)
[na,na,na]
else
[xadl,bcdl,xcdl] = t.pat_xabcd_prz(xY,aY,bY,cY,xad(tp),bcd(tp),xcd(tp))
[lPrz,hPrz] = t.harmonic_xabcd_przClosest(xadl,bcdl,xcdl)
[u,l] = t.harmonic_xabcd_przRange(xadl,bcdl,xcdl)
float afterD = na
float afterC = na
if e_afterD
afterD := if na(dY)
na
else
t ? dY * (1 + e_lvldPct/100) : dY * (1 - e_lvldPct/100)
if e_afterC
afterC := switch e_lvlc
"Nearest confluent PRZ level" => t ? hPrz : lPrz
"Farthest confluent PRZ level" => t ? lPrz : hPrz
"Nearest PRZ level" => t ? u : l
"Farthest PRZ level" => t ? l : u
=> hPrz - ((hPrz-lPrz)/2)
// if we have a value for both entry params, use the closest one
lvl = if not na(afterD) and not na(afterC)
t ? math.max(afterD,afterC) : math.min(afterD,afterC)
else if not na(afterD)
afterD
else
afterC
// [nearest lvl, after C lvl, after D lvl]
[lvl,afterC,afterD]
// Determine if entry level was reached. Assumes pattern is active/not timed out.
entryHit(t,tp,xX,cX,xY,aY,bY,cY,int dX=na,float dY=na,float score=na) =>
[_,afterC,afterD] = entry(t,tp,xY,aY,bY,cY,dY,score)
t.xabcd_entryHit(t, afterC, afterD, dX, e_afterC, e_afterD, t_b)
// returns [flag,bar,eLvl]
// Determine if pattern has succeeded or failed, or neither (na)
success(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,t1Hit,t2Hit,eHit,eX,eY) =>
// if within time limit and trade active / entry hit, check targets/stop
if (bar_index - dX) <= (bar_index - tLimit(xX,dX) + 1) and eHit
[t1,t2] = harmonic_xabcd_targets(tp,xY,aY,bY,cY,dY)
[upper,lower] = t.harmonic_xabcd_przRange(xadl,bcdl,xcdl)
stop = t.harmonic_xabcd_stop(stopB,stopPct,t,xY,dY,upper,lower,t1,eY)
t.tradeClosed(eX,stop,t1Hit,t2Hit,t1,t2)
// else nothing to update
else
[na,na,na,na,na,na]
rAndE(float l, float l1, float l2) =>
float r = na
float e = na
if l!=0
r := math.abs(l1)/math.abs(l2)
e := math.abs(1-(r/l))
[r,e]
scores(tp, xX, xY, aX, aY, bX, bY, cX, cY, int dX=na, float dY=na) =>
[_,xbre] = rAndE(xab(tp),aY-bY,aY-xY)
[_,acre] = rAndE(abc(tp),cY-bY,aY-bY)
[_,bdre] = rAndE(bcd(tp),cY-dY,cY-bY)
[_,xadre] = rAndE(xad(tp),aY-dY,aY-xY)
[_,xcdre] = rAndE(xcd(tp),cY-dY,cY-xY)
[xadl,bcdl,xcdl] = t.pat_xabcd_prz(xY,aY,bY,cY,xad(tp),bcd(tp),xcd(tp))
[przscore,cpl1,cpl2] = t.harmonic_xabcd_przScore(xY,aY,xadl,bcdl,xcdl)
a = array.from(xad(tp),bcd(tp),xcd(tp))
n = 0
for i in a
if not na(i)
n+=1
eavg = t.harmonic_xabcd_eAvg(xbre,acre,bdre,xadre,xcdre)
eD = t.harmonic_xabcd_eD(cpl1,cpl2,xY,aY,dY)
[eavg,eD,n>1?przscore:na,cpl1,cpl2]
scoreTot(float eavg, float przscore, float eD, float w_e, float w_p, float w_d)=>
float pscore = na(przscore) ? 0.0 : przscore
float pw = na(przscore) ? 0.0 : w_p
if not na(eD)
((1-eavg)*w_e + pscore*pw + (1-eD)*w_d)/(w_e+pw+w_d)
else // else incomplete pattern score
((1-eavg)*w_e + pscore*pw)/(w_e+pw)
// stringify pattern values for pseudo multi-dimensional array value (workaround for data structure limitations)
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// [t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1Hit,t2Hit,eHit,eX,eY,score]
stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,int dX=na,float dY=na,bool t1Hit=na,bool t2Hit=na,bool eHit=na,int eX=na,float eY=na) =>
string[] a = array.new_string(0)
array.push(a,t?"1":"0")
array.push(a,str.tostring(tp))
array.push(a,str.tostring(xX))
array.push(a,str.tostring(xY))
array.push(a,str.tostring(aX))
array.push(a,str.tostring(aY))
array.push(a,str.tostring(bX))
array.push(a,str.tostring(bY))
array.push(a,str.tostring(cX))
array.push(a,str.tostring(cY))
array.push(a,str.tostring(dX))
array.push(a,str.tostring(dY))
[eavg,eD,przscore,cpl1,cpl2] = scores(tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)
[xadl,bcdl,xcdl] = t.pat_xabcd_prz(xY,aY,bY,cY,xad(tp),bcd(tp),xcd(tp))
array.push(a,str.tostring(xadl))
array.push(a,str.tostring(bcdl))
array.push(a,str.tostring(xcdl))
array.push(a,str.tostring(przscore))
array.push(a,str.tostring(eD))
t1HitS = if na(t1Hit)
"na"
else if t1Hit
"1"
else
"0"
t2HitS = if na(t2Hit)
"na"
else if t2Hit
"1"
else
"0"
array.push(a,t1HitS)
array.push(a,t2HitS)
//
eH = if na(eHit)
"na"
else if eHit
"1"
else
"0"
eHx = na(eX) ? "na" : str.tostring(eX)
eHy = na(eY) ? "na" : str.tostring(eY)
array.push(a,eH)
array.push(a,eHx)
array.push(a,eHy)
array.push(a,str.tostring(scoreTot(eavg,przscore,eD,w_e,w_p,w_d)))
a
// get pattern values from pseudo multi-dimensional array value (workaround for data structure limitations)
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// [t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1Hit,t2Hit,eHit,eX,eY,score]
unstringify(v) =>
t1Hit = if array.get(v,17) == "na"
na
else if array.get(v,17) == "1"
true
else
false
t2Hit = if array.get(v,18) == "na"
na
else if array.get(v,18) == "1"
true
else
false
eHit = if array.get(v,19) == "na"
na
else if array.get(v,19) == "1"
true
else
false
[
array.get(v,0) == "1" ? true : false,
int(str.tonumber(array.get(v,1))),
int(str.tonumber(array.get(v,2))),
str.tonumber(array.get(v,3)),
int(str.tonumber(array.get(v,4))),
str.tonumber(array.get(v,5)),
int(str.tonumber(array.get(v,6))),
str.tonumber(array.get(v,7)),
int(str.tonumber(array.get(v,8))),
str.tonumber(array.get(v,9)),
int(str.tonumber(array.get(v,10))),
str.tonumber(array.get(v,11)),
array.get(v,12)=="NaN" ? na : str.tonumber(array.get(v,12)),
array.get(v,13)=="NaN" ? na : str.tonumber(array.get(v,13)),
array.get(v,14)=="NaN" ? na : str.tonumber(array.get(v,14)),
str.tonumber(array.get(v,15)),
str.tonumber(array.get(v,16)),
t1Hit,
t2Hit,
eHit,
array.get(v,20) == "na" ? na : int(str.tonumber(array.get(v,20))),
array.get(v,21) == "na" ? na : str.tonumber(array.get(v,21)),
str.tonumber(array.get(v,22))
]
name(bull,tp) =>
t = bull ? "Bullish " : "Bearish "
t + id(tp)
alertMsg(t,tp,inc=false) =>
if inc
"Potential " + name(t,tp) + " is forming."
else
name(t,tp) + " has formed."
pid(tp,xX,aX,bX,cX,int dX=na) =>
// TODO: convert PID to array (faster than string concat)
str.tostring(tp) + "_"
+ str.tostring(xX) + "_"
+ str.tostring(aX) + "_"
+ str.tostring(bX) + "_"
+ str.tostring(cX) + "_"
+ str.tostring(dX)
pidFromStr(s) =>
[_,tp,xX,_,aX,_,bX,_,cX,_,dX,_,_,_,_,_,_,_,_,_,_,_,_] = unstringify(s)
pid(tp,xX,aX,bX,cX,dX)
deleteFip() =>
for lbl in fullIpL
label.delete(lbl)
array.clear(fullIpL)
//
for ln in fullIpLn
line.delete(ln)
array.clear(fullIpLn)
//
for lf in fullIpLf
linefill.delete(lf)
array.clear(fullIpLf)
removePending(pid) =>
if matrix.rows(pending) > 0
for i=0 to matrix.rows(pending)-1
if pidFromStr(matrix.row(pending,i)) == pid
if i == matrix.rows(pending)-1
deleteFip()
matrix.remove_row(pending,i)
break
removeCompleted(pid,t,tp) =>
string[] rPending = array.new_string(0)
int[] rCompleted = array.new_int(0)
a = typeToMatrix(t,tp)
aL = typeToArrayL(t,tp)
mLn = typeToMatrixLn(t,tp)
n = matrix.rows(a)-1
if matrix.rows(a) >= 0
for i = 0 to matrix.rows(a)-1
s = matrix.row(a,n-i)
if pidFromStr(s) == pid
// Remove from data structures and delete drawings
// index should be same for all 1:1 mapped structures
array.push(rPending,pid)
array.push(rCompleted,n-i)
label.delete(array.remove(aL,n-i))
lines = matrix.remove_row(mLn,n-i)
for l in lines
line.delete(l)
break
for i in rCompleted
matrix.remove_row(a,i)
for p in rPending
removePending(p)
successTxt(t1Hit,t2Hit,eHit,xX,dX,score) =>
if t2Hit
" (Success - Target 1, Target 2)"
else if t1Hit
" (Success - Target 1)"
else if t1Hit==false
" (Failed)"
else if eHit==false and stillActive(xX,dX) == false
" (No entry)"
else if noEntry(not na(dX),score=score) and stillActive(xX,dX)
" (No entry)"
else if na(eHit) and stillActive(xX,dX)
" (Entry pending)"
else if na(t1Hit) and stillActive(xX,dX)
" (Targets pending)"
else
" (Timed out)"
ratDispTxt(tp) =>
[na(xab(tp)) ? "NA" : str.tostring(xab(tp)),
na(abc(tp)) ? "NA" : str.tostring(abc(tp)),
na(bcd(tp)) ? "NA" : str.tostring(bcd(tp)),
na(xad(tp)) ? "NA" : str.tostring(xad(tp)),
na(xcd(tp)) ? "NA" : str.tostring(xcd(tp))]
// Pattern tooltip
ttTxt(bull,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,bool t1Hit=na,bool t2Hit=na,eHit,score) =>
[t1,t2] = harmonic_xabcd_targets(tp,xY,aY,bY,cY,dY)
[rb,rc,rd1,rd2,rd3] = ratDispTxt(tp)
[xbr,xbre] = rAndE(xab(tp),aY-bY,aY-xY)
[acr,acre] = rAndE(abc(tp),cY-bY,aY-bY)
[bdr,bdre] = rAndE(bcd(tp),cY-dY,cY-bY)
[xadr,xadre] = rAndE(xad(tp),aY-dY,aY-xY)
[xcdr,xcdre] = rAndE(xcd(tp),cY-dY,cY-xY)
[eavg,eD,przscore,cpl1,cpl2] = scores(tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)
l1 = name(bull,tp) + successTxt(t1Hit,t2Hit,eHit,xX,dX,score) + "\n\n"
l2 = "Total Score: " + str.tostring(score*100,"#.###") + "%\n"
l3 = " Leg retracement accuracy: " + str.tostring((1-eavg)*100, "#.##") + "%\n"
l42 = " PRZ level confluence: " + (na(przscore)?"NA":(str.tostring(przscore*100, "#.##") + "%")) + "\n"
l43 = " Point D confluence with PRZ: " + str.tostring((1-eD)*100, "#.##") + "%\n"
l5 = "\n Actual % Err Theoretical\n"
l6 = "AB/XA " + str.tostring(xbr, "0.000") + " " + str.tostring(xbre*100, "00.0") + "%" + " " + rb + "\n"
l7 = "BC/AB " + str.tostring(acr, "0.000") + " " + str.tostring(acre*100, "00.0") + "% " + rc + "\n"
l8 = "CD/BC " + str.tostring(bdr, "0.000") + " " + str.tostring(bdre*100, "00.0") + "%" +" " + rd1 + "\n"
l9 = "AD/XA " + str.tostring(xadr, "0.000") + " " + str.tostring(xadre*100, "00.0") + "% " + rd2 + "\n"
l10 = "CD/XC " + str.tostring(xcdr, "0.000") + " " + str.tostring(xcdre*100, "00.0") + "% " + rd3 + "\n"
l1 + l2 + l3 + l42 + l43 + l5 + (na(xbr) ? "": l6) + (na(acr) ? "" : l7) + (na(bdr) ? "" : l8) + (na(xadr) ? "" : l9) + (na(xcdr) ? "" : l10)
// incomplete pattern tooltip
incTtTxt(bull,tp,xX,xY,aX,aY,bX,bY,cX,cY,xadl,bcdl,xcdl,score,e) =>
[rb,rc,rd1,rd2,rd3] = ratDispTxt(tp)
[xbr,xbre] = rAndE(xab(tp),aY-bY,aY-xY)
[acr,acre] = rAndE(abc(tp),cY-bY,aY-bY)
[eavg,eD,przscore,cpl1,cpl2] = scores(tp,xX,xY,aX,aY,bX,bY,cX,cY)
l1 = "Potential " + name(bull,tp) + " (" + str.tostring(score*100,"#.##") + "%)\n\n"
l2 = " Potential Reversal Zone:\n"
l21 = " Entry: " + str.tostring(e,"#.#####") + "\n"
l211 = " BC retracement (" + rd1 + "): " + str.tostring(bcdl, "#.#####") + "\n"
l41 = " XA retracement (" + rd2 + "): "+ str.tostring(xadl, "#.#####") + "\n"
l42 = " XC retracement (" + rd3 + "): "+ str.tostring(xcdl, "#.#####") + "\n"
l5 = "\n Actual % Err Theoretical\n"
l6 = "AB/XA " + str.tostring(xbr, "0.000") + " " + str.tostring(xbre*100, "00.0") + "%" + " " + rb + "\n"
l7 = "BC/AB " + str.tostring(acr, "0.000") + " " + str.tostring(acre*100, "00.0") + "% " + rc + "\n"
l8 = "CD/BC " + "TBD " + " - " + rd2 + "\n"
l9 = "AD/XA " + "TBD " + " - " + rd1 + "\n"
l10 = "CD/XC " + "TBD " + " - " + rd3 + "\n"
l1 + l2 + (na(e)?"":l21) + (na(bcdl)?"":l211) + (na(xadl)?"":l41) + (na(xcdl)?"":l42) + l5 + l6 + l7 + l8 + l9 + l10
status(xX,dX,bool t1Hit=na,bool t2Hit=na,eHit,score) =>
if t2Hit
" ✅✅"
else if t1Hit
" ✅"
else if t1Hit==false
" ❌"
else if stillActive(xX,dX) == false and eHit == false
" ⛔"
else if stillActive(xX,dX) and noEntry(not na(dX),score=score)
" ⛔"
else if stillActive(xX,dX)
" ⏳"
else
" 🕝"
lbTxt(t,tp,score,status) =>
id(tp) + " " + str.tostring(math.round(score,3)*100) + "%" + status
incLbTxt(t,tp,score) =>
"Potential " + name(t,tp) + " (" + str.tostring(score*100,"#.##") + "%)"
deleteInc(string pid) =>
n = matrix.rows(inc)
if not na(pid) and n > 0
for j=0 to n-1
if pid == pidFromStr(matrix.row(inc,j))
matrix.remove_row(inc,j)
label.delete(array.remove(incL,j))
for ln in matrix.remove_row(incLn,j)
line.delete(ln)
break
drawPattern(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,int dX=na,float dY=na,t1Hit,t2Hit,eHit,score) =>
if i_incOn or not na(dX)
status = status(xX,dX,t1Hit,t2Hit,eHit,score)
lbTxt = not na(dX) ? lbTxt(t,tp,score,status) : incLbTxt(t,tp,score)
tt = ttTxt(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,t1Hit,t2Hit,eHit,score)
[xadl,bcdl,xcdl] = t.pat_xabcd_prz(xY,aY,bY,cY,xad(tp),bcd(tp),xcd(tp))
[lower,higher] = t.harmonic_xabcd_przClosest(xadl,bcdl,xcdl)
[_,e,_] = entry(t,tp,xY,aY,bY,cY,score=score)
float iE = na(dX) ? (na(e) or e == 0 ? (t?higher:lower) : e) : na
[l1,l2,l3,l4,l5,l6] = draw.xabcd(xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,iE,t,c_bline,c_beline)
lbcol = t ? c_blab : c_belab
lbstyle = t ? label.style_label_up : label.style_label_down
incLbstyle = t ? label.style_label_down : label.style_label_up
label lbl = na
if not na(dX) // Completed pattern
lbl := label.new(dX,dY,text=lbTxt,textcolor=l_txt,size=size.small,style=lbstyle,tooltip=tt,color=lbcol)
else // Incomplete pattern
incTt = incTtTxt(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,xadl,bcdl,xcdl,score,e)
lbl := not na(l4) ? label.new(line.get_x2(l4),line.get_y2(l4),text=lbTxt,tooltip=incTt,textcolor=l_txt,size=size.small,style=lbstyle,color=lbcol)
: label.new(cX,cY,text=lbTxt,tooltip=incTt,textcolor=l_txt,size=size.small,style=lbstyle,color=lbcol)
// return pattern drawings
[lbl,l1,l2,l3,l4,l5,l6]
else
[na,na,na,na,na,na,na]
drawPatternFromStr(s) =>
[t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1Hit,t2Hit,eHit,_,_,score] = unstringify(s)
// Returns pattern drawings
// [label,line1,line2,line3,line4,line5,line6]
drawPattern(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,t1Hit,t2Hit,eHit,score)
addIncompletePattern(t,tp,xX,xY,aX,aY,bX,bY,cX,cY) =>
string[] s = na
line[] ln = na
label lbl = na
exists = false
// check last pattern. if same XABC, don't add it again.
if matrix.rows(inc) > 0
for i=0 to matrix.rows(inc)-1
last = matrix.row(inc,matrix.rows(inc)-1-i)
[lt,ltp,lxX,lxY,laX,laY,lbX,lbY,lcX,lcY,ldX,ldY,_,_,_,_,_,_,_,_,_,_,_] = unstringify(last)
if xX==lxX and aX==laX and bX==lbX and cX==lcX and tp==ltp
exists := true
break
if exists == false
s := stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY)
[_,eC,_] = entry(t,tp,xY,aY,bY,cY,score=getScore(s))
if not na(eC) and ((t and eC < ta.lowest(bar_index-cX)) or (t==false and eC > ta.highest(bar_index-cX)))
matrix.add_row(inc,matrix.rows(inc),s)
else
s := na
else
s := stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY)
[_,eC,_] = entry(t,tp,xY,aY,bY,cY,score=getScore(s))
if not na(eC) and ((t and eC < ta.lowest(bar_index-cX)) or (t==false and eC > ta.highest(bar_index-cX)))
matrix.add_row(inc,matrix.rows(inc),s)
else
s := na
if not na(s)
[lb,l1,l2,l3,l4,l5,l6] = drawPatternFromStr(s)
array.push(incL,lb)
matrix.add_row(incLn,matrix.rows(incLn),array.from(l1,l2,l3,l4,l5,l6))
if a_on and (a_type == "Potential patterns" or a_type == "Both")
alert(alertMsg(t,tp,true),alert.freq_once_per_bar_close) // temporarily changing to fire on bar close until real-time bar multiple alert issue is resolved
// Draw completed pattern and update data structures
addCompleted(t,tp,s) =>
m = typeToMatrix(t,tp)
aL = typeToArrayL(t,tp)
mLn = typeToMatrixLn(t,tp)
matrix.add_row(m,matrix.rows(m),s) // add pattern
[lbl,l1,l2,l3,l4,l5,l6] = drawPatternFromStr(s)
array.push(aL,lbl) // addlabel
matrix.add_row(mLn,matrix.rows(mLn),array.from(l1,l2,l3,l4,l5,l6)) // add lines
if noEntry(true,s)==false
matrix.add_row(pending,matrix.rows(pending),s)
// fire alert if appropriate
if a_on and (a_type == "Complete patterns" or a_type == "Both")
alert(alertMsg(t,tp),alert.freq_once_per_bar_close) // temporarily changing to fire on bar close until real-time bar multiple alert issue is resolved
updatePending(pid,str) =>
if matrix.rows(pending) > 0
for i=0 to matrix.rows(pending)-1
if pidFromStr(matrix.row(pending,i)) == pid
matrix.remove_row(pending,i)
matrix.add_row(pending,i,str)
break
updateCompleted(pid,t,tp,str) =>
a = typeToMatrix(t,tp)
n = matrix.rows(a)-1
label l = na
if matrix.rows(a) > 0
for i = 0 to n
s = matrix.row(a,n-i)
if pidFromStr(s) == pid
updatePending(pid,str)
matrix.remove_row(a,n-i)
matrix.add_row(a,n-i,str)
l := array.get(typeToArrayL(t,tp),n-i)
break
// return the label so it can be updated, if necessary
l
// Add pattern to completed pattern structures
addValidPattern(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY) =>
string[] s = na
bool lasteH = na
int lasteX = na
float lasteY = na
float lastScore = na
m = typeToMatrix(t,tp)
if matrix.rows(m) > 0
// check last pattern of same type
last = matrix.row(m,matrix.rows(m)-1)
[lt,ltp,lxX,lxY,laX,laY,lbX,lbY,lcX,lcY,ldX,ldY,_,_,_,_,_,lt1H,lt2H,leH,leX,leY,lscore]
= unstringify(last)
lastScore := lscore
// if A, B or C is different = new pattern
if aX!=laX or bX!=lbX or cX!=lcX
s := stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)
addCompleted(t,tp,s)
// if ABC are same but D is beyond last pattern's D, replace it with this one. We want to draw the
// new/updated pattern and calculate its updated score, but maintain any entry/targets that have
// already been hit.
else if (t and dY < ldY) or (t==false and dY > ldY)
if leH and na(lt1H)
lasteH := true // inherit entry from last pattern (trade is active)
lasteX := leX
lasteY := leY
s := stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,lt1H,lt2H,leH,leX,leY)
else
s := stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)
//
if lastScore > getScore(s) // if lower score, keep last pattern
s := na
else if not na(lt1H) // if last pattern trade closed, just add the new pattern
addCompleted(t,tp,s)
else // else, remove the last pattern in favor of the new one
lpid = pid(ltp,lxX,laX,lbX,lcX,ldX)
removeCompleted(lpid,t,tp)
addCompleted(t,tp,s)
else
s := stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)
addCompleted(t,tp,s)
// Update newly added pattern
if not na(s)
// update entry, if necessary
if lasteH
draw.eHitLbl(lasteX,lasteY,dX,dY,t,true)
else
score = getScore(s)
[eHit,eX,eY] = entryHit(t,tp,xX,cX,xY,aY,bY,cY,dX,dY,score)
if eHit
draw.eHitLbl(eX,eY,dX,dY,t)
pid = pid(tp,xX,aX,bX,cX,dX)
s := setEntry(s,eHit,eX,eY)
l = updateCompleted(pid,t,tp,s)
tt = ttTxt(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,eHit=eHit,score=score)
status = status(xX,dX,eHit=eHit,score=score)
lbTxt = lbTxt(t,tp,score,status)
label.set_text(l,lbTxt)
label.set_tooltip(l,tt)
""
// Get the most recent pending pattern
lastPending() =>
n = matrix.rows(pending)
if n > 0
unstringify(matrix.row(pending,n-1))
updatePendingPatterns() =>
string[] remove = array.new_string(0)
if matrix.rows(pending) > 0
for i=0 to matrix.rows(pending)-1
[t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1Hit,t2Hit,eHit,eX,eY,score]
= unstringify(matrix.row(pending,i))
pid = pid(tp,xX,aX,bX,cX,dX)
[eH,eHx,eHy] = entryHit(t,tp,xX,cX,xY,aY,bY,cY,dX,dY,score)
ehVal = eHit ? eHit : (eTimeout(xX,dX)?false:eH)
exVal = eHit ? eX : (eTimeout(xX,dX)?na:eHx)
eyVal = eHit ? eY : (eTimeout(xX,dX)?na:eHy)
tLimit = tLimit(xX,dX)
expired = bar_index == (dX + tLimit + 1) or (eTimeout(xX,dX) and (na(ehVal) or ehVal==false))
[t1h,t2h,t1x,t1y,t2x,t2y] = success(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,t1Hit,t2Hit,ehVal,exVal,eyVal)
s = stringify(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,t1h,t2h,ehVal,exVal,eyVal)
// if time has expired or there's nothing left to update, no longer pending
if expired or (ehVal and (not na(t2h) or t1h == false))
array.push(remove,pid)
// if anything to update, update completed array entry and label if necessary
if expired
or (ehVal
and ((not na(t1h) and na(t1Hit)) or (not na(t2h) and na(t2Hit))))
or (ehVal != eHit) or (ehVal and na(eHit))
l = updateCompleted(pid,t,tp,s)
if ehVal and ((ehVal != eHit) or na(eHit))
draw.eHitLbl(exVal,eyVal,dX,dY,t)
// targets will be na if eH==false, so no need to also check eH
if t1h and na(t1Hit)
draw.tHitLbl(t1x,t1y,exVal,eyVal,t)
else if t1h == false
draw.sHitLbl(t1x,t1y,exVal,eyVal,t)
if t2h
draw.tHitLbl(t2x,t2y,exVal,eyVal,t)
tt = ttTxt(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,t1h,t2h,ehVal,score)
status = status(xX,dX,t1h,t2h,ehVal,score)
lbTxt = lbTxt(t,tp,score,status)
label.set_text(l,lbTxt)
label.set_tooltip(l,tt)
""
for p in remove
removePending(p)
updateIncompletePatterns() =>
string[] remove = array.new_string(0)
if matrix.rows(inc) > 0
for i=0 to matrix.rows(inc)-1
[t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1Hit,t2Hit,eHit,_,_,score]
= unstringify(matrix.row(inc,i))
[upper,lower] = t.harmonic_xabcd_przRange(xadl,bcdl,xcdl)
tLimit = incTLimit(xX,cX)
[eH,eHx,eHy] = entryHit(t,tp,xX,cX,xY,aY,bY,cY,score=score)
pid = pid(tp,xX,aX,bX,cX,dX)
if eH and e_afterC
addValidPattern(t,tp,xX,xY,aX,aY,bX,bY,cX,cY,eHx,eHy)
array.push(remove,pid)
// else delete incomplete pattern if timed out or no longer valid
else if bar_index == (cX + tLimit + 1)
array.push(remove,pid)
else if t and (high > cY or low < lower)
array.push(remove,pid)
else if t==false and (low < cY or high > upper)
array.push(remove,pid)
for p in remove
deleteInc(p)
drawFullInProgress() =>
[t,tp,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xadl,bcdl,xcdl,prz,eD,t1h,t2h,_,_,eY,score] = lastPending()
if not na(dX)
bb = last_bar_index - dX
tLimit = tLimit(xX,dX)
if bb <= tLimit and noEntry(true,score=score)==false and eTimeout(xX,dX)==false and (na(t1h) or (t1h and na(t2h))) // draw if within time limit and target/stop not hit
deleteFip() // delete previously drawn completed pattern in progress
[highest,lowest] = t.harmonic_xabcd_przRange(xadl,bcdl,xcdl)
[t1,t2] = harmonic_xabcd_targets(tp,xY,aY,bY,cY,dY)
stop = t.harmonic_xabcd_stop(stopB,stopPct,t,xY,dY,highest,lowest,t1,eY)
[e,_,_] = entry(t,tp,xY,aY,bY,cY,dY,score)
entry = na(eY) ? e : eY
[ln,lb] = draw.xabcd_inProgress2(t,tLimit>500?500:tLimit,entry,stop,t1,t2,xadl,bcdl,xcdl,xX,xY,bX,bY,dX,dY,c_bline,c_beline,l_txt)
for l in ln
array.push(fullIpLn,l)
for l in lb
array.push(fullIpL,l)
else
deleteFip()
rowValues(tp) =>
a1 = typeToMatrix(true,tp)
a2 = typeToMatrix(false,tp)
float[] ra = array.new_float(0)
t1_tot = 0
t2_tot = 0
closed = 0
if matrix.rows(a1) > 0
for i=0 to matrix.rows(a1)-1
[_,_,_,xY,_,aY,_,bY,_,cY,_,dY,xadl,bcdl,xcdl,_,_,t1Hit,t2Hit,eHit,_,eY,score] = unstringify(matrix.row(a1,i))
if not na(t1Hit) and eHit
[t1,t2] = harmonic_xabcd_targets(tp,xY,aY,bY,cY,dY)
if t1Hit==false
[upper,lower] = t.harmonic_xabcd_przRange(xadl,bcdl,xcdl)
stop = t.harmonic_xabcd_stop(stopB,stopPct,true,xY,dY,upper,lower,t1,eY)
r = (stop/eY) - 1
array.push(ra,r)
closed+=1
else
if t2Hit
r = (t2/eY) - 1
array.push(ra,r)
t2_tot+=1
t1_tot+=1
closed+=1
else if t1Hit
r = (t1/eY) - 1
array.push(ra,r)
t1_tot+=1
closed+=1
//for p in a2
if matrix.rows(a2) > 0
for i=0 to matrix.rows(a2)-1
[_,_,_,xY,_,aY,_,bY,_,cY,_,dY,xadl,bcdl,xcdl,_,_,t1Hit,t2Hit,eHit,_,eY,score] = unstringify(matrix.row(a2,i))
if not na(t1Hit) and eHit
[t1,t2] = harmonic_xabcd_targets(tp,xY,aY,bY,cY,dY)
if t1Hit==false
[upper,lower] = t.harmonic_xabcd_przRange(xadl,bcdl,xcdl)
stop = t.harmonic_xabcd_stop(stopB,stopPct,false,xY,dY,upper,lower,t1,eY)
r = (eY/stop) - 1
array.push(ra,r)
closed+=1
else
if t2Hit
r = (eY/t2) - 1
array.push(ra,r)
t2_tot+=1
t1_tot+=1
closed+=1
else if t1Hit
r = (eY/t1) - 1
array.push(ra,r)
t1_tot+=1
closed+=1
tot = matrix.rows(a1) + matrix.rows(a2)
array.push(pTot,tot)
array.push(tTot,closed)
if closed > 0
array.push(t1Tot,(t1_tot/closed)*100)
array.push(t2Tot,(t2_tot/closed)*100)
if not na(array.avg(ra))
array.push(arTot,array.avg(ra)*100)
if not na(array.sum(ra))
array.push(trTot,array.sum(ra)*100)
st1 = closed>0 ? str.tostring((t1_tot/closed)*100,"#.##")+"%" : "NA"
st2 = closed>0 ? str.tostring((t2_tot/closed)*100,"#.##")+"%" : "NA"
ravg = not na(array.avg(ra)) ? str.tostring(array.avg(ra)*100,"#.##")+"%" : "NA"
rtot = not na(array.sum(ra)) ? str.tostring(array.sum(ra)*100,"#.##")+"%" : "NA"
[str.tostring(tot),str.tostring(closed),st1,st2,ravg,rtot]
printStats() =>
if i_tbl
nR = array.size(pTypes) + 3
r = 0
pos = switch i_tblLoc
"Bottom left" => position.bottom_left
"Middle left" => position.middle_left
"Top left" => position.top_left
"Bottom center" => position.bottom_center
"Middle center" => position.middle_center
"Top center" => position.top_center
"Bottom right" => position.bottom_right
"Middle right" => position.middle_right
"Top right" => position.top_right
t = table.new(pos, 7, nR, bgcolor = color.new(color.black,30), border_width = 1)
table.cell(t, 0, 0, " ", text_color=color.white, text_halign=text.align_center)
table.cell(t, 1, 0, "Patterns", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 2, 0, "Trades", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 3, 0, "T1 Success", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 4, 0, "T2 Success", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 5, 0, "Avg Return %", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 6, 0, "Total Return %", text_color=color.white, text_halign=text.align_center,text_size=size.small)
for tp in pTypes
r+=1
[tot,trd,st1,st2,ar,tr] = rowValues(tp)
table.cell(t, 0, r, " "+id(tp)+" ", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 1, r, tot, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 2, r, trd, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 3, r, st1, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 4, r, st2, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 5, r, ar, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 6, r, tr, text_color=color.white, text_halign=text.align_center,text_size=size.small)
r+=1
t1Total = not na(array.avg(t1Tot)) ? (str.tostring(array.avg(t1Tot),"#.##") + "%") : "NA"
t2Total = not na(array.avg(t2Tot)) ? (str.tostring(array.avg(t2Tot),"#.##") + "%") : "NA"
arTotal = not na(array.avg(arTot)) ? (str.tostring(array.avg(arTot),"#.##") + "%") : "NA"
trTotal = not na(array.sum(trTot)) ? (str.tostring(array.sum(trTot),"#.##") + "%") : "NA"
table.cell(t, 0, r, "Total", text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 1, r, str.tostring(array.sum(pTot)), text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 2, r, str.tostring(array.sum(tTot)), text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 3, r, t1Total, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 4, r, t2Total, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 5, r, arTotal, text_color=color.white, text_halign=text.align_center,text_size=size.small)
table.cell(t, 6, r, trTotal, text_color=color.white, text_halign=text.align_center,text_size=size.small)
r+=1
keyTxt = "✅ = Success | ❌ = Failure | 🕝 = Timed out* | ⛔ = No entry* | ⏳ = In progress* \n*Not included in Success Rate/Return % statistics"
table.cell(t, 0, r, keyTxt, text_color=color.white, text_halign=text.align_right, text_size=size.small)
table.merge_cells(t,0,r,6,r)
array.clear(pTot),array.clear(tTot),array.clear(t1Tot),array.clear(t2Tot),array.clear(arTot),array.clear(trTot)
find_pattern(pl,t=true) =>
if (t and i_bullOn) or (t==false and i_bearOn)
[f,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY] = t.pat_xabcd(t,pl,conf_length=t_b)
if f
for p in pTypes
if t.pat_xabcd_validate(xX,xY,aX,aY,bX,bY,cX,cY,dX,dY,xab(p),abc(p),bcd(p),xad(p),xcd(p),pctErr,pctAsym)
addValidPattern(t,p,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)
""
[f2,xX2,xY2,aX2,aY2,bX2,bY2,cX2,cY2,dX2,dY2] = t.pat_xabcd(t,pl,conf_length=t_b,incomplete=true)
if f2
for p in pTypes
if t.pat_xabcd_validateIncomplete(xX2,xY2,aX2,aY2,bX2,bY2,cX2,cY2,xab(p),abc(p),pctErr,pctAsym)
addIncompletePattern(t,p,xX2,xY2,aX2,aY2,bX2,bY2,cX2,cY2)
""
// Find XABCD patterns of various pivot lengths
find(bull=true) =>
find_pattern(3,bull)
find_pattern(4,bull)
find_pattern(5,bull)
find_pattern(6,bull)
find_pattern(7,bull)
find_pattern(8,bull)
find_pattern(9,bull)
find_pattern(10,bull)
find_pattern(11,bull)
find_pattern(12,bull)
find_pattern(13,bull)
find_pattern(14,bull)
find_pattern(15,bull)
find_pattern(16,bull)
find_pattern(17,bull)
find_pattern(18,bull)
find_pattern(19,bull)
find_pattern(20,bull)
//-----------------------------------------
// Main
//-----------------------------------------
// update patterns in progress
updateIncompletePatterns() // update potential/incomplete pattern
updatePendingPatterns() // update any completed patterns pending results
// find new patterns
find() // find bullish patterns
find(false) // find bearish patterns
// last bar business
if barstate.islast
drawFullInProgress() // draw most recent complete pattern, if still in progress
printStats() // compile stats and draw results table |
(2) Two Alerts | https://www.tradingview.com/script/h8KFFDJl-2-Two-Alerts/ | LeoTheMors | https://www.tradingview.com/u/LeoTheMors/ | 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/
// © LeoTheMors
//@version=5
indicator(title='Two Alerts', shorttitle='2alerts', overlay=true)
inAlertPriceHigh = input.price(18000, 'AlertPriceHigh')
useAlertHigh = input.bool(false, 'useAlertHigh')
inAlertPriceLow = input.price(16000, 'AlertPriceLow')
useAlertLow = input.bool(false, 'useAlertLow')
plot(useAlertHigh ? inAlertPriceHigh : na, color=color.new(color.green, 38), style=plot.style_linebr)
plot(useAlertLow ? inAlertPriceLow : na, color=color.new(color.yellow, 38), style=plot.style_linebr)
if (useAlertHigh and close > inAlertPriceHigh)
alert('PriceBrokeAbove', alert.freq_once_per_bar)
if (useAlertLow and close < inAlertPriceLow)
alert('PriceBrokeBelow', alert.freq_once_per_bar) |
Volume Candles Standardized (VCS) | https://www.tradingview.com/script/dOHf5EG1-Volume-Candles-Standardized-VCS/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 127 | 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/
// © peacefulLizard50262
//@version=5
indicator("VCS")
OHLC(src, int len = 4) =>
Open = ta.sma(src[1], len)
High = ta.highest(src, 1)
Low = ta.lowest(src, 1)
Close = ta.wma(src, len)
[Open, High, Low, Close]
select = input.string("Cumulative Volume", "Style", ["OBV","Cumulative Volume"])
candle = input.int(4, "Candle Transform", 1, tooltip = "1 is regular candles and 4 is ashi candles. That being said you can smooth it untill the cows come home.")
red = input.color(color.new(#ef5350, 0), "", inline = "col")
green = input.color(color.new(#26a69a, 0), "", inline = "col")
sel = input.bool(true, "Candle Colour", "Chance how the candles are colored. If this is enabled it will color the candles bassed on the transformed open/close. Otherwise this indicator will use source/source[1]")
ma = input.bool(false, "Enable MA")
len = input.int(28, "MA Length")
st = input.bool(true, "Standardization")
back = input.int(12, "Standardization Length", 1)
perc = input.bool(true, "Percent Rank Enable")
per_75 = input.int(75 , "Percentile Cloud Top")
per_25 = input.int(25 , "Percentile Cloud Bottom")
rank = input.int(48, "Percent Rank Look Back")
cum = select == "OBV" ? ta.cum(math.sign(ta.change(close)) * volume) : ta.cum(open > close ? -float(volume) : float(volume))
src = st ? (cum - ta.sma(cum, back)) / ta.stdev(cum, back) : cum
osc = src
[Open, High, Low, Close] = OHLC(src, candle)
ma1 = ma ? ta.ema(Close, len) : na
ma2 = perc ? ta.percentile_nearest_rank(src, rank, 100) : na
ma3 = perc ? ta.percentile_nearest_rank(src, rank, per_75) : na
ma4 = perc ? ta.percentile_nearest_rank(src, rank, per_25) : na
ma5 = perc ? ta.percentile_nearest_rank(src, rank, 0) : na
ma6 = ma ? ta.ema(Close, 10*len) : na
plot(ma1, "Fast MA", color = color.new(color.blue, 30))
plot(ma6, "Slow MA", color = color.new(color.orange, 30))
m1 = plot(ma2, "100", color = color.new(color.orange, 100))
m2 = plot(ma3, "75", color = color.new(color.orange, 100))
m3 = plot(ma4, "25", color = color.new(color.orange, 100))
m4 = plot(ma5, "0", color = color.new(color.orange, 100))
fill(m1, m2, color = color.new(color.green, 80))
fill(m2, m4, color = color.new(color.gray, 90))
fill(m3, m4, color = color.new(color.red, 80))
colour = sel ? Open < Close ? green : red : src > src[1] ? green : red
plotcandle(Open, High, Low, Close, "RSI Candle", colour, colour, true, bordercolor = colour)
plot(Close, "Out", color.new(color.white, 100))
|
VWAP & Previous VWAP - MTF | https://www.tradingview.com/script/OtYKFo1y-VWAP-Previous-VWAP-MTF/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 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/
//@version=5
indicator("VWAP m-tf • Yata",
overlay = true)
// ----------------------------------------
groupVWAP = "Volume Weighted Average Price"
// ----------------------------------------
computeVWAP(src, isNewPeriod) =>
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
var float _lvwap = na
sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
// sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]
_vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
stDev = math.sqrt(variance)
_lvwap := isNewPeriod ? _vwap[1] : _lvwap[1]
[_vwap, stDev, _lvwap]
// ----------------------------------------
f_drawLabel(_x, _y, _text, _textcolor, _style, _size) =>
var _label = label.new(
x = _x,
y = _y,
text = _text,
textcolor = _textcolor,
style = _style,
size = _size,
xloc = xloc.bar_time
)
label.set_xy(_label, _x, _y)
// ----------------------------------------
src = input(hlc3, title="VWAP Source", inline="V0", group=groupVWAP)
pvD_color = input.color(color.new(#E12D7B, 75), title="", inline="V1", group=groupVWAP)
pvW_color = input.color(color.new(#F67B52, 75), title="", inline="V2", group=groupVWAP)
pvM_color = input.color(color.new(#EDCD3B, 75), title="", inline="V3", group=groupVWAP)
pvQ_color = input.color(color.new(#3BBC54, 75), title="", inline="V4", group=groupVWAP)
pvY_color = input.color(color.new(#2665BD, 75), title="", inline="V5", group=groupVWAP)
plot_pvD = input(true, title="Prev." , inline="V1", group=groupVWAP)
plot_pvW = input(true, title="Prev." , inline="V2", group=groupVWAP)
plot_pvM = input(true, title="Prev." , inline="V3", group=groupVWAP)
plot_pvQ = input(true, title="Prev." , inline="V4", group=groupVWAP)
plot_pvY = input(true, title="Prev." , inline="V5", group=groupVWAP)
vD_color = input.color(color.new(#E12D7B, 50), title="" , inline="V1", group=groupVWAP)
vW_color = input.color(color.new(#F67B52, 50), title="" , inline="V2", group=groupVWAP)
vM_color = input.color(color.new(#EDCD3B, 50), title="" , inline="V3", group=groupVWAP)
vQ_color = input.color(color.new(#3BBC54, 50), title="" , inline="V4", group=groupVWAP)
vY_color = input.color(color.new(#2665BD, 50), title="" , inline="V5", group=groupVWAP)
plot_vD = input(true, title="Show Daily VWAP" , inline="V1", group=groupVWAP)
plot_vW = input(true, title="Show Weekly VWAP" , inline="V2", group=groupVWAP)
plot_vM = input(true, title="Show Monthly VWAP" , inline="V3", group=groupVWAP)
plot_vQ = input(true, title="Show Quarterly VWAP" , inline="V4", group=groupVWAP)
plot_vY = input(true, title="Show Yearly VWAP" , inline="V5", group=groupVWAP)
vR_color = input.color(color.new(#481899, 50) , title="" , inline="V6", group=groupVWAP)
rolling_sv = input(true , title="Show Rolling VWAP" , inline="V6", group=groupVWAP)
rolling_period = input.int(200 , title="" , inline="V6", group=groupVWAP)
vwap_r = ta.vwma(src, rolling_period)
line_width_VWAP = input.int(1, minval=0, title="Lines Width", inline="V0A", group=groupVWAP)
line_width_pVWAP = line_width_VWAP
Vstyle = input(true, title="Circles Style", inline="V0A", group=groupVWAP)
VstyleC = Vstyle ? plot.style_circles : plot.style_line
VstylepC = Vstyle ? plot.style_circles : plot.style_stepline
// ----------------------------------------
groupL = "Labels"
// ----------------------------------------
show_labels = input(true, title="Show Labels |", inline="L1", group=groupL)
show_VWAPlabels = input(true, title="VWAP", inline="L1", group=groupL)
show_pVWAPlabels = input(true, title="Previous", inline="L1", group=groupL)
off_mult = input(15, title="Labels Offset", inline="L2", group=groupL)
var DEFAULT_LABEL_SIZE = size.normal
var DEFAULT_LABEL_STYLE = label.style_none
ll_offset = timenow + math.round(ta.change(time) * off_mult)
// ----------------------------------------
timeChange(period) =>
ta.change(time(period))
newSessionD = timeChange("D")
newSessionW = timeChange("W")
newSessionM = timeChange("M")
newSessionQ = timeChange("3M")
newSessionY = timeChange("12M")
[vD, stdevD, pvD] = computeVWAP(src, newSessionD)
[vW, stdevW, pvW] = computeVWAP(src, newSessionW)
[vM, stdevM, pvM] = computeVWAP(src, newSessionM)
[vQ, stdevQ, pvQ] = computeVWAP(src, newSessionQ)
[vY, stdevY, pvY] = computeVWAP(src, newSessionY)
// ----------------------------------------
vRplot = plot(rolling_sv ? vwap_r : na, title="VWAP - Rolling" , color=vR_color, style=VstyleC, linewidth=line_width_VWAP)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and rolling_sv ? vwap_r : na, "rV", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vDplot = plot(plot_vD ? vD : na, title="VWAP - Daily" , color=vD_color, style=VstyleC, linewidth=line_width_VWAP)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vD ? vD : na, "vD", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vWplot = plot(plot_vW ? vW : na, title="VWAP - Weekly" , color=vW_color, style=VstyleC, linewidth=line_width_VWAP)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vW ? vW : na, "vW", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vMplot = plot(plot_vM ? vM : na, title="VWAP - Monthly" , color=vM_color, style=VstyleC, linewidth=line_width_VWAP)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vM ? vM : na, "vM", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vQplot = plot(plot_vQ ? vQ : na, title="VWAP - Quarter" , color=vQ_color, style=VstyleC, linewidth=line_width_VWAP)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vQ ? vQ : na, "vQ", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vYplot = plot(plot_vY ? vY : na, title="VWAP - Year" , color=vY_color, style=VstyleC, linewidth=line_width_VWAP)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vY ? vY : na, "vY", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
// ----------------------------------------
pvDplot = plot(plot_pvD ? pvD : na, title="pVWAP - Daily" , color=pvD_color, style=VstylepC, linewidth=line_width_pVWAP)
f_drawLabel(ll_offset, show_labels and show_pVWAPlabels and plot_pvD ? pvD : na, "pvD", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pvWplot = plot(plot_pvW ? pvW : na, title="pVWAP - Weekly" , color=pvW_color, style=VstylepC, linewidth=line_width_pVWAP)
f_drawLabel(ll_offset, show_labels and show_pVWAPlabels and plot_pvW ? pvW : na, "pvW", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pvMplot = plot(plot_pvM ? pvM : na, title="pVWAP - Monthly" , color=pvM_color, style=VstylepC, linewidth=line_width_pVWAP)
f_drawLabel(ll_offset, show_labels and show_pVWAPlabels and plot_pvM ? pvM : na, "pvM", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pvQplot = plot(plot_pvQ ? pvQ : na, title="pVWAP - Quarter" , color=pvQ_color, style=VstylepC, linewidth=line_width_pVWAP)
f_drawLabel(ll_offset, show_labels and show_pVWAPlabels and plot_pvQ ? pvQ : na, "pvQ", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pvYplot = plot(plot_pvY ? pvY : na, title="pVWAP - Year" , color=pvY_color, style=VstylepC, linewidth=line_width_pVWAP)
f_drawLabel(ll_offset, show_labels and show_pVWAPlabels and plot_pvY ? pvY : na, "pvY", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE) |
Volume percentrank[TV1] | https://www.tradingview.com/script/Jji6k7G0-volume-percentrank-tv1/ | TV-1ndicators | https://www.tradingview.com/u/TV-1ndicators/ | 17 | 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/
// © TV-1ndicators
//
//**************************Volume normalized by percentile.**********************************
//The indicator calculates the percentile of the trading volume.
//The volume in the base asset or the quote asset can be selected as data.
//To calculate the volume in a quote asset, the closing price or another standard method for calculating the price of a bar can be used.
//A feature of percentile calculation with a small data sample length is low accuracy.
//Although the script allows you to calculate a percentile with a length of 1, using a percentile length less than 100 is not recommended.
//On the other hand, huge length values do not allow correctly calculating the percentile at the beginning of the chart,
//so when the date of the first bar changes (this happens on small timeframes if the TradingView subscription does not allow you to see all historical data),
//the indicator is subject to redrawing up to the bar number equal to the percentile sampling length.
//Also, huge percentile length values can cause script errors.
//If the indicator doesn't work, just make the percentile length smaller.
//********************************************************************************************
//**************************Объем, нормализованный по процентилью.****************************
//Индикатор вычисляет процентиль объема торгов.
//В качестве данных может быть выбран объем в базовом(base) активе или котировочном(qute) активе.
//Для расчета объема в котировочном активе может использоваться цена закрытия либо другой стандатный метод расчета цены бара.
//Особенностью расчета процентиля при малой длине выборки данных является малая точность.
//Не смотря на то, что скрипт позволяет вычилить процентиль с длинной 1, использовавть длину процентиля меньше 100 не рекомендуется.
//С другой стороны, большие значения длины не позволяют корректно рассчитать процентиль в начале графика,
//поэтому при изменении даты первого бара (это происходит на малых таймфреймах, если подписка TradingView не позволяет видеть все исторические данные)
//индикатор подвержен перерисовке вплоть до номера бара равного длине выборки процентиля.
//Кроме того, большие значения длины процентиля могут приводить к ошибке скрипта.
//Если индикатор не работает, просто сделайте длину процентиля меньше.
//********************************************************************************************
//@version=5
indicator("Volume percentrank[TV1]",'VP[TV1]',precision = 2)
var percentileQuote = input.string('quote','Percentile:' ,options=['quote','base'] ,inline = 'pecentile') == 'quote'
quoteSrc = input.source(close ,'Source' ,inline = 'pecentile')
var percentileLength = input.int(1000 ,'Length' ,minval=1 ,maxval=4999 ,inline = 'pecentile')
var maType = input.string ("SMA" ,'Moving average' ,options=["RMA", "SMA", "EMA", "WMA"] ,inline = 'ma')
var maLength = input.int(100 ,'Length' ,inline = 'ma')
ma_function(source, length, type) =>
switch type
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
volume_percentrank(percentileQuote_ ,src_ ,percentileLength_) =>
var volume_ = percentileQuote_? volume*src_: volume
var volume_percentrank = 0.0
volume_ := percentileQuote_? volume * src_: volume
if bar_index
volume_percentrank := ta.percentrank(volume_, math.min(bar_index, percentileLength_))
volume_percentrank
vp = volume_percentrank(percentileQuote ,quoteSrc ,percentileLength)
ma = ma_function(vp, maLength, maType)
plot(vp ,'VP' ,close>open?color.rgb(64, 192, 160, 65):color.rgb(255, 82, 82, 65) ,style=plot.style_columns)
plot(ma ,'MA' ,color.rgb(33, 149, 243, 85) ,style=plot.style_area)
bgcolor(bar_index < percentileLength?color.rgb(120, 123, 134, 85):color.rgb(255, 255, 255, 100),title='Insufficient Data') |
Currency translate indicator v1.0 | https://www.tradingview.com/script/KXy9dcmj/ | yechankun | https://www.tradingview.com/u/yechankun/ | 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/
// © yechankun
//@version=5
indicator("Currency translate indicator", overlay=false)
stock = input.symbol(defval = "FX_IDC:KRWUSD", title="자산")
[price_o, price_h, price_l, price_c] = request.security(stock, timeframe.period, [open, high, low, close])
nextPriceOpen = price_o * open
nextPriceHigh = price_h * high
nextPriceLow = price_l * low
nextPriceClose = price_c * close
paletteColor = nextPriceClose >= nextPriceOpen ? color.teal : color.red
plotcandle(nextPriceOpen, nextPriceHigh, nextPriceLow, nextPriceClose, color = paletteColor, bordercolor = paletteColor, wickcolor = paletteColor) |
Adaptive VWAP Stdev Bands | https://www.tradingview.com/script/TpfAd8at-Adaptive-VWAP-Stdev-Bands/ | simwai | https://www.tradingview.com/u/simwai/ | 85 | 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/
// © simwai
//@version=5
indicator('VWAP Stdev Bands', overlay=true)
// -- Input --
src = input.source(hl2, 'Choose Source', group='General', inline='1')
resetMode = input.string('Adaptive – Homodyne Discriminator', 'Choose Reset Mode', options=['Resolution', 'Adaptive – Inphase-Quadrature Transform', 'Adaptive – Hilbert Transform', 'Adaptive – Homodyne Discriminator'], group='General', inline='2')
resetResolution = input.timeframe('D', 'Choose Reset Timeframe', group='General', inline='3', tooltip='Used for resolution reset mode')
minLength = input.int(2, minval=2, title='Min Length', group='General', inline='4', tooltip='Used for adaptive reset mode')
maxLength = input.int(200, minval=2, title='Max Length', group='General', inline='4', tooltip='Used for adaptive reset mode')
showPrevVWAP = input(false, title='Enable Previous VWAP Close Plot', group='General', inline='5')
isSmoothingEnabled = input(false, 'Enable Smoothing', group='General', inline='6', tooltip='Hann Window is the smoothing method')
smoothingLength = input.int(10, 'Smoothing Length', minval=2, group='General', inline='6')
devUp1 = input(1.28, title='Stdev above (1)', group='Band Levels', inline='1')
devDn1 = input(1.28, title='Stdev below (1)', group='Band Levels', inline='1')
devUp2 = input(2.01, title='Stdev above (2)', group='Band Levels', inline='2')
devDn2 = input(2.01, title='Stdev below (2)', group='Band Levels', inline='2')
devUp3 = input(2.51, title='Stdev above (3)', group='Band Levels', inline='3')
devDn3 = input(2.51, title='Stdev below (3)', group='Band Levels', inline='3')
devUp4 = input(3.09, title='Stdev above (4)', group='Band Levels', inline='4')
devDn4 = input(3.09, title='Stdev below (4)', group='Band Levels', inline='4')
devUp5 = input(4.01, title='Stdev above (5)', group='Band Levels', inline='5')
devDn5 = input(4.01, title='Stdev below (5)', group='Band Levels', inline='5')
showDv1 = input(true, title='Show first group of bands?', group='Band Levels', inline='6')
showDv2 = input(true, title='Show second group of bands?', group='Band Levels', inline='7')
showDv3 = input(true, title='Show third group of bands?', group='Band Levels', inline='8')
showDv4 = input(true, title='Show fourth group of bands?', group='Band Levels', inline='9')
showDv5 = input(true, title='Show fifth group of bands?', group='Band Levels', inline='10')
// -- Colors --
color lightGray = color.rgb(214, 214, 214)
color lightCyan = color.rgb(207, 243, 235)
color aeroBlue = color.rgb(189, 239, 227)
color middleBlueGreen = color.rgb(156, 231, 214)
color middleBlueGreen2 = color.rgb(140, 227, 207)
color turquoise = color.rgb(107, 219, 193)
color mikadoYellow = color.rgb(255, 197, 51)
color selectiveYellow = color.rgb(255, 183, 3)
color orangePeel = color.rgb(253, 158, 2)
color yellowOrangeColorWheel = color.rgb(252, 146, 1)
color tangerine = color.rgb(251, 133, 0)
color transpTurquoise = color.new(turquoise, 50)
color transpTangerine = color.new(tangerine, 50)
// -- Functions --
// Get Dominant Cyber Cycle – Inphase-Quadrature -- Credits to @DasanC
getIqDc(float src, int min, int max) =>
PI = 3.14159265359
P = src - src[7]
lenIQ = 0.0
lenC = 0.0
imult = 0.635
qmult = 0.338
inphase = 0.0
quadrature = 0.0
re = 0.0
im = 0.0
deltaIQ = 0.0
instIQ = 0.0
V = 0.0
inphase := 1.25 * (P[4] - imult * P[2]) + imult * nz(inphase[3])
quadrature := P[2] - qmult * P + qmult * nz(quadrature[2])
re := 0.2 * (inphase * inphase[1] + quadrature * quadrature[1]) + 0.8 * nz(re[1])
im := 0.2 * (inphase * quadrature[1] - inphase[1] * quadrature) + 0.8 * nz(im[1])
if re != 0.0
deltaIQ := math.atan(im / re)
deltaIQ
for i = 0 to max by 1
V += deltaIQ[i]
if V > 2 * PI and instIQ == 0.0
instIQ := i
instIQ
if instIQ == 0.0
instIQ := nz(instIQ[1])
instIQ
lenIQ := 0.25 * instIQ + 0.75 * nz(lenIQ[1], 1)
lenIQ < min ? min : lenIQ
// Get Dominant Cyber Cycle – Hilbert Transform -- Credits to @DasanC
getHtDc(float src) =>
Imult = .635
Qmult = .338
PI = 3.14159
InPhase = 0.0
Quadrature = 0.0
Phase = 0.0
DeltaPhase = 0.0
InstPeriod = 0.0
Period = 0.0
Value4 = 0.0
if bar_index > 5
// Detrend src
Value3 = src - src[7]
// Compute InPhase and Quadrature components
InPhase := 1.25 * (Value3[4] - Imult * Value3[2]) + Imult * nz(InPhase[3])
Quadrature := Value3[2] - Qmult * Value3 + Qmult * nz(Quadrature[2])
// Use ArcTangent to compute the current phase
if math.abs(InPhase + InPhase[1]) > 0
Phase := 180 / PI * math.atan(math.abs((Quadrature + Quadrature[1]) / (InPhase + InPhase[1])))
Phase
// Resolve the ArcTangent ambiguity
if InPhase < 0 and Quadrature > 0
Phase := 180 - Phase
Phase
if InPhase < 0 and Quadrature < 0
Phase := 180 + Phase
Phase
if InPhase > 0 and Quadrature < 0
Phase := 360 - Phase
Phase
// Compute a differential phase, resolve phase wraparound, and limit delta phase errors
DeltaPhase := Phase[1] - Phase
if Phase[1] < 90 and Phase > 270
DeltaPhase := 360 + Phase[1] - Phase
DeltaPhase
if DeltaPhase < 1
DeltaPhase := 1
DeltaPhase
if DeltaPhase > 60
DeltaPhase := 60
DeltaPhase
// Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous period.
for i = 0 to 50 by 1
Value4 += DeltaPhase[i]
if Value4 > 360 and InstPeriod == 0
InstPeriod := i
InstPeriod
// Resolve Instantaneous Period errors and smooth
if InstPeriod == 0
nz(InstPeriod[1])
Period := .25 * InstPeriod + .75 * Period[1]
Period
Period
// Get Dominant Cyber Cycle - Homodyne Discriminator With Hilbert Dominant Cycle -- Credits to @blackcat1402
getHdDc(float Price, int min, int max, simple float CycPart = 0.5) =>
Smooth = 0.00
Detrender = 0.00
I1 = 0.00
Q1 = 0.00
jI = 0.00
jQ = 0.00
I2 = 0.00
Q2 = 0.00
Re = 0.00
Im = 0.00
Period = 0.00
SmoothPeriod = 0.00
pi = 2 * math.asin(1)
DomCycle = 0.0
//Hilbert Transform
Smooth := bar_index > 7 ? (4 * Price + 3 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 10 : Smooth
Detrender := bar_index > 7 ? (.0962 * Smooth + .5769 * nz(Smooth[2]) - .5769 * nz(Smooth[4]) - .0962 * nz(Smooth[6])) * (.075 * nz(Period[1]) + .54) : Detrender
//Compute InPhase and Quadrature components
Q1 := bar_index > 7 ? (.0962 * Detrender + .5769 * nz(Detrender[2]) - .5769 * nz(Detrender[4]) - .0962 * nz(Detrender[6])) * (.075 * nz(Period[1]) + .54) : Q1
I1 := bar_index > 7 ? nz(Detrender[3]) : I1
//Advance the phase of I1 and Q1 by 90 degrees
jI := (.0962 * I1 + .5769 * nz(I1[2]) - .5769 * nz(I1[4]) - .0962 * nz(I1[6])) * (.075 * nz(Period[1]) + .54)
jQ := (.0962 * Q1 + .5769 * nz(Q1[2]) - .5769 * nz(Q1[4]) - .0962 * nz(Q1[6])) * (.075 * nz(Period[1]) + .54)
//Phasor addition for 3 bar averaging
I2 := I1 - jQ
Q2 := Q1 + jI
//Smooth the I and Q components before applying the discriminator
I2 := .2 * I2 + .8 * nz(I2[1])
Q2 := .2 * Q2 + .8 * nz(Q2[1])
//Homodyne Discriminator
Re := I2 * nz(I2[1]) + Q2 * nz(Q2[1])
Im := I2 * nz(Q2[1]) - Q2 * nz(I2[1])
Re := .2 * Re + .8 * nz(Re[1])
Im := .2 * Im + .8 * nz(Im[1])
Period := Im != 0 and Re != 0 ? 2 * pi / math.atan(Im / Re) : Period
Period := Period > 1.5 * nz(Period[1]) ? 1.5 * nz(Period[1]) : Period
Period := Period < .67 * nz(Period[1]) ? .67 * nz(Period[1]) : Period
Period := Period < min ? min : Period
Period := Period > max ? max : Period
Period := .2 * Period + .8 * nz(Period[1])
SmoothPeriod := .33 * Period + .67 * nz(SmoothPeriod[1])
//it can add filter to Period here
DomCycle := math.ceil(CycPart * SmoothPeriod) > 34 ? 34 : math.ceil(CycPart * SmoothPeriod) < 1 ? 1 : math.ceil(CycPart * SmoothPeriod)
// Limit dominant cycle
DomCycle := DomCycle < min ? min : DomCycle
DomCycle := DomCycle > max ? max : DomCycle
// Zero-lag Least Squared Moving Average (ZLSMA) -- Credits to @veryfid
zlsma(float _src, int _period, int _offset=0) =>
lsma = ta.linreg(_src, _period, _offset)
lsma2 = ta.linreg(lsma, _period, _offset)
eq = lsma - lsma2
zlsma = lsma + eq
// -- Calculation --
float _src = src[1]
float _volume = volume[1]
float _close = close[1]
float _high = high[1]
float _low = low[1]
float start = request.security(syminfo.tickerid, resetResolution, _src, barmerge.gaps_off, barmerge.lookahead_on)
int newSession = ta.change(start) ? 1 : 0
bool isReset = switch resetMode
'Resolution' => newSession
'Adaptive – Inphase-Quadrature Transform' => bar_index % math.round(getIqDc(_src, minLength, maxLength) / 2) == 0
'Adaptive – Hilbert Transform' => bar_index % math.round(getHtDc(_src) / 2) == 0
'Adaptive – Homodyne Discriminator' => bar_index % math.round(getHdDc(_src, minLength, maxLength)) == 0
vwapsum = 0.0
volumesum = 0.0
v2sum = 0.0
vwapsum := isReset ? _src * _volume : vwapsum[1] + _src * _volume
volumesum := isReset ? _volume : volumesum[1] + _volume
v2sum := isReset ? _volume * _src * _src : v2sum[1] + _volume * _src * _src
myvwap = vwapsum / volumesum
dev = math.sqrt(math.max(v2sum / volumesum - myvwap * myvwap, 0))
myvwap := isSmoothingEnabled ? zlsma(myvwap, smoothingLength) : myvwap
plot(myvwap, title='VWAP', color=lightGray)
getUpperPlot(float stdev, float vwap, float dev) => myvwap + stdev * dev
getLowerPlot(float stdev, float vwap, float dev) => myvwap - stdev * dev
upperPlot1 = plot(showDv1 ? getUpperPlot(devUp1, myvwap, dev) : na, title='VWAP Upper (1)', color=mikadoYellow)
lowerPlot1 = plot(showDv1 ? getLowerPlot(devDn1, myvwap, dev) : na, title='VWAP Lower (1)', color=lightCyan)
upperPlot2 = plot(showDv2 ? getUpperPlot(devUp2, myvwap, dev) : na, title='VWAP Upper (2)', color=selectiveYellow)
lowerPlot2 = plot(showDv2 ? getLowerPlot(devDn2, myvwap, dev) : na, title='VWAP Lower (2)', color=aeroBlue)
upperPlot3 = plot(showDv3 ? getUpperPlot(devUp3, myvwap, dev) : na, title='VWAP Upper (3)', color=orangePeel)
lowerPlot3 = plot(showDv3 ? getLowerPlot(devDn3, myvwap, dev) : na, title='VWAP Lower (3)', color=middleBlueGreen)
upperPlot4 = plot(showDv4 ? getUpperPlot(devUp4, myvwap, dev) : na, title='VWAP Upper (4)', color=yellowOrangeColorWheel)
lowerPlot4 = plot(showDv4 ? getLowerPlot(devDn4, myvwap, dev) : na, title='VWAP Lower (4)', color=middleBlueGreen2)
upperPlot5 = plot(showDv5 ? getUpperPlot(devUp5, myvwap, dev) : na, title='VWAP Upper (5)', color=tangerine)
lowerPlot5 = plot(showDv5 ? getLowerPlot(devDn5, myvwap, dev) : na, title='VWAP Lower (5)', color=turquoise)
fill(upperPlot5, upperPlot4, color=showDv5 ? transpTangerine : na)
fill(lowerPlot5, lowerPlot4, color=showDv5 ? transpTurquoise : na)
fill(upperPlot4, upperPlot3, color=((not showDv5) and showDv4) ? transpTangerine : na)
fill(lowerPlot4, lowerPlot3, color=((not showDv5) and showDv4) ? transpTurquoise : na)
fill(upperPlot3, upperPlot2, color=((not showDv5) and (not showDv4) and showDv3) ? transpTangerine : na)
fill(lowerPlot3, lowerPlot2, color=((not showDv5) and (not showDv4) and showDv3) ? transpTurquoise : na)
fill(upperPlot2, upperPlot1, color=((not showDv5) and (not showDv4) and (not showDv3) and showDv2) ? transpTangerine : na)
fill(lowerPlot2, lowerPlot1, color=((not showDv5) and (not showDv4) and (not showDv3) and showDv2) ? transpTurquoise : na)
prevwap = 0.0
prevwap := newSession ? myvwap[1] : prevwap[1]
plot(showPrevVWAP ? prevwap : na, style=plot.style_circles, color=_src > prevwap ? middleBlueGreen : orangePeel) |
Fibonacci Zones EMA Zones Strategy | https://www.tradingview.com/script/EnNoyewR-Fibonacci-Zones-EMA-Zones-Strategy/ | UnknownUnicorn33336554 | https://www.tradingview.com/u/UnknownUnicorn33336554/ | 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/
// © Matrix01010
//@version=5
indicator("Fibonacci Zones EMA Zones Strategy", overlay=true, max_lines_count = 500, max_labels_count = 500)
////// This script is intended for pienscript learning purposes only.
////// I would like to Clarify this script is only designed for pinescript learning purposes to help learn useful PineScript coding.
///// Strategy
///// Simple Algorthims/Math Formulas
L = input.int(10, "Length", [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000])
Fib_Zone_Up_Down = input.float(defval = 0.1, title = "Fibonacci Move Zone Up/Down", step = 0.010)
Fib_Zone_Size = input.float(defval = 0.03, title = "Fibonacci Zone Size" , step = 0.010)
oo2 = float(0.3) - Fib_Zone_Size
hl = ta.highest(high, L)
ll = ta.lowest(low, L)
x = hl - ll
Fib2 = hl - x * Fib_Zone_Size + Fib_Zone_Up_Down
Fib1 = hl - x * oo2 + Fib_Zone_Up_Down
EMA1L = input.int(20, "EMA1", step=5)
EMA1 = ta.ema(close, EMA1L)
EMA2L = input.int(250, "EMA2", step=5)
EMA2 = ta.ema(close, EMA2L)
plot1 = plot(Fib1, "Fib 1", color=color.blue, linewidth = 1)
plot2 = plot(Fib2, "Fib 2", color=color.blue, linewidth = 1)
plot(EMA1, "EMA 1", color=color.yellow, linewidth = 2)
plot(EMA2, "EMA 2", color=color.orange, linewidth = 2)
fill(plot1, plot2, color=color.rgb(0, 89, 255, 84)) |
Centered Moving Average | https://www.tradingview.com/script/EaAHVKaD/ | valiant-hero | https://www.tradingview.com/u/valiant-hero/ | 45 | 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/
//
// ██╗░░░██╗░█████╗░██╗░░░░░██╗░█████╗░███╗░░██╗████████╗ ██╗░░██╗███████╗██████╗░░█████╗░
// ██║░░░██║██╔══██╗██║░░░░░██║██╔══██╗████╗░██║╚══██╔══╝ ██║░░██║██╔════╝██╔══██╗██╔══██╗
// ╚██╗░██╔╝███████║██║░░░░░██║███████║██╔██╗██║░░░██║░░░░███████║█████╗░░██████╔╝██║░░██║
// ░╚████╔╝░██╔══██║██║░░░░░██║██╔══██║██║╚████║░░░██║░░░░██╔══██║██╔══╝░░██╔══██╗██║░░██║
// ░░╚██╔╝░░██║░░██║███████╗██║██║░░██║██║░╚███║░░░██║░░░░██║░░██║███████╗██║░░██║╚█████╔╝
// ░░░╚═╝░░░╚═╝░░╚═╝╚══════╝╚═╝╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝░╚════╝░
// QUICK REFERENCE
// Centered moving averages tries to resolve the problem that simple moving average are still not able to handle significant trends when forecasting
// When computing a running moving average in a centered way, placing the average in the middle time period makes sense
// If we average an even number of terms, we need to smooth the smoothed values
// Try to describe it with an example:
// The following table shows the results using a centered moving average of 4.
//
// nterim Steps
// Period Value SMA Centered
// 1 9
// 1.5
// 2 8
// 2.5 9.5
// 3 9 9.5
// 3.5 9.5
// 4 12 10.0
// 4.5 10.5
// 5 9 10.750
// 5.5 11.0
// 6 12
// 6.5
// 7 11
//
// This is the final table:
// Period Value Centered MA
// 1 9
// 2 8
// 3 9 9.5
// 4 12 10.0
// 5 9 10.75
// 6 12
// 7 11
//
// With this script we are able to process and display the centered moving average as described above.
// In addition to this, however, the script is also able to estimate the potential projection of future data based on the available data
// by replicating where necessary the data of the last bar until the number of data necessary for the calculation of the required centered moving average is reached.
//
// If for example I have 20 daily closings and I look for the moving average centered at 10, I receive the first data on the fifth day
// and the last data on the fourteenth day, so I have 5 days left uncovered, to remedy this I have to give the last value to the uncovered data
// the closing price of the last day.
// The deviations work like the bollinger bands but must refer to the centered moving average.
//@version=5
// @description This indicator is a centered moving average!
indicator("Centered Moving Average",max_lines_count = 500, overlay=true)
mySma(float[] values,float[] mvalues,int length,int shift) =>
float sum = 0
size=0
end=array.size(values)-1
start=end-length+shift
for i=start to end
sum+=array.get(values,i)
size+=1
lastValue=array.get(values,end)
for i=shift-1 to 0
value=lastValue
if (not na(mvalues))
idx=array.size(mvalues)-i-2
value:=array.get(mvalues,idx)
sum+=value
size+=1
sum / size
plotall(data,dataGui,int xstart,float average,float dev)=>
ly=average+dev
for i=0 to array.size(data)-1
y=array.get(data,i)+dev
array.push(dataGui,line.new(xstart+i,ly,xstart+i+1,y,width = 1,color=color.white))
ly:=y
redesign(data,dataGui,int xstart,int offset,float average,float dev=0)=>
for g in dataGui
line.delete(g)
plotall(data,dataGui,xstart,average,0)
if (dev>0)
plotall(data,dataGui,xstart,average,dev)
plotall(data,dataGui,xstart,average,-1*dev)
source = input.source(defval = high,title = 'source')
length = input.int(defval = 10,title = 'length')
future=input.bool(defval = true,title = 'show future')
double=input.bool(defval = false,title = 'use double moving average')
sdtDev = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
offset = math.ceil(length/2)
average = ta.sma(source,length)
var values=array.new_float(0)
var data=array.new_float(0)
var dataGui=array.new_line(0)
if (array.size(values)>length+1)
array.remove(values,0)
array.push(values,source[0])
length_BC_Tminus1_MAX = length
src_BC_Tminus1_MAX = source
devMax = sdtDev * ta.stdev(src_BC_Tminus1_MAX, length_BC_Tminus1_MAX)
upper = average + devMax
lower = average - devMax
plot(upper, "Upper", color=color.orange, offset = -offset)
plot(lower, "Lower", color=color.orange, offset = -offset)
if (barstate.islast)
array.clear(data)
offsetEnd=(future?offset*2:offset)
for i=0 to offsetEnd
v= mySma(values,na,length,i)
array.push(data,v)
if (double)
cdata=array.new_float(0)
array.insert(data,0,average)
for i=0 to offsetEnd
v= mySma(values,data,length,i)
array.push(cdata,v)
data:=cdata
redesign(data,dataGui,bar_index-offset,offset,average,devMax)
// Plot SMA on the chart
plot(series=average,offset = -offset, color=color.lime, linewidth=2)
|
Movement Polarization (MoP) | https://www.tradingview.com/script/Ilwet1UY-Movement-Polarization-MoP/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 95 | 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/
// © More-Than-Enough
//@version=5
indicator(title = "Movement Polarization", shorttitle = "MoP", precision = 3)
Factor = input.float(1.0, "Factor", 1)
Polarization = 0.0
Rsi = ta.rsi(close, 14) * 0.1 - 5
Low_Tsi = ta.tsi(close, 1, 54)
Low_Polarization = ta.rsi(close, 35) * 0.1 - 5 + Low_Tsi
High_Tsi = ta.tsi(close, 1, 13)
High_Polarization = ta.rsi(close, 35) * 0.1 - 5 + High_Tsi
if Rsi > 0
Polarization := High_Polarization
if Rsi < 0
Polarization := Low_Polarization
/////////////// Thresholds ///////////////
High_Extremity_Color = input.color(color.new(color.lime, 50), "High Extremity Color")
High_Extremity = input.float(3.0, "High Extremity", minval = 0.0, step = 0.1)
High_Color = input.color(color.new(color.lime, 50), "High Color")
High = input.float(2.0, "High", minval = 0.0, step = 0.1)
High_Mid_Color = input.color(color.aqua, "High-Mid Color")
Mid = 0
Mid_Color = input.color(color.rgb(91, 156, 246, 50), "Middle Color")
Low_Mid_Color = input.color(color.aqua, "Low-Mid Color")
Low = input.float(-2.0, "Low", maxval = 0.0, step = 0.1)
Low_Color = input.color(color.new(color.red, 50), "Low Color")
Low_Extremity = input.float(-3.0, "Low Extremity", maxval = 0.0, step = 0.1)
Low_Extremity_Color = input.color(color.new(color.red, 50), "Low Extremity Color")
/////////////// Plots ///////////////
High_Extremity_Line = hline(High_Extremity, "High Extremity Line", High_Extremity_Color, linestyle = hline.style_dotted, editable = false)
High_Line = hline(High, "High Line", High_Color, linestyle = hline.style_solid, editable = false)
High_Mid_Line = hline(Mid + ((math.abs(High) - math.abs(Mid)) / 2), "High-Mid Line", High_Mid_Color, linestyle = hline.style_dotted, editable = false)
Mid_Line = hline(Mid, "Middle Line", Mid_Color, linestyle = hline.style_solid, editable = false)
Low_Mid_Line = hline(Mid - ((math.abs(Mid) + math.abs(Low)) / 2), "Low-Mid Line", Low_Mid_Color, linestyle = hline.style_dotted, editable = false)
Low_Line = hline(Low, "Low Line", Low_Color, linestyle = hline.style_solid, editable = false)
Low_Extremity_Line = hline(Low_Extremity, "Low Extremity Line", Low_Extremity_Color, linestyle = hline.style_dotted, editable = false)
fill(Mid_Line, High_Line, color.new(color.aqua, 85), "Up Zone")
fill(Mid_Line, Low_Line, color.rgb(0, 96, 100, 85), "Down Zone")
plot(volume * 0.0000000001 * math.pow(10, Factor), "Volume", color = color.rgb(255, 245, 157), style = plot.style_columns)
plot(Polarization, "Polarization", color = color.rgb(165, 214, 167, 50), style = plot.style_columns)
plot(Polarization, "Polarization Outline", color = color.rgb(8, 153, 129), style = plot.style_stepline)
plot(Rsi, "RSI", color = color.rgb(206, 147, 216), style = plot.style_stepline, display = display.none)
|
Bitcoin Miner Sell Pressure | https://www.tradingview.com/script/eesNSyNo-Bitcoin-Miner-Sell-Pressure/ | capriole_charles | https://www.tradingview.com/u/capriole_charles/ | 681 | 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/
// © capriole_charles
//@version=5
indicator("Bitcoin Miner Sell Pressure",overlay=false)
miner_out = request.security("INTOTHEBLOCK:BTC_MINEROUTFLOWS","D",close)
miner_res = request.security("INTOTHEBLOCK:BTC_MINERRESERVES","D",close)
m = math.sum(miner_out,30)/ta.sma(miner_res,30)
bbl = ta.sma(m,200) - 1*ta.stdev(m,200)
bbu = ta.sma(m,200) + 1*ta.stdev(m,200)
plot(m,color=color.blue,linewidth=2)
plot(bbl,color=color.new(color.gray,70))
plot(bbu,color=color.new(color.gray,70))
bgcolor(m>bbu?color.new(color.red,80):na)
// Sourcing
var table_source = table(na)
table_source := table.new(position=position.bottom_left, columns=1, rows=1, bgcolor=color.white, border_width=1)
table.cell(table_source, 0, 0, text="Source: Capriole Investments", bgcolor=color.white, text_color=color.black, width=20, height=7, text_size=size.normal, text_halign=text.align_left) |
Equity Bond Currency Dashboard | https://www.tradingview.com/script/6F7zTDvH-Equity-Bond-Currency-Dashboard/ | iravan | https://www.tradingview.com/u/iravan/ | 576 | 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/
// © iravan
//@version=5
indicator("Equity, Bond, Currency Dashboard", overlay=false, max_boxes_count=500, max_lines_count=100, max_labels_count=100)
grp_us = "Currency, yield and equity indices for the US"
grp_country = "Currency, yield and equity indices for countries"
sym01 = input.symbol("TVC:DXY", title="US", inline="country0", group=grp_us)
sym02 = input.symbol("TVC:US02Y", title="", inline="country0", group=grp_us)
sym03 = input.symbol("CURRENCYCOM:US500", title="", inline="country0", group=grp_us)
sym11 = input.symbol("FX_IDC:USDINR", title="C1", inline="country1", group=grp_country)
sym12 = input.symbol("TVC:IN02Y", title="", inline="country1", group=grp_country)
sym13 = input.symbol("NSE:NIFTY", title="", inline="country1", group=grp_country)
sym21 = input.symbol("FX_IDC:USDEUR", title="C2", inline="country2", group=grp_country)
sym22 = input.symbol("TVC:DE02Y", title="", inline="country2", group=grp_country)
sym23 = input.symbol("CURRENCYCOM:DE40", title="", inline="country2", group=grp_country)
sym31 = input.symbol("FX_IDC:USDGBP", title="C3", inline="country3", group=grp_country)
sym32 = input.symbol("TVC:GB02Y", title="", inline="country3", group=grp_country)
sym33 = input.symbol("FXOPEN:UK100", title="", inline="country3", group=grp_country)
sym41 = input.symbol("FX_IDC:USDCNY", title="C4", inline="country4", group=grp_country)
sym42 = input.symbol("TVC:CN02Y", title="", inline="country4", group=grp_country)
sym43 = input.symbol("OANDA:CN50USD", title="", inline="country4", group=grp_country)
sym51 = input.symbol("FX_IDC:USDJPY", title="C5", inline="country5", group=grp_country)
sym52 = input.symbol("TVC:JP02Y", title="", inline="country5", group=grp_country)
sym53 = input.symbol("OANDA:JP225USD", title="", inline="country5", group=grp_country)
custom_bar = input.bool(false, "", inline="begin", group="Run on a historical bar")
bar = input.time(timestamp("23 Mar 2020"), "Render On", inline="begin", confirm=false, group="Run on a historical bar", tooltip="Enable and set this option to use a custom date. If this option is unchecked, current date will be used")
[o01, h01, l01, c01] = request.security(sym01, timeframe.period, [open, high, low, close])
[o02, h02, l02, c02] = request.security(sym02, timeframe.period, [open, high, low, close])
[o03, h03, l03, c03] = request.security(sym03, timeframe.period, [open, high, low, close])
[o11, h11, l11, c11] = request.security(sym11, timeframe.period, [open, high, low, close])
[o12, h12, l12, c12] = request.security(sym12, timeframe.period, [open, high, low, close])
[o13, h13, l13, c13] = request.security(sym13, timeframe.period, [open, high, low, close])
[o21, h21, l21, c21] = request.security(sym21, timeframe.period, [open, high, low, close])
[o22, h22, l22, c22] = request.security(sym22, timeframe.period, [open, high, low, close])
[o23, h23, l23, c23] = request.security(sym23, timeframe.period, [open, high, low, close])
[o31, h31, l31, c31] = request.security(sym31, timeframe.period, [open, high, low, close])
[o32, h32, l32, c32] = request.security(sym32, timeframe.period, [open, high, low, close])
[o33, h33, l33, c33] = request.security(sym33, timeframe.period, [open, high, low, close])
[o41, h41, l41, c41] = request.security(sym41, timeframe.period, [open, high, low, close])
[o42, h42, l42, c42] = request.security(sym42, timeframe.period, [open, high, low, close])
[o43, h43, l43, c43] = request.security(sym43, timeframe.period, [open, high, low, close])
[o51, h51, l51, c51] = request.security(sym51, timeframe.period, [open, high, low, close])
[o52, h52, l52, c52] = request.security(sym52, timeframe.period, [open, high, low, close])
[o53, h53, l53, c53] = request.security(sym53, timeframe.period, [open, high, low, close])
var o_0 = array.new<float>()
var h_0 = array.new<float>()
var l_0 = array.new<float>()
var c_0 = array.new<float>()
var c_1 = array.new<float>()
var bar_set = false
if not bar_set and ((custom_bar and time_close > bar) or (not custom_bar and barstate.islast))
bar_set := true
o_0 := array.from(o01, o02, o03, o11, o12, o13, o21, o22, o23, o31, o32, o33, o41, o42, o43, o51, o52, o53)
h_0 := array.from(h01, h02, h03, h11, h12, h13, h21, h22, h23, h31, h32, h33, h41, h42, h43, h51, h52, h53)
l_0 := array.from(l01, l02, l03, l11, l12, l13, l21, l22, l23, l31, l32, l33, l41, l42, l43, l51, l52, l53)
c_0 := array.from(c01, c02, c03, c11, c12, c13, c21, c22, c23, c31, c32, c33, c41, c42, c43, c51, c52, c53)
c_1 := array.from(c01[1], c02[1], c03[1], c11[1], c12[1], c13[1], c21[1], c22[1], c23[1], c31[1], c32[1], c33[1], c41[1], c42[1], c43[1], c51[1], c52[1], c53[1])
var box_space = timeframe.isdwm ? 5 : 5
var box_width = 20
var cell_width = 10
getCords(int i, int j) =>
[last_bar_index - i * cell_width, j * cell_width, last_bar_index - i * cell_width + box_width, j * cell_width - box_width]
getAnchor(b, side) =>
if side == 0
[box.get_left(b), (box.get_bottom(b) + box.get_top(b)) / 2]
else if side == 1
[(box.get_left(b) + box.get_right(b)) / 2, box.get_top(b)]
else if side == 2
[box.get_right(b), (box.get_bottom(b) + box.get_top(b)) / 2]
else if side == 3
[(box.get_left(b) + box.get_right(b)) / 2, box.get_bottom(b)]
var symbols = array.from(sym01, sym02, sym03, sym11, sym12, sym13, sym21, sym22, sym23, sym31, sym32, sym33, sym41, sym42, sym43, sym51, sym52, sym53)
var locs = array.from(10, 8, 12, 0, 8, 0, 10, 16, 7, 20, 13, 20, 15, 13, 18, 16, 18, 10, 15, 3, 18, 5, 18, 0, 5, 13, 2, 16, 2, 10, 5, 3, 2, 5, 2, 0)
var arrows = array.from(0, 3, 1, 1, 0, 3, 2, 1, 3, 2, 4, 3, 3, 0, 5, 3, 6, 0, 7, 2, 6, 0, 8, 2, 9, 0, 10, 2, 9, 0, 11, 2, 12, 2, 13, 0, 12, 2, 14, 0, 15, 2, 16, 0, 15, 2, 17, 0, 0, 1, 3, 3, 0, 0, 6, 2, 0, 0, 9, 2, 0, 2, 12, 0, 0, 2, 15, 0)
var box_legends = array.new<box>(array.size(symbols))
var box_legend_borders = array.new<box>(array.size(symbols))
var box_names = array.new<box>(array.size(symbols))
var box_values = array.new<box>(array.size(symbols))
var box_changes = array.new<box>(array.size(symbols))
var lines = array.new<line>(array.size(arrows) / 4)
var changes = array.new<float>(array.size(symbols))
var display = true
var render = false
if last_bar_index < cell_width * array.max(locs) and barstate.isfirst
display := false
label.new(last_bar_index, 0, "Oops! Not enough bars are available for display!\nPlease chose another symbol or timeframe.", color=color.yellow)
if barstate.islast and (barstate.isrealtime or custom_bar)
render := true
if barstate.islast and not barstate.isrealtime and display and not render
label.new(last_bar_index - 7, cell_width * 20, "Market closed!", size=size.small, color=color.yellow, style=label.style_label_center)
if barstate.islast and custom_bar
label.new(last_bar_index - 6, cell_width * 20, "Historical Bar", size=size.small, color=color.yellow, style=label.style_label_center)
if barstate.isfirst and display
for i = 0 to array.size(symbols) - 1
name = syminfo.ticker(array.get(symbols, i))
[l, t, r, b] = getCords(array.get(locs, i * 2), array.get(locs, i * 2 + 1))
box.new(l, t, r, b, text="", border_width=0, bgcolor=color.black )
box_legend = box.new(l, t, l+1, b, text="", border_width=0)
box_legend_border = box.new(l, t, l+1, b, text="", border_width=1, bgcolor=color.rgb(0,0,0,100))
box_value = box.new(l, t, r, b, text="", text_size=size.normal, border_width=0, bgcolor=color.rgb(0,0,0,100), text_color=color.white)
box_name = box.new(l+1, t, l + cell_width, t - cell_width, text=name, text_size=size.tiny, text_halign=text.align_left, bgcolor=color.rgb(0,0,0,100), border_width=0, text_color=color.white)
box_change = box.new(r - cell_width, b + cell_width, r, b, text="", text_size=size.small, text_halign=text.align_right, bgcolor=color.rgb(0,0,0,100), border_width=0, text_color=color.white)
array.set(box_legends, i, box_legend)
array.set(box_legend_borders, i, box_legend_border)
array.set(box_names, i, box_name)
array.set(box_values, i, box_value)
array.set(box_changes, i, box_change)
for i = 0 to array.size(arrows) - 4 by 4
src_box = array.get(box_values, array.get(arrows, i))
tgt_box = array.get(box_values, array.get(arrows, i + 2))
[x1, y1] = getAnchor(src_box, array.get(arrows, i + 1))
[x2, y2] = getAnchor(tgt_box, array.get(arrows, i + 3))
_x1 = x1 > x2 ? x1 - 1 : x1 + 1
_y1 = y1 > y2 ? y1 - 2: y1 + 2
_x2 = x2 > x1 ? x2 - 1 : x2 + 1
_y2 = y2 > y1 ? y2 - 2: y2 + 2
array.set(lines, i / 4, line.new(_x1, _y1, _x2, _y2))
if barstate.islast and display
for i = 0 to array.size(symbols) - 1
o = array.get(o_0, i)
h = array.get(h_0, i)
l = array.get(l_0, i)
c = array.get(c_0, i)
c1 = array.get(c_1, i)
box_legend = array.get(box_legends, i)
box_legend_border = array.get(box_legend_borders, i)
box_name = array.get(box_names, i)
box_value = array.get(box_values, i)
box_change = array.get(box_changes, i)
chg = math.round((c - c1) / math.abs(c1) * 100, 2)
array.set(changes, i, chg)
box.set_text(box_value, str.tostring(c))
box.set_text(box_change, str.tostring(chg)+"%")
bg_color = c >= o ? color.teal: color.red
if not render or (o == c and h == l) or (c == c1)
bg_color := color.gray
[_l, _t, _r, _b] = getCords(array.get(locs, i * 2), array.get(locs, i * 2 + 1))
box.set_bottom(box_legend, _b + (_t - _b) / (h - l) * (o - l))
box.set_top(box_legend, _t - (_t - _b) / (h - l) * (h - c))
box.set_bgcolor(box_legend, bg_color)
border_color = c >= c1 ? color.teal: color.red
if not render or (o == c and h == l) or (c == c1)
border_color := color.gray
box.set_border_color(box_legend, border_color)
box.set_border_color(box_legend_border, border_color)
for i = 0 to array.size(arrows) - 4 by 4
src_idx = array.get(arrows, i)
tgt_idx = array.get(arrows, i + 2)
src_chg = array.get(changes, src_idx)
tgt_chg = array.get(changes, tgt_idx)
lin = array.get(lines, i / 4)
usdpair = str.startswith(syminfo.ticker(array.get(symbols, tgt_idx)), "USD")
if src_idx == 0 and tgt_idx % 3 == 0 and usdpair and render
line.set_style(lin, tgt_chg < 0 ? line.style_arrow_right : line.style_arrow_left)
else if src_idx == 0 and tgt_idx % 3 == 0 and render
line.set_style(lin, tgt_chg > 0 ? line.style_arrow_right : line.style_arrow_left)
else if src_idx % 3 == 0 and tgt_idx % 3 == 1 and render
line.set_style(lin, tgt_chg < 0 ? line.style_arrow_right : line.style_arrow_left)
else if src_idx % 3 == 0 and tgt_idx % 3 == 2 and render
line.set_style(lin, tgt_chg > 0 ? line.style_arrow_right : line.style_arrow_left)
line.set_color(lin, color.aqua)
if(src_idx % 3 == 0 and tgt_chg == 0 and render)
line.set_style(lin, line.style_dashed)
line.set_color(lin, color.gray)
// if barstate.isfirst
// for i = 0 to 20
// line.new(last_bar_index - i * cell_width, 1, last_bar_index - i * cell_width, 0, extend=extend.both, color=color.yellow)
// line.new(0, i * cell_width, 1, i * cell_width, extend=extend.both, color=color.yellow) |
Market Structure - By Leviathan | https://www.tradingview.com/script/bXic0E3l-Market-Structure-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 4,802 | 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/
// © Leviathan
// Swing point generation inspired by @BacktestRookies
//@version=5
indicator("Market Structure - By Leviathan", overlay=true, max_labels_count=500, max_lines_count=500)
// Constants
color CLEAR = color.rgb(0,0,0,100)
// Inputs
swingSize = input.int(20, 'Swing Length', tooltip='The number of left and right bars checked when searching for a swing point. Higher value = less swing points plotted and lower value = more swing points plotted.' )
bosConfType = input.string('Candle Close', 'BOS Confirmation', ['Candle Close', 'Wicks'], tooltip='Choose whether candle close/wick above previous swing point counts as a BOS.')
choch = input.bool(false, 'Show CHoCH', tooltip='Renames the first counter trend BOS to CHoCH' )
showSwing = input.bool(true, 'Show Swing Points', tooltip='Show or hide HH, LH, HL, LL')
showHalf = input.bool(false, 'Show 0.5 Retracement Level', group='0.5 Retracement Level', tooltip='Show a possible 0.5 retracement level between the swing highs and lows of an expansion move.')
halfColor = input.color(color.rgb(41, 39, 176), 'Color', group='0.5 Retracement Level')
halfStyle = input.string('Solid', 'Line Style', ['Solid', 'Dashed', 'Dotted'], group='0.5 Retracement Level')
halfWidth = input.int(1, 'Width', minval=1, group='0.5 Retracement Level')
bosColor = input.color(color.rgb(112, 114, 119), 'Color', group='BOS Settings')
bosStyle = input.string('Dashed', 'Line Style', ['Solid', 'Dashed', 'Dotted'], group='BOS Settings')
bosWidth = input.int(1, 'Width', minval=1, group='BOS Settings')
// Functions
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
// Calculations
//Finding high and low pivots
pivHi = ta.pivothigh(high, swingSize, swingSize)
pivLo = ta.pivotlow(low, swingSize, swingSize)
//Tracking the previous swing levels to determine hh lh hl ll
var float prevHigh = na
var float prevLow = na
var int prevHighIndex = na
var int prevLowIndex = na
//Tracking whether previous levels have been breached
var bool highActive = false
var bool lowActive = false
bool hh = false
bool lh = false
bool hl = false
bool ll = false
//Variable to track the previous swing type, used later on to draw 0.5 Retracement Levels (HH = 2, LH = 1, HL = -1, LL = -2)
var int prevSwing = 0
if not na(pivHi)
if pivHi >= prevHigh
hh := true
prevSwing := 2
else
lh := true
prevSwing := 1
prevHigh := pivHi
highActive := true
prevHighIndex := bar_index - swingSize
if not na(pivLo)
if pivLo >= prevLow
hl := true
prevSwing := -1
else
ll := true
prevSwing := -2
prevLow := pivLo
lowActive := true
prevLowIndex := bar_index - swingSize
//Generating the breakout signals
bool highBroken = false
bool lowBroken = false
//Tracking prev breakout
var int prevBreakoutDir = 0
float highSrc = bosConfType == 'Candle Close' ? close : high
float lowSrc = bosConfType == 'Candle Close' ? close : low
if highSrc > prevHigh and highActive
highBroken := true
highActive := false
if lowSrc < prevLow and lowActive
lowBroken := true
lowActive := false
// Visual Output
//Swing level labels
if hh and showSwing
label.new(bar_index - swingSize, pivHi, 'HH', color=CLEAR, style=label.style_label_down, textcolor=chart.fg_color)
//Detecting if it is a hh after a hl
if prevSwing[1] == -1 and showHalf
line.new(prevLowIndex, (prevLow + pivHi) / 2, bar_index - swingSize, (prevLow + pivHi) / 2, color=halfColor, style=lineStyle(halfStyle), width=halfWidth)
if lh and showSwing
label.new(bar_index - swingSize, pivHi, 'LH', color=CLEAR, style=label.style_label_down, textcolor=chart.fg_color)
if hl and showSwing
label.new(bar_index - swingSize, pivLo, 'HL', color=CLEAR, style=label.style_label_up, textcolor=chart.fg_color)
if ll and showSwing
label.new(bar_index - swingSize, pivLo, 'LL', color=CLEAR, style=label.style_label_up, textcolor=chart.fg_color)
//Detecting if it is a ll after a lh
if prevSwing[1] == 1 and showHalf
line.new(prevHighIndex, (prevHigh + pivLo) / 2, bar_index - swingSize, (prevHigh + pivLo) / 2, color=halfColor, style=lineStyle(halfStyle), width=halfWidth)
//Generating the BOS Lines
if highBroken
line.new(prevHighIndex, prevHigh, bar_index, prevHigh, color=bosColor, style=lineStyle(bosStyle), width=bosWidth)
label.new(math.floor(bar_index - (bar_index - prevHighIndex) / 2), prevHigh, prevBreakoutDir == -1 and choch ? 'CHoCH' : 'BOS', color=CLEAR, textcolor=bosColor, size=size.tiny)
prevBreakoutDir := 1
if lowBroken
line.new(prevLowIndex, prevLow, bar_index, prevLow, color=bosColor, style=lineStyle(bosStyle), width=bosWidth)
label.new(math.floor(bar_index - (bar_index - prevLowIndex) / 2), prevLow, prevBreakoutDir == 1 and choch ? 'CHoCH' : 'BOS', color=CLEAR, textcolor=bosColor, style=label.style_label_up, size=size.tiny)
prevBreakoutDir := -1 |
Stock Market Emotion Index (SMEI) | https://www.tradingview.com/script/AjMmZgWV-Stock-Market-Emotion-Index-SMEI/ | Lantzwat | https://www.tradingview.com/u/Lantzwat/ | 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/
// © Lantzwat
//@version=5
indicator("Stock Market Emotion Index", "SMEI")
// Implementation of Charlie Q. Yang research paper “The stock market emotion index”, subtitle “A New Sentiment Measure Using Enhanced OBV and Money Flow Indicators” (2007)
// where he combined “five simple emotion statistics” -
// "Close Emotion Statistic (CES), Money Flow Statistic (MFS), Supply Demand Statistic (SDS), Relative Strength Statistic (RSS), and Psychological Level Statistic (PLS)"
// - into one indicator.
_sgn (float x) =>
_return = x == 0 ? 0 : x > 0 ? 1 : -1
MasterTimeFrame = input.timeframe("","Set Timeframe")
period = input(260, "Period")
autoper =input.bool(true, "script sets period")
MTF = MasterTimeFrame == "" ? timeframe.period : MasterTimeFrame
preset= MTF=="M"? 14: MTF=="W"? 14: MTF=="D"? 21: MTF=="240"? 28: MTF=="180"? 28: MTF=="120"? 35: MTF=="60"? 35: MTF=="45"? 35: MTF=="30"? 42: MTF=="15"? 42: MTF=="5"? 49: MTF=="3"? 49: MTF=="1"? 56: 14
period:= autoper ? preset : period
src_close = request.security(syminfo.tickerid , MTF, close)
src_volume = request.security(syminfo.tickerid , MTF, volume)
src_high = request.security(syminfo.tickerid , MTF, high)
src_low = request.security(syminfo.tickerid , MTF, low)
src_open = request.security(syminfo.tickerid , MTF, open)
//Close Emotion Statistic (CES)
CES = _sgn(src_close - src_close[1]) * src_volume
//Money Flow Statistic (MFS)
MFS = _sgn(src_close - (src_high-src_low)/2) * src_volume
//Supply Demand Statistic (SDS)
SDS = _sgn(src_close - src_open) * src_volume
//Relative Strength Statistic (RSS)
RSS = _sgn(ta.rsi(src_close,1) - 0.5) * src_volume
//Psychological Level Statistic (PLS).
PLS = 0.0
if src_close > ta.highest(src_high,21)
PLS := src_volume
if src_close > ta.lowest(src_low, 21)
PLS := src_volume * -1
if src_close > ta.highest(src_high,21) and src_close > ta.lowest(src_low, 21)
PLS := 0.0
//Stock Market Emotion Index =>
//SMES = (CES + MFS + SDS + RSS + PLS) / math.avg(src_volume,21) * 5
//plot (SMES)
vol_avg = math.avg(src_volume,21)
SMEI = math.sum( (CES + MFS + SDS + RSS + PLS) / (10 * 5 * vol_avg), period)
SMEI_up = SMEI > SMEI[1]
SMEI_down = SMEI < SMEI[1]
SMEIcol = SMEI_up ? color.lime : SMEI_down ? color.red : color.aqua
plot(SMEI,title = "SMEI", color = color.new(SMEIcol, 50), linewidth = 1, style = plot.style_area)
// Bull and bear market coloration
bgcolor(SMEI < 0 ? color.new(color.red,80) : SMEI > 0 ? color.new(color.green, 80) : color.new(color.white,100))
//Rating scheme from the paper:
//1. SMEI is positive and up in an early bull market - Strong Buy
//2. SMEI is positive and down in an early bull market - Hold
//3. SMEI is positive and up in a middle bull market - Buy
//4. SMEI is positive and down in a middle bull market - Hold
//5. SMEI is positive and up in a late bull market - Buy
//6. SMEI is positive and down in a late bull market - Weak Sell (reduce)
//7. SMEI is negative and up in an early bear market - Hold
//8. SMEI is negative and down in an early bear market - Strong Sell
//9. SMEI is negative and up in a middle bear market - Hold
//10. SMEI is negative and down in a middle bear market - Sell
//11. SMEI is negative and up in a late bear market - Weak Buy (accumulate)
//12. SMEI is negative and down in a late bear market - Sell
//13. The absolute value of SMEI is less than 0.2 - Wait (sideline)
|
Adaptive Fisherized ROC | https://www.tradingview.com/script/Ufbx4DRV-Adaptive-Fisherized-ROC/ | simwai | https://www.tradingview.com/u/simwai/ | 42 | 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/
// © simwai
//@version=5
indicator('Adaptive Fisherized ROC', 'AF_ROC', false)
// -- Input --
string rocResolution = input.timeframe(defval='', title='Resolution', group='ROC', inline='1')
int min = input.int(defval=4, minval=2, title='Min Length', group='ROC', inline='2')
int rocLength = input.int(defval=13, minval=2, title='Length', group='ROC', inline='2')
bool isRocFisherized = input.bool(defval=true, title='Enable Fisherization', group='ROC', inline='3')
string adaptiveMode = input.string('Inphase-Quadrature Transform', 'Choose Adaptive Mode', options=['Hilbert Transform', 'Inphase-Quadrature Transform', 'Median', 'Homodyne Discriminator', 'None'], group='ROC', inline='4')
bool isHighlighted = input.bool(defval=true, title='Enable Positive/Negative Highlightning', group='ROC', inline='5')
string sourceSmoothingMode = input.string('Hann Window', 'Choose Smoothing Mode', options=['T3', 'T3 New', 'Hann Window', 'NET', 'Super Smoother', 'None'], group='Source Smoothing', inline='1')
int sourceSmoothingLength = input.int(3, 'Source Smoothing Length', minval=2, group='Source Smoothing', inline='2')
bool isAdaptiveLengthAppliedOnSourceSmoothing = input.bool(false, 'Override source smoothing length with the adaptive length', group='Source Smoothing', inline='3')
string indicatorSmoothingMode = input.string('T3', 'Choose Smoothing Mode', options=['T3', 'T3 New', 'Hann Window', 'NET', 'Super Smoother', 'None'], group='Indicator Smoothing', inline='1')
int indicatorSmoothingLength = input.int(5, 'Indicator Smoothing Length', minval=2, group='Indicator Smoothing', inline='2')
bool isAdaptiveLengthAppliedOnIndicatorSmoothing = input.bool(true, 'Override indicator smoothing length with the adaptive length', group='Indicator Smoothing', inline='3')
string divergenceMode = input.string('Both', title='Divergence Mode', options=['Regular', 'Hidden', 'Both', 'None'], group='Divergences', inline='1')
bool isDivergencePlotEnabled = input.bool(false, title='Enable Divergence Lines Plot', group='Divergences', inline='2')
int rangeUpper = input.int(title='Max Lookback Range', minval=1, defval=60, group='Divergences', inline='3')
int rangeLower = input.int(title='Min Lookback Range', minval=1, defval=5, group='Divergences', inline='3')
int lbR = input.int(title='Pivot Lookback Right', minval=2, defval=12, group='Divergences', inline='4')
int lbL = input.int(title='Pivot Lookback Left', minval=2, defval=12, group='Divergences', inline='4')
// -- Colors --
color maximumYellowRed = color.rgb(255, 203, 98) // yellow
color rajah = color.rgb(242, 166, 84) // orange
color magicMint = color.rgb(171, 237, 198)
color lightPurple = color.rgb(193, 133, 243)
color languidLavender = color.rgb(232, 215, 255)
color maximumBluePurple = color.rgb(181, 161, 226)
color skyBlue = color.rgb(144, 226, 244)
color lightGray = color.rgb(214, 214, 214)
color quickSilver = color.rgb(163, 163, 163)
color mediumAquamarine = color.rgb(104, 223, 153)
// Divergence colors
color bullColor = mediumAquamarine
color bearColor = lightPurple
color hiddenBullColor = bullColor
color hiddenBearColor = bearColor
color noneColor = color.new(color.white, 100)
color textColor = color.white
// -- Functions --
inRange(bool cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
// Apply normalization
normalize(float _src, int _min, int _max) =>
var float _historicMin = 1.0
var float _historicMax = -1.0
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 1)
// Inverse Fisher Transformation (IFT)
fisherize(float _value) => (math.exp(2 * _value) - 1) / (math.exp(2 * _value) + 1)
// Convert length to alpha
getAlpha(float _length) => 2 / (_length + 1)
// Get dominant cyber cycle – Median – Credits to @blackcat1402
getMedianDc(float Price, float alpha=0.07, simple float CycPart=0.5) =>
Smooth = 0.00
Cycle = 0.00
Q1 = 0.00
I1 = 0.00
DeltaPhase = 0.00
MedianDelta = 0.00
DC = 0.00
InstPeriod = 0.00
Period = 0.00
I2 = 0.00
Q2 = 0.00
IntPeriod = 0
Smooth := (Price + 2 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 6
Cycle := (1 - .5 * alpha) * (1 - .5 * alpha) * (Smooth - 2 * nz(Smooth[1]) + nz(Smooth[2])) + 2 * (1 - alpha) * nz(Cycle[1]) - (1 - alpha) * (1 - alpha) * nz(Cycle[2])
Cycle := bar_index < 7 ? (Price - 2 * nz(Price[1]) + nz(Price[2])) / 4 : Cycle
Q1 := (.0962 * Cycle + .5769 * nz(Cycle[2]) - .5769 * nz(Cycle[4]) - .0962 * nz(Cycle[6])) * (.5 + .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]))) : DeltaPhase
DeltaPhase := DeltaPhase < 0.1 ? 0.1 : DeltaPhase
DeltaPhase := DeltaPhase > 1.1 ? 1.1 : DeltaPhase
MedianDelta := ta.median(DeltaPhase, 5)
DC := MedianDelta == 0.00 ? 15.00 : 6.28318 / MedianDelta + .5
InstPeriod := .33 * DC + .67 * nz(InstPeriod[1])
Period := .15 * InstPeriod + .85 * nz(Period[1])
//it can add filter to Period here
//IntPeriod := round((4*Period + 3*nz(Period[1]) + 2*nz(Period[3]) + nz(Period[4])) / 20)
IntPeriod := math.round(Period * CycPart) > 34 ? 34 : math.round(Period * CycPart) < 1 ? 1 : math.round(Period * CycPart)
IntPeriod
// Get dominant cyber cycle – Inphase-Quadrature -- Credits to @DasanC
getIqDc(float src, int min, int max) =>
PI = 3.14159265359
P = src - src[7]
lenIQ = 0.0
lenC = 0.0
imult = 0.635
qmult = 0.338
inphase = 0.0
quadrature = 0.0
re = 0.0
im = 0.0
deltaIQ = 0.0
instIQ = 0.0
V = 0.0
inphase := 1.25 * (P[4] - imult * P[2]) + imult * nz(inphase[3])
quadrature := P[2] - qmult * P + qmult * nz(quadrature[2])
re := 0.2 * (inphase * inphase[1] + quadrature * quadrature[1]) + 0.8 * nz(re[1])
im := 0.2 * (inphase * quadrature[1] - inphase[1] * quadrature) + 0.8 * nz(im[1])
if re != 0.0
deltaIQ := math.atan(im / re)
deltaIQ
for i = 0 to max by 1
V += deltaIQ[i]
if V > 2 * PI and instIQ == 0.0
instIQ := i
instIQ
if instIQ == 0.0
instIQ := nz(instIQ[1])
instIQ
lenIQ := 0.25 * instIQ + 0.75 * nz(lenIQ[1], 1)
length = lenIQ < min ? min : lenIQ
math.round(length)
// Get dominant cyber cycle – Hilbert Transform -- Credits to @DasanC
getHtDc(float src) =>
Imult = .635
Qmult = .338
PI = 3.14159
InPhase = 0.0
Quadrature = 0.0
Phase = 0.0
DeltaPhase = 0.0
InstPeriod = 0.0
Period = 0.0
Value4 = 0.0
if bar_index > 5
// Detrend src
Value3 = src - src[7]
// Compute InPhase and Quadrature components
InPhase := 1.25 * (Value3[4] - Imult * Value3[2]) + Imult * nz(InPhase[3])
Quadrature := Value3[2] - Qmult * Value3 + Qmult * nz(Quadrature[2])
// Use ArcTangent to compute the current phase
if math.abs(InPhase + InPhase[1]) > 0
Phase := 180 / PI * math.atan(math.abs((Quadrature + Quadrature[1]) / (InPhase + InPhase[1])))
Phase
// Resolve the ArcTangent ambiguity
if InPhase < 0 and Quadrature > 0
Phase := 180 - Phase
Phase
if InPhase < 0 and Quadrature < 0
Phase := 180 + Phase
Phase
if InPhase > 0 and Quadrature < 0
Phase := 360 - Phase
Phase
// Compute a differential phase, resolve phase wraparound, and limit delta phase errors
DeltaPhase := Phase[1] - Phase
if Phase[1] < 90 and Phase > 270
DeltaPhase := 360 + Phase[1] - Phase
DeltaPhase
if DeltaPhase < 1
DeltaPhase := 1
DeltaPhase
if DeltaPhase > 60
DeltaPhase := 60
DeltaPhase
// Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous period.
for i = 0 to 50 by 1
Value4 += DeltaPhase[i]
if Value4 > 360 and InstPeriod == 0
InstPeriod := i
InstPeriod
// Resolve Instantaneous Period errors and smooth
if InstPeriod == 0
nz(InstPeriod[1])
Period := .25 * InstPeriod + .75 * Period[1]
math.round(Period)
// Get Dominant Cyber Cycle - Homodyne Discriminator With Hilbert Dominant Cycle – Credits to @blackcat1402
getHdDc(float Price, int min, int max, simple float CycPart = 0.5) =>
Smooth = 0.00
Detrender = 0.00
I1 = 0.00
Q1 = 0.00
jI = 0.00
jQ = 0.00
I2 = 0.00
Q2 = 0.00
Re = 0.00
Im = 0.00
Period = 0.00
SmoothPeriod = 0.00
pi = 2 * math.asin(1)
DomCycle = 0.0
//Hilbert Transform
Smooth := bar_index > 7 ? (4 * Price + 3 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 10 : Smooth
Detrender := bar_index > 7 ? (.0962 * Smooth + .5769 * nz(Smooth[2]) - .5769 * nz(Smooth[4]) - .0962 * nz(Smooth[6])) * (.075 * nz(Period[1]) + .54) : Detrender
//Compute InPhase and Quadrature components
Q1 := bar_index > 7 ? (.0962 * Detrender + .5769 * nz(Detrender[2]) - .5769 * nz(Detrender[4]) - .0962 * nz(Detrender[6])) * (.075 * nz(Period[1]) + .54) : Q1
I1 := bar_index > 7 ? nz(Detrender[3]) : I1
//Advance the phase of I1 and Q1 by 90 degrees
jI := (.0962 * I1 + .5769 * nz(I1[2]) - .5769 * nz(I1[4]) - .0962 * nz(I1[6])) * (.075 * nz(Period[1]) + .54)
jQ := (.0962 * Q1 + .5769 * nz(Q1[2]) - .5769 * nz(Q1[4]) - .0962 * nz(Q1[6])) * (.075 * nz(Period[1]) + .54)
//Phasor addition for 3 bar averaging
I2 := I1 - jQ
Q2 := Q1 + jI
//Smooth the I and Q components before applying the discriminator
I2 := .2 * I2 + .8 * nz(I2[1])
Q2 := .2 * Q2 + .8 * nz(Q2[1])
//Homodyne Discriminator
Re := I2 * nz(I2[1]) + Q2 * nz(Q2[1])
Im := I2 * nz(Q2[1]) - Q2 * nz(I2[1])
Re := .2 * Re + .8 * nz(Re[1])
Im := .2 * Im + .8 * nz(Im[1])
Period := Im != 0 and Re != 0 ? 2 * pi / math.atan(Im / Re) : Period
Period := Period > 1.5 * nz(Period[1]) ? 1.5 * nz(Period[1]) : Period
Period := Period < .67 * nz(Period[1]) ? .67 * nz(Period[1]) : Period
Period := Period < min ? min : Period
Period := Period > max ? max : Period
Period := .2 * Period + .8 * nz(Period[1])
SmoothPeriod := .33 * Period + .67 * nz(SmoothPeriod[1])
//it can add filter to Period here
DomCycle := math.ceil(CycPart * SmoothPeriod) > 34 ? 34 : math.ceil(CycPart * SmoothPeriod) < 1 ? 1 : math.ceil(CycPart * SmoothPeriod)
// Limit dominant cycle
DomCycle := DomCycle < min ? min : DomCycle
DomCycle := DomCycle > max ? max : DomCycle
// Noise Elimination Technology (NET) – Credits to @blackcat1402
doNet(float _series, int _netLength, int _lowerBand=-1, int _upperBand=1) =>
var netX = array.new_float(102)
var netY = array.new_float(102)
num = 0.00
denom = 0.00
net = 0.00
trigger = 0.00
for count = 1 to _netLength
array.set(netX, count, nz(_series[count - 1]))
array.set(netY, count, -count)
num := 0
for count = 2 to _netLength
for k = 1 to count - 1
num := num - math.sign(nz(array.get(netX, count)) - nz(array.get(netX, k)))
denom := 0.5 * _netLength * (_netLength - 1)
net := num / denom
trigger := 0.05 + 0.9 * nz(net[1])
trigger := normalize(trigger, _lowerBand, _upperBand)
// Hann Window Smoothing – Credits to @cheatcountry
doHannWindow(float _series, float _hannWindowLength) =>
sum = 0.0, coef = 0.0
for i = 1 to _hannWindowLength
cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1))
sum := sum + (cosine * nz(_series[i - 1]))
coef := coef + cosine
h = coef != 0 ? sum / coef : 0
// T3 - Credits to @loxx
t3(float _src, float _length, float hot=0.5, string clean='T3')=>
a = hot
_c1 = -a * a * a
_c2 = 3 * a * a + 3 * a * a * a
_c3 = -6 * a * a - 3 * a - 3 * a * a * a
_c4 = 1 + 3 * a + a * a * a + 3 * a * a
alpha = 0.
if (clean == 'T3 New')
alpha := 2.0 / (2.0 + (_length - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + _length)
_t30 = _src, _t31 = _src
_t32 = _src, _t33 = _src
_t34 = _src, _t35 = _src
_t30 := nz(_t30[1]) + alpha * (_src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
// Super Smoother Function - Credits to @balipour
ss(Series, Period) => // Super Smoother Function
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
doSmoothing(float src, int length, string smoothingMode, float t3Hot=0.5) =>
switch smoothingMode
'T3' => t3(src, length, t3Hot, 'T3')
'T3 New' => t3(src, length, t3Hot, 'T3 New')
'Super Smoother' => ss(src, length)
'Hann Window' => doHannWindow(src, length)
'NET' => doNet(src, length)
=> src
// -- ROC Calculation --
[src, _high, _low] = request.security(syminfo.tickerid, rocResolution, [close[1], high[1], low[1]], barmerge.gaps_off, barmerge.lookahead_on)
// Source Smoothing
if (not isAdaptiveLengthAppliedOnSourceSmoothing)
src := doSmoothing(src, sourceSmoothingLength, sourceSmoothingMode)
int _length = switch adaptiveMode
'Hilbert Transform' => math.round(getHtDc(src) / 2)
'Inphase-Quadrature Transform' => math.round(getIqDc(src, min, rocLength) / 2)
'Median' => getMedianDc(src, getAlpha(rocLength)),
'Homodyne Discriminator' => math.round(getHdDc(src, min, rocLength))
=> rocLength
if (_length < min and adaptiveMode != 'None')
_length := min
if (isAdaptiveLengthAppliedOnSourceSmoothing)
src := doSmoothing(src, _length, sourceSmoothingMode)
float roc = 100 * (src - src[_length]) / src[_length]
// Indicator Smoothing
if (isAdaptiveLengthAppliedOnIndicatorSmoothing)
roc := doSmoothing(roc, _length, indicatorSmoothingMode)
else
roc := doSmoothing(roc, indicatorSmoothingLength, indicatorSmoothingMode)
if (isRocFisherized)
roc := fisherize(roc)
bool rocLong = roc >= 0
bool rocShort = roc < 0
topBand = plot(1, 'Top Band', color=color.new(lightGray, 50))
zeroLine = plot(0, 'Zero Line', color=color.new(lightGray, 50))
bottomBand = plot(-1, 'Bottom Band', color=color.new(lightGray, 50))
rocPlot = plot(roc, title='ROC', color=languidLavender)
fill(zeroLine, topBand, color=(isHighlighted and rocLong) ? color.new(magicMint, 90) : na)
fill(zeroLine, bottomBand, color=(isHighlighted and rocShort) ? color.new(rajah, 90) : na)
// -- Divergences – Credits to @tista --
float top = na
float bot = na
top := ta.pivothigh(roc, lbL, lbR)
bot := ta.pivotlow(roc, lbL, lbR)
bool phFound = na(top) ? false : true
bool plFound = na(bot) ? false : true
// -- Regular Bullish --
// Osc: Higher Low
bool rocHL = roc[lbR] > ta.valuewhen(plFound, roc[lbR], 1) and inRange(plFound[1])
// Price: Lower Low
bool priceLL = _low[lbR] < ta.valuewhen(plFound, _low[lbR], 1)
bool bullCond = priceLL and rocHL and plFound
plot(
(((divergenceMode == 'Regular') or (divergenceMode == 'Both')) and plFound and isDivergencePlotEnabled) ? roc[lbR] : na,
offset=-lbR,
title='Regular Bullish',
linewidth=1,
color=(bullCond ? bullColor : noneColor),
editable = false)
plotshape(
(((divergenceMode == 'Regular') or (divergenceMode == 'Both')) and bullCond) ? roc[lbR] : na,
offset=-lbR,
title='Regular Bullish Label',
text='R',
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
editable = false)
alertcondition(bullCond, title='Regular bullish divergence in roc found', message='roc – Regular Bullish Divergence')
// -- Hidden Bullish Divergence --
// Osc: Lower Low
bool rocLL = roc[lbR] < ta.valuewhen(plFound, roc[lbR], 1) and inRange(plFound[1])
// Price: Higher Low
bool priceHL = _low[lbR] > ta.valuewhen(plFound, _low[lbR], 1)
bool hiddenBullCond = priceHL and rocLL and plFound
plot(
(((divergenceMode == 'Hidden') or (divergenceMode == 'Both')) and plFound and isDivergencePlotEnabled) ? roc[lbR] : na,
offset=-lbR,
title='Hidden Bullish',
linewidth=1,
color=(hiddenBullCond ? hiddenBullColor : noneColor),
editable = false)
plotshape(
(((divergenceMode == 'Hidden') or (divergenceMode == 'Both')) and hiddenBullCond) ? roc[lbR] : na,
offset=-lbR,
title='Hidden Bullish Label',
text='H',
style=shape.labelup,
location=location.absolute,
color=hiddenBullColor,
textcolor=textColor,
editable = false)
alertcondition(hiddenBullCond, title='Hidden bullish divergence in roc found', message='roc – Hidden Bullish Divergence')
// -- Regular Bullish Divergence --
// Osc: Lower High
bool rocLH = roc[lbR] < ta.valuewhen(phFound, roc[lbR], 1) and inRange(phFound[1])
// Price: Higher High
bool priceHH = _high[lbR] > ta.valuewhen(phFound, _high[lbR], 1)
bool bearCond = priceHH and rocLH and phFound
plot(
(((divergenceMode == 'Regular') or (divergenceMode == 'Both')) and phFound and isDivergencePlotEnabled) ? roc[lbR] : na,
offset=-lbR,
title='Regular Bearish',
linewidth=1,
color=(bearCond ? bearColor : noneColor),
editable = false)
plotshape(
(((divergenceMode == 'Regular') or (divergenceMode == 'Both')) and bearCond) ? roc[lbR] : na,
offset=-lbR,
title='Regular Bearish Label',
text='R',
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
editable = false)
alertcondition(bearCond, title='Regular bearish divergence in roc found', message='roc – Regular Bullish Divergence')
// -- Hidden Bearish Divergence --
// Osc: Higher High
bool rocHH = roc[lbR] > ta.valuewhen(phFound, roc[lbR], 1) and inRange(phFound[1])
// Price: Lower High
bool priceLH = _high[lbR] < ta.valuewhen(phFound, _high[lbR], 1)
bool hiddenBearCond = priceLH and rocHH and phFound
plot(
(((divergenceMode == 'Hidden') or (divergenceMode == 'Both')) and phFound and isDivergencePlotEnabled) ? roc[lbR] : na,
offset=-lbR,
title='Hidden Bearish',
linewidth=1,
color=(hiddenBearCond ? hiddenBearColor : noneColor),
editable=false)
plotshape(
(((divergenceMode == 'Hidden') or (divergenceMode == 'Both')) and hiddenBearCond) ? roc[lbR] : na,
offset=-lbR,
title='Hidden Bearish Label',
text='H',
style=shape.labeldown,
location=location.absolute,
color=hiddenBearColor,
textcolor=textColor,
editable=false)
alertcondition(hiddenBearCond, title='Hidden bearish divergence in roc found', message='roc – Hidden Bearish Divergence')
// Try to fix scale with hidden plots
plot(1.35, 'Scale fix', transp=100, editable=false, color=color.black)
plot(-1.35, 'Scale fix', transp=100, editable=false, color=color.black) |
Crypto Market Breadth [QuantVue] | https://www.tradingview.com/script/ZI5tLixB-Crypto-Market-Breadth-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 129 | 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/
// © AlgoBuddy
//@version=5
///updated: added 15 total crypto markets show breadth of market, can pick choose tickers///
indicator("Crypto Market Breadth [AlgoBuddy]", overlay=false)
currentTimeFrame = input.timeframe("","Timeframe")
stock1 = input.symbol(defval="BTCUSDT", title="Ticker 1")
stock2 = input.symbol(defval="ETHUSDT", title="Ticker 2")
stock3 = input.symbol(defval="BNBUSDT", title="Ticker 3")
stock4 = input.symbol(defval="XRPUSDT", title="Ticker 4")
stock5 = input.symbol(defval="DOGEUSDT", title="Ticker 5")
stock6 = input.symbol(defval="ADAUSDT", title="Ticker 6")
stock7 = input.symbol(defval="SOLUSDT", title="Ticker 7")
stock8 = input.symbol(defval="MATICUSDT", title="Ticker 8")
stock9 = input.symbol(defval="DOTUSDT", title="Ticker 9")
stock10 = input.symbol(defval="SHIBUSDT", title="Ticker 10")
stock11 = input.symbol(defval="AVAXUSDT", title="Ticker 11")
stock12 = input.symbol(defval="UNIUSDT", title="Ticker 12")
stock13 = input.symbol(defval="LTCUSDT", title="Ticker 13")
stock14 = input.symbol(defval="ATOMUSDT", title="Ticker 14")
stock15 = input.symbol(defval="LINKUSDT", title="Ticker 15")
Price1 = request.security(stock1, "1D", close[1])
Price2 = request.security(stock1, currentTimeFrame, close)
Price3 = request.security(stock2, "1D", close[1])
Price4 = request.security(stock2, currentTimeFrame, close)
Price5 = request.security(stock3, "1D", close[1])
Price6 = request.security(stock3, currentTimeFrame, close)
Price7 = request.security(stock4, "1D", close[1])
Price8 = request.security(stock4, currentTimeFrame, close)
Price9 = request.security(stock5, "1D", close[1])
Price10 = request.security(stock5, currentTimeFrame, close)
Price11 = request.security(stock6, "1D", close[1])
Price12 = request.security(stock6, currentTimeFrame, close)
Price13 = request.security(stock7, "1D", close[1])
Price14 = request.security(stock7, currentTimeFrame, close)
Price15 = request.security(stock8, "1D", close[1])
Price16 = request.security(stock8, currentTimeFrame, close)
Price17 = request.security(stock9, "1D", close[1])
Price18 = request.security(stock9, currentTimeFrame, close)
Price19 = request.security(stock10, "1D", close[1])
Price20 = request.security(stock10, currentTimeFrame, close)
Price21 = request.security(stock11, "1D", close[1])
Price22 = request.security(stock11, currentTimeFrame, close)
Price23 = request.security(stock12, "1D", close[1])
Price24 = request.security(stock12, currentTimeFrame, close)
Price25 = request.security(stock13, "1D", close[1])
Price26 = request.security(stock13, currentTimeFrame, close)
Price27 = request.security(stock14, "1D", close[1])
Price28 = request.security(stock14, currentTimeFrame, close)
Price29 = request.security(stock15, "1D", close[1])
Price30 = request.security(stock15, currentTimeFrame, close)
PercentChg3 = ((Price2 - Price1)+ (Price4 - Price3)+ (Price6 - Price5)+ (Price8 - Price7)+ (Price10 - Price9)+ (Price12 - Price11)+ (Price14 - Price13)+ (Price16 - Price15) + (Price18 - Price17) + (Price20 - Price19) + (Price22-Price21) + (Price24 - Price23) + (Price26 - Price25) + (Price28 - Price27) + (Price30 - Price29))/(Price1+Price3+Price5+Price7+Price9+Price11+Price13+Price15+Price17+Price19+Price21+Price23+Price25+Price27+Price29) *100
plot(PercentChg3,style=plot.style_columns,color=PercentChg3>0 ? color.rgb(156, 209, 158) : color.rgb(216, 145, 145)) |
Trend & atr day & calc | https://www.tradingview.com/script/Lt29GEv3-trend-atr-day-calc/ | EmoeTeam | https://www.tradingview.com/u/EmoeTeam/ | 155 | 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/
// © EmoeTeam
//@version=5
indicator(title="Trend & ATR daily & calc_rus", shorttitle="TrAtrCalc", overlay=true)
//Дневной ATR
show_trend = input(true, 'Trend', tooltip = "Hide the trends", inline = "Hide / Show")
show_atr = input(true, 'Progress ATR', tooltip = "Hide the trend on the selected timeframe and the progress ATR within the day", inline = "Hide / Show")
show_calc = input.bool (true, "Сalculator RR", tooltip = "Калькулятор больше ориентирован на русскоговорящую аудиторию", inline = "Hide / Show")
color_bull = input.color(color.rgb(48, 150, 51, 10), title = "Bull", inline = "color", group = "✏️ Colour settings for trends")
color_bear = input.color(color.rgb(156, 57, 57, 10), title = "Bear", inline = "color", group = "✏️ Colour settings for trends")
color_net = input.color(color.rgb(201, 141, 50, 10), title = "Flat", inline = "color", group = "✏️ Colour settings for trends")
//1.1 Получение данных об ATR активного инструмента, с дневного таймфрейма
timeframe = "1D"
atr_day = ta.atr(5)
ticker = ticker.new(syminfo.prefix, syminfo.ticker, session = session.regular)
previous_close = request.security(ticker, "1D", close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
atr = request.security(ticker, "1D", atr_day, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
period_high = request.security(ticker, "1D", high,gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
period_low = request.security(ticker, "1D", low,gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
range_1 = period_high - period_low
tr_percent_of_atr = (range_1 / atr) * 100
//1.2 Расчеты для выделения цветом пройденого дневного ATR
tr_vs_atr_color = color_bull
if tr_percent_of_atr <= 70
tr_vs_atr_color := color_bull
else if tr_percent_of_atr >= 90
tr_vs_atr_color := color_bear
else
tr_vs_atr_color := color_net
// 1.3 Вывод данных на экран
var note = "Green - there is room for movement within the ATR; Yellow - daytime ATR, almost passed; Red - Ticker has already passed its daily ATR"
var tbl = table.new(position.top_center, 3,3, border_width = 2)
if barstate.islast and show_atr
//table.cell(tbl, 0, 0, trading_mode, bgcolor = trend_color)
//table.cell(tbl, 0 ,0, " way " + str.tostring (tr_percent_of_atr, '#.##') + "% " + "($" + str.tostring(range_1, '#.#') + ") " + " daily ATR = $" + str.tostring(atr, '#.##'), bgcolor = tr_vs_atr_color, tooltip = note)
table.cell(tbl, 0 ,0, " way " + str.tostring (tr_percent_of_atr, '#.##') + "% " + "($" + str.tostring(range_1, '#.#') + ") ", bgcolor = tr_vs_atr_color, tooltip = note, text_size = size.small)
table.cell(tbl, 0 ,1, " daily ATR = $" + str.tostring(atr, '#.##'), bgcolor = tr_vs_atr_color, tooltip = note, text_size = size.small)
//table.cell(tbl, 0 ,1, " " )
//table.cell(tbl, 0 ,2, " " )
// Тренд на разных таймфреймах
// 2.1 Определение тренда на основе индикатора Вильямса
jawLength = 13
jawOffset = 8
teethLength = 8
teethOffset = 5
lipsLength = 5
lipsOffset = 3
source = hl2
smma(source, lenght) =>
smma1 = 0.0000
smma11 = ta.sma(source, lenght)
smma1 := na(smma1[1]) ? smma11 : ((smma1[1] * (lenght - 1) + source) / lenght)
jawInput = smma(source, jawLength)
jaw_5 = request.security(syminfo.tickerid, "5", jawInput)
jaw_15 = request.security(syminfo.tickerid, "15", jawInput)
jaw_30 = request.security(syminfo.tickerid, "30", jawInput)
jaw_60 = request.security(syminfo.tickerid, "60", jawInput)
jaw_240 = request.security(syminfo.tickerid, "240", jawInput)
jaw_day = request.security(syminfo.tickerid, "D", jawInput)
teethInput = smma(source, teethLength)
teeth_5 = request.security(syminfo.tickerid, "5", teethInput)
teeth_15 = request.security(syminfo.tickerid, "15", teethInput)
teeth_30 = request.security(syminfo.tickerid, "30", teethInput)
teeth_60 = request.security(syminfo.tickerid, "60", teethInput)
teeth_240 = request.security(syminfo.tickerid, "240", teethInput)
teeth_day = request.security(syminfo.tickerid, "D", teethInput)
lipsInput = smma(source, lipsLength)
lips_5 = request.security(syminfo.tickerid, "5", lipsInput)
lips_15 = request.security(syminfo.tickerid, "15", lipsInput)
lips_30 = request.security(syminfo.tickerid, "30", lipsInput)
lips_60 = request.security(syminfo.tickerid, "60", lipsInput)
lips_240 = request.security(syminfo.tickerid, "240", lipsInput)
lips_day = request.security(syminfo.tickerid, "D", lipsInput)
price_5 = request.security(syminfo.tickerid, "5", close)
price_15 = request.security(syminfo.tickerid, "15", close)
price_30 = request.security(syminfo.tickerid, "30", close)
price_60 = request.security(syminfo.tickerid, "60", close)
price_240 = request.security(syminfo.tickerid, "240", close)
price_day = request.security(syminfo.tickerid, "D", close)
bullish_5 = price_5 >= lips_5 and lips_5 >= teeth_5 and teeth_5 >= jaw_5
bearish_5 = price_5 <= lips_5 and lips_5 <= teeth_5 and teeth_5 <= jaw_5
bullish_15 = price_15 >= lips_15 and lips_15 >= teeth_15 and teeth_15 >= jaw_15
bearish_15 = price_15 <= lips_15 and lips_15 <= teeth_15 and teeth_15 <= jaw_15
bullish_30 = price_30 >= lips_30 and lips_30 >= teeth_30 and teeth_30 >= jaw_30
bearish_30 = price_30 <= lips_30 and lips_30 <= teeth_30 and teeth_30 <= jaw_30
bullish_60 = price_60 >= lips_60 and lips_60 >= teeth_60 and teeth_60 >= jaw_60
bearish_60 = price_60 <= lips_60 and lips_60 <= teeth_60 and teeth_60 <= jaw_60
bullish_240 = price_240 >= lips_240 and lips_240 >= teeth_240 and teeth_240 >= jaw_240
bearish_240 = price_240 <= lips_240 and lips_240 <= teeth_240 and teeth_240 <= jaw_240
bullish_day = price_day >= lips_day and lips_day >= teeth_day and teeth_day >= jaw_day
bearish_day = price_day <= lips_day and lips_day <= teeth_day and teeth_day <= jaw_day
trend_color_5 = bullish_5 ? color_bull : bearish_5 ? color_bear : color_net
trend_color_15 = bullish_15 ? color_bull : bearish_15 ? color_bear : color_net
trend_color_30 = bullish_30 ? color_bull : bearish_30 ? color_bear : color_net
trend_color_60 = bullish_60 ? color_bull : bearish_60 ? color_bear : color_net
trend_color_240 = bullish_240 ? color_bull : bearish_240 ? color_bear : color_net
trend_color_day = bullish_day ? color_bull : bearish_day ? color_bear : color_net
//alertbull_5 = bullish_5
//alertbear_5 = bearish_5
alertany = bullish_5 and bullish_15 or bearish_5 and bearish_15
alertall = bearish_5 and bullish_15 and bullish_30 and bullish_60 or bullish_5 and bearish_15 and bearish_30 and bearish_60
// Вывод данных о трендах на экран
var note1 = "the trend direction on the TF ? - based on Bill Williams' alligator indicator"
var tbl_tr = table.new(position.top_right, 7,7, border_width = 3)
if barstate.islast and show_trend
table.cell(tbl_tr, 0, 0, "", width = 2.7, height = 2.5)
table.cell(tbl_tr, 1, 1, "5", width = 2.7, bgcolor = trend_color_5, text_font_family = font.family_monospace, tooltip = note1)
table.cell(tbl_tr, 2, 1, "15", width = 2.7, bgcolor = trend_color_15, text_font_family = font.family_monospace, tooltip = note1)
table.cell(tbl_tr, 3, 1, "30", width = 2.7, bgcolor = trend_color_30, text_font_family = font.family_monospace, tooltip = note1)
table.cell(tbl_tr, 4, 1, "1H", width = 2.7, bgcolor = trend_color_60, text_font_family = font.family_monospace, tooltip = note1)
table.cell(tbl_tr, 5, 1, "4H", width = 2.7, bgcolor = trend_color_240, text_font_family = font.family_monospace, tooltip = note1)
table.cell(tbl_tr, 6, 1, "1D", width = 2.7, bgcolor = trend_color_day, text_font_family = font.family_monospace, tooltip = note1)
///Сигналы
alertcondition(bullish_5, title = "Long 5", message = "Сигнал с 5 ки на лонг")
alertcondition(bearish_5, title = "Short 5", message = "Сигнал с 5ки на шорт")
alertcondition(alertany, title = "5 + 15", message = "Сигнал на 5 и 15 ки - определить направление")
alertcondition(alertall, title = "All", message = "4-ре ТФ в одном направлении ")
///// Калькулятор рисков и позиции /////
// Titles
CALC = '✏️ Калькулятор мани-менеджмент'
OPTIONAL = '✏️ Optional inputs'
SENTIMENT = '✏️ Sentiment'
ATR = '✏️ Atr'
TABLE_SETTINGS = '✏️ Table Settings'
// Tooltips
tt_position = 'Размер счета, а более правльно сколько денег выделяем на 1 сделку. Выберите знак денежной системы, просто для красоты.'
tt_risk = 'Здесь задаем размер максимальной просадки для одной сделки, рекомендуемый диапазон от 0,5% до 5%. Этот показатель должен быть ОДИНАКОВЫМ во всех сделках.'
tt_leverage = 'Размер кредитного плеча'
tt_comission = "Здесь указываем совокупную биржевую (0,01%) и брокерскую комисии. ВТБ онлайн - 0,05% и Мосбиржа (мейкер 0% - тейкер 0,03%) среднее 0,015%"
tt_spread = "Здесь нужно указать предполагаемую величину проскальзывания. Величина приблизительная, поэтому нужно округлять в сторону ее увеличения"
tt_shares = 'В случае, если хотите рассчитать прибыль или стоп-лосс на основе количества акций. Если указано, то ввод \'Capital\' будет проигнорирован'
tt_entry = 'Цена, по которой мы открываем позицию'
tt_stop = 'Цена, где мы закрываем сделку с убытком'
tt_close = 'Цена, при достижении которой мы фиксируем прибыль, а также желаемое отношение риска к прибыли'
tt_important = "Следует отличать риск по позиции и риск по бумаге. Риск по бумаге обычно определяется по графику и представляет собой расстояние от уровня открытия позиции до уровня стоп-заявки.
Риск по позиции относит эту величину к размеру депозита трейдера и показывает, какая часть депозита будет потеряна в случае, если позиция закроется с убытком."
i_position = input.int(title='Депозит', minval=1, defval=60000, tooltip=tt_position, inline = 'money', group=CALC)
i_type_money = input.string ("руб", "Валюта", options = ["usd", "руб"], inline = 'money', group=CALC)
i_riskPercent = input.float(title='Риск %', minval=0.25, defval=1, step = 0.25, tooltip=tt_risk + " " +tt_important, group=CALC)
i_leverage = input.int(title='Кредит', minval=1, defval=1, tooltip=tt_leverage, group=CALC)
i_commisionPercent = input.float(title='Комиссия %', minval=0, defval=0.065, tooltip = tt_comission, group=CALC)
i_pos_type = input.bool (false, "сделка в short", group=CALC, inline='MM')
//Colors
c_posCalcColor = input.color(#d1d4dc, '', inline='MM', group=CALC)
c_posCalcColor1 = input.color(#50450D, '', inline='MM', group=CALC)
c_posCalcColor2 = input.color(#50450D, '', inline='MM', group=CALC)
c_posCalcCol1Bg = input.color(#A89B5B, '', inline='MM', group=CALC)
c_posCalcCol2Bg = input.color(#0E1936, '', inline='MM', group=CALC)
c_posCalcCol3Bg = input.color(#5C6C9B, '', inline='MM', group=CALC)
//c_posCalcPosTypeLong = "👆"
//c_posCalcPosTypeShort = "👇"
//posCalcPosType = i_pos_type ? c_posCalcPosTypeShort : c_posCalcPosTypeLong
//Ввод данных вручную для расчета
i_entryPrice = input.float(0, 'Entry position price', minval=0, step =0.01, tooltip=tt_entry, group=OPTIONAL)
i_stopPrice = input.float(0.3, 'Stop price', minval=0, step =0.01, tooltip=tt_stop, group=OPTIONAL, inline='loss')
i_spread = input.float(title='Размер спреда', minval=0, defval=0.00, tooltip = tt_spread, group=OPTIONAL)
i_takeProfitPrice = input.float(0, 'Take Profit price', step =0.01, minval=0, tooltip=tt_close, inline = 'profit', group=OPTIONAL)
loss_type = input.string("%", "тип", options = ['%', 'цена'], inline='loss', group=OPTIONAL)
profit_X = input.float(3.6, "R/R", options = [2.26, 2.87, 3.6, 4.58, 5.85], inline = 'profit', group=OPTIONAL)
///// ВЫЧИСЛЕНИЯ /////
money_symbol = i_type_money == "usd" ? "$" : "р."
type_trade = i_pos_type ? "SHORT ⬇" : "LONG ⬆"
// Вычисляем сколько в деньгах - указанный процент риска
risk_amount = i_position * i_riskPercent / 100
//Определяем какую цену (точку входа) берем для расчета
entryPrice = i_entryPrice > 0 ? i_entryPrice : close
f_amount(amount) =>
val = amount > 1 ? str.tostring(amount, '##.##') : str.tostring(amount, '##.#####')
val
//Вычисляем значение SL
//при long
sl_val0 = loss_type == '%' ? entryPrice - i_stopPrice/100 * entryPrice : i_stopPrice
//при short
sl_val3 = loss_type == '%' ? entryPrice + i_stopPrice/100 * entryPrice : i_stopPrice
sl_val1 = i_pos_type ? sl_val3 : sl_val0
sl_val2 = loss_type == 'цена' ? i_stopPrice * 100 / entryPrice : i_stopPrice
//Описываем символ стопа и выбираем вариант для отображения
Stop = loss_type == '%' and sl_val1 ? " %": money_symbol
Stop_loss = loss_type == '%' and sl_val1 ? money_symbol: " %"
sl_val = math.abs (loss_type == '%' ? sl_val1 : math.round (100 - sl_val2, 2))
//Потенциал потерь (с учетом проскальзывания и комиссий)
//при сделке в LONG
loss_long = loss_type == 'цена' ? entryPrice * (1+i_commisionPercent/100) - i_stopPrice * (1-i_commisionPercent/100) + i_spread * 2 : entryPrice * (1+i_commisionPercent/100) - sl_val * (1-i_commisionPercent/100) + i_spread * 2
//при сделке в SHORT
loss_short = loss_type == 'цена' ? i_stopPrice * (1+i_commisionPercent/100) - entryPrice * (1-i_commisionPercent/100) + i_spread * 2 : sl_val * (1+i_commisionPercent/100) - entryPrice * (1-i_commisionPercent/100) + i_spread * 2
loss = i_pos_type ? loss_short : loss_long
loss_perc = math.round (loss / entryPrice * 100, 2)
//Потенциал заработка (с учетом проскальзывания)
size_protit = loss_type == 'цена' ? i_takeProfitPrice : i_stopPrice * profit_X
auto_protit_long = loss_type == 'цена' ? i_takeProfitPrice : entryPrice + (entryPrice * size_protit * 0.01)
auto_protit_short = loss_type == 'цена' ? i_takeProfitPrice : entryPrice - (entryPrice * size_protit * 0.01)
auto_protit = i_pos_type ? auto_protit_short : auto_protit_long
//при сделке в LONG
profit_long = loss_type == 'цена' ? i_takeProfitPrice * (1-i_commisionPercent/100) - entryPrice * (1+i_commisionPercent/100) - i_spread * 2 : auto_protit * (1-i_commisionPercent/100) - entryPrice * (1+i_commisionPercent/100) - i_spread * 2
//при сделке в SHORT
profit_short = loss_type == 'цена' ? entryPrice * (1-i_commisionPercent/100) - i_takeProfitPrice * (1+i_commisionPercent/100) - i_spread * 2 : entryPrice * (1-i_commisionPercent/100) - auto_protit * (1+i_commisionPercent/100) - i_spread * 2
profit = i_pos_type ? profit_short : profit_long
profit_perc = math.round (profit / entryPrice * 100, 2)
//Соотношение Profit/Risk
RR = math.round (profit / loss , 2)
//Рейтинги анатации
rating1 = "🔥"
rating2 = "👍"
rating3 = "🤓"
rating4 = "🤡"
rating5 = "⛔"
rating6 = '🙄'
rating7 = "🔴"
rating8 = "🟢"
tool1 = "Отличные ожидания от сделки"
tool2 = "Хорошо смотрится"
tool3 = "Неплохо, но можно и лучше, ботаник - ты"
tool4 = "оно того стоит, подумай еще раз"
tool5 = "ты ничего не попутал, прибыль в другой стороне"
tool6 = "Знакомое чувство...?"
rating = RR <= 0.8 ? rating5 : RR > 0.8 and RR <= 1.2 ? rating4 : RR > 1.2 and RR <= 2.0 ? rating3 : RR > 2.0 and RR <= 3.0 ? rating2 : RR > 3.0 ? rating1 : rating6
tools = RR <= 0.8 ? tool5 : RR > 0.8 and RR <= 1.2 ? tool4 : RR > 1.2 and RR <= 2.0 ? tool3 : RR > 2.0 and RR <= 3.0 ? tool2 : RR > 3.0 ? tool1 : tool6
//Максимальный объем позиции (в руб. и % от счета) и объем позиции (в лотах)
maxvol = math.round (i_position * (i_riskPercent / loss_perc), 0)
maxvol_perc = math.round ((i_position * (i_riskPercent / loss_perc)) / i_position * 100, 2)
lots = math.round (maxvol / entryPrice, 0 )
//Прибыль / убыток в денежном выражении
loss_money = math.round (lots * loss, 0 )
profit_money = math.round (lots * profit, 0)
var tbl_money = table.new(position.bottom_right, 12, 12, border_width = 1, bgcolor = c_posCalcCol3Bg, border_color = c_posCalcCol2Bg)
if barstate.islast and show_calc
table.cell(tbl_money, 0, 0, "Депозит", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, tooltip = tt_position, text_halign = text.align_left)
table.cell(tbl_money, 0, 1, '💰 ' + str.tostring(i_position) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, text_size = size.small, tooltip = tt_position, text_halign = text.align_left)
table.cell(tbl_money, 1, 0, "Риск", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, tooltip = tt_risk)
table.cell(tbl_money, 1, 1, str.tostring(i_riskPercent) + ' % ' + "( " + str.tostring(risk_amount) + " " + str.tostring(money_symbol) + ")", text_color = c_posCalcColor, text_size = size.small, tooltip = tt_risk)
table.cell(tbl_money, 2, 0, "Точка входа", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small)
table.cell(tbl_money, 2, 1, str.tostring(entryPrice) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 0, 2, "Стоп", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 2, str.tostring(i_stopPrice) + str.tostring(Stop), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 2, 2, rating7 + " " + str.tostring(f_amount (sl_val)), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 0, 3, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 0.2)
table.cell(tbl_money, 1, 3, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 0.2)
table.cell(tbl_money, 2, 3, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 0.2)
table.cell(tbl_money, 0, 4, "Убыток", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 4, str.tostring(f_amount (loss)) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, bgcolor = c_posCalcCol3Bg , text_size = size.small)
table.cell(tbl_money, 2, 4, str.tostring(f_amount (loss_perc)) + " %", text_color = c_posCalcColor, bgcolor = c_posCalcCol3Bg, text_size = size.small)
table.cell(tbl_money, 0, 5, "Прибыль", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 5, str.tostring(f_amount (profit )) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, bgcolor = c_posCalcCol3Bg, text_size = size.small)
table.cell(tbl_money, 2, 5, str.tostring(f_amount (profit_perc)) + " %", text_color = c_posCalcColor, bgcolor = c_posCalcCol3Bg, text_size = size.small)
table.cell(tbl_money, 0, 6, "Риск / Профит", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 6, str.tostring(RR), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 2, 6, str.tostring(rating), text_color = c_posCalcColor, text_size = size.small, tooltip = str.tostring(tools))
table.cell(tbl_money, 0, 7, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 0.2)
table.cell(tbl_money, 1, 7, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 0.2)
table.cell(tbl_money, 2, 7, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 0.2)
table.cell(tbl_money, 0, 8, "Max объем", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 8, str.tostring(maxvol) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 2, 8, str.tostring(maxvol_perc) + " %", text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 0, 9, "Купить в " + str.tostring (type_trade), text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 9, str.tostring(lots) + " шт", text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 2, 9, rating8 + " " + str.tostring(f_amount (auto_protit)), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 0, 10, "Результат", text_color = c_posCalcColor1, bgcolor = c_posCalcCol1Bg, text_size = size.small, text_halign = text.align_left)
table.cell(tbl_money, 1, 10, "SL" + " 💰" + str.tostring(loss_money) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 2, 10, "TP" + " 💰" + str.tostring(profit_money) + " " + str.tostring(money_symbol), text_color = c_posCalcColor, text_size = size.small)
table.cell(tbl_money, 0, 11, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 2)
table.cell(tbl_money, 1, 11, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 2)
table.cell(tbl_money, 2, 11, "", bgcolor = c_posCalcCol2Bg, text_size = size.small, height = 2) |
BU4U Suite | https://www.tradingview.com/script/1wBkaJE0-BU4U-Suite/ | meyerclaire | https://www.tradingview.com/u/meyerclaire/ | 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/
// © meyerclaire
//@version=5
indicator("BU4U Suite",shorttitle="BU4U Suite", overlay=true, max_lines_count=100, max_labels_count=100)
// Settings Inputs
var candleMarkers = input.bool(true,"'Hey How Ya Doin' Candle Detection", group="Hey, How Ya Doin'?", tooltip="Labels chart candles above X% change, where X is the 'Hey How Ya Doin' Threshold'")
var threshold_mult = input.float(10.0, title="Hey How Ya Doin' Threshold (%)", minval=0, maxval=100, group="Hey, How Ya Doin'?")/100.0
var scale = input.float(0.2,title="Image Scale", step=0.1, group="Image Settings")
var height = input.float(1, title="Height Multiplier", step=0.2,group="Image Settings",tooltip="Value of 1 to render a square image, unless chart view is compressed. Tweak value if table seems oblong")*2
var position = input.string(position.top_right,title="Position",options=[position.top_right,position.top_left,position.top_center,position.middle_right,position.middle_left,position.middle_center,position.bottom_right,position.bottom_left,position.bottom_center], group="Image Settings")
var flipImageX = input.bool(false, title="Flip Image Over X Axis", group="Image Settings")
var flipImageD = input.bool(false, title="Flip Image Over Diagonal", group="Image Settings")
// Shirt Inputs
var add_on = input.bool(false,"Enable Shirt Color Add",group="Shirt Color")
var add = input.color(color.rgb(255, 165, 29), "Add Color", group="Shirt Color")
var addInt = input.int(100, "Strength (%)", maxval = 500, minval = -500, group="Shirt Color",tooltip="Use negative strength to subtract color, and positive strength to add it.")
addInt := addInt/100
// Image Hex Array
var steve = array.from(#9FC2E7FF, #A0C2E7FF, #A0C2E7FF, #A0C2E7FF, #9FC2E8FF, #9FC1E8FF, #9EC1E7FF, #9DC1E5FF, #9CC0E5FF, #9EC1E6FF, #9FC0E5FF, #9FBFE5FF, #9EBFE5FF, #9FBFE5FF, #A0C0E6FF, #A0C0E6FF, #A0BFE5FF, #A0C0E5FF, #A0C0E6FF, #A0BFE6FF, #A0C0E6FF, #A1C1E6FF, #A1C1E6FF, #A2C1E6FF, #A3C1E4FF, #A2C1E6FF, #A2C1E5FF, #A4C3E7FF, #A7C7EAFF, #A6C4E6FF, #A5C1E2FF, #AECDF1FF, #ADCDF0FF, #A5C2E1FF, #A3BDDEFF, #A4BFE0FF, #A5BFDFFF, #A6C0DEFF, #A6C0DFFF, #A8C0DFFF, #AAC0DEFF, #ABBFDFFF, #ABBEDDFF, #ABBEDCFF, #ACBFDDFF, #ACBEDCFF, #AEBEDCFF, #AEBFDCFF, #AEBFDBFF, #AEBEDBFF, #9FBFE5FF, #9EBFE4FF, #9DBFE4FF, #9DBEE3FF, #9DBEE4FF, #9CBDE3FF, #9BBCE2FF, #9ABAE1FF, #9BBBE1FF, #9BBBE1FF, #9ABBE1FF, #9ABBE1FF, #9ABBE1FF, #9ABBE1FF, #9BBCE2FF, #9BBCE2FF, #9BBDE3FF, #9BBCE3FF, #9BBCE2FF, #9ABCE2FF, #9BBDE2FF, #9CBCE3FF, #9DBCE3FF, #9EBCE3FF, #9DBDE2FF, #9DBCE2FF, #A3C1E7FF, #AAC9F0FF, #A6C2E5FF, #626E84FF, #3C4052FF, #70829AFF, #9AB6D5FF, #AECAEEFF, #A6BFE1FF, #A1BADCFF, #A3BCDCFF, #A3BCDBFF, #A4BCDCFF, #A7BBDCFF, #A8BCDCFF, #A8BDDCFF, #A9BCDCFF, #AABCDAFF, #AABDDBFF, #AABDDBFF, #ABBDDCFF, #ACBDDCFF, #ACBCD8FF, #ACBCD8FF, #9DBDE3FF, #9CBCE2FF, #9BBCE1FF, #9ABBE1FF, #9ABBE0FF, #9ABAE0FF, #99BAE0FF, #98B9DFFF, #99BAE0FF, #98BAE0FF, #97BAE0FF, #97B9DFFF, #97B9DFFF, #97B9DFFF, #97B9DFFF, #97B9DFFF, #97B9DFFF, #97BAE0FF, #97BAE0FF, #97B9DFFF, #97B8DFFF, #98B8DFFF, #99B9DFFF, #99B9DFFF, #9AB9DFFF, #9FBEE5FF, #98B6DBFF, #7F95B3FF, #545C71FF, #14111BFF, #040004FF, #0B090CFF, #1F222DFF, #8096B3FF, #BADAFEFF, #A3BBDCFF, #A1B9DAFF, #A1BCDAFF, #A3BADAFF, #A6B8DBFF, #A6BADBFF, #A6BCDAFF, #A8BBDBFF, #A8BBDAFF, #A8BBDAFF, #A9BBD9FF, #A9BBD8FF, #A9BAD8FF, #A9B9D7FF, #AAB8D6FF, #99B9E0FF, #99B9E0FF, #98B9DFFF, #98BAE0FF, #98BADFFF, #97BAE0FF, #97B9DFFF, #97B9DFFF, #96B9DFFF, #96B8DEFF, #96B9DFFF, #95B8DEFF, #95B8DEFF, #95B8DEFF, #95B8DEFF, #95B8DEFF, #95B8DEFF, #96B7DEFF, #96B7DEFF, #97B6DEFF, #97B7DEFF, #97B7DEFF, #97B8DEFF, #97B8DEFF, #9CBBE1FF, #A2BFE8FF, #7185A3FF, #2C313DFF, #05040CFF, #00010AFF, #04090FFF, #0D0A0CFF, #130A0CFF, #222129FF, #798CA6FF, #B3CEF4FF, #A0B9DAFF, #A2BBD9FF, #A4B9D9FF, #A5B9DAFF, #A5BAD9FF, #A6BAD9FF, #A6B9D9FF, #A6B9D9FF, #A4B8D8FF, #A4B7D6FF, #A6B6D5FF, #A6B6D4FF, #A5B6D4FF, #A7B5D6FF, #9CBAE0FF, #9CBADEFF, #9BBADFFF, #9ABADFFF, #99BADEFF, #97BADDFF, #96B9DEFF, #97B9DFFF, #96B9DEFF, #96B8DEFF, #97B8DFFF, #99B9DFFF, #98B8DFFF, #98B8DFFF, #99B9DFFF, #99B9DFFF, #99B9DFFF, #98B8DFFF, #98B8DEFF, #98B8DFFF, #99B9DFFF, #9AB9E0FF, #9AB9DFFF, #9AB9DFFF, #9EBDE3FF, #A4C3ECFF, #707F9BFF, #0E1016FF, #0B090DFF, #403136FF, #5F474CFF, #775961FF, #594449FF, #241A1CFF, #1A1218FF, #8FA6C6FF, #B3CEF1FF, #A2B6D7FF, #A5B8D9FF, #A4B9D9FF, #A4B8D7FF, #A4B7D8FF, #A4B7D8FF, #A4B7D7FF, #A1B5D5FF, #A2B4D5FF, #A4B3D5FF, #A3B4D5FF, #A3B3D3FF, #A1B2D3FF, #A0BDDEFF, #A0BDDBFF, #9FBDDDFF, #9EBCDFFF, #9EBCDFFF, #9DBCDDFF, #9BBBDEFF, #9CBADEFF, #9CBADEFF, #9CBBDFFF, #9DBADFFF, #9DBADFFF, #9DBADFFF, #9DBADFFF, #9DBADFFF, #9DB9DEFF, #9CB9DFFF, #99B9DFFF, #9AB9DEFF, #99B9DEFF, #99B9DEFF, #9BB8DEFF, #9BB9DEFF, #9BB9DEFF, #9BBADFFF, #A6C7F0FF, #879EBEFF, #5F4B55FF, #865E60FF, #AD7A7DFF, #B68589FF, #B9878DFF, #846369FF, #4C414AFF, #1E1214FF, #414A59FF, #B1CAF1FF, #A2B6D7FF, #A2B6D6FF, #A2B5D6FF, #A2B4D5FF, #A2B4D5FF, #A0B4D4FF, #A0B2D3FF, #9FB2D4FF, #A0B1D3FF, #A1B1D3FF, #9FB0D3FF, #9DAFD2FF, #9BAED1FF, #9FBAD9FF, #9EBADBFF, #9EB9DBFF, #9DB9DDFF, #9DB9DEFF, #9DB9DDFF, #9CB9DDFF, #9BB8DCFF, #9BB8DBFF, #9CB9DBFF, #9BB8DAFF, #9BB7DAFF, #9CB6DCFF, #9BB7DCFF, #9BB6DCFF, #9AB6DBFF, #9AB6DCFF, #9AB6DCFF, #98B5DCFF, #98B5DBFF, #97B4DAFF, #96B4DAFF, #96B4DBFF, #96B4DAFF, #97B4DBFF, #9ABEE9FF, #8FA3C7FF, #A17680FF, #B47C80FF, #AD7B7BFF, #AE8280FF, #AD8180FF, #916F71FF, #624E54FF, #47383CFF, #272730FF, #85A1C4FF, #ADC0E6FF, #9FB1D2FF, #A0B2D4FF, #A1B2D4FF, #A1B1D3FF, #9EB1D1FF, #9EB0D2FF, #9DAFD5FF, #9CADD3FF, #99AED3FF, #98AED4FF, #97AED3FF, #98ACD5FF, #9AB3D6FF, #9AB3D9FF, #9AB3DAFF, #9AB3D8FF, #99B2D8FF, #99B3D8FF, #97B3D8FF, #96B2D8FF, #97B3D8FF, #96B2D7FF, #96B2D7FF, #96B2D7FF, #96B1D8FF, #96B2D9FF, #95B1D8FF, #94B1D8FF, #94B1D8FF, #94B0D8FF, #93B0D9FF, #93AFD8FF, #92AFD8FF, #92AFD8FF, #92AEDAFF, #91AFDAFF, #93B0DBFF, #92BBEBFF, #8288A5FF, #9A676BFF, #AB777CFF, #A87676FF, #A57675FF, #A07373FF, #9C7476FF, #7C5E64FF, #524147FF, #603934FF, #8887A0FF, #ABC8F1FF, #9CAED3FF, #9DB0D6FF, #9DB0D5FF, #9DAED6FF, #9BAED4FF, #99AED5FF, #99ADD6FF, #97ACD5FF, #95ADD5FF, #95ACD6FF, #95ACD4FF, #94ACD5FF, #97B0D7FF, #96B1D6FF, #96B1D6FF, #96B0D6FF, #96AFD7FF, #94B0D7FF, #93B0D7FF, #93AFD6FF, #93AFD7FF, #93AFD6FF, #93B0D7FF, #93AFD7FF, #92AED6FF, #92AED6FF, #91AED7FF, #90ADD7FF, #91AED7FF, #91ADD9FF, #90ADD8FF, #90AED8FF, #92B0DBFF, #93B0DBFF, #90AEDAFF, #8EAEDBFF, #8FAFDAFF, #90BAECFF, #8389A6FF, #905F5CFF, #925F5EFF, #5E3A42FF, #412B32FF, #563B39FF, #845952FF, #976A6CFF, #57454CFF, #6E362AFF, #926568FF, #9BB6E3FF, #9BB0D9FF, #9BADD6FF, #99ADD7FF, #98ACD7FF, #97ACD6FF, #94ACD5FF, #96B0DAFF, #96AED8FF, #94AAD3FF, #97AED7FF, #96AFD8FF, #90AAD4FF, #95AED6FF, #93AED5FF, #92AED5FF, #91ADD4FF, #91ADD6FF, #90ACD5FF, #91ACD5FF, #8FACD4FF, #8FACD5FF, #8FACD5FF, #8FACD4FF, #8FACD5FF, #8FACD7FF, #8EABD6FF, #8EABD7FF, #8EACD8FF, #8EACD8FF, #8EACD8FF, #8EABD8FF, #8CACD9FF, #95B3DEFF, #94B1DDFF, #8BABD8FF, #8BACDAFF, #8CAFDEFF, #8EB4E2FF, #7C92ABFF, #341F22FF, #4F2E2DFF, #5B363BFF, #45242EFF, #5D3838FF, #966662FF, #AE7979FF, #412F33FF, #644241FF, #8E615DFF, #7789B1FF, #A6BCECFF, #9AABD7FF, #97ABD6FF, #95ACD5FF, #93ABD6FF, #92ACD5FF, #91A9D1FF, #93ADD7FF, #93ADD6FF, #8FAAD5FF, #8DACD9FF, #8EABD8FF, #91AAD3FF, #90A9D3FF, #90A9D3FF, #8FAAD3FF, #8EAAD4FF, #8EA8D4FF, #8DA8D3FF, #8DA9D4FF, #8CAAD4FF, #8CA9D4FF, #8CA9D4FF, #8CA9D5FF, #8CAAD6FF, #8CAAD6FF, #8BAAD7FF, #8AAAD6FF, #8BAAD6FF, #8BA9D7FF, #8BACD9FF, #90B0DCFF, #5A80B2FF, #476DA0FF, #85A5D2FF, #8CAEDBFF, #8CB1E5FF, #81A0CAFF, #6A7B86FF, #42333AFF, #774B55FF, #9F676BFF, #8D5258FF, #A56771FF, #A7747AFF, #A57475FF, #3C2628FF, #211A1DFF, #7C6160FF, #96A2BFFF, #B0CBF8FF, #ACC3E9FF, #A2BBE3FF, #8FA8D5FF, #8EABDAFF, #92B3E2FF, #797F99FF, #748BABFF, #99C0EFFF, #687BA1FF, #4F6082FF, #8FA8CEFF, #90A9D1FF, #90A8D4FF, #8EA8D4FF, #8EA9D4FF, #8DA9D4FF, #8DA8D3FF, #8DA7D3FF, #8CA9D3FF, #8CA9D3FF, #8CA9D3FF, #8CA9D4FF, #8AA8D5FF, #89A8D4FF, #8AAAD6FF, #8BA9D9FF, #8BA9DAFF, #8CACDBFF, #8BABDBFF, #90B2DFFF, #88AAD6FF, #103B72FF, #0F366CFF, #85A6D3FF, #8FB1E0FF, #8AACDCFF, #8DB2E5FF, #687C8FFF, #6F4F4FFF, #995B66FF, #894F54FF, #7E4245FF, #985E63FF, #9F6B6AFF, #966766FF, #2C1D21FF, #000000FF, #524241FF, #717CA5FF, #3F65ABFF, #496AA6FF, #6F8CBBFF, #97B9E6FF, #92B7E9FF, #85ABDEFF, #3D4660FF, #454153FF, #869EC9FF, #42597EFF, #433A43FF, #9197A9FF, #90A9D2FF, #90A8D4FF, #90A8D4FF, #8FA8D4FF, #8EA9D4FF, #8DA8D3FF, #8DA9D3FF, #8CA9D3FF, #8DA9D3FF, #8DA9D5FF, #8BA9D5FF, #8AA9D5FF, #8BA9D7FF, #88A6D5FF, #8CABD0FF, #95B4DFFF, #88A7D6FF, #87A6D2FF, #99B7E7FF, #6D92C5FF, #002059FF, #2A4B7DFF, #90AFDCFF, #8EB1E2FF, #87ADE0FF, #92BEF7FF, #658EC1FF, #784E5AFF, #834A49FF, #392222FF, #33191CFF, #482C28FF, #905D54FF, #5F3D3AFF, #0B0B10FF, #030405FF, #342420FF, #21306CFF, #00339CFF, #002180FF, #104197FF, #85ADDAFF, #88A5C2FF, #536E90FF, #716776FF, #9F7B83FF, #776E81FF, #4A5A6FFF, #798194FF, #909EB4FF, #90A8D3FF, #91A8D4FF, #8FAAD4FF, #8FA9D3FF, #90A9D4FF, #8EA9D3FF, #8FAAD4FF, #8EAAD4FF, #8EAAD5FF, #8DAAD6FF, #8CAAD7FF, #8BAAD7FF, #8CABDAFF, #87A9D7FF, #7FA7C0FF, #6E889AFF, #6E839CFF, #7B90AFFF, #8195B3FF, #4B6087FF, #172953FF, #4E7099FF, #89B0E0FF, #81A6D4FF, #79A1CFFF, #80A9DAFF, #5B8BB8FF, #5F4B59FF, #593430FF, #3E2221FF, #723D3EFF, #492F2CFF, #302322FF, #160F11FF, #04070CFF, #0A0100FF, #121123FF, #1647A9FF, #1E5CC8FF, #1D5DC9FF, #175ED2FF, #3474D1FF, #626F8BFF, #5E3E32FF, #9B7978FF, #968A94FF, #505B65FF, #566878FF, #7B99BDFF, #819CBCFF, #8BA8D5FF, #8AA8D4FF, #89A8D4FF, #88A8D3FF, #88A7D3FF, #85A6D3FF, #84A5D3FF, #82A5D2FF, #81A5D1FF, #7EA3D0FF, #7CA2D1FF, #7CA6D8FF, #76A3DAFF, #82AEDCFF, #7290A2FF, #1D303FFF, #67839BFF, #86A9D3FF, #7895AEFF, #415C7BFF, #415B83FF, #6D97C5FF, #6FA3D6FF, #7892B2FF, #898C97FF, #929CABFF, #858596FF, #3F3941FF, #1F1618FF, #362323FF, #5C373BFF, #201519FF, #000106FF, #030508FF, #050304FF, #060000FF, #133A89FF, #1C64DFFF, #1F61D0FF, #2161CDFF, #1F5ECAFF, #1259D2FF, #1C61D2FF, #47538CFF, #8D6A5EFF, #676763FF, #3D5768FF, #657481FF, #7E8A98FF, #7D8892FF, #779DCBFF, #749DCAFF, #749DCAFF, #729CC8FF, #6F9AC6FF, #6E9AC7FF, #6B99C6FF, #6A98C5FF, #6A97C5FF, #6A98C7FF, #6797C5FF, #6586AAFF, #6D8BACFF, #7699BCFF, #6C707AFF, #3E3F51FF, #496D97FF, #668EB3FF, #5F7E95FF, #547A9BFF, #6D95BDFF, #71A4D9FF, #6CA5DCFF, #7A9DC3FF, #9CA9BFFF, #9DA0AFFF, #9D706EFF, #4C3B42FF, #00060DFF, #141218FF, #171318FF, #0A0C11FF, #09080EFF, #030204FF, #000000FF, #102759FF, #2369E7FF, #1D5AC9FF, #1957C3FF, #1954BFFF, #1952BBFF, #1951B7FF, #1353C3FF, #0D60DFFF, #4774BAFF, #988E7DFF, #928A80FF, #8C8B89FF, #8E8A84FF, #8B8780FF, #6D98C5FF, #6B9AC7FF, #699BCBFF, #679ACBFF, #659ACAFF, #679BCDFF, #6799CDFF, #6898CAFF, #6999CAFF, #6E9FD0FF, #6DA1D2FF, #4D698BFF, #6F7485FF, #547091FF, #275374FF, #4E5F75FF, #425F7BFF, #5A7D8EFF, #6385A3FF, #5C82ADFF, #7493B5FF, #7BA2C8FF, #7EA0C2FF, #8398B3FF, #8495AFFF, #948C99FF, #997C7DFF, #372E36FF, #03060BFF, #05070BFF, #07080DFF, #0E0C12FF, #08080BFF, #000000FF, #0B142AFF, #1E5CCEFF, #1856C4FF, #1850B9FF, #1851B9FF, #1A57C2FF, #1B59C8FF, #1A57C2FF, #1A55BBFF, #1753BBFF, #0855D3FF, #4F7ABFFF, #A89B89FF, #97938CFF, #8F8E8DFF, #908F8CFF, #6E9FCFFF, #729DCAFF, #7596B7FF, #7594B4FF, #7697BAFF, #7B98B6FF, #7B98B9FF, #789EC4FF, #789FC7FF, #7BA2C9FF, #7CA3CAFF, #6C85A2FF, #788091FF, #5E6E82FF, #47687AFF, #738590FF, #5C6B7AFF, #697685FF, #828F9CFF, #737E89FF, #7E8690FF, #808992FF, #808184FF, #939297FF, #898C94FF, #909599FF, #A4A7A9FF, #3F3F43FF, #04050DFF, #08070BFF, #0E0D12FF, #0B0A10FF, #030101FF, #040204FF, #1C4FA8FF, #2064DAFF, #1346A7FF, #164CAFFF, #1A53BBFF, #1B55BEFF, #1C54B8FF, #1B51B4FF, #1A55BDFF, #1C5BC5FF, #1753BDFF, #0854D1FF, #6683AEFF, #A99B85FF, #93928FFF, #92918FFF, #8594A5FF, #888D93FF, #8E8885FF, #908783FF, #908B87FF, #928C86FF, #8F8B86FF, #8D8D8FFF, #8F8F92FF, #8C8F91FF, #8D8D8FFF, #908E8EFF, #898987FF, #8A8682FF, #8C857EFF, #8D8C8CFF, #7E828AFF, #717378FF, #6A6763FF, #706B64FF, #7C7B79FF, #7F7C7BFF, #77726EFF, #979695FF, #999895FF, #9E9E9CFF, #ABAEB6FF, #444E65FF, #02030EFF, #09080BFF, #0E0D11FF, #0B0B0FFF, #010000FF, #122651FF, #2167E2FF, #1D58C0FF, #1B51B7FF, #1547ABFF, #1548AAFF, #11419FFF, #0F3C94FF, #113F98FF, #14439EFF, #194CABFF, #1B4FB0FF, #124FBDFF, #155FD1FF, #8490A2FF, #AA9B84FF, #8D8E8EFF, #948882FF, #908982FF, #918B88FF, #8F8B88FF, #8D8A86FF, #908D8AFF, #8D8A86FF, #8C8782FF, #8C8781FF, #8B8883FF, #8C8785FF, #8E8989FF, #8B8987FF, #8B8985FF, #8C8A86FF, #888684FF, #888787FF, #848482FF, #827F7DFF, #83807DFF, #848381FF, #868482FF, #83817CFF, #919599FF, #9599A0FF, #B2AEA3FF, #5E74A2FF, #06256BFF, #0A0911FF, #080504FF, #09090DFF, #0B090DFF, #050002FF, #194394FF, #205FD0FF, #1F5AC2FF, #194EB2FF, #0F40A4FF, #0C41A4FF, #0D43A8FF, #0C44AEFF, #1149AFFF, #1448A8FF, #1043A5FF, #124DB9FF, #154FB9FF, #0547BFFF, #2F6FD4FF, #9E9A95FF, #A09789FF, #928D8CFF, #8E8D8BFF, #928E8DFF, #92908EFF, #8D8D8AFF, #8F8E8BFF, #908F8DFF, #8E8E8BFF, #8B8B89FF, #909090FF, #8E8E8EFF, #929292FF, #919190FF, #8F8F8FFF, #8D8E90FF, #8D8C8DFF, #8F8E8DFF, #8E8E8EFF, #8D8E8EFF, #8B8C8DFF, #8C8D8DFF, #8E8F90FF, #8E8E8FFF, #878A8EFF, #9B9D9EFF, #989FAAFF, #1948A4FF, #092569FF, #0E0F19FF, #0D0D15FF, #0B0B11FF, #050000FF, #0D1732FF, #1E52B7FF, #1F56BAFF, #1A53B9FF, #0F43A6FF, #1048B0FF, #0E46AFFF, #0C45B0FF, #0E47B1FF, #104BB2FF, #0B47B7FF, #0A45B1FF, #0D3FA0FF, #0E42A1FF, #1549AAFF, #0749BAFF, #4575C4FF, #A59F93FF, #949290FF, #8F8E8CFF, #939290FF, #979595FF, #939393FF, #8F8F8FFF, #91908EFF, #919190FF, #8E8F90FF, #939494FF, #939393FF, #909090FF, #898889FF, #8C8D8EFF, #919295FF, #8D8D8FFF, #8E8C8BFF, #878683FF, #8A8988FF, #8D8B89FF, #8D8A84FF, #908E8CFF, #8E8D91FF, #878888FF, #A69D8CFF, #5B75A2FF, #0037A2FF, #142659FF, #132043FF, #142140FF, #0C0F1BFF, #000000FF, #153471FF, #1F55BAFF, #1C53B6FF, #1048AEFF, #1149B0FF, #114AB1FF, #0C47AFFF, #0E46AFFF, #1048B0FF, #0E49B1FF, #1146AAFF, #13409CFF, #133B89FF, #112E6EFF, #132A64FF, #081444FF, #003FB4FF, #6B8ABAFF, #929191FF, #959492FF, #918F8FFF, #8E8C8CFF, #8E8D8DFF, #8F9090FF, #908F90FF, #858481FF, #8A8885FF, #8F8E8EFF, #8E8E90FF, #89898AFF, #898988FF, #8D8D8EFF, #8F9092FF, #8C8C8DFF, #898785FF, #888684FF, #898786FF, #8C8A86FF, #8C8882FF, #8C8A85FF, #8D8D8EFF, #8D9091FF, #999694FF, #30569EFF, #002279FF, #102863FF, #1A3675FF, #162247FF, #090A17FF, #0B1837FF, #1B48A1FF, #194397FF, #174FB1FF, #104AB3FF, #114AB1FF, #1248AFFF, #0F47AEFF, #1048AEFF, #1349ADFF, #184AA7FF, #19479DFF, #1648A4FF, #174FB0FF, #194FADFF, #183F8FFF, #080C34FF, #002982FF, #3373D7FF, #929192FF, #939292FF, #908E8FFF, #8D8C88FF, #898887FF, #8F9092FF, #8F9193FF, #868483FF, #908E8BFF, #929393FF, #8F9195FF, #8C8E91FF, #8B8C8DFF, #8D8D8FFF, #8D8D8FFF, #8F9093FF, #8E9094FF, #898A8DFF, #868888FF, #8A8C8CFF, #909297FF, #8F9297FF, #8B8F90FF, #999995FF, #828897FF, #0B3484FF, #03287AFF, #174399FF, #193778FF, #102456FF, #0E1E4BFF, #1A4596FF, #1A48A0FF, #123681FF, #164FB3FF, #134EB9FF, #1249B0FF, #1649AAFF, #1648A9FF, #1549AAFF, #164BAAFF, #164AA7FF, #194AA6FF, #1951B3FF, #1957BEFF, #1B5BC7FF, #1C64D8FF, #1E52B0FF, #163780FF, #185AC8FF, #939392FF, #909091FF, #8D8E8FFF, #898A8AFF, #8F908FFF, #909192FF, #8E8F91FF, #909295FF, #929396FF, #8E9093FF, #8E9093FF, #8C8C90FF, #868587FF, #8E8E8EFF, #8D8E8FFF, #8B8C8FFF, #919399FF, #8C8F94FF, #8C9095FF, #8E929AFF, #909192FF, #909396FF, #909599FF, #969998FF, #8C8E90FF, #224489FF, #0641A8FF, #1752B9FF, #143A85FF, #133880FF, #1A499FFF, #2057BCFF, #143A85FF, #113581FF, #1A4EB1FF, #1850B4FF, #164BA8FF, #174AA5FF, #1948A3FF, #1C49A1FF, #1B48A0FF, #1949A1FF, #194AA3FF, #1949A2FF, #1847A1FF, #174AA5FF, #184EAEFF, #2368D7FF, #1D4592FF, #123A88FF, #8E8E91FF, #8D8E91FF, #89898DFF, #8A8B8FFF, #959699FF, #8C8F91FF, #888B8EFF, #909195FF, #8F9196FF, #898B8CFF, #8C8B8AFF, #8B8C8EFF, #8B8C8DFF, #8C8C8CFF, #8D8F92FF, #8D8E91FF, #8A8A8AFF, #8F9295FF, #9397A0FF, #9296A0FF, #8E8F90FF, #8A8D8DFF, #8C9194FF, #8F969DFF, #BBAEAAFF, #6B7293FF, #0038A0FF, #1247A8FF, #1751B5FF, #1D5CBFFF, #1E5DC6FF, #1F50ADFF, #13357BFF, #113785FF, #1A4FAFFF, #1C50ADFF, #1B4AA1FF, #1A489FFF, #1A489CFF, #1B479CFF, #1C469CFF, #1A459AFF, #19459AFF, #1A459AFF, #1B48A0FF, #184EABFF, #1950B3FF, #1C58C1FF, #2461C4FF, #1A479AFF, #84858AFF, #84868AFF, #898A8FFF, #8E8F93FF, #909092FF, #888B8EFF, #85898EFF, #8B8E92FF, #8F9497FF, #8A8C8DFF, #8C8B8CFF, #8D8D90FF, #929396FF, #8E9095FF, #8E9195FF, #919396FF, #8A8B8CFF, #8B8F91FF, #91959BFF, #90939AFF, #8A8E91FF, #8C9192FF, #98949CFF, #AF9EA1FF, #B3A3A9FF, #426CBAFF, #033391FF, #1E5DC7FF, #2676EDFF, #206DE0FF, #1C57BAFF, #1D489CFF, #163C86FF, #123683FF, #184DABFF, #1C50ADFF, #1B48A1FF, #1A489FFF, #19489DFF, #1A469AFF, #1C4498FF, #1A449BFF, #1A469CFF, #1A49A3FF, #194CA9FF, #194EAEFF, #1950B0FF, #1A51B4FF, #2265D2FF, #245FC1FF, #848586FF, #898B8FFF, #8D8E92FF, #86888CFF, #858484FF, #8F9091FF, #8E9297FF, #888E91FF, #8D9294FF, #898C8FFF, #898C8EFF, #8E9294FF, #8F9093FF, #8D8C90FF, #8C8F94FF, #8F9597FF, #8E9297FF, #8C9093FF, #909496FF, #8C9394FF, #888F93FF, #92909DFF, #B099A6FF, #BA9F9EFF, #BA9F92FF, #4568ADFF, #0344B3FF, #174490FF, #1C4EA8FF, #1847A1FF, #102D71FF, #12347EFF, #1A4498FF, #133988FF, #154399FF, #1D51B0FF, #1B49A3FF, #1A49A0FF, #1A469AFF, #194393FF, #194296FF, #1A459BFF, #1B479EFF, #1B49A3FF, #1A4AA4FF, #1B4AA3FF, #1A4AA4FF, #1A4CA8FF, #1952B4FF, #235FC4FF, #88888AFF, #8F9095FF, #88898DFF, #85858AFF, #888C8FFF, #8E9092FF, #8F9191FF, #919698FF, #8B9093FF, #8D9195FF, #8F9499FF, #8B8F93FF, #85888AFF, #89898EFF, #91959DFF, #8C9094FF, #898C91FF, #8F9396FF, #8A9395FF, #8D919AFF, #A89BA9FF, #7E798DFF, #A5919AFF, #D3A89AFF, #A48985FF, #2D4C96FF, #0D3A98FF, #143A80FF, #1D53B5FF, #1545A0FF, #103888FF, #0E317DFF, #103078FF, #0E2D73FF, #10357FFF, #1D51ABFF, #1C4AA0FF, #1A479BFF, #1B479CFF, #1B4395FF, #1B4397FF, #1B469CFF, #19489FFF, #1A48A1FF, #1A489FFF, #1B49A1FF, #1B48A1FF, #1A49A2FF, #184AA4FF, #1F58B8FF, #878582FF, #888788FF, #88888DFF, #8C8E92FF, #8D9196FF, #8B8D91FF, #8C8D8CFF, #8D8E8EFF, #8F9295FF, #92969AFF, #8D9195FF, #8C9092FF, #8C9196FF, #8C919AFF, #8F9297FF, #8E9094FF, #8E9294FF, #8E9599FF, #9795A4FF, #B09CABFF, #C6A9B4FF, #6F7281FF, #897D83FF, #D1A18EFF, #4460A1FF, #003BB3FF, #12439EFF, #1F5CC6FF, #1F61CEFF, #1957C4FF, #1A5DCDFF, #124BAEFF, #0E3486FF, #0D296AFF, #08205BFF, #173D8AFF, #1F4EA2FF, #1B4695FF, #1C489FFF, #1C479DFF, #1A4599FF, #1A449AFF, #194496FF, #194496FF, #194598FF, #1B459DFF, #1A479DFF, #1B4AA2FF, #1B4DA7FF, #114FB7FF, #90908FFF, #8F9191FF, #909397FF, #8E9397FF, #8B8E96FF, #84888DFF, #85898CFF, #898989FF, #8E9091FF, #8C9195FF, #8E9396FF, #8F9498FF, #8B8F94FF, #878A8EFF, #898A8BFF, #8C908FFF, #859399FF, #A0949DFF, #C29BA2FF, #C1A0A2FF, #BA9C99FF, #867779FF, #54473FFF, #615A6DFF, #135CCEFF, #1251BAFF, #0D3890FF, #0F3587FF, #1A51B2FF, #1A57BFFF, #164AA7FF, #134094FF, #164091FF, #18408FFF, #0D2969FF, #071B50FF, #173E8AFF, #1C4795FF, #1B4698FF, #1B49A2FF, #1A479DFF, #184397FF, #184294FF, #194295FF, #194396FF, #194397FF, #1B4599FF, #0F44A2FF, #003EA9FF, #2752A7FF, #A6AFB6FF, #A7AFB2FF, #A0A4A1FF, #9D9E98FF, #999A94FF, #8B8E8FFF, #88898EFF, #8A9093FF, #898F92FF, #8C8F92FF, #909193FF, #8C9093FF, #878D92FF, #8A8B8EFF, #868B8BFF, #A19598FF, #A2939BFF, #7E7B87FF, #6F6E7EFF, #645F6BFF, #615E67FF, #5D5C67FF, #3A3C3EFF, #164487FF, #145DD2FF, #1550B3FF, #1346A4FF, #0D3588FF, #12398BFF, #164499FF, #19469DFF, #1B489EFF, #173F8CFF, #123780FF, #174192FF, #0F3176FF, #071B4FFF, #133175FF, #1A4392FF, #1B499EFF, #19479CFF, #1A489DFF, #194499FF, #1A4599FF, #194696FF, #15459EFF, #003CA7FF, #0B40A0FF, #596291FF, #A18386FF, #A3A8A9FF, #A3A4A3FF, #A29F9CFF, #A4A4A0FF, #A3B1B5FF, #919CA4FF, #818081FF, #87898DFF, #87898BFF, #838587FF, #878685FF, #8F9296FF, #8D949EFF, #7E878EFF, #918888FF, #C99695FF, #968DA2FF, #4274A7FF, #2F5D8CFF, #2F567CFF, #3C6895FF, #3B658FFF, #396391FF, #1F64CEFF, #1B65DAFF, #1858C0FF, #134CB0FF, #113E96FF, #12429BFF, #1346A2FF, #153D8FFF, #102E77FF, #0D2F76FF, #1A47A0FF, #19469CFF, #113174FF, #0E2863FF, #09245CFF, #12357CFF, #1C499FFF, #1C4BA2FF, #1C489EFF, #1B479CFF, #1748A3FF, #0042ACFF, #003BA5FF, #455691FF, #A28489FF, #CC9588FF, #AC8888FF, #AFB0A9FF, #8F9995FF, #4E6E70FF, #537A84FF, #517681FF, #697378FF, #7D7F83FF, #7D8082FF, #808285FF, #858A8DFF, #8B8E8FFF, #8C8C8BFF, #8D9196FF, #848283FF, #8C6B6FFF, #6D82AEFF, #4684C8FF, #3F77B3FF, #1E416AFF, #2B4F75FF, #3D6B98FF, #34577AFF, #2D5FA1FF, #1D62D9FF, #195CCBFF, #1959C6FF, #1452BAFF, #1348ACFF, #12419DFF, #1146A4FF, #0F3889FF, #123786FF, #1948A0FF, #153D8CFF, #091E52FF, #071F56FF, #0D2C6DFF, #092560FF, #07215AFF, #184396FF, #1D4BA2FF, #1B489EFF, #0D4DB8FF, #0041AFFF, #274891FF, #816C81FF, #CC9481FF, #CA9687FF, #AA858BFF, #A1858CFF, #C2C2C5FF, #5E8084FF, #164F4DFF, #134D49FF, #274543FF, #5C5D60FF, #727477FF, #808386FF, #868A8DFF, #8A8B8DFF, #8B8D8EFF, #8A8A8AFF, #938A7CFF, #959293FF, #698AC0FF, #2367ADFF, #235283FF, #2A5482FF, #173762FF, #153056FF, #264F7DFF, #214467FF, #225AAFFF, #195BD0FF, #1A57C4FF, #1957C7FF, #1656C2FF, #1451B9FF, #103F9CFF, #0B2B73FF, #08225CFF, #102A64FF, #10265FFF, #071744FF, #0A2664FF, #0E2F74FF, #0F2E70FF, #102D70FF, #09215AFF, #0B2969FF, #1B4DA7FF, #0848B1FF, #113B8FFF, #5F506BFF, #BE8273FF, #D39985FF, #A88077FF, #A57972FF, #B68C88FF, #9C7F86FF, #71898CFF, #60828CFF, #476A66FF, #32453DFF, #484A4AFF, #6B6A6CFF, #86888AFF, #8A8A8EFF, #868584FF, #888786FF, #948E88FF, #95918DFF, #7590B3FF, #6297DBFF, #588BC9FF, #587194FF, #244773FF, #153E72FF, #254B7AFF, #132E56FF, #173761FF, #1B406BFF, #1E5CC0FF, #1858C9FF, #1753BBFF, #1753BEFF, #1652BAFF, #144EB4FF, #134CB2FF, #1346A5FF, #0D3481FF, #051F5DFF, #091E58FF, #102968FF, #0E286BFF, #0E2D74FF, #0C2D71FF, #0B2B6BFF, #0B2868FF, #031C52FF, #072D73FF, #414871FF, #8D5A4EFF, #C78775FF, #C59896FF, #B48D8EFF, #A37971FF, #976D64FF, #9E705EFF, #4E4868FF, #304636FF, #12362FFF, #4A504AFF, #574E48FF, #6D645FFF, #888683FF, #8F9094FF, #8B8C91FF, #8A8B8DFF, #8F8C89FF, #919292FF, #728EB0FF, #578DD2FF, #5079AFFF, #546886FF, #708CB1FF, #5B7CA9FF, #1F3F6BFF, #20406AFF, #122849FF, #19375DFF, #1B4273FF, #1B59BFFF, #1859C6FF, #1650B3FF, #154EB0FF, #164FB2FF, #164DB2FF, #1347AAFF, #1043A1FF, #14449FFF, #143F97FF, #0F3481FF, #0C2B6EFF, #091D56FF, #051A56FF, #041A53FF, #051B53FF, #071C53FF, #051A50FF, #000331FF, #5A4344FF, #C29087FF, #B58B8DFF, #B89191FF, #B88F90FF, #B58986FF, #A48385FF, #A28379FF, #424871FF, #2E3B33FF, #4E5048FF, #83776CFF, #9B9189FF, #979390FF, #8D8C8AFF, #8B8988FF, #8D8F93FF, #909295FF, #8C8A80FF, #6C85A5FF, #5688CFFF, #6486B2FF, #546C8AFF, #5B7BA4FF, #6889B4FF, #6E8AAAFF, #3C5473FF, #082448FF, #122642FF, #1B3350FF, #244A80FF, #1855BAFF, #1756C2FF, #1852BAFF, #174DB2FF, #154DADFF, #154CADFF, #1547A5FF, #13419BFF, #133E95FF, #113A8BFF, #103785FF, #0A2B73FF, #082B78FF, #092D79FF, #07286EFF, #072569FF, #092766FF, #072363FF, #000B43FF, #162046FF, #A68287FF, #BB8E8CFF, #B99191FF, #BD9595FF, #BF9494FF, #B28E92FF, #C0A3A0FF, #807389FF, #8C827DFF, #9F948EFF, #6B737BFF, #565D69FF, #918C8AFF, #979492FF, #90908FFF, #898E8FFF, #7F8587FF, #95959EFF, #9A99ABFF, #6587B7FF, #4E6E98FF, #4D6889FF, #5B79A0FF, #6580A6FF, #56708AFF, #425B76FF, #0C284EFF, #122D51FF, #0B1A2FFF, #173459FF, #0F3D91FF, #0E43ABFF, #184FB3FF, #194FB1FF, #174AAAFF, #1748A7FF, #174AA7FF, #1648A4FF, #13419AFF, #144199FF, #164198FF, #123C8EFF, #133E8FFF, #144091FF, #123B8BFF, #0D3684FF, #083282FF, #073081FF, #022167FF, #051A4DFF, #8A6F76FF, #B88F8AFF, #B78E8EFF, #BA9392FF, #BE9595FF, #AD8788FF, #A78989FF, #A58B93FF, #968F87FF, #747881FF, #20365BFF, #000E2DFF, #616775FF, #7F8488FF, #777F83FF, #838790FF, #9A98AAFF, #BBAEC2FF, #D8BEC6FF, #848EA4FF, #405E80FF, #5D7899FF, #577597FF, #557093FF, #425B79FF, #3E576FFF, #1A2E48FF, #000921FF, #000000FF, #0B1E33FF, #224B86FF, #18408EFF, #073289FF, #0F3F9AFF, #1C4BA7FF, #1948A5FF, #1847A3FF, #1946A2FF, #19479FFF, #18459BFF, #17429AFF, #174294FF, #153F8EFF, #113A8AFF, #0E3889FF, #0C3483FF, #0A2D75FF, #0A2664FF, #061E54FF, #001044FF, #6E5A69FF, #B68D88FF, #B08888FF, #B58D8CFF, #B68D8DFF, #AB8486FF, #A18386FF, #AD9498FF, #9D9691FF, #474F5EFF, #303F5AFF, #42536EFF, #4C6486FF, #767789FF, #8F889EFF, #A999B1FF, #BDA7BBFF, #C3AEB5FF, #CCB3B5FF, #B69899FF, #5C6A7EFF, #4A6989FF, #506A89FF, #374B65FF, #253144FF, #202F3FFF, #17263AFF, #182E4EFF, #2F5180FF, #4170AEFF, #4E86C5FF, #4477ACFF, #2A5490FF, #0A2F79FF, #042B7FFF, #12419AFF, #1B49A3FF, #1A48A1FF, #18479FFF, #17449BFF, #164399FF, #164195FF, #153F90FF, #123C8DFF, #123986FF, #103074FF, #0E2A66FF, #0D2763FF, #092763FF, #001559FF, #43415CFF, #B48780FF, #A98383FF, #B08888FF, #B78D8EFF, #AF898AFF, #A7888BFF, #AA949AFF, #878485FF, #484B52FF, #212E3EFF, #59708EFF, #8689A0FF, #BCA1ABFF, #B39EB2FF, #AE97A5FF, #BA9EA4FF, #BD9D97FF, #A9837BFF, #A97B70FF, #8F6C65FF, #414859FF, #385577FF, #305078FF, #2D4F78FF, #365C8FFF, #4575B1FF, #558FD5FF, #5691D8FF, #4E81BDFF, #4774A9FF, #4B7AABFF, #5583B2FF, #446E9FFF, #1B3E79FF, #03256DFF, #05287AFF, #10398CFF, #19469CFF, #1C489CFF, #1A4598FF, #184397FF, #184192FF, #19408CFF, #153981FF, #123377FF, #13387FFF, #123884FF, #0C2E74FF, #002067FF, #1D2E5DFF, #9B7473FF, #A78082FF, #AD8486FF, #B68D8DFF, #AF8889FF, #AC8B8EFF, #AC949AFF, #6F7277FF, #555354FF, #1A232FFF, #496283FF, #9E91A7FF, #C0A0A7FF, #AD898CFF, #A17977FF, #967776FF, #786A77FF, #67708FFF, #5C739DFF, #4F6085FF, #466490FF, #497DBCFF, #528BD2FF, #5691DAFF, #5790D7FF, #588BCBFF, #507DB6FF, #4C78ADFF, #4E78A9FF, #4D75A4FF, #4C76A3FF, #4E78A9FF, #5681B1FF, #5480ADFF, #416698FF, #2A4E84FF, #113472FF, #052571FF, #103588FF, #1C4394FF, #1B4292FF, #19418EFF, #183E86FF, #173D87FF, #173D87FF, #143C83FF, #163983FF, #133279FF, #072D71FF, #022262FF, #725B68FF, #AB807FFF, #AA8387FF, #B58D8DFF, #B1898AFF, #AB8B8DFF, #AB9397FF, #838281FF, #838184FF, #2A3446FF, #445B78FF, #918399FF, #85758DFF, #7D86A7FF, #6B7CA3FF, #45689CFF, #4E85CAFF, #5393DFFF, #4E88CEFF, #3C75B7FF, #5088CAFF, #5E90CFFF, #5D8BC5FF, #5B8AC2FF, #5884BCFF, #5A83BAFF, #5881B5FF, #527CADFF, #517CA8FF, #5079A4FF, #4F78A4FF, #527BAAFF, #537CABFF, #5982B2FF, #608DBFFF, #5682A7FF, #496D92FF, #395987FF, #0F295FFF, #001B60FF, #0C2C78FF, #11307DFF, #13357EFF, #15387FFF, #15377FFF, #13377DFF, #14357BFF, #123073FF, #0B2868FF, #00175CFF, #494360FF, #A97D79FF, #A27E82FF, #AE8A8DFF, #B18C8DFF, #AE8D8FFF, #AC9296FF, #777D83FF, #6D7583FF, #434858FF, #425777FF, #6182B3FF, #658BC4FF, #649CE1FF, #3C7AC3FF, #528FD8FF, #6A9DDDFF, #618ABFFF, #5C82B3FF, #5680B4FF, #5C88BDFF, #658FC4FF, #6590C5FF, #648DC2FF, #6088BEFF, #5A83B7FF, #5880B0FF, #5881AFFF, #5983AFFF, #5982ADFF, #547DA9FF, #517BA8FF, #517AA7FF, #557FADFF, #557FADFF, #4D749EFF, #4E719AFF, #5A80A4FF, #496887FF, #203B5EFF, #112C58FF, #0D255CFF, #08215EFF, #062162FF, #0C286FFF, #0E2A6FFF, #0F2C70FF, #103076FF, #0F3074FF, #002166FF, #202C58FF, #966E6DFF, #A47D80FF, #AB878BFF, #B08E91FF, #B09091FF, #B19396FF, #7D8094FF, #8E8B9BFF, #959BBAFF, #6991CBFF, #5884BFFF, #84ADE6FF, #4E7AB0FF, #4677B4FF, #6793CBFF, #648DC0FF, #648CBEFF, #678FC3FF, #5E86BAFF, #6088BCFF, #668FC4FF, #6690C5FF, #648EBFFF, #6189BAFF, #5E86B7FF, #5C80AFFF, #5C82AEFF, #597EAAFF, #587EAAFF, #577CA9FF, #5379A5FF, #4F79A3FF, #537AA6FF, #5379A3FF, #5477A2FF, #4C6E97FF, #42658BFF, #4F749DFF, #557B9EFF, #3B5B76FF, #2F4D6BFF, #243E5EFF, #142649FF, #081B44FF, #0A1E52FF, #071F5AFF, #07205DFF, #0C276BFF, #021D5CFF, #021345FF, #715863FF, #A77F7FFF, #AC878BFF, #AF8C92FF, #AD8F91FF, #B29397FF, #A38A96FF, #BDA5B3FF, #9AAAD3FF, #618BC5FF, #789BD0FF, #779ACCFF, #41699BFF, #5B88BEFF, #658CBEFF, #678CBEFF, #678FC0FF, #658EC0FF, #6089BBFF, #6089BBFF, #6890C4FF, #6991C2FF, #648BB8FF, #6186B1FF, #6283B0FF, #5D7FACFF, #5B7EA9FF, #577AA5FF, #5479A4FF, #567BA8FF, #5478A4FF, #5177A1FF, #4D7098FF, #4F729AFF, #4C6F98FF, #486B93FF, #486C93FF, #40638AFF, #51739CFF, #496D94FF, #34567CFF, #3B5C80FF, #385777FF, #274159FF, #1B3049FF, #172944FF, #15294AFF, #0E1E46FF, #0A1C42FF, #000D34FF, #554555FF, #AC8183FF, #A88483FF, #AE8B8BFF, #AE8E8CFF, #B19293FF, #A38187FF, #B69FA5FF, #7D93BAFF, #638BC4FF, #85A7DBFF, #6382B0FF, #3E6495FF, #5D86B7FF, #688BB8FF, #6A8AB7FF, #678BB5FF, #678EBAFF, #668DB9FF, #6188B5FF, #668CBCFF, #678BB6FF, #6586B1FF, #5F81ABFF, #5D7EA5FF, #57799EFF, #55779DFF, #52759CFF, #52769EFF, #51759EFF, #4B7199FF, #496F97FF, #456890FF, #45688FFF, #43668CFF, #42658BFF, #4A6C93FF, #46688EFF, #3F6188FF, #4E7097FF, #37577EFF, #38597FFF, #36567CFF, #30537CFF, #223D5DFF, #192E45FF, #304E6DFF, #263C57FF, #182B47FF, #042041FF, #413E51FF, #A2787BFF, #A68081FF, #AD8987FF, #AD8A88FF, #AF8F90FF, #9C7B7DFF, #B0999AFF, #7A93B9FF, #6D92C8FF, #84A6DBFF, #5A7AA6FF, #40648FFF, #6083ACFF, #6A8AB3FF, #6E8DB6FF, #6786ABFF, #6686ACFF, #6184ADFF, #5F82AEFF, #6283AEFF, #5E80A6FF, #5D7EA3FF, #5C7CA2FF, #55759BFF, #4F7094FF, #507296FF, #4F7197FF, #4B6E94FF, #496C92FF, #44688EFF, #3F6389FF, #40648AFF, #416389FF, #3D5F85FF, #395C81FF, #3E6086FF, #43668CFF, #34567CFF, #39597FFF, #42638AFF, #3B5D86FF, #2E4B70FF, #213C5EFF, #2D4C72FF, #1A2D48FF, #1F3551FF, #28436AFF, #1D375EFF, #062245FF, #2E3752FF, #977075FF, #A47E80FF, #AD8988FF, #B18989FF, #AE8D8FFF, #68514AFF, #8B7476FF, #7895BFFF, #7C9ECCFF, #82A1CEFF, #4A6993FF, #3A5F8CFF, #6386B3FF, #6889AFFF, #6485AAFF, #6281A6FF, #5B789CFF, #58759AFF, #59789EFF, #55769BFF, #4F708EFF, #516F90FF, #55749AFF, #4E6E94FF, #48688EFF, #46678DFF, #46688EFF, #45678DFF, #406388FF, #406288FF, #3C5E83FF, #395B81FF, #385A80FF, #34557CFF, #36587EFF, #34557CFF, #33547AFF, #304D73FF, #2D4A71FF, #325278FF, #28456CFF, #1C3558FF, #182B47FF, #263C5DFF, #253A59FF, #0F1E34FF, #122644FF, #1B3258FF, #152F56FF, #1F2B45FF, #81646AFF, #A88081FF, #AC8484FF, #B08A89FF, #AF9395FF)
// list of masked pixel indices for shirt colorization
var mask = array.from(588, 589, 637, 638, 639, 640, 687, 688, 689, 690, 691, 736, 737, 738, 739, 740, 741, 742, 743, 786, 787, 788, 789, 790, 791, 792, 793, 794, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 976, 977, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 1026, 1027, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1075, 1076, 1077, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1125, 1126, 1127, 1128, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1175, 1176, 1177, 1178, 1179, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1672, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1694, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1821, 1822, 1823, 1824, 1825, 1826, 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1839, 1840, 1871, 1872, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, 2140, 2141, 2142, 2182, 2183, 2184, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2234, 2235, 2236, 2237, 2238, 2239, 2240, 2241, 2242, 2243, 2289, 2290, 2291, 2292)
// Get Array Size (Square Image, x*x dim)
var size = int(math.sqrt(array.size(steve)))
// temp variables for later
var element = array.get(steve,0)
var temp = array.from(array.get(steve,0))
// customization
// color add
if add_on
// temps
var c = array.new_float(3)
var green = 0.0
// iterate through unmasked pixel indices
for i in mask
element := array.get(steve, i)
// set temp c arr
array.set(c,0,color.r(element) + color.r(add)*addInt)
array.set(c,1,color.g(element) + color.g(add)*addInt)
array.set(c,2,color.b(element) + color.b(add)*addInt)
// handle 2 hex digit overflow
if array.max(c) > 255 or array.min(c) < 0
for j = 0 to array.size(c)-1
if array.get(c,j) > 255
array.set(c,j,255)
else if array.get(c,j) < 0
array.set(c,j,0)
// modify pixels in original image
array.set(steve, i, color.rgb(array.get(c,0),array.get(c,1),array.get(c,2),0))
// clear mask, no further use
array.clear(mask)
if flipImageX
array.reverse(steve)
// ----Build Table----
var image = table.new(position,size,size)
// only on last bar
if barstate.islast
for i = 0 to array.size(steve)-1 // iterate through full steve array
element := array.get(steve, i) // get next element
// pack element into table, flipped or unflipped based on input.
// floor(i/size) = row num
// i%size = col num
if flipImageD
table.cell(image, math.floor(i/size), i%size, bgcolor=element, width=scale, height=scale*height)
else
table.cell(image, i%size, math.floor(i/size), bgcolor=element, width=scale, height=scale*height)
// ----Build Markers----
var lines = array.new_line(0)
var labels = array.new_label(0)
var dif = 0.0
var tcolor = color.red
var dir = label.style_label_up
if candleMarkers
dif := (close[1]-close[2])/close[2]
if dif >= threshold_mult or dif <= -threshold_mult
if dif > 0
tcolor := color.green
else if dif < 0
tcolor := color.red
dir := label.style_label_down
else
tcolor := color.blue
array.push(labels, label.new(bar_index[1], dif > 0 ? close[1] : open[1], text="Hey How Ya' Doin\nCandle ("+str.format("{0,number,##.##}",dif*100)+"%)",size=size.normal,textcolor=color.white,color=tcolor,style = dir))
|
Parametric VaR | https://www.tradingview.com/script/8TrpP04s-Parametric-VaR/ | mks17 | https://www.tradingview.com/u/mks17/ | 17 | 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("VaR", timeframe = "D", max_bars_back = 5000)
import loxx/norminv/1 as lib
percentile = input(1.0 , title = "Percentile Threshold")
length = input(4000, title = "Length")
in_percent = input(true, title = "Result in Percentage")
length := bar_index > length ? math.min(length, bar_index) : bar_index + 1
rt_formula = close/close[1] - 1
return_ = in_percent ? rt_formula * 100 : rt_formula
mu = ta.sma(return_, length)
std = ta.stdev(return_, length)
norm = lib.norminv(percentile/100, mu, std)
// VaR = ta.percentile_linear_interpolation(return_, length, percentile)
//Plots
cColor = return_ >= 0 ? color.green : color.red
plot(return_, style = plot.style_histogram, title = "Return", color=cColor)
// plot(VaR, style = plot.style_stepline, title = "VaR")
plot(norm, style = plot.style_stepline, title = "Parametric VaR", color=color.blue)
|
Net Liquidity | https://www.tradingview.com/script/IkKcOVBA-Net-Liquidity/ | calebsandfort | https://www.tradingview.com/u/calebsandfort/ | 265 | 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/
// © calebsandfort
//@version=5
indicator("Net Liq", shorttitle = "Net Liq", overlay = false, scale = scale.right)
import calebsandfort/NetLiquidityLibrary/7
net_liquidity = NetLiquidityLibrary.get_net_liquidity()
plot(net_liquidity > 0 ? net_liquidity / 1000000000 : na, title = "Net Liq", trackprice = true, linewidth = 2)
var fed_c_delta = "8,677b"
var tga_c_delta = "545b"
var rrp_c_delta = "2,238b"
var nl_c_delta = "5,894b"
var fed_d_delta = "0b"
var tga_d_delta = "+15b"
var rrp_d_delta = "+5b"
var nl_d_delta = "-20b"
var fed_w_delta = "0b"
var tga_w_delta = "-6b"
var rrp_w_delta = "+8b"
var nl_w_delta = "-2b"
var fed_ww_delta = "-46b"
var tga_ww_delta = "-114b"
var rrp_ww_delta = "+51b"
var nl_ww_delta = "+17b"
var fed_www_delta = "-67b"
var tga_www_delta = "-110b"
var rrp_www_delta = "-4b"
var nl_www_delta = "+47b"
var fed_m_delta = "-82b"
var tga_m_delta = "-69b"
var rrp_m_delta = "-9b"
var nl_m_delta = "-3b"
var fed_d_delta_pos = false
var tga_d_delta_pos = true
var rrp_d_delta_pos = true
var nl_d_delta_pos = false
var fed_w_delta_pos = false
var tga_w_delta_pos = false
var rrp_w_delta_pos = true
var nl_w_delta_pos = false
var fed_ww_delta_pos = false
var tga_ww_delta_pos = false
var rrp_ww_delta_pos = true
var nl_ww_delta_pos = true
var fed_www_delta_pos = false
var tga_www_delta_pos = false
var rrp_www_delta_pos = false
var nl_www_delta_pos = true
var fed_m_delta_pos = false
var tga_m_delta_pos = false
var rrp_m_delta_pos = false
var nl_m_delta_pos = false
textColor = color.white
bullishColor = color.green
bearishColor = color.red
header_color = #2196F3
bg_color = #2A2E39
current_bg_color = color.purple
var table infoTable = table.new(position.bottom_left, 7, 5, frame_color=textColor, frame_width = 1, border_color=textColor, border_width = 1)
if barstate.islast
table.cell(infoTable, 0, 0, "Metric", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 1, 0, "Current", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 2, 0, "1DΔ", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 3, 0, "1WΔ", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 4, 0, "2WΔ", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 5, 0, "3WΔ", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 6, 0, "1MΔ", bgcolor=header_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 0, 1, "FED BS", bgcolor=bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 1, 1, fed_c_delta, bgcolor=current_bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 2, 1, fed_d_delta, bgcolor=fed_d_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 3, 1, fed_w_delta, bgcolor=fed_w_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 4, 1, fed_ww_delta, bgcolor=fed_ww_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 5, 1, fed_www_delta, bgcolor=fed_ww_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 6, 1, fed_m_delta, bgcolor=fed_m_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 0, 2, "TGA", bgcolor=bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 1, 2, tga_c_delta, bgcolor=current_bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 2, 2, tga_d_delta, bgcolor=tga_d_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 3, 2, tga_w_delta, bgcolor=tga_w_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 4, 2, tga_ww_delta, bgcolor=tga_ww_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 5, 2, tga_www_delta, bgcolor=tga_ww_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 6, 2, tga_m_delta, bgcolor=tga_m_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 0, 3, "RRP", bgcolor=bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 1, 3, rrp_c_delta, bgcolor=current_bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 2, 3, rrp_d_delta, bgcolor=rrp_d_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 3, 3, rrp_w_delta, bgcolor=rrp_w_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 4, 3, rrp_ww_delta, bgcolor=rrp_ww_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 5, 3, rrp_ww_delta, bgcolor=rrp_www_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 6, 3, rrp_m_delta, bgcolor=rrp_m_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 0, 4, "Net Liq", bgcolor=bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 1, 4, nl_c_delta, bgcolor=current_bg_color, text_color=textColor, text_size = size.small)
table.cell(infoTable, 2, 4, nl_d_delta, bgcolor=nl_d_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 3, 4, nl_w_delta, bgcolor=nl_w_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 4, 4, nl_ww_delta, bgcolor=nl_ww_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 5, 4, nl_www_delta, bgcolor=nl_www_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small)
table.cell(infoTable, 6, 4, nl_m_delta, bgcolor=nl_m_delta_pos ? bullishColor : bearishColor, text_color=textColor, text_size = size.small) |
Adaptive Fisherized CMF | https://www.tradingview.com/script/wE6fK7Hu-Adaptive-Fisherized-CMF/ | simwai | https://www.tradingview.com/u/simwai/ | 49 | 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/
// © simwai
//@version=5
indicator('Adaptive Fisherized CMF', 'AF_CMF', false)
// -- Input --
string resolution = input.timeframe(defval='', title='Resolution', group='CMF', inline='1')
int min = input.int(defval=9, minval=2, title='Min Length', group='CMF', inline='2')
int length = input.int(defval=21, minval=2, title='Length', group='CMF', inline='2')
float upperBandValue = input.float(defval=0.5, title='Upper Band', minval=-1, maxval=1, group='CMF', inline='5')
float lowerBandValue = input.float(defval=-0.5, title='Lower Band', minval=-1, maxval=1, group='CMF', inline='5')
bool isFisherized = input.bool(defval=false, title='Enable Fisherization', group='CMF', inline='6')
string highlightMode = input.string('Zero Line', title='Choose Highlight Mode', options=['Zero Line', 'Inner Bands', 'None'], group='CMF', inline='7')
string adaptiveMode = input.string('Homodyne Discriminator', 'Choose Adaptive Mode', options=['Inphase-Quadrature Transform', 'Homodyne Discriminator', 'None'], group='CMF', inline='7')
string smoothingMode = input.timeframe('NET', 'Choose Smoothing Mode', options=['NET', 'Hann Window', 'None'], group='Smoothing', inline='1')
int netLength = input.int(9, 'NET Length', minval=2, group='Smoothing', inline='2')
int hannLength = input.int(3, 'Hann Window Length', minval=2, group='Smoothing', inline='2')
string maType = input.string(defval='TEMA', title='Choose MA Smoothing Mode', options=['ZLSMA', 'TEMA', 'None'], group='Smoothing', inline='3')
int maLength = input.int(13, minval=2, title='MA Length', group='Smoothing', inline='3')
string divergenceMode = input.string('None', title='Divergence Mode', options=['Regular', 'Hidden', 'Both', 'None'], group='Divergences', inline='1')
bool isDivLinePlotEnabled = input.bool(false, title='Enable Divergence Lines Plot', group='Divergences', inline='2')
int rangeUpper = input.int(title='Max of Lookback Range', minval=1, defval=60, group='Divergences', inline='3')
int rangeLower = input.int(title='Min of Lookback Range', minval=1, defval=5, group='Divergences', inline='3')
int lbR = input.int(title='Pivot Lookback Right', minval=2, defval=12, group='Divergences', inline='4')
int lbL = input.int(title='Pivot Lookback Left', minval=2, defval=12, group='Divergences', inline='4')
// -- Input Evaluation --
bool areBothDivsEnabled = divergenceMode == 'Both'
bool areRegularDivsEnabled = divergenceMode == 'Regular'
bool areHiddenDivsEnabled = divergenceMode == 'Hidden'
// -- Colors --
color maximumYellowRed = color.rgb(255, 203, 98) // yellow
color rajah = color.rgb(242, 166, 84) // orange
color magicMint = color.rgb(171, 237, 198)
color lightPurple = color.rgb(193, 133, 243)
color languidLavender = color.rgb(232, 215, 255)
color maximumBluePurple = color.rgb(181, 161, 226)
color skyBlue = color.rgb(144, 226, 244)
color lightGray = color.rgb(214, 214, 214)
color quickSilver = color.rgb(163, 163, 163)
color mediumAquamarine = color.rgb(104, 223, 153)
color transpLightGray = color.new(lightGray, 50)
color transpMagicMint = color.new(magicMint, 45)
color transpRajah = color.new(rajah, 45)
// Divergence colors
color bullColor = lightPurple
color bearColor = maximumBluePurple
color hiddenBullColor = bullColor
color hiddenBearColor = bearColor
color noneColor = lightGray
color textColor = color.white
// -- Functions --
// Apply normalization
normalize(float _src, int _min, int _max) =>
var float _historicMin = 1.0
var float _historicMax = -1.0
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 1)
// Inverse Fisher Transformation (IFT)
fisherize(float _value) => (math.exp(2 * _value) - 1) / (math.exp(2 * _value) + 1)
// Convert length to alpha
getAlpha(float _length) => 2 / (_length + 1)
inRange(bool cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
// Get dominant cyber cycle – Median – Credits to @blackcat1402
getMedianDc(float Price, float alpha=0.07, simple float CycPart=0.5) =>
Smooth = 0.00
Cycle = 0.00
Q1 = 0.00
I1 = 0.00
DeltaPhase = 0.00
MedianDelta = 0.00
DC = 0.00
InstPeriod = 0.00
Period = 0.00
I2 = 0.00
Q2 = 0.00
IntPeriod = 0
Smooth := (Price + 2 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 6
Cycle := (1 - .5 * alpha) * (1 - .5 * alpha) * (Smooth - 2 * nz(Smooth[1]) + nz(Smooth[2])) + 2 * (1 - alpha) * nz(Cycle[1]) - (1 - alpha) * (1 - alpha) * nz(Cycle[2])
Cycle := bar_index < 7 ? (Price - 2 * nz(Price[1]) + nz(Price[2])) / 4 : Cycle
Q1 := (.0962 * Cycle + .5769 * nz(Cycle[2]) - .5769 * nz(Cycle[4]) - .0962 * nz(Cycle[6])) * (.5 + .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]))) : DeltaPhase
DeltaPhase := DeltaPhase < 0.1 ? 0.1 : DeltaPhase
DeltaPhase := DeltaPhase > 1.1 ? 1.1 : DeltaPhase
MedianDelta := ta.median(DeltaPhase, 5)
DC := MedianDelta == 0.00 ? 15.00 : 6.28318 / MedianDelta + .5
InstPeriod := .33 * DC + .67 * nz(InstPeriod[1])
Period := .15 * InstPeriod + .85 * nz(Period[1])
//it can add filter to Period here
//IntPeriod := round((4*Period + 3*nz(Period[1]) + 2*nz(Period[3]) + nz(Period[4])) / 20)
IntPeriod := math.round(Period * CycPart) > 34 ? 34 : math.round(Period * CycPart) < 1 ? 1 : math.round(Period * CycPart)
IntPeriod
// Get dominant cyber cycle – Inphase-Quadrature -- Credits to @DasanC
getIqDc(float src, int min, int max) =>
PI = 3.14159265359
P = src - src[7]
lenIQ = 0.0
lenC = 0.0
imult = 0.635
qmult = 0.338
inphase = 0.0
quadrature = 0.0
re = 0.0
im = 0.0
deltaIQ = 0.0
instIQ = 0.0
V = 0.0
inphase := 1.25 * (P[4] - imult * P[2]) + imult * nz(inphase[3])
quadrature := P[2] - qmult * P + qmult * nz(quadrature[2])
re := 0.2 * (inphase * inphase[1] + quadrature * quadrature[1]) + 0.8 * nz(re[1])
im := 0.2 * (inphase * quadrature[1] - inphase[1] * quadrature) + 0.8 * nz(im[1])
if re != 0.0
deltaIQ := math.atan(im / re)
deltaIQ
for i = 0 to max by 1
V += deltaIQ[i]
if V > 2 * PI and instIQ == 0.0
instIQ := i
instIQ
if instIQ == 0.0
instIQ := nz(instIQ[1])
instIQ
lenIQ := 0.25 * instIQ + 0.75 * nz(lenIQ[1], 1)
length = lenIQ < min ? min : lenIQ
math.round(length)
// Get dominant cyber cycle – Hilbert Transform -- Credits to @DasanC
getHtDc(float src) =>
Imult = .635
Qmult = .338
PI = 3.14159
InPhase = 0.0
Quadrature = 0.0
Phase = 0.0
DeltaPhase = 0.0
InstPeriod = 0.0
Period = 0.0
Value4 = 0.0
if bar_index > 5
// Detrend src
Value3 = src - src[7]
// Compute InPhase and Quadrature components
InPhase := 1.25 * (Value3[4] - Imult * Value3[2]) + Imult * nz(InPhase[3])
Quadrature := Value3[2] - Qmult * Value3 + Qmult * nz(Quadrature[2])
// Use ArcTangent to compute the current phase
if math.abs(InPhase + InPhase[1]) > 0
Phase := 180 / PI * math.atan(math.abs((Quadrature + Quadrature[1]) / (InPhase + InPhase[1])))
Phase
// Resolve the ArcTangent ambiguity
if InPhase < 0 and Quadrature > 0
Phase := 180 - Phase
Phase
if InPhase < 0 and Quadrature < 0
Phase := 180 + Phase
Phase
if InPhase > 0 and Quadrature < 0
Phase := 360 - Phase
Phase
// Compute a differential phase, resolve phase wraparound, and limit delta phase errors
DeltaPhase := Phase[1] - Phase
if Phase[1] < 90 and Phase > 270
DeltaPhase := 360 + Phase[1] - Phase
DeltaPhase
if DeltaPhase < 1
DeltaPhase := 1
DeltaPhase
if DeltaPhase > 60
DeltaPhase := 60
DeltaPhase
// Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous period.
for i = 0 to 50 by 1
Value4 += DeltaPhase[i]
if Value4 > 360 and InstPeriod == 0
InstPeriod := i
InstPeriod
// Resolve Instantaneous Period errors and smooth
if InstPeriod == 0
nz(InstPeriod[1])
Period := .25 * InstPeriod + .75 * Period[1]
math.round(Period)
// Get Dominant Cyber Cycle - Homodyne Discriminator With Hilbert Dominant Cycle – Credits to @blackcat1402
getHdDc(float Price, int min, int max, simple float CycPart=0.5) =>
Smooth = 0.00
Detrender = 0.00
I1 = 0.00
Q1 = 0.00
jI = 0.00
jQ = 0.00
I2 = 0.00
Q2 = 0.00
Re = 0.00
Im = 0.00
Period = 0.00
SmoothPeriod = 0.00
pi = 2 * math.asin(1)
DomCycle = 0.0
//Hilbert Transform
Smooth := bar_index > 7 ? (4 * Price + 3 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 10 : Smooth
Detrender := bar_index > 7 ? (.0962 * Smooth + .5769 * nz(Smooth[2]) - .5769 * nz(Smooth[4]) - .0962 * nz(Smooth[6])) * (.075 * nz(Period[1]) + .54) : Detrender
//Compute InPhase and Quadrature components
Q1 := bar_index > 7 ? (.0962 * Detrender + .5769 * nz(Detrender[2]) - .5769 * nz(Detrender[4]) - .0962 * nz(Detrender[6])) * (.075 * nz(Period[1]) + .54) : Q1
I1 := bar_index > 7 ? nz(Detrender[3]) : I1
//Advance the phase of I1 and Q1 by 90 degrees
jI := (.0962 * I1 + .5769 * nz(I1[2]) - .5769 * nz(I1[4]) - .0962 * nz(I1[6])) * (.075 * nz(Period[1]) + .54)
jQ := (.0962 * Q1 + .5769 * nz(Q1[2]) - .5769 * nz(Q1[4]) - .0962 * nz(Q1[6])) * (.075 * nz(Period[1]) + .54)
//Phasor addition for 3 bar averaging
I2 := I1 - jQ
Q2 := Q1 + jI
//Smooth the I and Q components before applying the discriminator
I2 := .2 * I2 + .8 * nz(I2[1])
Q2 := .2 * Q2 + .8 * nz(Q2[1])
//Homodyne Discriminator
Re := I2 * nz(I2[1]) + Q2 * nz(Q2[1])
Im := I2 * nz(Q2[1]) - Q2 * nz(I2[1])
Re := .2 * Re + .8 * nz(Re[1])
Im := .2 * Im + .8 * nz(Im[1])
Period := Im != 0 and Re != 0 ? 2 * pi / math.atan(Im / Re) : Period
Period := Period > 1.5 * nz(Period[1]) ? 1.5 * nz(Period[1]) : Period
Period := Period < .67 * nz(Period[1]) ? .67 * nz(Period[1]) : Period
Period := Period < min ? min : Period
Period := Period > max ? max : Period
Period := .2 * Period + .8 * nz(Period[1])
SmoothPeriod := .33 * Period + .67 * nz(SmoothPeriod[1])
//it can add filter to Period here
DomCycle := math.ceil(CycPart * SmoothPeriod) > 34 ? 34 : math.ceil(CycPart * SmoothPeriod) < 1 ? 1 : math.ceil(CycPart * SmoothPeriod)
// Limit dominant cycle
DomCycle := DomCycle < min ? min : DomCycle
DomCycle := DomCycle > max ? max : DomCycle
// Noise Elimination Technology (NET) – Credits to @blackcat1402
doNet(float _series, simple int _netLength, int _lowerBand=-1, int _upperBand=1) =>
var netX = array.new_float(102)
var netY = array.new_float(102)
num = 0.00
denom = 0.00
net = 0.00
trigger = 0.00
for count = 1 to _netLength
array.set(netX, count, nz(_series[count - 1]))
array.set(netY, count, -count)
num := 0
for count = 2 to _netLength
for k = 1 to count - 1
num := num - math.sign(nz(array.get(netX, count)) - nz(array.get(netX, k)))
denom := 0.5 * _netLength * (_netLength - 1)
net := num / denom
trigger := 0.05 + 0.9 * nz(net[1])
trigger := normalize(trigger, _lowerBand, _upperBand)
// Hann Window Smoothing – Credits to @cheatcountry
doHannWindow(float _series, float _hannWindowLength) =>
sum = 0.0, coef = 0.0
for i = 1 to _hannWindowLength
cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1))
sum := sum + (cosine * nz(_series[i - 1]))
coef := coef + cosine
h = coef != 0 ? sum / coef : 0
sma(float _src, int _period) =>
sum = 0.0
for i = 0 to _period - 1
sum := sum + _src[i] / _period
sum
ema(float _src, int _period) =>
alpha = 2 / (_period + 1)
sum = 0.0
sum := na(sum[1]) ? sma(_src, _period) : alpha * _src + (1 - alpha) * nz(sum[1])
// Zero-lag Least Squared Moving Average (ZLSMA)
zlsma(float _src, int _period, int _offset=0) =>
lsma = ta.linreg(_src, _period, _offset)
lsma2 = ta.linreg(lsma, _period, _offset)
eq = lsma - lsma2
zlsma = lsma + eq
// Tripple Exponential Moving Average (TEMA)
tema(float _src, int _period) =>
ema1 = ema(_src, _period)
ema2 = ema(ema1, _period)
ema3 = ema(ema2, _period)
(3 * ema1) - (3 * ema2) + ema3
// Chaikin Money Flow (CMF)
cmf(float _close, float _high, float _low, float _volume, int _length) =>
ad = _close == _high and _close == _low or _high == _low ? 0 : ((2 * _close - _low - _high) / (_high - _low)) * _volume
mf = math.sum(ad, _length) / math.sum(_volume, _length)
// -- CMF Calculation --
[_close, _high, _low, _volume] = request.security(syminfo.tickerid, resolution, [close[1], high[1], low[1], volume[1]], barmerge.gaps_off, barmerge.lookahead_on)
int _maLength = maLength
int _length = length
if (smoothingMode == 'Hann Window')
_close := doHannWindow(_close, hannLength)
_high := doHannWindow(_high, hannLength)
_low := doHannWindow(_low, hannLength)
_volume := doHannWindow(_volume, hannLength)
if (adaptiveMode == 'Inphase-Quadrature Transform')
_length := math.round(getIqDc(_close, min, length) / 2)
_maLength := math.round(getIqDc(_close, min, maLength) / 2)
if (adaptiveMode == 'Homodyne Discriminator')
_length := math.round(getHdDc(_close, min, length))
_maLength := math.round(getHdDc(_close, min, maLength))
if (_length < min)
_length := min
float cmf = cmf(_close, _high, _low, _volume, _length) * 20
cmf := normalize(cmf, -1, 1)
if (isFisherized)
cmf := fisherize(cmf)
if (maType == 'ZLSMA')
cmf := zlsma(cmf, _maLength)
else if (maType == 'TEMA')
cmf := tema(cmf, _maLength)
if (smoothingMode == 'NET')
cmf := doNet(cmf, netLength)
topBand = plot(1, 'Top Band', color=transpLightGray)
upperBand = plot(upperBandValue, 'Upper Band', color=transpLightGray)
zeroLine = plot(0, 'Zero Line', color=transpLightGray)
lowerBand = plot(lowerBandValue, 'Lower Band', color=transpLightGray)
bottomBand = plot(-1, 'Bottom Band', color=transpLightGray)
plot = plot(cmf, title='CMF', color=languidLavender)
fill(zeroLine, topBand, color=((highlightMode == 'Zero Line') and cmf >= 0) ? transpMagicMint : na)
fill(zeroLine, bottomBand, color=((highlightMode == 'Zero Line') and cmf < 0) ? transpRajah : na)
fill(upperBand, topBand, color=((highlightMode == 'Inner Bands') and cmf > upperBandValue) ? transpMagicMint : na)
fill(lowerBand, bottomBand, color=((highlightMode == 'Inner Bands') and cmf < lowerBandValue) ? transpRajah : na)
// -- Divergences – Credits to @tista --
float top = na
float bot = na
top := ta.pivothigh(cmf, lbL, lbR)
bot := ta.pivotlow(cmf, lbL, lbR)
bool phFound = na(top) ? false : true
bool plFound = na(bot) ? false : true
// -- Regular Bullish --
// Osc: Higher Low
bool cmfHL = cmf[lbR] > ta.valuewhen(plFound, cmf[lbR], 1) and inRange(plFound[1])
// Price: Lower Low
bool priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bool bullCond = priceLL and cmfHL and plFound
plot(
((areRegularDivsEnabled or areBothDivsEnabled) and plFound and isDivLinePlotEnabled) ? cmf[lbR] : na,
offset=-lbR,
title='Regular Bullish',
linewidth=1,
color=(bullCond ? bullColor : noneColor),
editable = false)
plotshape(
((areRegularDivsEnabled or areBothDivsEnabled) and bullCond) ? cmf[lbR] : na,
offset=-lbR,
title='Regular Bullish Label',
text='R',
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
editable = false)
alertcondition(bullCond, title='Regular bullish divergence in CMF found', message='Check charts for a regular bullish divergence found with CMF')
// -- Hidden Bullish Divergence --
// Osc: Lower Low
bool cmfLL = cmf[lbR] < ta.valuewhen(plFound, cmf[lbR], 1) and inRange(plFound[1])
// Price: Higher Low
bool priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
bool hiddenBullCond = priceHL and cmfLL and plFound
plot(
((areHiddenDivsEnabled or areBothDivsEnabled) and plFound and isDivLinePlotEnabled) ? cmf[lbR] : na,
offset=-lbR,
title='Hidden Bullish',
linewidth=1,
color=(hiddenBullCond ? hiddenBullColor : noneColor),
editable = false)
plotshape(
((areHiddenDivsEnabled or areBothDivsEnabled) and hiddenBullCond) ? cmf[lbR] : na,
offset=-lbR,
title='Hidden Bullish Label',
text='H',
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
editable = false)
alertcondition(hiddenBullCond, title='Hidden bullish divergence in CMF found', message='Check charts for a hidden bullish divergence found with CMF')
// -- Regular Bullish Divergence --
// Osc: Lower High
bool cmfLH = cmf[lbR] < ta.valuewhen(phFound, cmf[lbR], 1) and inRange(phFound[1])
// Price: Higher High
bool priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bool bearCond = priceHH and cmfLH and phFound
plot(
((areBothDivsEnabled or areRegularDivsEnabled) and phFound and isDivLinePlotEnabled) ? cmf[lbR] : na,
offset=-lbR,
title='Regular Bearish',
linewidth=1,
color=(bearCond ? bearColor : noneColor),
editable = false)
plotshape(
((areBothDivsEnabled or areRegularDivsEnabled) and bearCond) ? cmf[lbR] : na,
offset=-lbR,
title='Regular Bearish Label',
text='R',
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
editable = false)
alertcondition(bearCond, title='Regular bearish divergence in CMF found', message='Check charts for a regular bearish divergence found with CMF')
// -- Hidden Bearish Divergence --
// Osc: Higher High
bool cmfHH = cmf[lbR] > ta.valuewhen(phFound, cmf[lbR], 1) and inRange(phFound[1])
// Price: Lower High
bool priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
bool hiddenBearCond = priceLH and cmfHH and phFound
plot(
((areHiddenDivsEnabled or areBothDivsEnabled) and phFound and isDivLinePlotEnabled) ? cmf[lbR] : na,
offset=-lbR,
title='Hidden Bearish',
linewidth=1,
color=(hiddenBearCond ? hiddenBearColor : noneColor),
editable=false)
plotshape(
((areHiddenDivsEnabled or areBothDivsEnabled) and hiddenBearCond) ? cmf[lbR] : na,
offset=-lbR,
title='Hidden Bearish Label',
text='H',
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
editable=false)
alertcondition(hiddenBearCond, title='Hidden bearish divergence in CMF found', message='Check charts for a hidden bearish divergence found with CMF') |
Significance Condensed | https://www.tradingview.com/script/wSf94s8d-Significance-Condensed/ | LvNThL | https://www.tradingview.com/u/LvNThL/ | 40 | 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/
// © LvNThL
//@version=5
// *EDIT* NOTE *EDIT*
// For the sake of clarity, after using Significance for some time, I have collapsed the overall asthetic to be more easily readible for the trader.
// I have removed the Auto-Trendline function and 1 ema, along with all zone fills and inter-high/low ranges. These modifications have made it easier for me to use this indicator.
// I would like to share this revision to Significance, to well, be straight-forwardly, more isolated, focused, and clear on the significance of levels as we approach them.
// I am working on a isolated auto-trendline code to accompany this script, one that works right.
// Feel free to message me if you have a script you want and I'll see what I can do!
// *EDIT* DESCRIPTION *EDIT*
// Indicator Name: "Significance Condensed"
// This is a "Multi-Indicator", which includes:
// *EDIT*
// Custom Candlesticks with Bearish/Bullish Engulfing Body Fills, otherwise hollow.
// 2 EMA's with user inputs.
// Continuous plots of high/low values with up to 3 overlapping timeframes.
// Two Tables: Bottom_Left displays TickerId and Timeframe Period, Bottom_Right displays Current Price (Red/Green for DownDay/UpDay), Daily Percentile Change (Red/Green for DownDay/UpDay), Volume: Daily Volume Total and Current Bar Volume, and RSI: Value. Respectively.
// *EDIT*
//CANDLESTICK DISCLAIMER
// If you would like to use the custom candlestick plots, (hollow, else engulfing), that come along with this indicator,
// be sure to disable the Candlestick Body, Wick, and Border under Chart Appearance; and then enable "Candlesticks Active" in the indicator settings.
indicator("Significance Condensed", overlay=true, precision=4, format=format.price, max_labels_count = 500, max_bars_back = 500, max_lines_count = 500)
[o,h,l,c,v] = request.security(syminfo.tickerid, "", [open, high, low, close, volume], lookahead=barmerge.lookahead_on)
[o1,o1_1,h1,h1_1,l1,l1_1,c1,c1_1,v1] = request.security(syminfo.tickerid, input.timeframe("D", title="Timeframe #1", group="High/Low Timeframes"), [open, open[1], high, high[1], low, low[1], close, close[1], volume], lookahead=barmerge.lookahead_on)
[o4,o4_1,h4,h4_1,l4,l4_1,c4,c4_1,v4] = request.security(syminfo.tickerid, input.timeframe("W", title="Timeframe #2", group="High/Low Timeframes"), [open, open[1], high, high[1], low, low[1], close, close[1], volume], lookahead=barmerge.lookahead_on)
[o2,o2_1,h2,h2_1,l2,l2_1,c2,c2_1,v2] = request.security(syminfo.tickerid, input.timeframe("M", title="Timeframe #3", group="High/Low Timeframes", tooltip = string("This Timeframe is coordinated with the Spread Math shown on the Table")), [open, open[1], high, high[1], low, low[1], close, close[1], volume], lookahead=barmerge.lookahead_on)
[o3,h3,l3,c3] = request.security(syminfo.tickerid, "D", [open, high, low, close], lookahead=barmerge.lookahead_on)
[c5] = request.security(syminfo.tickerid, input.timeframe("", title = "User Ema Timeframe:", group = "User Ema Input"), [close], lookahead=barmerge.lookahead_on, gaps = barmerge.gaps_off)
[_volume] = request.security(syminfo.tickerid, "", [volume], lookahead=barmerge.lookahead_on)
var int _emainput1 = na
var int _emainput2 = na
var int _emainput3 = na
var int _emainput4 = na
string _timeframe1input = na
string _timeframe2input = na
string _timeframe3input = na
if timeframe.ismonthly
_emainput1 := 6
_emainput2 := 12
else if timeframe.isweekly
_emainput1 := 26
_emainput2 := 52
else if timeframe.period == "10D"
_emainput1 := 26
_emainput2 := 52
else if timeframe.period == "5D"
_emainput1 := 26
_emainput2 := 52
else if timeframe.isdaily
_emainput1 := 180
_emainput2 := 360
else if timeframe.period == "4H"
_emainput1 := 180
_emainput2 := 360
else if timeframe.isintraday
_emainput1 := 7
_emainput2 := 30
_ema1 = ta.ema(close, int(_emainput1))
_ema2 = ta.ema(close, int(_emainput2))
_ema3 = ta.ema(c5, input.int(50, title = "User Ema #1", minval = 1, maxval = 4999, step = 1, group = "User Ema Input"))
_ema4 = ta.ema(c5, input.int(100, title = "User Ema #2", minval = 1, maxval = 4999, step = 1, group = "User Ema Input"))
_ema5 = ta.ema(c5, input.int(200, title = "User Ema #3", minval = 1, maxval = 4999, step = 1, group = "User Ema Input"))
_rsi = ta.rsi(hlc3,input.int(14, title="RSI Length", minval=1, step=1, group="RSI Settings"))
var float _highlowavg1 = na
var float _highlowavg2 = na
var float _highlowavg3 = na
var float _bottomquartile = na
var float _topquartile = na
var float _bottomoctile = na
var float _topoctile = na
var float _wbottomquartile = na
var float _wtopquartile = na
var float _wbottomoctile = na
var float _wtopoctile = na
var float _mbottomquartile = na
var float _mtopquartile = na
var float _mbottomoctile = na
var float _mtopoctile = na
var float _bottomsharp = na
var float _topsharp = na
var float _wbottomsharp = na
var float _wtopsharp = na
var float _mbottomsharp = na
var float _mtopsharp = na
var float _dailyvolume = na
var float _open = na
var float _high = na
var float _low = na
var float _close = na
var float y_open = na
var float y_high = na
var float y_low = na
var float y_close = na
var float w_open = na
var float w_high = na
var float w_low = na
var float w_close = na
var float m_open = na
var float m_high = na
var float m_low = na
var float m_close = na
var float d_high = na
var float d_low = na
var float _currentprice = na
float _dailychange = na
float _dailychangepos = ((close/o3)-1)
float _dailychangeneg = (-(o3/close)+1)
var label _lbl1 = na
var label _lbl2 = na
var label _lbl3 = na
var label _lbl4 = na
var label _lbl5 = na
var label _lbl6 = na
var label _lbl7 = na
var label _lbl8 = na
var label _lbl9 = na
var label _lblema1 = na
var label _lblema2 = na
var label _lblema3 = na
var label _lblema4 = na
var label _lblema5 = na
bool _candlesticks = input.bool(false, title="Candlesticks Active", group="Switches")
bool _highlowswitch1 = input.bool(true, title="High/Low #1", group="Switches")
bool _highlowswitch2 = input.bool(true, title="High/Low #2", group="Switches")
bool _highlowswitch3 = input.bool(true, title="High/Low #3", group="Switches")
bool _above = close >= o3
bool _below = close < o3
bool _ema1switch = input.bool(true, title="EMA #1", group="Switches")
bool _ema2switch = input.bool(true, title="EMA #2", group="Switches")
bool _ema3switch = input.bool(true, title="User EMA #1", group="Switches")
bool _ema4switch = input.bool(true, title="User EMA #2", group="Switches")
bool _ema5switch = input.bool(true, title="User EMA #3", group="Switches")
color _green = open<=close?color.new(#27ad75, 0):na
color _red = open>=close?color.new(#fa5252, 0):na
color _greenw = open<=close?color.new(#27ad75, 50):na
color _redw = open>=close?color.new(#fa5252, 50):na
color _bullishengulf = open<close and open[1]>close[1] and close>open[1]?color.new(#27ad75, 0):na
color _bearishengulf = open>close and open[1]<close[1] and close<open[1]?color.new(#fa5252, 0):na
var string s_dailyvolume = " Daily Volume: "
var string s_currentprice = " Current Price: "
var string _volumetext = na
var table _tbl1 = na
var table _tbl2 = na
var line _ln1 = na
_currentprice := c1
_dailyvolume := v1
_open := o1
_high := h1
_low := l1
_close := c1
y_open := o1_1
y_high := h1_1
y_low := l1_1
y_close := c1_1
w_open := o4
w_high := h4
w_low := l4
w_close := c4
m_open := o2
m_high := h2
m_low := l2
m_close := c2
d_high := h3
d_low := l3
if _dailyvolume >= 1000000000000
_volumetext := str.tostring(str.format("{0,number, ###.## T }", _dailyvolume / 1000000000000) + " + " + str.tostring(str.format("{0,number, ###,###,###,###,###.## }", volume)))
else if _dailyvolume >= 1000000000
_volumetext := str.tostring(str.format("{0,number, ###.## B }", _dailyvolume / 1000000000) + " + " + str.tostring(str.format("{0,number, ###,###,###,###,###.## }", volume)))
else if _dailyvolume >= 1000000
_volumetext := str.tostring(str.format("{0,number, ###.## M }", _dailyvolume / 1000000) + " + " + str.tostring(str.format("{0,number, ###,###,###,###,###.## }", volume)))
else if _dailyvolume >= 1000
_volumetext := str.tostring(str.format("{0,number, ###.## k }", _dailyvolume / 1000) + " + " + str.tostring(str.format("{0,number, ###,###,###,###,###.## }", volume)))
else
_volumetext := str.tostring(str.format("{0,number, ###,###,###,###,### }", _dailyvolume) + " + " + str.tostring(str.format("{0,number, ###,###,###,###,###.## }", volume)))
dhi = plot(not timeframe.isdwm?d_high:na, title="Persistent Daily High", color=color.rgb(255,0,0,50))
dlw = plot(not timeframe.isdwm?d_low:na, title="Persistent Daily Low" , color=color.rgb(0,255,0,50))
hi = plot(_highlowswitch1?m_high:na, title="High Line #1", color=color.rgb(255,0,0,50))
lw = plot(_highlowswitch1?m_low:na, title="Low Line #1" , color=color.rgb(0,255,0,50))
whi = plot(_highlowswitch2?w_high:na, title="High Line #2", color=color.rgb(255,0,0,50))
wlw = plot(_highlowswitch2?w_low:na, title="Low Line #2", color=color.rgb(0,255,0,50))
mhi = plot(_highlowswitch3?_high:na, title="High Line #3", color=color.rgb(255,0,0,50))
mlw = plot(_highlowswitch3?_low:na, title="Low Line #3", color=color.rgb(0,255,0,50))
float _spread = (m_high - m_low)
float _upside = (((m_high - close)/100) / _spread) * 100
float _downside = (((close - m_low)/100) / _spread) * 100
if barstate.islast
if _above
_dailychange := _dailychangepos
if _below
_dailychange := _dailychangeneg
//TABLES
// _tbl1 := table.new(position.bottom_left, 50, 50, bgcolor=color.rgb(0,0,0,100), frame_color=na, frame_width=1, border_color=color.new(color.white, 25), border_width=1)
_tbl2 := table.new(position.top_right, 50, 50, bgcolor=color.rgb(0,0,0,100), frame_color=na, frame_width=1, border_color=color.new(color.white, 25), border_width=1)
table.cell(_tbl2, 0, 0, text= " " + string(syminfo.ticker) + " " + string(timeframe.period) + " ",
text_color=color.new(color.white, 0), text_size=size.small)
table.cell(_tbl2, 1, 0, text= " " + str.tostring(str.format("{0,number, $#,###,###.##########}", _currentprice)) + " ",
text_color=close>=_open?color.rgb(0,255,0,0):close<=_open?color.rgb(255,0,0,0):color.white, text_size=size.small)
table.cell(_tbl2, 2, 0, text=_dailychange?_below?" " + str.tostring(str.format("{0,number,###.### % ▼}", _dailychange)) + " "
:_dailychange?_above? " " + str.tostring(str.format("{0,number,###.### % ▲}", _dailychange)) + " "
:_dailychange == 0? " " + str.tostring(str.format("{0,number,###.### % -}", _dailychange)) + " ":na:na:na,
text_color=_above?color.rgb(0,255,0,0):_below?color.rgb(255,0,0,0):color.white, text_size=size.small)
table.cell(_tbl2, 3, 0, text= " " + string("RSI:") + " " + str.tostring(str.format("{0,number,##.##}", _rsi)) + " ",
text_color=color.new(color.white, 0), text_size=size.small)
table.cell(_tbl2, 1, 1, text= " " + str.tostring(str.format("{0,number, $###,###.########}", _spread)) + " " + string("Spread") + " ",
text_color=color.new(color.white, 0), bgcolor = color.rgb(0,255,0,85), text_size=size.tiny)
table.cell(_tbl2, 1, 2, text= " " + str.tostring(str.format("{0,number, #.#%}", _upside)) + " " + string("Upside") + " ",
text_color=color.new(color.white, 0), text_size=size.tiny)
table.cell(_tbl2, 1, 3, text= " " + str.tostring(str.format("{0,number, #.#%}", _downside)) + " " + string("Downside") + " ",
text_color=color.new(color.white, 0), text_size=size.tiny)
table.cell(_tbl2, 2, 1, text= " " + str.tostring(str.format("{0,number}", _emainput1)) + " " + string("EMA") + " ",
text_color=color.new(color.white, 0), bgcolor = color.rgb(255,255,0,85), text_size=size.tiny)
table.cell(_tbl2, 2, 2, text= " " + str.tostring(str.format("{0,number}", _emainput2)) + " " + string("EMA") + " ",
text_color=color.new(color.white, 0), bgcolor = color.rgb(255,255,0,85), text_size=size.tiny)
table.cell(_tbl2, 2, 3, text= " " + string("Volume:") + " " + _volumetext + " ",
text_color=color.new(color.white, 0), text_size=size.tiny)
//LABELS
_lbl2 := label.new(_highlowswitch1?bar_index:na, h1, str.tostring(str.format("{0,number, $#,###,###.########## }", h1)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl2[1])
_lbl3 := label.new(_highlowswitch1?bar_index:na, l1, str.tostring(str.format("{0,number, $#,###,###.########## }", l1)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl3[1])
_lbl4 := label.new(_highlowswitch2?bar_index:na, h4, str.tostring(str.format("{0,number, $#,###,###.########## }", h4)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl4[1])
_lbl5 := label.new(_highlowswitch2?bar_index:na, l4, str.tostring(str.format("{0,number, $#,###,###.########## }", l4)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl5[1])
_lbl6 := label.new(_highlowswitch3?bar_index:na, h2, str.tostring(str.format("{0,number, $#,###,###.########## }", h2)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl6[1])
_lbl7 := label.new(_highlowswitch3?bar_index:na, l2, str.tostring(str.format("{0,number, $#,###,###.########## }", l2)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl7[1])
_lblema1 := label.new(_ema3switch?bar_index:na, _ema3, close<0.0000?str.tostring(str.format("{0,number, $#,###,###.############## }", _ema3)):str.tostring(str.format("{0,number, $#,###,###.#### }", _ema3)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lblema1[1])
_lblema2 := label.new(_ema4switch?bar_index:na, _ema4, close<0.0000?str.tostring(str.format("{0,number, $#,###,###.############## }", _ema4)):str.tostring(str.format("{0,number, $#,###,###.#### }", _ema4)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lblema2[1])
_lblema3 := label.new(_ema5switch?bar_index:na, _ema5, close<0.0000?str.tostring(str.format("{0,number, $#,###,###.############## }", _ema5)):str.tostring(str.format("{0,number, $#,###,###.#### }", _ema5)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lblema3[1])
_lblema4 := label.new(_ema1switch?bar_index:na, _ema1, close<0.0000?str.tostring(str.format("{0,number, $#,###,###.############## }", _ema1)):str.tostring(str.format("{0,number, $#,###,###.#### }", _ema1)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lblema4[1])
_lblema5 := label.new(_ema2switch?bar_index:na, _ema2, close<0.0000?str.tostring(str.format("{0,number, $#,###,###.############## }", _ema2)):str.tostring(str.format("{0,number, $#,###,###.#### }", _ema2)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lblema5[1])
_lbl8 := label.new(not timeframe.isdwm?bar_index:na, d_high, str.tostring(str.format("{0,number, $#,###,###.########## }", d_high)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl8[1])
_lbl9 := label.new(not timeframe.isdwm?bar_index:na, d_low, str.tostring(str.format("{0,number, $#,###,###.########## }", d_low)),
color=color.rgb(0,0,0,100),textcolor=color.white, style=label.style_label_left, size=size.small)
label.delete(_lbl9[1])
plot(_ema1switch?_ema1:na, title="EMA #1", color=#00fff9, linewidth=1)
plot(_ema2switch?_ema2:na, title="EMA #2", color=#00fff9, linewidth=1)
plot(_ema3switch?_ema3:na, title="User EMA #1", color=#ff0000, linewidth=1)
plot(_ema4switch?_ema4:na, title="User EMA #2", color=#ff0000, linewidth=1)
plot(_ema5switch?_ema5:na, title="User EMA #3", color=#ff0000, linewidth=1)
_h1 = plot(high, display = display.none)
_l1 = plot(low, display = display.none)
_cl1 = plot(close, display = display.none)
fill(hi,_h1, color = color.rgb(255,0,127.5,80))
fill(lw,_l1, color = color.rgb(0,127.5,255,80))
fill(_h1, _cl1, color = _highlowswitch3?color.rgb(255,0,127.5,80):na)
fill(_l1,_cl1, color = _highlowswitch3?color.rgb(0,127.5,255,80):na)
plotcandle(_candlesticks?open:na, high, low, close, title="Green Candles", color=_bullishengulf, wickcolor=_greenw, bordercolor=_green)
plotcandle(_candlesticks?open:na, high, low, close, title="Red Candles", color=_bearishengulf, wickcolor=_redw, bordercolor=_red)
|
Minervini Qualifier | https://www.tradingview.com/script/zDQQ3mFb-Minervini-Qualifier/ | Lantzwat | https://www.tradingview.com/u/Lantzwat/ | 753 | 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/
// © Lantzwat
//@version=5
indicator("Minervini Qualifier", "MQ")
// From Mark Minervini's book "Trade Like a Stock Market Wizard"
// Trend Template
// 1. The current stock price is above both the 150-day (30-week) and the 200-day
// (40-week) moving average price lines.
// 2. The 150-day moving average is above the 200-day moving average.
// 3. The 200-day moving average line is trending up for at least 1 month (preferably
// 4–5 months minimum in most cases).
// 4. The 50-day (10-week) moving average is above both the 150-day and 200-day
// moving averages.
// 5. The current stock price is trading above the 50-day moving average.
// 6. The current stock price is at least 30 percent above its 52-week low. (Many of
// the best selections will be 100 percent, 300 percent, or greater above their
// 52-week low before they emerge from a solid consolidation period and mount
// a large scale advance.)
// 7. The current stock price is within at least 25 percent of its 52-week high (the
// closer to a new high the better).
// 8. The relative strength ranking (as reported in Investor’s Business Daily) is no
// less than 70, and preferably in the 80s or 90s, which will generally be the case
// with the better selections
RefTickerId = input.symbol("SP:SPX+NASDAQ_DLY:NDX+DJ:DWCPF", title="Reference index", tooltip = "e.g. SPX/NDX/RUT/DWCPF or combinations of it")
bCriteria = input.bool(true,"Show qualifiying criterias seperately")
bStrength = input.bool(true,"Calculate relative strength")
bSMA = input.bool(true,"Show SMA lines")
bBuysell = input.bool(true,"Draw verical buy signal lines")
var table infoTable = table.new(position.top_right, 1, 2, border_width = 0)
f_fillCell(_table, _column, _row, _value) =>
_cellText = str.tostring(_value, "#.##")
table.cell(_table, _column, _row, _cellText, text_color = color.yellow)
f_fillCell2(_table, _column, _row, _value) =>
_cellText = _value
table.cell(_table, _column, _row, _cellText, text_color = color.yellow)
bShowText = input(false, "ShowLabel")
_label(bool showlabel, float yPosition, string Name) =>
var TEXTCOLOR = color.new(color.white,50)
if barstate.islast and showlabel
offset = str.length(Name)/2 + 1
var _label = label.new(bar_index+offset, y=yPosition-2, text=Name, color=color.white, textcolor=TEXTCOLOR, style=label.style_none, size=size.tiny, textalign=text.align_left, text_font_family=font.family_monospace)
label.set_x(_label, bar_index+offset)
// SMA/EMA Calculation
s_close = request.security(syminfo.tickerid, 'D', close)
low_of_52week = ta.lowest(s_close,260)
high_of_52week = ta.highest(s_close,260)
//sma5 = ta.sma(s_close,5)
sma20 = ta.sma(s_close, 20)
sma50 = ta.sma(s_close, 50)
sma150 = ta.sma(s_close, 150)
sma200 = ta.sma(s_close, 200)
//Condition 1: Current Price > 150 SMA and > 200 SMA
condition_1 = s_close > sma150 and s_close > sma200
// # Condition 2: 150 SMA > 200 SMA
condition_2 = sma150 > sma200
// # Condition 3: 200 SMA trending up for at least 1 month, enhanced for 5 months
condition_3 = ta.rising(sma200,30) //sma200 > sma200[30] //sma200 > sma200[10] and sma200[10] > sma200[20] and sma200[20] > sma200[30]
condition_3_enhanced = ta.rising(sma200,5*30) //condition_3 and sma200[30] > sma200[60] and sma200[60] > sma200[90] and sma200[90] > sma200[120] and sma200[120] > sma200[150]
// # Condition 4: 50 SMA> 150 SMA and 50 SMA> 200 SMA
condition_4 = sma50 > sma150 and sma50 > sma200
// # Condition 5: Current Price > 50 SMA
condition_5 = s_close > sma50
// # Condition 6: Current Price is at least 30% above 52 week low
condition_6 = s_close >= (1.3 * low_of_52week) // 30% above 52 week low
condition_6_plus = s_close >= (1.7 * low_of_52week) // 70% above 52 week low
// # Condition 7: Current Price is within 25% of 52 week high
condition_7 = s_close >= (0.75 * high_of_52week)
condition_minervini = condition_1 and condition_2 and condition_3 and condition_4 and condition_5 and condition_6 and condition_7
condition_minervini_light = condition_1 and condition_2 and condition_3 and condition_4 and condition_6 and condition_7
condition_minervini_enhanced = condition_1 and condition_2 and condition_3_enhanced and condition_4 and condition_5 and condition_6 and condition_7
condCol = condition_minervini_light ? condition_minervini ? condition_minervini_enhanced ? color.new(color.blue,0) : color.new(color.green, 0) : color.new(color.yellow, 0) : na
// draw vertical line when SMA20 crossover and the conditions are fullfilled
buy = ta.crossover(s_close,sma20) and condition_minervini_light
plot(bBuysell and buy ? 28 : na,color=color.new(color.green,50), linewidth=1,style = plot.style_histogram)
plot(bBuysell and buy ? -45 : na,color=color.new(color.green,50), linewidth=1,style = plot.style_histogram)
// calculate and draw envelope curve with condition matching fillcolor
lb = last_bar_index < 200 ? last_bar_index : 200
range_m = sma20-s_close
factor = 20 / (ta.highest(range_m,lb)-ta.lowest(range_m,lb))
range_m := range_m * factor
condCol2 = range_m < 0 ? color.new(color.blue,0) : color.new(color.red,50)
mp1 = plot(range_m , title = "SMA20 + conditions match", color=condCol2, linewidth=2)
mp2 = plot(range_m * -1 , title = "SMA20 + conditions match", color=condCol2, linewidth=2)
fill(mp1, mp2, color=condCol)
// Plot flatline SMAs
FirstlineSMA = input.int(20,"First line SMA")
sma20a = ta.sma(s_close,FirstlineSMA)
//plot(bSMA ? 32 : na, color = (sma5 - sma20) > 0? color.blue : color.red, linewidth = 3, title = "SMA5/SMA20 crossover")
plot(bSMA ? 28 : na, color = sma20a < s_close ? color.green : color.red, linewidth = 3, title = "SMA20 or so")
plot(bSMA ? 24 : na, color = sma50 < s_close ? color.green : color.red, linewidth = 3, title = "SMA50")
plot(bSMA ? 20 : na, color = sma150 < s_close ? color.green : color.red, linewidth = 3, title = "SMA150")
plot(bSMA ? 16 : na, color = sma200 < s_close ? color.green : color.red, linewidth = 3, title = "SMA200")
// Plot Minervini condition lines
plot (bCriteria ? -15 : na, linewidth = 3, title = "close>150MA and >200MA" , color = condition_1 ? color.new(color.blue,0) : color.new(color.red,0))
plot (bCriteria ? -20 : na, linewidth = 3, title = "150MA>200MA" , color = condition_2 ? color.new(color.blue,0) : color.new(color.red,0))
plot (bCriteria ? -25 : na, linewidth = 3, title = "200MA uptrending 1+month" , color = condition_3 ? color.new(color.blue,0) : color.new(color.red,0))
plot (bCriteria and condition_3_enhanced ? -25 : na, linewidth = 6, title = "200MA uptrending 5+month", color = condition_3_enhanced ? color.new(#2521f3, 0) : color.new(color.red,0))
plot (bCriteria ? -30 : na, linewidth = 3, title = "50MA>150MA and 50MA>200MA" , color = condition_4 ? color.new(color.blue,0) : color.new(color.red,0))
plot (bCriteria ? -35 : na, linewidth = 3, title = "close>50MA" , color = condition_5 ? color.new(color.green,0) : color.new(color.red,0))
plot (bCriteria ? -40 : na, linewidth = 3, title = "close 30%+ above 52-week low", color = condition_6 ? color.new(color.blue,0) : color.new(color.red,0))
plot (bCriteria and condition_6_plus ? -40 : na, linewidth = 6, title = "close 70%+ above 52-week low", color = condition_6_plus ? color.new(color.green, 0) : color.new(color.red,0))
plot (bCriteria ? -45 : na, linewidth = 3, title = "close within 25% 52-week high", color = condition_7 ? color.new(color.blue,0) : color.new(color.red,0))
// Create label next to the lines to ease identification
//_label(bShowText, 32, "SMA5/SMA20 crossover")
_label(bShowText, 28, "SMA20 ")
_label(bShowText, 24 ,"SMA50 ")
_label(bShowText, 20 ,"SMA150")
_label(bShowText, 16 ,"SMA200")
_label(bShowText, -15, "close>150MA and >200MA" )
_label(bShowText, -20, "150MA>200MA " )
_label(bShowText, -25, "200MA uptrending 1+month" )
_label(bShowText, -30, "50MA>150MA and 50MA>200MA " )
_label(bShowText, -35, "close>50MA " )
_label(bShowText, -40, "close 30%+ above 52-week low" )
_label(bShowText, -45, "close within 25% 52-week high " )
if not timeframe.isdaily
f_fillCell2(infoTable, 0, 1, "only valid on daily timeframes")
// Calculate relative strength, just one way to calculate it
// value > 100, better performance compared to reference index
// value < 100, worse performance compared to reference index
// ...over the period of one year, last quarter double counted
quarter_performance(closes, n) =>
length = math.min(last_bar_index, (252/4))
start = (n-1) * length
stop = n * length
pct_cum = 0.0
for i=start to stop -1
pct_cum := pct_cum + closes[i]
pct_cum
strength(closes) =>
quarters1 = quarter_performance(closes ,1)
quarters2 = quarter_performance(closes ,2)
quarters3 = quarter_performance(closes ,3)
quarters4 = quarter_performance(closes ,4)
ret = 0.4*quarters1 + 0.2*quarters2 + 0.2*quarters3 + 0.2*quarters4
ret
relative_strength(closes, ref_close) =>
rs_stock = strength(closes)
rs_ref = strength(ref_close)
rs = (1 + rs_stock) / (1 + rs_ref) * 100
rs := math.round(rs,2)
rs
s_ref_close = request.security(RefTickerId, 'D', close)
relStrength = 0.0
if bStrength
s_close_pct = (s_close - s_close[1]) / s_close[1]
s_ref_close_pct = (s_ref_close - s_ref_close[1]) / s_ref_close[1]
relStrength := relative_strength(s_close_pct,s_ref_close_pct)
f_fillCell(infoTable, 0, 0, relStrength)
// alerts ----------------------------------------------
alertcondition(condition_minervini and not condition_minervini[1],"MQ - All Miverini conditions match", "All Minervini conditions match")
alertcondition(condition_minervini_light and not condition_minervini_light[1],"MQ - Miverini (light) conditions match", "All Minervini light conditions matched")
alertcondition(not condition_minervini_light and condition_minervini_light[1],"MQ - Miverini conditions unmatch", "At least one Minervini condition doesn't match")
alertcondition(buy,"MQ - buy signal", "SMA20 crossover and Minervini conditions match")
UptrendAlert = input.int(70, "Alertcondition when close xx% above 52week low", minval = 30)
Percent_above_52weeklow = ((s_close * 100) / low_of_52week) - 100 // Strong uptrend signal when close is 70%+ above 52week low
alertcondition(Percent_above_52weeklow >= UptrendAlert, "MQ - in strong uptrend mode", "close is xx% (70% default value) above 52week low")
|
GDP Breakdown | https://www.tradingview.com/script/UJAUBU5o-GDP-Breakdown/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 7 | 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/
// © EsIstTurnt
//@version=5
indicator("GDP Breakdown",overlay=false,shorttitle='GDPB')
//Not every country provides all data needed, only countries providing data for all sub sections below are able to be selected below.
local=input.string('US',title='Select Country',options=['AM','AR','AZ','BD','BH','BN','BR','BT','BY','CA','CR','CV','EC','GE','GH','GN','JM','JO','JP','KE','KH','KZ','LA','LK','LS','MA','MW','MX','MZ','NA','NG','NL','NP','NZ','OM','PE','PH','PS','QA','SE','SV','TW','UA','US','VN','XK'])
var string agr= local+"GDPA "
var string con= local+"GDPC "
var string ser= local+"GDPS "
var string pub= local+"GDPPA "
var string min= local+"GDPMIN"
var string uti= local+"GDPU "
var string man= local+"GDPMAN"
var string gdp= local+"GDP "
total=input.bool(false,'Show Total GDP')
agriculture =request.security(agr,'M',close)
construction =request.security(con,'M',close)
manufacturing=request.security(man,'M',close)
mining =request.security(min,'M',close)
publicadmin =request.security(pub,'M',close)
services =request.security(ser,'M',close)
utilities =request.security(uti,'M',close)
combined =total?request.security(gdp,'M',close):na
plot(agriculture ,color=color.green ,title='Agriculture ',linewidth=1)
plot(construction ,color=color.orange ,title='Construction ',linewidth=1)
plot(manufacturing,color=color.blue ,title='Manufacturing ',linewidth=1)
plot(mining ,color=color.gray ,title='Mining ',linewidth=1)
plot(publicadmin ,color=color.fuchsia,title='Public Administration ',linewidth=1)
plot(services ,color=color.red ,title='Services ',linewidth=1)
plot(utilities ,color=color.yellow ,title='Utilities ',linewidth=1)
plot(combined ,color=color.white ,title='Total ',linewidth=2) |
Pro Trading Art - Top N Candle's Gainers/Losers(1-40) | https://www.tradingview.com/script/QJAQyFeQ-Pro-Trading-Art-Top-N-Candle-s-Gainers-Losers-1-40/ | protradingart | https://www.tradingview.com/u/protradingart/ | 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/
// © protradingart
//@version=5
indicator("Pro Trading Art - Top N Candle's Gainers/Losers(1-40)", "PTA - Top N Candle's Gainers/Losers(1-40)", overlay = true)
timeframe = input.timeframe("", "Timeframe")
period = input.int(5, "Period")
type = input.string("Gainers", "Top", options = ['Gainers', "Losers"])
location = input.string("Top", "Table Location", options = ['Top', "Middle", "Bottom"])
order = type == "Gainers"? order.ascending : order.descending
tableLocation = location == "Top" ? position.top_right : location == "Middle" ? position.middle_right : position.bottom_right
topGainer(symbol, tf, period, symbolArray, changeArray)=>
[current, prev] = request.security(symbol, tf, [close, close[period]])
changePer = (current-prev)/prev*100
array.push(symbolArray, symbol)
array.push(changeArray, changePer)
gticker = '=============== Watchlist ==============='
symbol1 = input.symbol(defval = "NSE:ACC", title="Symbol1", group=gticker)
symbol2 = input.symbol(defval = "NSE:ADANIENT", title="Symbol2", group=gticker)
symbol3 = input.symbol(defval = "NSE:ADANIGREEN", title="Symbol3", group=gticker)
symbol4 = input.symbol(defval = "NSE:ADANIPORTS", title="Symbol4", group=gticker)
symbol5 = input.symbol(defval = "NSE:ADANITRANS", title="Symbol5", group=gticker)
symbol6 = input.symbol(defval = "NSE:AMBUJACEM", title="Symbol6", group=gticker)
symbol7 = input.symbol(defval = "NSE:APOLLOHOSP", title="Symbol7", group=gticker)
symbol8 = input.symbol(defval = "NSE:ASIANPAINT", title="Symbol8", group=gticker)
symbol9 = input.symbol(defval = "NSE:DMART", title="Symbol9", group=gticker)
symbol10 = input.symbol(defval = "NSE:AXISBANK", title="Symbol10", group=gticker)
symbol11 = input.symbol(defval = "NSE:BAJAJ_AUTO", title="Symbol11", group=gticker)
symbol12 = input.symbol(defval = "NSE:BAJFINANCE", title="Symbol12", group=gticker)
symbol13 = input.symbol(defval = "NSE:BAJAJFINSV", title="Symbol13", group=gticker)
symbol14 = input.symbol(defval = "NSE:BAJAJHLDNG", title="Symbol14", group=gticker)
symbol15 = input.symbol(defval = "NSE:BANDHANBNK", title="Symbol15", group=gticker)
symbol16 = input.symbol(defval = "NSE:BANKBARODA", title="Symbol16", group=gticker)
symbol17 = input.symbol(defval = "NSE:BERGEPAINT", title="Symbol17", group=gticker)
symbol18 = input.symbol(defval = "NSE:BPCL", title="Symbol18", group=gticker)
symbol19 = input.symbol(defval = "NSE:BHARTIARTL", title="Symbol19", group=gticker)
symbol20 = input.symbol(defval = "NSE:BIOCON", title="Symbol20", group=gticker)
symbol21 = input.symbol(defval = "NSE:BOSCHLTD", title="Symbol21", group=gticker)
symbol22 = input.symbol(defval = "NSE:BRITANNIA", title="Symbol22", group=gticker)
symbol23 = input.symbol(defval = "NSE:CHOLAFIN", title="Symbol23", group=gticker)
symbol24 = input.symbol(defval = "NSE:CIPLA", title="Symbol24", group=gticker)
symbol25 = input.symbol(defval = "NSE:COALINDIA", title="Symbol25", group=gticker)
symbol26 = input.symbol(defval = "NSE:COLPAL", title="Symbol26", group=gticker)
symbol27 = input.symbol(defval = "NSE:DLF", title="Symbol27", group=gticker)
symbol28 = input.symbol(defval = "NSE:DABUR", title="Symbol28", group=gticker)
symbol29 = input.symbol(defval = "NSE:DIVISLAB", title="Symbol29", group=gticker)
symbol30 = input.symbol(defval = "NSE:DRREDDY", title="Symbol30", group=gticker)
symbol31 = input.symbol(defval = "NSE:EICHERMOT", title="Symbol31", group=gticker)
symbol32 = input.symbol(defval = "NSE:NYKAA", title="Symbol32", group=gticker)
symbol33 = input.symbol(defval = "NSE:GAIL", title="Symbol33", group=gticker)
symbol34 = input.symbol(defval = "NSE:GLAND", title="Symbol34", group=gticker)
symbol35 = input.symbol(defval = "NSE:GODREJCP", title="Symbol35", group=gticker)
symbol36 = input.symbol(defval = "NSE:GRASIM", title="Symbol36", group=gticker)
symbol37 = input.symbol(defval = "NSE:HCLTECH", title="Symbol37", group=gticker)
symbol38 = input.symbol(defval = "NSE:HDFCAMC", title="Symbol38", group=gticker)
symbol39 = input.symbol(defval = "NSE:HDFCBANK", title="Symbol39", group=gticker)
symbol40 = input.symbol(defval = "NSE:HDFCLIFE", title="Symbol40", group=gticker)
symbol = array.new_string(na)
changePer = array.new_float(na)
topGainer(symbol1, timeframe, period, symbol, changePer)
topGainer(symbol2, timeframe, period, symbol, changePer)
topGainer(symbol3, timeframe, period, symbol, changePer)
topGainer(symbol4, timeframe, period, symbol, changePer)
topGainer(symbol5, timeframe, period, symbol, changePer)
topGainer(symbol6, timeframe, period, symbol, changePer)
topGainer(symbol7, timeframe, period, symbol, changePer)
topGainer(symbol8, timeframe, period, symbol, changePer)
topGainer(symbol9, timeframe, period, symbol, changePer)
topGainer(symbol10, timeframe, period, symbol, changePer)
topGainer(symbol11, timeframe, period, symbol, changePer)
topGainer(symbol12, timeframe, period, symbol, changePer)
topGainer(symbol13, timeframe, period, symbol, changePer)
topGainer(symbol14, timeframe, period, symbol, changePer)
topGainer(symbol15, timeframe, period, symbol, changePer)
topGainer(symbol16, timeframe, period, symbol, changePer)
topGainer(symbol17, timeframe, period, symbol, changePer)
topGainer(symbol18, timeframe, period, symbol, changePer)
topGainer(symbol19, timeframe, period, symbol, changePer)
topGainer(symbol20, timeframe, period, symbol, changePer)
topGainer(symbol21, timeframe, period, symbol, changePer)
topGainer(symbol22, timeframe, period, symbol, changePer)
topGainer(symbol23, timeframe, period, symbol, changePer)
topGainer(symbol24, timeframe, period, symbol, changePer)
topGainer(symbol25, timeframe, period, symbol, changePer)
topGainer(symbol26, timeframe, period, symbol, changePer)
topGainer(symbol27, timeframe, period, symbol, changePer)
topGainer(symbol28, timeframe, period, symbol, changePer)
topGainer(symbol29, timeframe, period, symbol, changePer)
topGainer(symbol30, timeframe, period, symbol, changePer)
topGainer(symbol31, timeframe, period, symbol, changePer)
topGainer(symbol32, timeframe, period, symbol, changePer)
topGainer(symbol33, timeframe, period, symbol, changePer)
topGainer(symbol34, timeframe, period, symbol, changePer)
topGainer(symbol35, timeframe, period, symbol, changePer)
topGainer(symbol36, timeframe, period, symbol, changePer)
topGainer(symbol37, timeframe, period, symbol, changePer)
topGainer(symbol38, timeframe, period, symbol, changePer)
topGainer(symbol39, timeframe, period, symbol, changePer)
topGainer(symbol40, timeframe, period, symbol, changePer)
sortKeyValue(key, value, order=order.ascending)=>
if array.size(key) == array.size(value)
sortedKey= array.new_string(na)
sortedIndices = array.sort_indices(value, order)
sortedValue = array.new_float(na)
for i = 0 to array.size(key) - 1
index = array.get(sortedIndices, i)
array.push(sortedKey, array.get(key, index))
array.push(sortedValue, array.get(value, index))
[sortedKey, sortedValue]
[sortedKey, sortedValue] = sortKeyValue(symbol, changePer, order)
if barstate.islast
size = array.size(sortedKey)
if size > 0
var table = table.new(position = tableLocation, columns = size + 2, rows = 3, bgcolor = color.yellow, border_width = 1, border_color=color.black)
if barstate.islast
table.cell(table_id = table, column = 0, row = 0, text = "Size")
table.cell(table_id = table, column = 1, row = 0, text = "Index")
table.cell(table_id = table, column = 0, row = 1, text = str.tostring(size))
table.cell(table_id = table, column = 1, row = 1, text = "Value")
for i = 0 to size - 1
table.cell(table_id = table, column = i + 2, row = 0, text = str.tostring(size-i))
table.cell(table_id = table, column = i + 2, row = 1, text = str.tostring(array.get(sortedKey, i)))
table.cell(table_id = table, column = i + 2, row = 2, text = str.tostring(array.get(sortedValue, i), format.percent))
else
var table = table.new(position = tableLocation, columns = 2, rows = 3, bgcolor = color.yellow, border_width = 1, border_color=color.black)
if barstate.islast
table.cell(table_id = table, column = 0, row = 0, text = "Size")
table.cell(table_id = table, column = 1, row = 0, text = "Message")
table.cell(table_id = table, column = 0, row = 1, text = str.tostring(size))
table.cell(table_id = table, column = 1, row = 1, text = "No element in your array", text_color=color.red)
|
Intrabar Efficiency Ratio | https://www.tradingview.com/script/o8tRZCzT-Intrabar-Efficiency-Ratio/ | TradingView | https://www.tradingview.com/u/TradingView/ | 487 | 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/
// © TradingView
//@version=5
indicator("Intrabar Efficiency Ratio", precision = 4)
// Intrabar Efficiency Ratio indicator
// v2, 2023.03.25
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/Time/4 as PCtime
import PineCoders/lower_tf/4 as PCltf
//#region ———————————————————— Constants and Inputs
// ————— Constants
// Colors
color AQUA = color.aqua
color FUCHSIA = color.fuchsia
color GRAY = #80808080
color GRAY_LT = #f5f3f3
color LIME = color.lime
color MAROON = color.maroon
color ROYAL = #3BB3E4
color ROSE = #FF0080
color TEAL = color.teal
color WHITE = color.white
color YELLOW = color.yellow
// MAs
string MA01 = "Simple"
string MA02 = "Exponential"
string MA03 = "Wilder (RMA)"
string MA04 = "Weighted"
string MA05 = "Volume-Weighted"
string MA06 = "Arnaud Legoux"
string MA07 = "Hull"
// LTF distinction
string LTF1 = "Covering most chart bars (least precise)"
string LTF2 = "Covering some chart bars (less precise)"
string LTF3 = "Covering less chart bars (more precise)"
string LTF4 = "Covering few chart bars (very precise)"
string LTF5 = "Covering the least chart bars (most precise)"
string LTF6 = "~12 intrabars per chart bar"
string LTF7 = "~24 intrabars per chart bar"
string LTF8 = "~50 intrabars per chart bar"
string LTF9 = "~100 intrabars per chart bar"
string LTF10 = "~250 intrabars per chart bar"
// Tooltips
string TT_DT = "Three display options are available:
\n• 'Line' displays an MA of IER of the selected type over the medium length number of bars.
\n• 'Candles' displays candles using the short and long MAs.
\n• 'Circles' uses the three MAs."
string TT_LTF = "Your selection here controls how many intrabars will be analyzed for each chart bar.
The more intrabars you analyze, the more precise the calculations will be,
but the less chart bars will be covered by the indicator's calculations because a maximum of 100K intrabars can be analyzed.\n\n
The first five choices determine the lower timeframe used for intrabars using how much chart coverage you want.
The last five choices allow you to select approximately how many intrabars you want analyzed per chart bar."
string TT_CDL = "[Down body, down wick, up body, up wick]"
string TT_CIR = "[Extreme low, down color, up color, extreme high]"
string TT_RW = "Applies weighting to IER values based on the relative size of the close-to-close value over the specified number of bars."
string TT_LEN = "These are the short, medium and long lengths used to calculate the MAs. Different display modes use different MAs. Only the 'Circles' mode uses all three."
// Strings
string TAB_TXT = "Uses intrabars at {0}\nAvg intrabars per chart bar: {1,number,#.#}\nChart bars covered: {2} of {3}"
// Error Messages
string NI_ERR1 = "No intrabar information exists at the '{0}' timeframe."
string MA_ERR1 = "The length of the short MA must be less than or equal to that of the medium MA."
string MA_ERR2 = "The length of the medium MA must be less than or equal to that of the long MA."
// ————— Inputs
string GRP1 = "Visuals"
string displayTypeInput = input.string("Line", "Display", group = GRP1, inline = "10", options = ["Line", "Candles", "Circles"], tooltip = TT_DT)
color lineColorInput = input.color(AQUA, "Line ", group = GRP1, inline = "13")
color bearBodyInput = input.color(FUCHSIA, "Candles", group = GRP1, inline = "11", tooltip = TT_CDL)
color bearWickInput = input.color(MAROON, "", group = GRP1, inline = "11")
color bullBodyInput = input.color(LIME, "", group = GRP1, inline = "11")
color bullWickInput = input.color(TEAL, "", group = GRP1, inline = "11")
color lowColorInput = input.color(YELLOW, "Circles ", group = GRP1, inline = "12", tooltip = TT_CIR)
color bearColorInput = input.color(ROSE, "", group = GRP1, inline = "12")
color bullColorInput = input.color(ROYAL, "", group = GRP1, inline = "12")
color highColorInput = input.color(LIME, "", group = GRP1, inline = "12")
bool showInfoBoxInput = input.bool(true, "Show information box ", group = GRP1)
string infoBoxSizeInput = input.string("small", "Size ", group = GRP1, inline = "14", options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", group = GRP1, inline = "14", options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", group = GRP1, inline = "14", options = ["left", "center", "right"])
color infoBoxColorInput = input.color(GRAY, "", group = GRP1, inline = "14")
color infoBoxTxtColorInput = input.color(GRAY_LT, "T", group = GRP1, inline = "14")
string GRP2 = "Settings"
string ltfModeInput = input.string(LTF3, "Intrabar Precision", group = GRP2, options = [LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10], tooltip = TT_LTF)
string maTypeInput = input.string(MA06, "MA Type ", group = GRP2, inline = "20", options = [MA01, MA02, MA03, MA04, MA05, MA06, MA07])
int shortLengthInput = input.int(10, "MA lengths: S", group = GRP2, inline = "21")
int midLengthInput = input.int(20, "M", group = GRP2, inline = "21")
int longLengthInput = input.int(40, "L", group = GRP2, inline = "21", tooltip = TT_LEN)
bool rankWeightInput = input.bool(false, "Weigh using relative close changes", group = GRP2, inline = "22")
int rankLengthInput = input.int(100, "", group = GRP2, inline = "22", tooltip = TT_RW)
//#endregion
//#region ———————————————————— Functions
//@function Returns the `type` MA of the `src` over the `length`.
//@param src (series float) The source value used to calculate the MA.
//@param length (simple int) The length value used to calculate the MA.
//@param type (simple string) The type of MA required (uses constants that must be defined earlier in the script).
//@returns (series float) The MA value.
ma(series float src, simple int length, simple string type) =>
float result = switch type
MA01 => ta.sma( src, length)
MA02 => ta.ema( src, length)
MA03 => ta.rma( src, length)
MA04 => ta.wma( src, length)
MA05 => ta.vwma(src, length)
MA06 => ta.alma(src, length, 0.85, 6)
MA07 => ta.hma( src, length)
=> na
// @function Determines a color based on the 100 bar percent rank of the input `value`.
// @param value (series float) The value to determine the color.
// @returns (color) The output color (uses color variables that must be defined earlier in the script).
plotColor(series float value) =>
float percent = ta.percentrank(value, 100)
color result =
switch
percent > 90 => highColorInput
percent < 10 => lowColorInput
percent > 50 => bullColorInput
=> bearColorInput
//#endregion
//#region ———————————————————— Calculations
// Get the LTF corresponding to user's selection.
// NOTE
// This is a good example of a case where we declare a variable with `var` to improve the script's execution time.
// Declaring it this way calls the `ltf()` function only once, on the dataset's first bar.
// The `ltf()` function only needs to return a "simple string" for use in `request.security_lower_tf()`,
// which entails that its value cannot change on further bars, so it is more efficient to restrict its execution to the first bar.
// Also, because the function's code mostly manipulates strings, which the Pine runtime doesn't process as efficiently as numeric values, this speeds up the script.
var string ltfString = PCltf.ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10)
// ———— IER
// Get array of `close` to `close` changes in intrabars.
array<float> travels = request.security_lower_tf(syminfo.tickerid, ltfString, math.abs(ta.change(close)))
float totalTravels = travels.sum()
// Get the `close` to `close` change of the chart's last two bars.
float chartBarChange = nz(ta.change(close))
// Calculate a weight using the relative size of the `close` to `close` change.
float weight = rankWeightInput ? ta.percentrank(math.abs(chartBarChange), rankLengthInput) / 100.0 : 1.0
// Calculate IER and its MAs.
float ier = nz(chartBarChange / totalTravels) * weight
float maLong = ma(ier, longLengthInput, maTypeInput)
float maMid = ma(ier, midLengthInput, maTypeInput)
float maShort = ma(ier, shortLengthInput, maTypeInput)
// ———— Intrabar stats
[intrabars, chartBarsCovered, avgIntrabars] = PCltf.ltfStats(travels)
int chartBars = bar_index + 1
//#endregion
//#region ———————————————————— Visuals
// Display conditions.
bool candles = displayTypeInput == "Candles"
bool circles = displayTypeInput == "Circles"
bool maLine = displayTypeInput == "Line"
candlePlotDisplay = candles ? display.all - display.pane : display.none
candleDisplay = candles ? display.pane : display.none
circleDisplay = circles ? display.all : display.none
lineDisplay = maLine ? display.all : display.none
// IER candles.
float o = maLong
float h = math.max(ier, maLong, maShort)
float l = math.min(ier, maLong, maShort)
float c = maShort
color candleColor = c > o ? bullBodyInput : bearBodyInput
color wickColor = c > o ? bullWickInput : bearWickInput
plot(o, "IER Candle Open", candleColor, display = candlePlotDisplay)
plot(h, "IER Candle High", wickColor, display = candlePlotDisplay)
plot(l, "IER Candle Low", wickColor, display = candlePlotDisplay)
plot(c, "IER Candle Close", candleColor, display = candlePlotDisplay)
plotcandle(o, h, l, c, "IER candles", candleColor, wickColor, bordercolor = candleColor, display = candleDisplay)
// IER MAs.
plot(maLong, "Long MA", color.new(plotColor(maLong), 20), 2, plot.style_circles, display = circleDisplay)
plot(maMid, "Mid MA", color.new(plotColor(maMid), 10), 1, plot.style_circles, display = circleDisplay)
plot(maShort, "Short MA", color.new(plotColor(maShort), 0), 1, plot.style_circles, display = circleDisplay)
plot(maMid, "Mid MA", lineColorInput, 1, plot.style_line, display = lineDisplay)
hline(0)
// Key values in indicator values and the Data Window.
displayLocations = display.status_line + display.data_window
plot(ier, "Intrabar Efficiency Ratio", display = displayLocations)
plot(intrabars, "Intrabars in Chart Bar", display = displayLocations)
plot(avgIntrabars, "Avg. Intrabars", display = displayLocations)
plot(chartBarsCovered, "Chart Bars Covered", display = displayLocations)
plot(chartBars, "Total Chart Bars", display = displayLocations)
plot(totalTravels, "totalTravels", display = displayLocations)
plot(chartBarChange, "chartBarChange", display = displayLocations)
plot(weight, "weight", display = displayLocations)
// Information box.
if showInfoBoxInput
var table infoBox = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
string formattedLtf = PCtime.formattedNoOfPeriods(timeframe.in_seconds(ltfString) * 1000)
string txt = str.format(TAB_TXT, formattedLtf, avgIntrabars, chartBarsCovered, chartBars)
if barstate.isfirst
table.cell(infoBox, 0, 0, txt, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxColorInput)
else if barstate.islast
table.cell_set_text(infoBox, 0, 0, txt)
// Runtime errors.
if ta.cum(intrabars) == 0 and barstate.islast
runtime.error(str.format(NI_ERR1, ltfString))
else if shortLengthInput > midLengthInput
runtime.error(MA_ERR1)
else if midLengthInput > longLengthInput
runtime.error(MA_ERR2)
//#endregion
|
Margin Pressure Thresholds | https://www.tradingview.com/script/T5FENenR-Margin-Pressure-Thresholds/ | reees | https://www.tradingview.com/u/reees/ | 702 | 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/
// © reees
//@version=5
indicator("Margin Pressure Thresholds","MarginPressure",true,max_bars_back=500)
import reees/Draw/28 as draw
//-----------------------------------------
// inputs and globals
//-----------------------------------------
var i_lvl_l = input.float(0.0, "Long Liquidation Support Level", minval=0, group="Manual Level Entry",
tooltip="Choose a strong support level, i.e. a level below which a margin trader is likely to want his/her liquidation level")
var i_lvl_s = input.float(0.0, "Short Liquidation Resistance Level", minval=0, group="Manual Level Entry",
tooltip="Choose a strong resistance level, i.e. a level above which a margin trader is likely to want his/her liquidation level")
var i_l = input.int(100,"Level length",minval=0,maxval=250,inline="length",group="Display")
var i_lExt = input.bool(false,"Extend right",inline="length",group="Display")
var i_2x = input.bool(true, "2x", inline="2x",group="Display")
var i_3x = input.bool(true, "3x", inline="3x",group="Display")
var i_4x = input.bool(true, "4x", inline="4x",group="Display")
var i_5x = input.bool(true, "5x", inline="5x",group="Display")
var i_7x = input.bool(false, "7x", inline="7x",group="Display")
var i_10x = input.bool(false, "10x", inline="10x",group="Display")
var i_nx = input.bool(false, "", inline="nx",group="Display")
var i_n = input.int(15, "", minval=2,maxval=250, inline="nx",group="Display")
var i_2xC = input.color(color.blue, "", inline="2x",group="Display")
var i_3xC = input.color(color.green, "", inline="3x",group="Display")
var i_4xC = input.color(color.yellow, "", inline="4x",group="Display")
var i_5xC = input.color(color.orange, "", inline="5x",group="Display")
var i_7xC = input.color(color.fuchsia, "", inline="7x",group="Display")
var i_10xC = input.color(color.red, "", inline="10x",group="Display")
var i_nxC = input.color(color.teal, "", inline="nx",group="Display")
var i_txtSize = input.string("small","Text size",["tiny","small","normal","large"],group="Display")
var i_pad = input.float(1.0,"Level % padding",step=.1,group="Display",tooltip="Vertical padding to be added above and below the level, as a percentage of the level.")
var tt = "Click to select a support or resistance level. You can edit this level in Settings."
var i_y = input.price(0.0, "Clicked: ", confirm=true, inline="int", group="Interactive Level Entry")
var i_x = input.time(0, "", confirm=true, inline="int", group="Interactive Level Entry", tooltip=tt)
ind = i_x == time ? bar_index : -1
var lvlL =
if i_lvl_l > 0
i_lvl_l
else if i_y > 0 and bar_index==ind
open[bar_index-ind] > i_y ? i_y : 0.0
var lvlS =
if i_lvl_s > 0
i_lvl_s
else if i_y > 0 and bar_index==ind
open[bar_index-ind] < i_y ? i_y : 0.0
//-----------------------------------------
// functions
//-----------------------------------------
shortMulti(float n) =>
(n-1)/n
longMulti(float n) =>
n/(n-1)
drawShort() =>
ext = i_lExt ? extend.right : extend.none
txtSize = draw.size(i_txtSize)
draw.level(lvlS,ind-i_l,0,i_l*2,extend=ext,txt=(str.tostring(lvlS,"#.#####") + " (short liquidation resistance)"), txt_loc="right", padding=i_pad, txt_size=txtSize)
if i_2x
l = lvlS*shortMulti(2)
draw.level(l, ind, length=i_l, colr=i_2xC, txt=(str.tostring(l,"#.#####") + " (2x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_3x
l = lvlS*shortMulti(3)
draw.level(l, ind, length=i_l, colr=i_3xC, txt=(str.tostring(l,"#.#####") + " (3x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_4x
l = lvlS*shortMulti(4)
draw.level(l, ind, length=i_l, colr=i_4xC, txt=(str.tostring(l,"#.#####") + " (4x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_5x
l = lvlS*shortMulti(5)
draw.level(l, ind, length=i_l, colr=i_5xC, txt=(str.tostring(l,"#.#####") + " (5x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_7x
l = lvlS*shortMulti(7)
draw.level(l, ind, length=i_l, colr=i_7xC, txt=(str.tostring(l,"#.#####") + " (7x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_10x
l = lvlS*shortMulti(10)
draw.level(l, ind, length=i_l, colr=i_10xC, txt=(str.tostring(l,"#.#####") + " (10x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_nx
l = lvlS*shortMulti(i_n)
draw.level(l, ind, length=i_l, colr=i_nxC, txt=(str.tostring(l,"#.#####") + " (" + str.tostring(i_n) + "x short threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
drawLong() =>
ext = i_lExt ? extend.right : extend.none
txtSize = draw.size(i_txtSize)
draw.level(lvlL,ind-i_l,0,i_l*2,extend=ext,txt=(str.tostring(lvlL,"#.#####") + " (long liquidation support)"), txt_loc="right", padding=i_pad, txt_size=txtSize)
if i_2x
l = lvlL*longMulti(2)
draw.level(l, ind, length=i_l, colr=i_2xC, txt=(str.tostring(l,"#.#####") + " (2x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_3x
l = lvlL*longMulti(3)
draw.level(l, ind, length=i_l, colr=i_3xC, txt=(str.tostring(l,"#.#####") + " (3x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_4x
l = lvlL*longMulti(4)
draw.level(l, ind, length=i_l, colr=i_4xC, txt=(str.tostring(l,"#.#####") + " (4x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_5x
l = lvlL*longMulti(5)
draw.level(l, ind, length=i_l, colr=i_5xC, txt=(str.tostring(l,"#.#####") + " (5x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_7x
l = lvlL*longMulti(7)
draw.level(l, ind, length=i_l, colr=i_7xC, txt=(str.tostring(l,"#.#####") + " (7x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_10x
l = lvlL*longMulti(10)
draw.level(l, ind, length=i_l, colr=i_10xC, txt=(str.tostring(l,"#.#####") + " (10x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
if i_nx
l = lvlL*longMulti(i_n)
draw.level(l, ind, length=i_l, colr=i_nxC, txt=(str.tostring(l,"#.#####") + " (" + str.tostring(i_n) + "x long threshold)"), txt_loc="right", extend=ext, padding=i_pad, txt_size=txtSize)
//-----------------------------------------
// main
//-----------------------------------------
if ind > -1 // on evaluation of clicked location bar
if lvlS > 0
drawShort()
if lvlL > 0
drawLong() |
Crypto and FX PSC | https://www.tradingview.com/script/stywSefU-Crypto-and-FX-PSC/ | briancarlo09 | https://www.tradingview.com/u/briancarlo09/ | 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/
// © hanabil
//modified by brianusdtperp
//@version=5
indicator("Crypto and FX PSC", max_bars_back=50, overlay=true)
// -------------------------
// Stop Loss
gr1 = 'Stoploss Input'
slp = input.float(1, 'Stoploss' , group=gr1, inline='1', tooltip = "Input Percentage for Crypto and PIPS for FX")
// RISK Profile
gr11 = 'Risk Profile'
gr12 = "Crypto"
gr13 = "Forex"
equity = input(1000, 'Equity (USD)', group=gr11)
p_risk = input.float(1, title='Risk %' , group=gr11, maxval=100)
leverage = input.int(10, title="Leverage", group=gr12, maxval=125, minval=1)
cz = input.int(100000,"Contract Size",options=[100000,10000,1000,100],group=gr13, tooltip="100,000 = Standard lot\n10,000 = Mini lot\n1,000 = Micro lot\n100 = Nano lot")
// Calculation crypto
slpv = slp/100
riskv = p_risk/100
riskdv = equity*riskv
pz = riskdv/slpv
margin = pz/leverage
//Detect Market
market = syminfo.type
//Calculation Forex
//Exchange Rate / Pip Value
iscrypto = "crypto" == market ? "" : "USD"+syminfo.currency
currency = "USD" == syminfo.currency ? "" : iscrypto
exRate = "USD" == syminfo.currency ? 1 : request.security(currency, timeframe.period, close)
exRateFlPoint = "JPY" == syminfo.currency ? 0.01 : 0.0001
//lot size
lotSize = ((riskdv * exRate) / (slp * exRateFlPoint)) / cz
// ----------------
// Smart Table
// --------
gr10 = 'Table'
tabPosI = input.string('Bot', 'Table Position', ['Bot', 'Middle', 'Top'], group=gr10)
tabCol = input.color(color.new(#ffffff, 29), 'Table Color', inline='1', group=gr10)
textCol = input.color(color.rgb(0, 0, 0), 'Text', inline='1', group=gr10)
textSizeI = input.string('Tiny', 'Text Size', ['Small', 'Tiny', 'Normal'], group=gr10)
textSize = textSizeI=='Small'? size.small : textSizeI=='Tiny'? size.tiny : size.normal
tabPos = tabPosI=='Top'? position.top_right : tabPosI=='Bot'? position.bottom_right : position.middle_right
var smartTable = table.new(tabPos, 50, 50, color.new(color.black,100), color.black, 1, color.black,1)
table.cell(smartTable, 0, 0, 'Equity' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 0, 1, 'Risk %' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 0, 2, 'Risk (USD)' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 0, 3, 'Stoploss PIP/Percent' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if market == "crypto"
table.cell(smartTable, 0, 4, 'Position Size' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 0, 5, 'Margin' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if market == "forex" or market == "cfd" or market == "index"
table.cell(smartTable, 0, 6, 'Lot Size (FX)' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 1, 0, str.tostring(equity) , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 1, 1, str.tostring(p_risk) , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 1, 2, str.tostring(math.round(riskdv,2)), text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 1, 3, str.tostring(math.round(slp,2)), text_color=textCol, text_size=textSize, bgcolor=tabCol)
if market == "crypto"
table.cell(smartTable, 1, 4, str.tostring(math.round(pz,2)), text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell(smartTable, 1, 5, str.tostring(math.round(margin,2)), text_color=textCol, text_size=textSize, bgcolor=tabCol)
if market == "forex" or market == "cfd" or market == "index"
table.cell(smartTable, 1, 6, str.tostring(math.round(lotSize,2)), text_color=textCol, text_size=textSize, bgcolor=tabCol) |
MTF Commodity Oddity Index (CCI+) | https://www.tradingview.com/script/8pojkwUW-MTF-Commodity-Oddity-Index-CCI/ | tvenn | https://www.tradingview.com/u/tvenn/ | 87 | 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/
// © tvenn
//@version=5
indicator(title="MTF Commodity Oddity Index (CCI+)", shorttitle="CCI+", overlay = true, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400)
//=Constants
green = #95BD5F
red = #EA1889
// =MTF CCI
//==================================================================================================================================
grp_CCI = "General settings"
ccisrc = input(hlc3, title="CCI source", group=grp_CCI)
ccilen = input(20, title="CCI length", group=grp_CCI)
cci_val = ta.cci(ccisrc, ccilen) // CCI
cciRibbonPosition = input.string('Bottom', title="CCI ribbon position", options=['Top', 'Bottom'], group=grp_CCI)
grp_MTFCCI1 = "MTF CCI #1"
enableOBOSCCI = input(true, title="Enable MTF CCI OB/OS ribbon", group=grp_MTFCCI1)
useBgColorMTFCCIOBOS = input(true, title="Color background where MTF #1 OB/OS", group=grp_MTFCCI1, tooltip="This will color the background to indicate the overbought / oversold state of the CCI on all 3x selected timeframes together at the same time.")
useBarColorMTFcciOBOS_1 = input(false, title="Color candles where MTF #1 OB/OS", group=grp_MTFCCI1, tooltip="This will color the candles to indicate the overbought / oversold state of the CCI on all 3x selected timeframes together at the same time.")
overboughtColor_1 = input(red, title="CCI overbought color", group=grp_MTFCCI1)
oversoldColor_1 = input(green, title="CCI oversold color", group=grp_MTFCCI1)
includeCurrentTFOBOSCCI = input(false, title="Include current timeframe OB/OS in ribbon", group="Current timeframe [Timeframe] [OS level] [OB level]", tooltip="this will include in the ribbon indications where the CCI is overbought or oversold on the current timeframe")
CCITF_1 = input.string("Chart", title="CTF", options=["Chart"], group="Current timeframe [Timeframe] [OS level] [OB level]", inline="tf1")
CCITF_OSTHRESH_1 = input(-150, title="", group="Current timeframe [Timeframe] [OS level] [OB level]", inline="tf1")
CCITF_OBTHRESH_1 = input(150, title="", group="Current timeframe [Timeframe] [OS level] [OB level]", inline="tf1")
//MTF CCI confluences
CCIMTF_1 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf1")
CCIMTF_2 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf2")
CCIMTF_3 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf3")
CCIMTF_OSTHRESH_1 = input(-150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf1")
CCIMTF_OSTHRESH_2 = input(-150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf2")
CCIMTF_OSTHRESH_3 = input(-150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf3")
CCIMTF_OBTHRESH_1 = input(150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf1")
CCIMTF_OBTHRESH_2 = input(150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf2")
CCIMTF_OBTHRESH_3 = input(150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf3")
CCIMTF1 = request.security(syminfo.tickerid, CCIMTF_1 == "Chart" ? "" : CCIMTF_1, cci_val, barmerge.gaps_off)
CCIMTF2 = request.security(syminfo.tickerid, CCIMTF_2 == "Chart" ? "" : CCIMTF_2, cci_val, barmerge.gaps_off)
CCIMTF3 = request.security(syminfo.tickerid, CCIMTF_3 == "Chart" ? "" : CCIMTF_3, cci_val, barmerge.gaps_off)
allMTFCCIOB_1 = (CCIMTF1 > CCIMTF_OBTHRESH_1 and CCIMTF2 > CCIMTF_OBTHRESH_2 and CCIMTF3 > CCIMTF_OBTHRESH_3)
allMTFCCIOS_1 = (CCIMTF1 < CCIMTF_OSTHRESH_1 and CCIMTF2 < CCIMTF_OSTHRESH_2 and CCIMTF3 < CCIMTF_OSTHRESH_3)
obColorCCI = (cci_val > CCITF_OBTHRESH_1+20 ? color.new(overboughtColor_1, 50) : cci_val > CCITF_OBTHRESH_1 ? color.new(overboughtColor_1, 70) : na)
osColorCCI = (cci_val < CCITF_OSTHRESH_1-20 ? color.new(oversoldColor_1, 50) : cci_val < CCITF_OSTHRESH_1 ? color.new(oversoldColor_1, 70) : na)
allOBColor_1 = (allMTFCCIOB_1 ? overboughtColor_1 : na)
allOSColor_1 = (allMTFCCIOS_1 ? oversoldColor_1 : na)
_cciRibbonPosition = switch cciRibbonPosition
"Top" => location.top
"Bottom" => location.bottom
plotchar(cci_val, title="Current TF overbought", color=(enableOBOSCCI and includeCurrentTFOBOSCCI ? obColorCCI : na), char="■", location=_cciRibbonPosition, size=size.auto)
plotchar(cci_val, title="Current TF oversold", color=(enableOBOSCCI and includeCurrentTFOBOSCCI ? osColorCCI : na), char="■", location=_cciRibbonPosition, size=size.auto)
plotchar(cci_val, title="All overbought", color=(enableOBOSCCI ? allOBColor_1 : na), char="■", location=_cciRibbonPosition, size=size.auto)
plotchar(cci_val, title="All oversold", color=(enableOBOSCCI ? allOSColor_1 : na), char="■", location=_cciRibbonPosition, size=size.auto)
bgcolor((useBgColorMTFCCIOBOS and allMTFCCIOB_1 ? color.new(allOBColor_1, 80) : (useBgColorMTFCCIOBOS and allMTFCCIOS_1 ? color.new(allOSColor_1, 80) : na)), title='CCI OB/OS background color')
barcolor(useBarColorMTFcciOBOS_1 and allMTFCCIOB_1 ? allOBColor_1 : (useBarColorMTFcciOBOS_1 and allMTFCCIOS_1 ? allOSColor_1 : na))
//Secondary MTF CCI confluences
grp_MTFCCI2 = "MTF CCI #2"
enableOBOS_2 = input(true, title="Show MTF #2 CCI OB/OS in ribbon", group=grp_MTFCCI2)
useBgColorMTFCCIOBOS_2 = input(false, title="Color background where MTF #2 CCI OB/OS", group=grp_MTFCCI2, tooltip="This will color the background to indicate the overbought / oversold state of the CCI on all 3x selected timeframes together at the same time.")
useBarColorMTFcciOBOS_2 = input(false, title="Color candles where MTF #2 OB/OS", group=grp_MTFCCI2, tooltip="This will color the candles to indicate the overbought / oversold state of the CCI on all 3x selected timeframes together at the same time.")
overboughtColor_2 = input.color(color.rgb(255, 68, 68, 50), title="CCI overbought color", group=grp_MTFCCI2)
oversoldColor_2 = input.color(color.rgb(43, 117, 46, 50), title="CCI oversold color", group=grp_MTFCCI2)
grp_MTFSRSI2_= "CCI MTF #2 [Timeframe] [OS level] [OB level]"
CCIMTF_1_2 = input.string("15", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2_, inline="mtf1")
CCIMTF_2_2 = input.string("30", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2_, inline="mtf2")
CCIMTF_3_2 = input.string("120", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2_, inline="mtf3")
CCIMTF_OSTHRESH_1_2 = input(-150, title="", group=grp_MTFSRSI2_, inline="mtf1")
CCIMTF_OSTHRESH_2_2 = input(-150, title="", group=grp_MTFSRSI2_, inline="mtf2")
CCIMTF_OSTHRESH_3_2 = input(-150, title="", group=grp_MTFSRSI2_, inline="mtf3")
CCIMTF_OBTHRESH_1_2 = input(150, title="", group=grp_MTFSRSI2_, inline="mtf1")
CCIMTF_OBTHRESH_2_2 = input(150, title="", group=grp_MTFSRSI2_, inline="mtf2")
CCIMTF_OBTHRESH_3_2 = input(150, title="", group=grp_MTFSRSI2_, inline="mtf3")
CCIMTF1_2 = request.security(syminfo.tickerid, CCIMTF_1_2 == "Chart" ? "" : CCIMTF_1_2, cci_val, barmerge.gaps_off)
CCIMTF2_2 = request.security(syminfo.tickerid, CCIMTF_2_2 == "Chart" ? "" : CCIMTF_2_2, cci_val, barmerge.gaps_off)
CCIMTF3_2 = request.security(syminfo.tickerid, CCIMTF_3_2 == "Chart" ? "" : CCIMTF_3_2, cci_val, barmerge.gaps_off)
allMTFCCIOB_2 = (CCIMTF1_2 > CCIMTF_OBTHRESH_1_2 and CCIMTF2_2 > CCIMTF_OBTHRESH_2_2 and CCIMTF3_2 > CCIMTF_OBTHRESH_3_2)
allMTFCCIOS_2 = (CCIMTF1_2 < CCIMTF_OSTHRESH_1_2 and CCIMTF2_2 < CCIMTF_OSTHRESH_2_2 and CCIMTF3_2 < CCIMTF_OSTHRESH_3_2)
allOBColor_2 = (allMTFCCIOB_2 ? overboughtColor_2 : na)
allOSColor_2 = (allMTFCCIOS_2 ? oversoldColor_2 : na)
plotchar(cci_val, title="3x TF all overbought", color=(enableOBOS_2 ? allOBColor_2 : na), char="■", location=location.bottom)
plotchar(cci_val, title="3x TF all oversold", color=(enableOBOS_2 ? allOSColor_2 : na), char="■", location=location.bottom)
bgcolor((useBgColorMTFCCIOBOS_2 and allMTFCCIOB_2 ? color.new(allOBColor_2, 90) : (useBgColorMTFCCIOBOS_2 and allMTFCCIOS_2 ? color.new(allOSColor_2, 90) : na)), title='CCI OB/OS background colour')
barcolor(useBarColorMTFcciOBOS_2 and allMTFCCIOB_2 ? allOBColor_2 : (useBarColorMTFcciOBOS_2 and allMTFCCIOS_2 ? allOSColor_2 : na))
//Alerts
alertcondition((allMTFCCIOB_1 and not allMTFCCIOB_1[1]) or (allMTFCCIOS_1 and not allMTFCCIOS_1[1]), title="MTF #1 CCI OB/OS Detected in COI+", message="MTF #1 CCI OB/OS Detected in COI+")
alertcondition(allMTFCCIOB_1 and not allMTFCCIOB_1[1], title="MTF #1 CCI Overbought Detected in COI+", message="MTF #1 CCI Overbought Detected in COI+")
alertcondition(allMTFCCIOS_1 and not allMTFCCIOS_1[1], title="MTF #1 CCI Oversold Detected in COI+", message="MTF #1 CCI Oversold Detected in COI+")
alertcondition((allMTFCCIOB_2 and not allMTFCCIOB_2[1]) or (allMTFCCIOS_2 and not allMTFCCIOS_2[1]), title="MTF #2 CCI OB/OS Detected in COI+", message="MTF #2 CCI OB/OS Detected in COI+")
alertcondition(allMTFCCIOB_2 and not allMTFCCIOB_2[1], title="MTF #2 CCI Overbought Detected in COI+", message="MTF #2 CCI Overbought Detected in COI+")
alertcondition(allMTFCCIOS_2 and not allMTFCCIOS_2[1], title="MTF #2 CCI Oversold Detected in COI+", message="MTF #2 CCI Oversold Detected in COI+")
//Oscillator value table
grp_TABLE = "MTF Table"
showMTFVals = input(false, title="Show MTF table for", group=grp_TABLE, inline="table")
MTFTableType = input.string("MTF #1 & #2", options=["MTF #1", "MTF #2", "MTF #1 & #2"], title="", group=grp_TABLE, inline="table")
dashboardSize = input.string(title='', defval='Mobile', options=['Mobile', 'Desktop'], group=grp_TABLE, inline="table")
labelPos = input.string(title="Table position", defval='Top right', options=['Top right', 'Top left', 'Bottom right', 'Bottom left'], group=grp_TABLE)
MTFTableColor = input(color.new(color.white, 100), title="Table color", group=grp_TABLE)
labelColor = color.new(color.white, 70)
valueColor = color.new(color.white, 20)
_MTF1labelColor(val, ob, os) =>
val > ob ? overboughtColor_1 : (val < os ? oversoldColor_1 : valueColor)
_MTF2labelColor(val, ob, os) =>
val > ob ? overboughtColor_2 : (val < os ? oversoldColor_2 : valueColor)
_labelPos = switch labelPos
"Top right" => position.top_right
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
_size = switch dashboardSize
"Mobile" => size.small
"Desktop" => size.normal
var table label = table.new(_labelPos, 4, 4, bgcolor = MTFTableColor, frame_width = 0, frame_color = color.new(color.gray, 100))
// We only populate the table on the last bar.
if barstate.islast and showMTFVals
if (MTFTableType=="MTF #1")
table.cell(label, 0, 0, text="CCI", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 1, text=CCIMTF_1+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 1, text=str.tostring(math.floor(CCIMTF1)), width=3, text_color=_MTF1labelColor(CCIMTF1, CCIMTF_OBTHRESH_1, CCIMTF_OSTHRESH_1), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 2, text=CCIMTF_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 2, text=str.tostring(math.floor(CCIMTF2)), width=3, text_color=_MTF1labelColor(CCIMTF2, CCIMTF_OBTHRESH_2, CCIMTF_OSTHRESH_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 3, text=CCIMTF_3+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 3, text=str.tostring(math.floor(CCIMTF3)), width=3, text_color=_MTF1labelColor(CCIMTF3, CCIMTF_OBTHRESH_3, CCIMTF_OSTHRESH_3), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
else if (MTFTableType=="MTF #2")
table.cell(label, 0, 0, text="CCI", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 1, text=CCIMTF_1_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 1, text=str.tostring(math.floor(CCIMTF1_2)), width=3, text_color=_MTF2labelColor(CCIMTF1_2, CCIMTF_OBTHRESH_1_2, CCIMTF_OSTHRESH_1_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 2, text=CCIMTF_2_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 2, text=str.tostring(math.floor(CCIMTF2_2)), width=3, text_color=_MTF2labelColor(CCIMTF2_2, CCIMTF_OBTHRESH_2_2, CCIMTF_OSTHRESH_2_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 3, text=CCIMTF_3_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 3, text=str.tostring(math.floor(CCIMTF3_2)), width=3, text_color=_MTF2labelColor(CCIMTF3_2, CCIMTF_OBTHRESH_3_2, CCIMTF_OSTHRESH_3_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
else if (MTFTableType=="MTF #1 & #2")
table.cell(label, 0, 0, text="CCI", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 1, text=CCIMTF_1+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 1, text=str.tostring(math.floor(CCIMTF1)), width=3, text_color=_MTF1labelColor(CCIMTF1, CCIMTF_OBTHRESH_1, CCIMTF_OSTHRESH_1), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 2, text=CCIMTF_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 2, text=str.tostring(math.floor(CCIMTF2)), width=3, text_color=_MTF1labelColor(CCIMTF2, CCIMTF_OBTHRESH_2, CCIMTF_OSTHRESH_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 0, 3, text=CCIMTF_3+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 1, 3, text=str.tostring(math.floor(CCIMTF3)), width=3, text_color=_MTF1labelColor(CCIMTF3, CCIMTF_OBTHRESH_3, CCIMTF_OSTHRESH_3), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 2, 1, text=CCIMTF_1_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 3, 1, text=str.tostring(math.floor(CCIMTF1_2)), width=3, text_color=_MTF2labelColor(CCIMTF1_2, CCIMTF_OBTHRESH_1_2, CCIMTF_OSTHRESH_1_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 2, 2, text=CCIMTF_2_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 3, 2, text=str.tostring(math.floor(CCIMTF2_2)), width=3, text_color=_MTF2labelColor(CCIMTF2_2, CCIMTF_OBTHRESH_2_2, CCIMTF_OSTHRESH_2_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
table.cell(label, 2, 3, text=CCIMTF_3_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
table.cell(label, 3, 3, text=str.tostring(math.floor(CCIMTF3_2)), width=3, text_color=_MTF2labelColor(CCIMTF3_2, CCIMTF_OBTHRESH_3_2, CCIMTF_OSTHRESH_3_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
|
Colorful Channel | https://www.tradingview.com/script/D2MQ5fww/ | faytterro | https://www.tradingview.com/u/faytterro/ | 82 | 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 Channel", overlay=true, timeframe = "", timeframe_gaps = true)
len=input.int(168,title="lenght")
tr=input.float(2, title="transp", minval=0.5, step=0.5)
ymom=100*(high-ta.lowest(low,len))/ta.lowest(low,len)
dmom=-100*(low-ta.highest(high,len))/ta.highest(high,len)
x=ta.lowest(low,len)
cl=plot((close/2+open/2), display = display.none)
p1=plot(x, color=color.gray, linewidth=1)
a=ta.highest(high,len)
fill(p1,cl,top_value=a ,bottom_value=x, top_color =color.rgb(255, 0, 0, 100-ymom*tr), bottom_color =color.rgb(255, 0, 0, 100), fillgaps = true)
a1=plot(a, color=color.gray, linewidth=1)
fill(a1,cl,top_value=x ,bottom_value=a, top_color =color.rgb(0,255,0,100-dmom*tr), bottom_color = color.rgb(0,255,0,100), fillgaps = true)
|
Sembang Kari Traders - EMA & Wave Stacked Labels + EMA 34 Lines | https://www.tradingview.com/script/5pWy6ckn-Sembang-Kari-Traders-EMA-Wave-Stacked-Labels-EMA-34-Lines/ | KhairulHadi | https://www.tradingview.com/u/KhairulHadi/ | 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/
//
// @version=5
//
// Stacked EMAs & Waves Labels on multiple timeframe
//
// EMA 34 Lines (Close, High and Low)
//
// Created by © Hadi
//
indicator("Stacked EMAs", overlay = true)
// EMAs
ema34dh = ta.ema (high, 34)
ema34d = ta.ema (close, 34)
ema34dl = ta.ema (low, 34)
ema200 = ta.ema (close, 200)
ema85 = request.security(syminfo.tickerid, '5', ta.ema(close, 8))
ema215 = request.security(syminfo.tickerid, '5', ta.ema(close, 21))
ema345 = request.security(syminfo.tickerid, '5', ta.ema(close, 34))
ema555h = request.security(syminfo.tickerid, '5', ta.ema(high, 55))
ema555c = request.security(syminfo.tickerid, '5', ta.ema(close, 55))
ema555l = request.security(syminfo.tickerid, '5', ta.ema(low, 55))
ema815 = request.security(syminfo.tickerid, '15', ta.ema(close, 8))
ema2115 = request.security(syminfo.tickerid, '15', ta.ema(close, 21))
ema3415 = request.security(syminfo.tickerid, '15', ta.ema(close, 34))
ema5515h = request.security(syminfo.tickerid, '15', ta.ema(high, 55))
ema5515c = request.security(syminfo.tickerid, '15', ta.ema(close, 55))
ema5515l = request.security(syminfo.tickerid, '15', ta.ema(low, 55))
ema830 = request.security(syminfo.tickerid, '30', ta.ema(close, 8))
ema2130 = request.security(syminfo.tickerid, '30', ta.ema(close, 21))
ema3430 = request.security(syminfo.tickerid, '30', ta.ema(close, 34))
ema5530h = request.security(syminfo.tickerid, '30', ta.ema(high, 55))
ema5530c = request.security(syminfo.tickerid, '30', ta.ema(close, 55))
ema5530l = request.security(syminfo.tickerid, '30', ta.ema(low, 55))
ema8hourly = request.security(syminfo.tickerid, '60', ta.ema(close, 8))
ema21hourly = request.security(syminfo.tickerid, '60', ta.ema(close, 21))
ema34hourly = request.security(syminfo.tickerid, '60', ta.ema(close, 34))
ema55hourlyh = request.security(syminfo.tickerid, '60', ta.ema(high, 55))
ema55hourlyc = request.security(syminfo.tickerid, '60', ta.ema(close, 55))
ema55hourlyl = request.security(syminfo.tickerid, '60', ta.ema(low, 55))
ema8hour4 = request.security(syminfo.tickerid, '240', ta.ema(close, 8))
ema21hour4 = request.security(syminfo.tickerid, '240', ta.ema(close, 21))
ema34hour4 = request.security(syminfo.tickerid, '240', ta.ema(close, 34))
ema55hour4h = request.security(syminfo.tickerid, '240', ta.ema(high, 55))
ema55hour4c = request.security(syminfo.tickerid, '240', ta.ema(close, 55))
ema55hour4l = request.security(syminfo.tickerid, '240', ta.ema(low, 55))
ema8daily = request.security(syminfo.tickerid, 'D', ta.ema(close, 8))
ema21daily = request.security(syminfo.tickerid, 'D', ta.ema(close, 21))
ema34daily = request.security(syminfo.tickerid, 'D', ta.ema(close, 34))
ema55dailyh = request.security(syminfo.tickerid, 'D', ta.ema(high, 55))
ema55dailyc = request.security(syminfo.tickerid, 'D', ta.ema(close, 55))
ema55dailyl = request.security(syminfo.tickerid, 'D', ta.ema(low, 55))
ema8weekly = request.security(syminfo.tickerid, 'W', ta.ema(close, 8))
ema21weekly = request.security(syminfo.tickerid, 'W', ta.ema(close, 21))
ema34weekly = request.security(syminfo.tickerid, 'W', ta.ema(close, 34))
ema55weeklyh = request.security(syminfo.tickerid, 'W', ta.ema(high, 55))
ema55weeklyc = request.security(syminfo.tickerid, 'W', ta.ema(close, 55))
ema55weeklyl = request.security(syminfo.tickerid, 'W', ta.ema(low, 55))
// Plots
plot(ema34dh, title='EMA 34H', color=#00ff08, linewidth=2)
plot(ema34d, title='EMA 34C', color=#002fff, linewidth=2)
plot(ema34dl, title='EMA 34L', color=#ff0000, linewidth=2)
plot(ema200, title='EMA 200', color=#ffffff, linewidth=2)
// Stacked EMAs & Stacked Weekly EMAs Table
string tableYposInput = input.string("top", "Panel position", inline = "11", options = ["top", "middle", "bottom"])
string tableXposInput = input.string("right", "", inline = "11", options = ["left", "center", "right"])
color bullColorInput = input.color(color.new(color.green, 0), "Bullish", inline = "12")
color bearColorInput = input.color(color.new(color.red, 0), "Bearish", inline = "12")
color neutColorInput = input.color(color.new(color.yellow, 0), "Neutral", inline = "12")
color titleColorInput = input.color(color.new(color.white, 0))
M5EMAsLabel = string ("5")
LabelColor5 = neutColorInput
if ema85 > ema215 and ema215 > ema345
LabelColor5 := bullColorInput
if ema85 < ema215 and ema215 < ema345
LabelColor5 := bearColorInput
WaveM5EMAsLabel = string ("5")
LabelColor5wave = neutColorInput
if ema85 > ema215 and ema215 > ema345 and ema345 > ema555h
LabelColor5wave := bullColorInput
if ema85 < ema215 and ema215 < ema345 and ema345 < ema555l
LabelColor5wave := bearColorInput
M15EMAsLabel = string ("15")
LabelColor15 = neutColorInput
if ema815 > ema2115 and ema2115 > ema3415
LabelColor15 := bullColorInput
if ema815 < ema2115 and ema2115 < ema3415
LabelColor15 := bearColorInput
WaveM15EMAsLabel = string ("15")
LabelColor15wave = neutColorInput
if ema815 > ema2115 and ema2115 > ema3415 and ema3415 > ema5515h
LabelColor15wave := bullColorInput
if ema815 < ema2115 and ema2115 < ema3415 and ema3415 < ema5515l
LabelColor15wave := bearColorInput
M30EMAsLabel = string ("30")
LabelColor30 = neutColorInput
if ema830 > ema2130 and ema2130 > ema3430
LabelColor30 := bullColorInput
if ema830 < ema2130 and ema2130 < ema3430
LabelColor30 := bearColorInput
WaveM30EMAsLabel = string ("30")
LabelColor30wave = neutColorInput
if ema830 > ema2130 and ema2130 > ema3430 and ema3430 > ema5530h
LabelColor30wave := bullColorInput
if ema830 < ema2130 and ema2130 < ema3430 and ema3430 < ema5530l
LabelColor30wave := bearColorInput
H1EMAsLabel = string ("H1")
LabelColorHr = neutColorInput
if ema8hourly > ema21hourly and ema21hourly > ema34hourly
LabelColorHr := bullColorInput
if ema8hourly < ema21hourly and ema21hourly < ema34hourly
LabelColorHr := bearColorInput
WaveH1EMAsLabel = string ("H1")
LabelColorHrwave = neutColorInput
if ema8hourly > ema21hourly and ema21hourly > ema34hourly and ema34hourly > ema55hourlyh
LabelColorHrwave := bullColorInput
if ema8hourly < ema21hourly and ema21hourly < ema34hourly and ema34hourly < ema55hourlyl
LabelColorHrwave := bearColorInput
H4EMAsLabel = string ("H4")
LabelColorH4 = neutColorInput
if ema8hour4 > ema21hour4 and ema21hour4 > ema34hour4
LabelColorH4 := bullColorInput
if ema8hour4 < ema21hour4 and ema21hour4 < ema34hour4
LabelColorH4 := bearColorInput
WaveH4EMAsLabel = string ("H4")
LabelColorH4wave = neutColorInput
if ema8hour4 > ema21hour4 and ema21hour4 > ema34hour4 and ema34hour4 > ema55hour4h
LabelColorH4wave := bullColorInput
if ema8hour4 < ema21hour4 and ema21hour4 < ema34hour4 and ema34hour4 < ema55hour4l
LabelColorH4wave := bearColorInput
DEMAsLabel = string ("D")
LabelColorD = neutColorInput
if ema8daily > ema21daily and ema21daily > ema34daily
LabelColorD := bullColorInput
if ema8daily < ema21daily and ema21daily < ema34daily
LabelColorD := bearColorInput
WaveDEMAsLabel = string ("D")
LabelColorDwave = neutColorInput
if ema8daily > ema21daily and ema21daily > ema34daily and ema34daily > ema55dailyh
LabelColorDwave := bullColorInput
if ema8daily < ema21daily and ema21daily < ema34daily and ema34daily < ema55dailyl
LabelColorDwave := bearColorInput
WEMAsLabel = string ("W")
LabelColorW = neutColorInput
if ema8weekly > ema21weekly and ema21weekly > ema34weekly
LabelColorW := bullColorInput
if ema8weekly < ema21weekly and ema21weekly < ema34weekly
LabelColorW := bearColorInput
WaveWEMAsLabel = string ("W")
LabelColorWwave = neutColorInput
if ema8weekly > ema21weekly and ema21weekly > ema34weekly and ema34weekly > ema55weeklyh
LabelColorWwave := bullColorInput
if ema8weekly < ema21weekly and ema21weekly < ema34weekly and ema34weekly < ema55weeklyl
LabelColorWwave := bearColorInput
EMAsTitle = string ("EMA")
LabelColorTE = titleColorInput
WAVETitle = string ("WAVE")
LabelColorTW = titleColorInput
Table = table.new(tableYposInput + "_" + tableXposInput, columns=9, rows=2, bgcolor=color.gray)
if barstate.islast
table.cell(table_id=Table, column=8, row=0, text=M5EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColor5)
table.cell(table_id=Table, column=7, row=0, text=M15EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColor15)
table.cell(table_id=Table, column=6, row=0, text=M30EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColor30)
table.cell(table_id=Table, column=5, row=0, text=H1EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorHr)
table.cell(table_id=Table, column=4, row=0, text=H4EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorH4)
table.cell(table_id=Table, column=3, row=0, text=DEMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorD)
table.cell(table_id=Table, column=2, row=0, text=WEMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorW)
table.cell(table_id=Table, column=1, row=0, text=EMAsTitle, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorTE)
table.cell(table_id=Table, column=8, row=1, text=WaveM5EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColor5wave)
table.cell(table_id=Table, column=7, row=1, text=WaveM15EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColor15wave)
table.cell(table_id=Table, column=6, row=1, text=WaveM30EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColor30wave)
table.cell(table_id=Table, column=5, row=1, text=WaveH1EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorHrwave)
table.cell(table_id=Table, column=4, row=1, text=WaveH4EMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorH4wave)
table.cell(table_id=Table, column=3, row=1, text=WaveDEMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorDwave)
table.cell(table_id=Table, column=2, row=1, text=WaveWEMAsLabel, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorWwave)
table.cell(table_id=Table, column=1, row=1, text=WAVETitle, height=0,text_color=color.black, text_halign=text.align_left, text_valign=text.align_center, bgcolor=LabelColorTW)
|
Volume Spike Backfills | https://www.tradingview.com/script/iDW9TkdF-Volume-Spike-Backfills/ | Vostok369 | https://www.tradingview.com/u/Vostok369/ | 92 | 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/
// © Vostok369
//@version=5
indicator("Volume Spike Backfills", shorttitle='VS Fills', overlay=true)
///// VOLUME SPIKES
volumePercent = input.int(150, title = "Volume Spike Candles (%)", tooltip="Marks candles with volume greater than a percentage of the previous candle average volume", minval = 100, maxval = 1000, step = 10)
avLookback = input.int(10, title = "Candle Average Lookback", tooltip="Can deviate from the standard 10 candle average")
timeframe = input.string(title = "Timeframe", defval = "Auto", options=["Auto", "5", "15", "30", "60" ])
GreenLB = input.int(4, title = "Green Volume Spike Look Back", tooltip="Alter to see more or less green bands on the chart", minval = 1, maxval = 10, step = 1)
RedLB = input.int(4, title = "Red Volume Spike Look Back", tooltip="Alter to see more or less red bands on the chart", minval = 1, maxval = 10, step = 1)
MaxLB = input.bool(false, title = "Max Look Back", tooltip="See a larger number of bands on the chart for an at a glance view of historical volume spikes")
EQbreak = input.int(50, title = "Median Break of Candle (%)", tooltip="Alter to view approximately how much of the candle body has been backfilled", minval = 20, maxval = 80, step = 10)
Complete = input.int(0, title = "Backfill completed within ($)", tooltip="Alter to remove bands that are almost completely backfilled or too small to be significant")
showVS = input.bool(true, title = "Show VS Labels")
ColorRed = input.color(color.new(color.red, 100) , title="Red Levels")
RedFill = input.color(color.new(color.red, 80), title="Red Fill First Level")
RedEQFill = input.color(color.new(color.red, 90), title="Red Fill SecondLevel")
ColorGreen = input.color(color.new(color.green, 100) , title="Green Levels")
GreenFill = input.color(color.new(color.green, 80), title="Green Fill First Level")
GreenEQFill = input.color(color.new(color.green, 90), title="Green Fill Second Level")
if timeframe == 'Auto'
timeframe := timeframe.period
[tflow, tfhigh, tftime, tfvol, tfopen, tfclose] = request.security(syminfo.tickerid, timeframe, [low, high, time, volume, open, close], lookahead=barmerge.lookahead_on)
candle = 'Green'
if tfclose < tfopen
candle := 'Red'
if MaxLB
GreenLB := 20
RedLB := 20
var volStore = array.new_float()
var volLabels = array.new_label()
total = 0.0
if array.size(volStore) >= avLookback
for i = 0 to array.size(volStore) - 1
total += array.get(volStore, i)
average = total/10
/// add volume store
if array.size(volStore) >= avLookback
array.shift(volStore)
array.push(volStore, tfvol)
var oLineRed = array.new_line()
var oLineGreen = array.new_line()
var cLineRed = array.new_line()
var cLineGreen = array.new_line()
var mLineRed = array.new_line()
var mLineGreen = array.new_line()
for x = 0 to 4
if array.size(oLineGreen) > 0
for i = 0 to array.size(oLineGreen) - 1
if array.size(oLineGreen) >= i+1
checkLineClose = array.get(cLineGreen, i)
checkLineOpen = array.get(oLineGreen, i)
checkLineEQ = array.get(mLineGreen, i)
checkOpen = line.get_y2(checkLineOpen)
checkClose = line.get_y2(checkLineClose)
checkEQ = line.get_y2(checkLineEQ)
if tflow < checkOpen + Complete
line.delete(array.remove(cLineGreen, i))
line.delete(array.remove(oLineGreen, i))
line.delete(array.remove(mLineGreen, i))
else if tflow < checkEQ
line.set_y1(checkLineClose, tflow)
line.set_y2(checkLineClose, tflow)
line.set_y1(checkLineEQ, tflow)
line.set_y2(checkLineEQ, tflow)
else if tflow < checkClose
line.set_y1(checkLineClose, tflow)
line.set_y2(checkLineClose, tflow)
for x = 0 to 4
if array.size(oLineRed) > 0
for i = 0 to array.size(oLineRed) - 1
if array.size(oLineRed) >= i+1
checkLineClose = array.get(cLineRed, i)
checkLineOpen = array.get(oLineRed, i)
checkLineEQ = array.get(mLineRed, i)
checkOpen = line.get_y2(checkLineOpen)
checkClose = line.get_y2(checkLineClose)
checkEQ = line.get_y2(checkLineEQ)
if tfhigh > checkOpen - Complete
line.delete(array.remove(cLineRed, i))
line.delete(array.remove(oLineRed, i))
line.delete(array.remove(mLineRed, i))
else if tfhigh > checkEQ
line.set_y1(checkLineClose, tfhigh)
line.set_y2(checkLineClose, tfhigh)
line.set_y1(checkLineEQ, tfhigh)
line.set_y2(checkLineEQ, tfhigh)
else if tfhigh > checkClose
line.set_y1(checkLineClose, tfhigh)
line.set_y2(checkLineClose, tfhigh)
pAverage = math.round((tfvol/average)*100)
vString = str.tostring(pAverage) + ' %'
alertVScandle = false
if tfvol > average * (volumePercent/100)
alertVScandle := true
if candle == 'Red'
oLine = line.new(x1=tftime, x2=tftime + 1, y1=tfopen, y2=tfopen, color=ColorRed, xloc=xloc.bar_time, extend=extend.right)
cLine = line.new(x1=tftime, x2=tftime + 1, y1=tfclose, y2=tfclose, color=ColorRed, xloc=xloc.bar_time, extend=extend.right)
eq = tfclose + math.abs(tfopen-tfclose)*(EQbreak/100)
mLine = line.new(x1=tftime, x2=tftime + 1, y1=eq, y2=eq, color=ColorRed, xloc=xloc.bar_time, extend=extend.right)
array.push(oLineRed, oLine)
array.push(cLineRed, cLine)
array.push(mLineRed, mLine)
if showVS
vLabel = label.new(x=tftime, y=tflow, text=vString, xloc=xloc.bar_time, color=color.rgb(165, 0, 0), textcolor= color.white, style=label.style_label_up , size=size.small)
if candle == 'Green'
oLine = line.new(x1=tftime, x2=tftime + 1, y1=tfopen, y2=tfopen, color=ColorGreen, xloc=xloc.bar_time, extend=extend.right)
cLine = line.new(x1=tftime, x2=tftime + 1, y1=tfclose, y2=tfclose, color=ColorGreen, xloc=xloc.bar_time, extend=extend.right)
eq = tfclose - math.abs(tfopen-tfclose)*(EQbreak/100)
mLine = line.new(x1=tftime, x2=tftime + 1, y1=eq, y2=eq, color=ColorGreen, xloc=xloc.bar_time, extend=extend.right)
array.push(oLineGreen, oLine)
array.push(cLineGreen, cLine)
array.push(mLineGreen, mLine)
if showVS
vLabel = label.new(x=tftime, y=tfhigh, text=vString, xloc=xloc.bar_time, color=color.rgb(25, 92, 19), textcolor= color.white, style=label.style_label_down , size=size.small)
if array.size(oLineRed) > RedLB
line.delete(array.shift(oLineRed))
line.delete(array.shift(cLineRed))
line.delete(array.shift(mLineRed))
if array.size(oLineGreen) > GreenLB
line.delete(array.shift(oLineGreen))
line.delete(array.shift(cLineGreen))
line.delete(array.shift(mLineGreen))
if barstate.islast
if array.size(oLineRed) > 0
for i = 0 to array.size(oLineRed) - 1
checkLineClose = array.get(cLineRed, i)
checkLineOpen = array.get(oLineRed, i)
checkLineEQ = array.get(mLineRed, i)
checkEQ = line.get_y2(checkLineOpen)
checkClose = line.get_y2(checkLineClose)
linefill.new(checkLineOpen, checkLineEQ, RedEQFill)
if checkEQ != checkClose
linefill.new(checkLineEQ, checkLineClose, RedFill)
if array.size(oLineGreen) > 0
for i = 0 to array.size(oLineGreen) - 1
checkLineClose = array.get(cLineGreen, i)
checkLineOpen = array.get(oLineGreen, i)
checkLineEQ = array.get(mLineGreen, i)
checkEQ = line.get_y2(checkLineOpen)
checkClose = line.get_y2(checkLineClose)
linefill.new(checkLineOpen, checkLineEQ, GreenEQFill)
if checkEQ != checkClose
linefill.new(checkLineEQ, checkLineClose, GreenFill)
/// alerts
alertcondition(alertVScandle, 'Volume Spike', 'Volume spike occured on timeframe' )
|
NSE Sector Performance | https://www.tradingview.com/script/rQ0xYU5P-NSE-Sector-Performance/ | ILuvMarkets | https://www.tradingview.com/u/ILuvMarkets/ | 191 | 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("Sector Performance v0.2", overlay = false)
if not timeframe.isdaily
runtime.error("Please switch timeframe to daily")
i_sector = input.string("Sectors", "Sector", ["Sectors", "NIFTY", "BANKNIFTY", "CNXAUTO", "CNXENERGY",
"CNXFMCG", "CNXINFRA", "CNXIT", "CNXMEDIA", "CNXMETAL", "CNXPHARMA", "CNXREALTY",
"CNXPSUBANK","CNXFINANCE"])
i_time_1_txt = input.string("Year", title="Period", inline="1")
i_time_1 = input.time(timestamp("2022-01-01T00:00:00"),title="Date", inline="1")
i_time_2_txt = input.string("Quarter", title="Period", inline="2")
i_time_2 = input.time(timestamp("2022-10-01T00:00:00"),title="Date", inline="2")
i_time_3_txt = input.string("Month", title="Period", inline="3")
i_time_3 = input.time(timestamp("2022-11-01T00:00:00"),title="Date", inline="3")
i_time_4_txt = input.string("Week", title="Period", inline="4")
i_time_4 = input.time(timestamp("2022-11-06T00:00:00"),title="Date", inline="4")
i_text_size = input.string(size.small, "Text Size", [size.auto, size.tiny, size.small, size.normal, size.large, size.huge])
int ROWS = 30
int COLS = 10
int CLOSE_1 = 0, CLOSE_2 = 1, CLOSE_3 = 2, CLOSE_4 = 3
int CLOSE_PCT_1 = 4, CLOSE_PCT_2 = 5, CLOSE_PCT_3 = 6, CLOSE_PCT_4 = 7
var matrix<float> data_ = matrix.new<float>(ROWS, COLS, 0.0)
var table table_ = na
var text_color_ = color.white
var bg_color_ = color.gray
f_color(val_) => val_ > 0 ? color.green : val_ < 0 ? color.red : color.gray
f_bg_color(val_) => val_ > 0 ? color.new(color.green,80) : val_ < 0 ? color.new(color.red,80) : color.new(color.black,80)
f_bg_color_price(val_) =>
fg_color_ = f_color(val_)
abs_val_ = math.abs(val_)
transp_ = switch
abs_val_ > .15 => 40
abs_val_ > .10 => 50
abs_val_ > .05 => 60
=> 80
color.new(fg_color_, transp_)
f_bg_color_highlow(val_) =>
fg_color_ = f_color(val_)
abs_val_ = math.abs(val_)
transp_ = switch
abs_val_ < .02 => 40
abs_val_ < .05 => 60
abs_val_ < .07 => 80
=> 100
color.new(fg_color_, transp_)
f_symbol(sector_, idx_) =>
switch sector_
"Sectors" =>
switch idx_
1 => "NIFTY"
2 => "BANKNIFTY"
3 => "CNXAUTO"
4 => "CNXENERGY"
5 => "CNXFMCG"
6 => "CNXINFRA"
7 => "CNXIT"
8 => "CNXMEDIA"
9 => "CNXMETAL"
10 => "CNXPHARMA"
11 => "CNXREALTY"
12 => "CNXPSUBANK"
13 => "CNXFINANCE"
14 => "CNXMIDCAP"
15 => "CNXSMALLCAP"
=> ""
"NIFTY" =>
switch idx_
1 => "NIFTY"
2 => "RELIANCE"
3 => "INFY"
4 => "HDFC"
5 => "TCS"
6 => "ITC"
7 => "HINDUNILVR"
8 => "LT"
9 => "BHARTIARTL"
10 => "BAJFINANCE"
11 => "BHARTIARTL"
12 => "ASIANPAINT"
13 => "M_M"
14 => "MARUTI"
15 => "TITAN"
=> ""
"BANKNIFTY" =>
switch idx_
1 => "BANKNIFTY"
2 => "HDFCBANK"
3 => "ICICIBANK"
4 => "SBIN"
5 => "KOTAKBANK"
6 => "AXISBANK"
7 => "INDUSINDBK"
8 => "AUBANK"
9 => "BANDHANBNK"
10 => "FEDERALBNK"
11 => "IDFCFIRSTB"
12 => "PNB"
13 => "RBLBANK"
=> ""
"CNXAUTO" =>
switch idx_
1 => "CNXAUTO"
2 => "TATAMOTORS"
3 => "BAJAJ_AUTO"
4 => "M_M"
5 => "MARUTI"
6 => "ASHOKLEY"
7 => "TVSMOTOR"
8 => "HEROMOTOCO"
9 => "EICHERMOT"
10 => "EXIDEIND"
11 => "AMARAJABAT"
12 => "BOSCHLTD"
13 => "MRF"
14 => "BHARATFORG"
15 => "BALKRISIND"
=> ""
"CNXENERGY" =>
switch idx_
1 => "CNXENERGY"
2 => "ADANIGREEN"
3 => "BPCL"
4 => "GAIL"
5 => "HINDPETRO"
6 => "IOC"
7 => "NTPC"
8 => "ONGC"
9 => "POWERGRID"
10 => "RELIANCE"
11 => "TATAPOWER"
12 => "GUJGASLTD"
13 => "IGL"
14 => "PETRONET"
=> ""
"CNXFMCG" =>
switch idx_
1 => "CNXFMCG"
2 => "BRITANNIA"
3 => "COLPAL"
4 => "DABUR"
5 => "UBL"
6 => "GODREJCP"
7 => "HINDUNILVR"
8 => "ITC"
9 => "JUBLFOOD"
10 => "MARICO"
11 => "MCDOWELL_N"
12 => "NESTLEIND"
13 => "PGHH"
14 => "TATACONSUM"
=> ""
"CNXINFRA" =>
switch idx_
1 => "CNXINFRA"
2 => "RELIANCE"
3 => "TATAPOWER"
4 => "ADANIPORTS"
5 => "BHARTIARTL"
6 => "AMBUJACEM"
7 => "NTPC"
8 => "LT"
9 => "ONGC"
10 => "POWERGRID"
11 => "SIEMENS"
12 => "CONCOR"
13 => "DLF"
14 => "INDIGO"
=> ""
"CNXIT" =>
switch idx_
1 => "CNXIT"
2 => "COFORGE"
3 => "HCLTECH"
4 => "INFY"
5 => "LTI"
6 => "MINDTREE"
7 => "MPHASIS"
8 => "OFSS"
9 => "TCS"
10 => "TECHM"
11 => "WIPRO"
12 => "PERSISTENT"
13 => "NAUKRI"
14 => "TATAELXSI"
15 => "JUSTDIAL"
=> ""
"CNXMEDIA" =>
switch idx_
1 => "CNXMEDIA"
2 => "DBCORP"
3 => "DISHTV"
4 => "INOXLEISUR"
5 => "JAGRAN"
6 => "NETWORK18"
7 => "PVR"
8 => "SUNTV"
9 => "TV18BRDCST"
10 => "TVTODAY"
11 => "ZEEL"
12 => "SAREGAMA"
13 => "PFOCUS"
14 => "TIPSINDLTD"
=> ""
"CNXMETAL" =>
switch idx_
1 => "CNXMETAL"
2 => "JSWSTEEL"
3 => "TATASTEEL"
4 => "SAIL"
5 => "JINDALSTEL"
6 => "APLAPOLLO"
7 => "COALINDIA"
8 => "RATNAMANI"
9 => "NMDC"
10 => "NATIONALUM"
11 => "VEDL"
12 => "HINDALCO"
13 => "ADANIENT"
14 => "WELCORP"
=> ""
"CNXPHARMA" =>
switch idx_
1 => "CNXPHARMA"
2 => "SUNPHARMA"
3 => "DIVISLAB"
4 => "CIPLA"
5 => "DRREDDY"
6 => "BIOCON"
7 => "TORNTPHARM"
8 => "ALKEM"
9 => "ZYDUSLIFE"
10 => "AUROPHARMA"
11 => "LUPIN"
12 => "PEL"
13 => "GLAND"
14 => "LAURUSLABS"
=> ""
"CNXREALTY" =>
switch idx_
1 => "CNXREALTY"
2 => "DLF"
3 => "LODHA"
4 => "GODREJPROP"
5 => "OBEROIRLTY"
6 => "PRESTIGE"
7 => "PHOENIXLTD"
8 => "BRIGADE"
9 => "NBCC"
10 => "SOBHA"
11 => "SUNTECK"
12 => "IBREALEST"
13 => "MAHLIFE"
14 => "HEMIPROP"
=> ""
"CNXPSUBANK" =>
switch idx_
1 => "CNXPSUBANK"
2 => "BANKBARODA"
3 => "BANKINDIA"
4 => "CANBK"
5 => "CENTRALBK"
6 => "INDIANB"
7 => "IOB"
8 => "J_KBANK"
9 => "MAHABANK"
10 => "PNB"
11 => "PSB"
12 => "SBIN"
13 => "UCOBANK"
14 => "UNIONBANK"
=> ""
"CNXFINANCE" =>
switch idx_
1 => "CNXFINANCE"
2 => "HDFCBANK"
3 => "ICICIBANK"
4 => "HDFC"
5 => "KOTAKBANK"
6 => "SBIN"
7 => "BAJFINANCE"
8 => "AXISBANK"
9 => "BAJAJFINSV"
10 => "SBILIFE"
11 => "HDFCLIFE"
12 => "ICICIGI"
13 => "CHOLAFIN"
14 => "SBICARD"
15 => "SRTRANSFIN"
=> ""
f_update_data(idx_, period_, start_time_, bar_time_, close_) =>
var time_array_ = array.new<int>(4,0)
time_ = array.get(time_array_, period_)
if time_ == 0 and bar_time_ >= start_time_
time_ := start_time_
array.set(time_array_, period_, start_time_)
if time_ == start_time_ and matrix.get(data_, idx_, period_) == 0.0
matrix.set(data_, idx_, period_, close_[1])
if barstate.islast
close_start_ = matrix.get(data_, idx_, period_)
close_pct_ = close_/close_start_ -1
matrix.set(data_, idx_, 4+period_, close_pct_)
row_ = idx_+1
col_ = 1 + period_
table.cell(table_, col_, row_, str.format("{0,number,0.00%}", close_pct_), text_color = f_color(close_pct_), bgcolor = f_bg_color_price(close_pct_), text_size = i_text_size), col_ += 1
f_security(symbol_, idx_) =>
if barstate.isfirst and symbol_ != ""
row_ = idx_+1, col_ = 0
table.cell(table_, col_, row_, symbol_, text_color = color.new(color.white,50), bgcolor = color.new(bg_color_,80), text_size = i_text_size, text_halign = text.align_left), col_ += 1
[close_, bar_time_, high_250d_, low_250d_] = request.security("NSE:" + symbol_, timeframe.period, [close, time, ta.highest(high, 250), ta.lowest(low,250)], ignore_invalid_symbol = true)
if symbol_ != ""
f_update_data(idx_, CLOSE_1, i_time_1, bar_time_, close_)
f_update_data(idx_, CLOSE_2, i_time_2, bar_time_, close_)
f_update_data(idx_, CLOSE_3, i_time_3, bar_time_, close_)
f_update_data(idx_, CLOSE_4, i_time_4, bar_time_, close_)
if barstate.islast and symbol_ != ""
row_ = idx_+1
col_ = 5
table.cell(table_, col_, row_, str.format("{0,number,#.00}", close_), text_color = color.new(color.white,50), bgcolor = color.new(bg_color_,80), text_size = i_text_size, text_halign = text.align_right), col_ += 1
table.cell(table_, col_, row_, str.format("{0,number,#.00}", high_250d_), text_color = color.new(color.white,50), bgcolor = color.new(bg_color_,80), text_size = i_text_size, text_halign = text.align_right), col_ += 1
val_ = 1 - close_/high_250d_
table.cell(table_, col_, row_, str.format("{0,number,0.00%}", val_), text_color = color.new(color.white,50), bgcolor = f_bg_color_highlow(val_), text_size = i_text_size, text_halign = text.align_right), col_ += 1
table.cell(table_, col_, row_, str.format("{0,number,#.00}", low_250d_), text_color = color.new(color.white,50), bgcolor = color.new(bg_color_,80), text_size = i_text_size, text_halign = text.align_right), col_ += 1
val_ := close_/low_250d_-1
table.cell(table_, col_, row_, str.format("{0,number,0.00%}", val_), text_color = color.new(color.white,50), bgcolor = f_bg_color_highlow(-val_), text_size = i_text_size, text_halign = text.align_right), col_ += 1
if barstate.isfirst
table_ := table.new(position.middle_center, 20, 30, border_width = 1)
row_ = 0, col_ = 0
table.cell(table_, col_, row_, i_sector, text_color = text_color_, bgcolor = color.blue, text_size = i_text_size)
table.merge_cells(table_, 0,0,9,0)
row_ += 1
table.cell(table_, col_, row_, "Symbol", text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, str.format("{0}\n{1,date,yyyy-MM-dd}", i_time_1_txt, i_time_1), text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, str.format("{0}\n{1,date,yyyy-MM-dd}", i_time_2_txt, i_time_2), text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, str.format("{0}\n{1,date,yyyy-MM-dd}", i_time_3_txt, i_time_3), text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, str.format("{0}\n{1,date,yyyy-MM-dd}", i_time_4_txt, i_time_4), text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, "Close", text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, "250d High", text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, "% from High", text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, "250d Low", text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
table.cell(table_, col_, row_, "% from Low", text_color = text_color_, bgcolor = bg_color_, text_size = i_text_size), col_ += 1
idx_ = 1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
f_security(f_symbol(i_sector, idx_), idx_), idx_ +=1
|
Tilson Bull-Bear-Marker | https://www.tradingview.com/script/cjEtrlaK-Tilson-Bull-Bear-Marker/ | Lantzwat | https://www.tradingview.com/u/Lantzwat/ | 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/
// © Lantzwat
//@version=5
indicator("Tilson Bull-Bear-Marker", "Tilson BBM")
src = input.source(close, 'Source')
L1 = input.int(5, "T3 Length 1") // 5
L2 = input.int(8, "T3 Length 2") // 8
bShowCrossover = input.bool(true, "Show crossover marker")
T3tilson(float src, int len) =>
e1 = ta.ema(src, len)
e2 = ta.ema(e1, len)
e3 = ta.ema(e2, len)
e4 = ta.ema(e3, len)
e5 = ta.ema(e4, len)
e6 = ta.ema(e5, len)
a = 0.7 // alternatively 0.618
c1 = -1 * (a * a * a)
c2 = 3 * (a * a) + 3 * (a * a * a)
c3 = -6 * (a * a) - 3 * a - 3 * (a * a * a)
c4 = 1 + 3 * a + (a * a * a) + 3 * (a * a)
_return = c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3
T3_1 = T3tilson(src, L1)
T3_2 = T3tilson(src, L2)
c1 = T3_1 > T3_1 [1]
c2 = T3_2 > T3_2 [1]
ColorC1 = c1 ? color.new(color.blue, 0) : color.new(color.red, 0)
ColorC2 = c2 ? color.new(color.blue, 0) : color.new(color.red, 0)
lookback = last_bar_index < 20 ? last_bar_index : 20
tdiff = T3_1 - T3_2
factor = 10 / (ta.highest(tdiff,lookback) - ta.lowest(tdiff,lookback))
tdiff := tdiff * factor
tp1 = plot(tdiff, color=ColorC1, linewidth = 3)
tp2 = plot(tdiff * -1, color=ColorC2)
fillcol = c1 == c2 ? ColorC1 : na
fill(tp1, tp2, color=color.new(fillcol,70))
// --------------------
plotshape(bShowCrossover and ta.crossover(T3_1,T3_2) ? tdiff - 5 : na, location = location.absolute, style = shape.triangleup, color = color.new(color.blue,0), size = size.tiny)
plotshape(bShowCrossover and ColorC1 == color.blue and ColorC1[1] == color.red ? tdiff - 5 : na, location = location.absolute, style = shape.triangleup, color = color.new(color.green,0), size = size.tiny)
plotshape(bShowCrossover and ta.crossunder(T3_1,T3_2) ? tdiff + 5 : na, location = location.absolute, style = shape.triangledown, color = color.new(color.red,0), size = size.tiny)
plotshape(bShowCrossover and ColorC1 == color.red and ColorC1[1] == color.blue ? tdiff + 5 : na, location = location.absolute, style = shape.triangledown, color = color.new(color.yellow,0), size = size.tiny)
// Alerts --------------------
alertcondition(ta.crossover(T3_1,T3_2),"Tilson - bullish marker", "Tilson - turned bullish")
alertcondition(ta.crossover(T3_1,T3_2),"Tilson - bearish marker", "Tilson - turned bearish")
alertcondition(ColorC1 == color.blue and ColorC1[1] == color.red, "Tilson - early bullish marker", "Tilson - potentially bullish turn")
alertcondition(ColorC1 == color.red and ColorC1[1] == color.blue, "Tilson - early bearish marker", "Tilson - potentially bearish turn")
|
Stochastic Candles | https://www.tradingview.com/script/WzjUY89v-Stochastic-Candles/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 201 | 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/
// © peacefulLizard50262
//@version=5
indicator("Stoch", overlay = false)
OHLC(src, int len = 4) =>
Open = ta.sma(src[1], len)
High = ta.highest(src, 1)
Low = ta.lowest(src, 1)
Close = ta.wma(src, len)
[Open, High, Low, Close]
can = input.int(4, "Candle Transform Length")
length = input.int(14, "Length")
d = input.int(9, "%D Smoothing")
sel = input.bool(true, "Candle Colour", "Chance how the candles are colored. If this is enabled it will color the candles bassed on the transformed open/close. Otherwise this indicator will use source/source[1]")
red = input.color(color.new(#ef5350, 0), "")
green = input.color(color.new(#26a69a, 0), "")
src = ta.stoch(close, high, low, length)
D = ta.sma(ta.sma(src, d), 2)
[Open, High, Low, Close] = OHLC(src, can)
colour = sel ? Open < Close ? green : red : src > src[1] ? green : red
plot(D, "%D", color.orange)
plotcandle(Open, High, Low, Close, "%K", colour, colour, true, bordercolor = colour)
h0 = hline(80, "Upper Band", color=#787B86)
hline(50, "Middle Band", color=color.new(#787B86, 50))
h1 = hline(20, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background") |
Trend Slope Meter - Kaspricci | https://www.tradingview.com/script/9HksptPT/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 127 | 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/
// © Kaspricci
//@version=5
indicator("Trend Slope Meter - Kaspricci", shorttitle = "Trend Slope Meter", overlay = false)
trendSource = input.source(close, title = "Source")
headlineTrend = "Trend Settings"
calcOwnTrend = input.bool(true, "Calculate trend by moving average", group = headlineTrend, tooltip = "In case you select an external source,you can disable moving average calculation.")
maType = input.string("EMA", title = " Type", group = headlineTrend, options = ["EMA", "HMA", "SMA", "SWMA", "VWMA", "WMA"])
maLength = input.int(50, title = " Length", minval = 1, group = headlineTrend)
headlineSlope = "Slope Settings"
slLength = input.int(defval = 10, minval = 1, title = "Length", group = headlineSlope, tooltip = "Number of bars back to calculate the slope")
float ma = switch maType
"EMA" => ta.ema(trendSource, maLength)
"HMA" => ta.hma(trendSource, maLength)
"SMA" => ta.sma(trendSource, maLength)
"SWMA" => ta.swma(trendSource)
"VWMA" => ta.vwma(trendSource, maLength)
"WMA" => ta.wma(trendSource, maLength)
slope = calcOwnTrend ? ta.change(ma, slLength) / slLength / syminfo.mintick : ta.change(trendSource, slLength) / slLength / syminfo.mintick
upTH = hline( 45, "Upper Threshold", color.gray)
base = hline( 0, "Base Line", color.black, hline.style_solid)
lwTH = hline(-45, "Lower Threshold", color.gray)
fill(upTH, lwTH, title = "Background", color = color.rgb(100, 100, 100, 90))
plot(slope, "Slope", color.purple, linewidth = 2) |
Zig Zag Ratio Simplified | https://www.tradingview.com/script/CIk186OY-Zig-Zag-Ratio-Simplified/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 465 | 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/
// © RozaniGhani-RG
//@version=5
indicator('Zig Zag Ratio Simplified', 'ZZRS', overlay = true)
// 0. Inputs
// 1. Variables
// 2. Switches
// 3. Custom Functions
// 4. Calculations
// 5. Constructs
// ============================================================================= 0. Inputs {
T0 = 'Default : 10\nMin : 2\nMax : 50'
i_i_len = input.int( 10, 'Length', minval = 2, maxval = 50, tooltip = T0)
i_s_dir = input.string( 'Both', 'Show Colored Ratios', options = ['Both', 'Main', 'Sub', 'none'])
i_b_stat = input.bool( false, 'Show Ratio Status')
i_b_HL = input.bool( false, 'Show High Low Labels')
G1 = 'HELPER'
T1 = '1) Tick to show table\n2) Small font size recommended for mobile app or multiple layout'
T2 = 'Table must be tick before change table position'
i_b_table = input.bool( false, 'Show Helper |', group = G1, inline = 'Table1')
i_s_font = input.string('normal', 'Font size', group = G1, inline = 'Table1', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T1)
i_s_Y = input.string('bottom', 'Table Position', group = G1, inline = 'Table2', options = [ 'top', 'middle', 'bottom'])
i_s_X = input.string( 'left', '', group = G1, inline = 'Table2', options = ['left', 'center', 'right'], tooltip = T2)
// }
// ============================================================================= 1. Variables {
// ————————————————————————————————————————————————————————————————————————————— 1.1 Highest / Lowest {
float PH = ta.highestbars(high, i_i_len) == 0 ? high : na
float PL = ta.lowestbars(low, i_i_len) == 0 ? low : na
// }
// ————————————————————————————————————————————————————————————————————————————— 1.2 Dir {
var int dir = 0, dir := PL and na(PH) ? -1 : PH and na(PL) ? 1 : dir
// }
// ————————————————————————————————————————————————————————————————————————————— 1.3 Bool {
bool bool_both = dir == -1 or dir == 1, bool bool_pos = dir == 1, bool bool_neg = dir == -1
// }
// ————————————————————————————————————————————————————————————————————————————— 1.4 Array {
var max_array_size = 10, var zigzag = array.new_float(0), oldzigzag = array.copy(zigzag)
// }
// ————————————————————————————————————————————————————————————————————————————— 1.5 Others {
var line line_zz = na, var line line_ratio = na
var linefill fill_ratio = na
var label label_zz = na, var label label_ratio = na
var string ratio_true = na, var string ratio_icon = na, var string str_stat = na
var float ratio = na
var color color_ratio = na
var TBL = table.new(i_s_Y + '_' + i_s_X, 2, 5, border_width = 1)
// }
// }
// ============================================================================= 2. Switches {
[sw_up, sw_dn] = switch i_b_HL
false => [color.new(color.teal, 100), color.new(color.red, 100)]
true => [color.new(color.teal, 0), color.new(color.red, 0)]
bool_dir = switch i_s_dir
'Both' => bool_both
'Main' => bool_pos
'Sub' => bool_neg
// }
// ============================================================================= 3. Custom Functions {
add_to_zigzag(float[] pointer, float value, int bindex) =>
array.unshift(pointer, bindex)
array.unshift(pointer, value)
if array.size(pointer) > max_array_size
array.pop(pointer)
array.pop(pointer)
update_zigzag(float[] pointer, float value, int bindex, int dir) =>
if array.size(pointer) == 0
add_to_zigzag(pointer, value, bindex)
else
if dir == 1 and value > array.get(pointer, 0) or dir == -1 and value < array.get(pointer, 0)
array.set(pointer, 0, value)
array.set(pointer, 1, bindex)
0.
calc_ratio(float[] _float) =>
math.abs(array.get(_float, 0) - array.get(_float, 2)) / math.abs(array.get(_float, 2) - array.get(_float, 4))
get_color(float _float) =>
_float >= 0.371 and _float <= 0.930 ? color.red :
_float >= 1.130 and _float <= 3.618 ? color.blue :
_float > 0.930 and _float < 1.130 ? color.purple :
color.gray
get_stat(float _float) =>
_float >= 0.371 and _float <= 0.930 ? '\nRETRACEMENT' :
_float >= 1.130 and _float <= 3.618 ? '\nPROJECTION' :
_float > 0.930 and _float < 1.130 ? '\nDOUBLE\nTOP\nBOTTOM' :
na
get_icon(float _float) =>
_float >= 0.371 and _float <= 0.930 ? '✅' :
_float >= 1.130 and _float <= 3.618 ? '✅' :
_float > 0.930 and _float < 1.130 ? '❌' :
'❌'
string_HL(int _int, float[] _float) =>
_int == 1 ?
array.get(_float, 0) > array.get(_float, 4) ? 'HH' : 'LH' :
array.get(_float, 0) < array.get(_float, 4) ? 'LL' : 'HL'
line_HL(int _int, float[] _float) =>
_int == 1 ?
array.get(_float, 0) > array.get(_float, 2) ? color.teal : color.red :
array.get(_float, 0) < array.get(_float, 2) ? color.red : color.teal
switch_color(int _int, float[] _float) =>
_int == 1 ?
array.get(_float, 0) > array.get(_float, 4) ? sw_up : sw_dn :
array.get(_float, 0) < array.get(_float, 4) ? sw_dn : sw_up
row_text(int _column, int _row, string _str1, string _str2, color _color) =>
table.cell(TBL, _column, _row, _str1, text_color = color.white, bgcolor = _color, text_size = i_s_font)
table.cell(TBL, _column + 1, _row, _str2, text_color = color.white, bgcolor = _color, text_size = i_s_font)
// }
// ============================================================================= 4. Calculations {
dirchanged = ta.change(dir)
if PH or PL
if dirchanged
add_to_zigzag(zigzag, dir == 1 ? PH : PL, bar_index)
else
update_zigzag(zigzag, dir == 1 ? PH : PL, bar_index, dir)
// }
// ============================================================================= 5. Constructs {
if array.size(zigzag) >= 6
if array.get(zigzag, 0) != array.get(oldzigzag, 0) or array.get(zigzag, 1) != array.get(oldzigzag, 1)
if array.get(zigzag, 2) == array.get(oldzigzag, 2) and array.get(zigzag, 3) == array.get(oldzigzag, 3)
line.delete(line_zz)
line.delete(line_ratio)
label.delete(label_zz)
label.delete(label_ratio)
line_zz := line.new(
x1 = math.round(array.get(zigzag, 1)),
y1 = array.get(zigzag, 0),
x2 = math.round(array.get(zigzag, 3)),
y2 = array.get(zigzag, 2),
color = dir == 1 ? color.teal : color.red,
width = 2)
line_ratio := line.new(
x1 = math.round(array.get(zigzag, 1)),
y1 = array.get(zigzag, 0),
x2 = math.round(array.get(zigzag, 5)),
y2 = array.get(zigzag, 4),
color = color.new(color.blue, 100))
fcol = line_HL( 1, zigzag)
text_HL = string_HL( 1, zigzag)
txtcol = switch_color(1, zigzag)
label_zz := label.new(
x = math.round(array.get(zigzag, 1)),
y = array.get(zigzag, 0),
text = text_HL,
color = color.new(color.blue, 100),
textcolor = txtcol,
style = dir == 1 ? label.style_label_down : label.style_label_up)
ratio := calc_ratio(zigzag)
color_ratio := get_color(ratio)
ratio_true := get_stat(ratio)
ratio_icon := get_icon(ratio)
str_stat := i_b_stat ? ratio_true : na
label_ratio := label.new(
x = math.round(array.get(zigzag, 3)),
y = math.avg( array.get(zigzag, 0), array.get(zigzag, 4)),
text = str.tostring(ratio, '0.000 ') + ratio_icon + str_stat,
color = color.new(color.blue, 100),
textcolor = color_ratio,
style = label.style_label_center,
tooltip = str.tostring(ratio, '0.000 ') + ratio_icon + ratio_true)
if bool_dir
fill_ratio := linefill.new(line_zz, line_ratio, color.new(color_ratio, 85))
else
fill_ratio := linefill.new(line_zz, line_ratio, color.new(color_ratio, 100))
if barstate.islast
if i_b_table
row_text(0, 0, 'RETRACEMENT', '0.371 <= PRICE <= 0.930', color.red)
row_text(0, 1, 'PROJECTION', '1.130 <= PRICE <= 3.618', color.blue)
row_text(0, 2, 'DOUBLE TOP / BOTTOM', '0.930 < PRICE < 1.130', color.purple)
// } |
4C Expected Move (Weekly Options) | https://www.tradingview.com/script/4qxx5aTS-4C-Expected-Move-Weekly-Options/ | FourC | https://www.tradingview.com/u/FourC/ | 371 | 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/
// © FourC
//@version=5
indicator("4C Expected Move (Weekly Options)", shorttitle="4C ExpMove", overlay=true)
em = input.price(1, "Weekly Expected Move - Input next week's EM number based on weekly option pricing [use your broker for this]. It is most accurate to use the EM number for next week AFTER the Friday close and/or before the Monday open of the upcoming week.")
linesright = input(title='Extend Lines Right', defval=true)
show2sigma = input(title='Show 2 Standard Deviation Move', defval=false)
styleOption = input.string(title="Line Style", options=["solid (─)", "dashed (╌)", "dotted (┈)"], defval="solid (─)")
styleOptionx2 = input.string(title="Line Style 2 Standard Deviation", options=["solid (─)", "dashed (╌)", "dotted (┈)"], defval= "dashed (╌)")
linewidth = input(2, "Line Thickness")
wclosecolor = input(title='Last Week Close', defval=color.rgb(0,255,255,0))
posemcolor = input(title='Upper Expected Move', defval=color.rgb(0,255,0,0))
negemcolor = input(title='Lower Expected Move', defval=color.rgb(255,0,0,0))
showlabels = input(title='Show Labels', defval=true)
labelcolor = input(title='Expected Move Label Color', defval=color.white)
labelposition = input(5,'Label Postion (Higher = Further Right)')
lineStyle = (styleOption == "dotted (┈)") ? line.style_dotted :
(styleOption == "dashed (╌)") ? line.style_dashed :
line.style_solid
lineStyle2 = (styleOptionx2 == "dotted (┈)") ? line.style_dotted :
(styleOptionx2 == "dashed (╌)") ? line.style_dashed :
line.style_solid
wclose = request.security(syminfo.tickerid, "W", close[1], barmerge.gaps_off, barmerge.lookahead_on)
var line wcloseline = na
var line posemline = na
var line negemline = na
var line posemlinex2 = na
var line negemlinex2 = na
var label wcloselabel = na
var label wemposlabel = na
var label wemneglabel = na
var label wemposlabelx2 = na
var label wemneglabelx2 = na
posemx2calc = wclose + (2*em)
negemx2calc = wclose - (2*em)
if wclose[1] != wclose
line.set_x2(wcloseline, bar_index)
line.set_x2(posemline, bar_index)
line.set_x2(negemline, bar_index)
line.set_x2(posemlinex2, bar_index)
line.set_x2(negemlinex2, bar_index)
line.set_extend(wcloseline, extend.none)
line.set_extend(posemline, extend.none)
line.set_extend(negemline, extend.none)
line.set_extend(posemlinex2, extend.none)
line.set_extend(negemlinex2, extend.none)
label.delete(wcloselabel)
label.delete(wemposlabel)
label.delete(wemneglabel)
label.delete(wemposlabelx2)
label.delete(wemneglabelx2)
//Expected Move Lines
wcloseline := line.new(bar_index, wclose, bar_index, wclose, color=wclosecolor, style=lineStyle, width=linewidth)
posemline := line.new(bar_index, wclose + em, bar_index, wclose + em, color=posemcolor, style=lineStyle, width=linewidth)
negemline := line.new(bar_index, wclose - em, bar_index, wclose - em, color=negemcolor, style=lineStyle, width=linewidth)
posemlinex2 := line.new(bar_index, posemx2calc, bar_index, posemx2calc, color=posemcolor, style=lineStyle2, width=linewidth)
negemlinex2 := line.new(bar_index, negemx2calc, bar_index, negemx2calc, color=negemcolor, style=lineStyle2, width=linewidth)
line.delete(wcloseline[1])
line.delete(posemline[1])
line.delete(negemline[1])
line.delete(posemlinex2[1])
line.delete(negemlinex2[1])
if show2sigma != true
line.delete(posemlinex2)
line.delete(negemlinex2)
if linesright == true
line.set_x2(wcloseline, bar_index)
line.set_x2(posemline, bar_index)
line.set_x2(negemline, bar_index)
line.set_x2(posemlinex2, bar_index)
line.set_x2(negemlinex2, bar_index)
line.set_extend(wcloseline, extend.right)
line.set_extend(posemline, extend.right)
line.set_extend(negemline, extend.right)
line.set_extend(posemlinex2, extend.right)
line.set_extend(negemlinex2, extend.right)
//Expected Move Labels
if showlabels == true
wcloselabel := label.new(bar_index, wclose, 'WC: ' + str.tostring(wclose, '#.##'), style=label.style_none)
wemposlabel := label.new(bar_index, wclose + em, 'UpperEM: ' + str.tostring(wclose + em, '#.##'), style=label.style_none)
wemneglabel := label.new(bar_index, wclose - em, 'LowerEM: ' + str.tostring(wclose - em, '#.##'), style=label.style_none)
wemposlabelx2 := label.new(bar_index, posemx2calc, 'UpperEM x 2: ' + str.tostring(posemx2calc, '#.##'), style=label.style_none)
wemneglabelx2 := label.new(bar_index, negemx2calc, 'LowerEM x 2: ' + str.tostring(negemx2calc, '#.##'), style=label.style_none)
label.set_textcolor(wcloselabel, labelcolor)
label.set_textcolor(wemposlabel, labelcolor)
label.set_textcolor(wemneglabel, labelcolor)
label.set_textcolor(wemposlabelx2, labelcolor)
label.set_textcolor(wemneglabelx2, labelcolor)
if show2sigma != true
label.delete(wemposlabelx2)
label.delete(wemneglabelx2)
if not na(wcloseline) and line.get_x2(wcloseline) != bar_index
line.set_x2(wcloseline, bar_index)
line.set_x2(posemline, bar_index)
line.set_x2(negemline, bar_index)
line.set_x2(posemlinex2, bar_index)
line.set_x2(negemlinex2, bar_index)
label.set_x(wcloselabel, bar_index + labelposition)
label.set_x(wemposlabel, bar_index + labelposition)
label.set_x(wemneglabel, bar_index + labelposition)
label.set_x(wemposlabelx2, bar_index + labelposition)
label.set_x(wemneglabelx2, bar_index + labelposition) |
Volume Delta | https://www.tradingview.com/script/EdoTNVn8-Volume-Delta/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 73 | 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/
// © peacefulLizard50262
//@version=5
indicator("Volume Delta", "VD", overlay = false, format = format.volume)
length = input.int(1, "Delta Length", 1, 10)
delta() =>
float delta = 0.0
if length == 1
delta := ta.cum(volume-volume[1])
if length == 2
delta := ta.cum((volume-volume[2])/2)
else if length == 3
delta := ta.cum((volume+volume[1]-volume[2]-volume[3])/4)
else if length == 4
delta := ta.cum((volume+2*volume[1]-2*volume[3]-volume[4])/8)
else if length == 5
delta := ta.cum((volume+3*volume[1]+2*volume[2]-2*volume[3]-3*volume[4]-volume[5])/16)
else if length == 6
delta := ta.cum((volume+4*volume[1]+5*volume[2]-5*volume[4]-4*volume[5]-volume[6])/32)
else if length == 7
delta := ta.cum((volume+5*volume[1]+9*volume[2]+5*volume[3]-5*volume[4]-9*volume[5]-5*volume[6]-volume[7])/64)
else if length == 8
delta := ta.cum((volume+6*volume[1]+14*volume[2]+14*volume[3]-14*volume[5]-14*volume[6]-6*volume[7]-volume[8])/128)
else if length == 9
delta := ta.cum((volume+7*volume[1]+20*volume[2]+28*volume[3]+14*volume[4]-14*volume[5]-28*volume[6]-20*volume[7]-7*volume[8]-volume[9])/256)
else if length == 10
delta := ta.cum((volume+8*volume[1]+27*volume[2]+48*volume[3]+42*volume[4]-42*volume[6]-48*volume[7]-27*volume[8]-8*volume[9]-volume[10])/512)
delta
volume_delta = delta()
plot(volume_delta <= 0 ? na : volume_delta, style = plot.style_columns, color = open < close ? color.green : color.red)
|
Sw1tchFX - Average Daily Range | https://www.tradingview.com/script/PlT10Exh-Sw1tchFX-Average-Daily-Range/ | Sw1tchFX | https://www.tradingview.com/u/Sw1tchFX/ | 250 | 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/
// © Sw1tchFX
// _________ ____ __ .__ _______________ ___
// / _____/_ _ _/_ |/ |_ ____ | |__ \_ _____/\ \/ /
// \_____ \\ \/ \/ /| \ __\/ ___\| | \ | __) \ /
// / \\ / | || | \ \___| \| \ / \
// /_______ / \/\_/ |___||__| \___ >___| /\___ / /___/\ \
// \/ \/ \/ \/ \_/
//@version=5
indicator(title = "Sw1tchFX - Average Daily Range", shorttitle = "SADR", overlay = true)
//#region -------------------- Inputs
hist_values = input.bool(defval = false, title = 'Show Past ADRs?', tooltip = 'This will show the past ADR values based off your selected resolution', group = 'Inputs')
show_swing = input.bool(defval = false, title = 'Show Long Term Ranges?', tooltip = 'This will show you longer term ranges. These ranges are a baseline for longer term trades (hours, days)', group = 'Inputs')
show_scalp = input.bool(defval = false, title = 'Show Short Term Ranges?', tooltip = 'These will show you shorter term ranges. These ranges are a baseline for scalping based trades where profit levels and ratios are set (i.e. 3:1, 2:1 Risk to Reward)', group = 'Inputs')
res = input.timeframe(defval = 'D', title = 'Resolution', options = ['D','W','M'], tooltip = 'Allow you to change the resolution of the ADR from Daily, Weekly, or Monthly', group = 'Resolution')
//#endregion
//#region -------------------- Functions
daily_calc() =>
[day_one_high, day_one_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[1], low[1]], lookahead = barmerge.lookahead_on)
[day_two_high, day_two_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[2], low[2]], lookahead = barmerge.lookahead_on)
[day_three_high, day_three_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[3], low[3]], lookahead = barmerge.lookahead_on)
[day_four_high, day_four_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[4], low[4]], lookahead = barmerge.lookahead_on)
[day_five_high, day_five_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[5], low[5]], lookahead = barmerge.lookahead_on)
adr = ((day_one_high - day_one_low) + (day_two_high - day_two_low) + (day_three_high - day_three_low) + (day_four_high - day_four_low) + (day_five_high - day_five_low)) / 5
yesterday_calc() =>
[day_one_high, day_one_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[1], low[1]], lookahead = barmerge.lookahead_on)
y_move = day_one_high - day_one_low
yesterday_adr() =>
[day_one_high, day_one_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[2], low[2]], lookahead = barmerge.lookahead_on)
[day_two_high, day_two_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[3], low[3]], lookahead = barmerge.lookahead_on)
[day_three_high, day_three_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[4], low[4]], lookahead = barmerge.lookahead_on)
[day_four_high, day_four_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[5], low[5]], lookahead = barmerge.lookahead_on)
[day_five_high, day_five_low] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [high[6], low[6]], lookahead = barmerge.lookahead_on)
y_adr = ((day_one_high - day_one_low) + (day_two_high - day_two_low) + (day_three_high - day_three_low) + (day_four_high - day_four_low) + (day_five_high - day_five_low)) / 5
nround(x) =>
n = math.round(x / syminfo.mintick) * syminfo.mintick
pip_to_whole(number) =>
atr = ta.atr(14)
if syminfo.type == 'forex'
pips = atr < 1.0 ? (number / syminfo.mintick) / 10 : number
pips := atr >= 1.0 and atr < 100.0 and (syminfo.currency == 'JPY' or syminfo.currency == 'HUF' or syminfo.currency == 'INR') ? pips * 100 : pips
else if syminfo.type == 'crypto'
pips = atr < 1.0 ? (number / syminfo.mintick) / 10 : number
pips := atr >= 1.0 ? pips * 100 : pips
else
number
//#endregion
//#region -------------------- Function Calls
adr = daily_calc()
adr_pips = pip_to_whole(adr)
adr_pips := math.round(adr_pips)
y_move = yesterday_calc()
y_move_pips = pip_to_whole(y_move)
y_move_pips := math.round(y_move_pips)
y_move_75 = yesterday_adr()
y_move_p = pip_to_whole(y_move_75)
y_move_p := math.round(y_move_p)
y_move_75_pips = y_move_p * 0.75
y_move_75_pips := math.round(y_move_75_pips)
//#endregion
//#region -------------------- Daily Open Calls
//Calc Open
dopen = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, open, lookahead = barmerge.lookahead_on)
[dday, dclose_y, dclose_t] = request.security(ticker.new(syminfo.prefix, syminfo.ticker), res, [time_tradingday, time_close(res)[1], time_close(res)], lookahead = barmerge.lookahead_on)
//#endregion
//#region -------------------- Line / Label Vars and ADR Calculations
var line tl = na
var line high_100 = na
var line high_75 = na
var line high_50 = na
var line high_25 = na
var line low_25 = na
var line low_50 = na
var line low_75 = na
var line low_100 = na
//Labels
var label label_t1_open = na
var label label_high_100 = na
var label label_high_75 = na
var label label_high_50 = na
var label label_high_25 = na
var label label_low_25 = na
var label label_low_50 = na
var label label_low_75 = na
var label label_low_100 = na
//ADR Percentage Calculations
high_100_p = dopen + adr
high_75_p = dopen + adr * 0.75
high_50_P = dopen + adr * 0.50
high_25_p = dopen + adr * 0.25
low_25_p = dopen - adr * 0.25
low_50_p = dopen - adr * 0.50
low_75_p = dopen - adr * 0.75
low_100_p = dopen - adr
//#endregion
//#region -------------------- Lines and Labels
if hist_values
if ta.change(dclose_y)
tl := line.new(dclose_y, dopen, dclose_t, dopen , xloc = xloc.bar_time, color = color.new(color.white, 40), style = line.style_solid)
high_100 := line.new(dclose_y, high_100_p, dclose_t, high_100_p, color = color.new(#5bd50f, 10), style = line.style_solid, xloc = xloc.bar_time)
high_75 := line.new(dclose_y, high_75_p, dclose_t, high_75_p, color = color.new(#5bd50f, 20), style = line.style_solid, xloc = xloc.bar_time)
high_50 := line.new(dclose_y, high_50_P, dclose_t, high_50_P, color = color.new(#5bd50f, 30), style = line.style_solid, xloc = xloc.bar_time)
high_25 := line.new(dclose_y, high_25_p, dclose_t, high_25_p, color = color.new(#5bd50f, 40), style = line.style_solid, xloc = xloc.bar_time)
low_25 := line.new(dclose_y, low_25_p, dclose_t, low_25_p, color = color.new(#ea2700, 40), style = line.style_solid, xloc = xloc.bar_time)
low_50 := line.new(dclose_y, low_50_p, dclose_t, low_50_p, color = color.new(#ea2700, 30), style = line.style_solid, xloc = xloc.bar_time)
low_75 := line.new(dclose_y, low_75_p, dclose_t, low_75_p, color = color.new(#ea2700, 20), style = line.style_solid, xloc = xloc.bar_time)
low_100 := line.new(dclose_y, low_100_p, dclose_t, low_100_p, color = color.new(#ea2700, 10), style = line.style_solid, xloc = xloc.bar_time)
else
tl := line.new(dclose_y, dopen, last_bar_time, dopen , xloc = xloc.bar_time, color = color.new(color.white, 40), style = line.style_solid)
high_100 := line.new(dclose_y, high_100_p, last_bar_time, high_100_p, color = color.new(#5bd50f, 10), style = line.style_solid, xloc = xloc.bar_time)
high_75 := line.new(dclose_y, high_75_p, last_bar_time, high_75_p, color = color.new(#5bd50f, 20), style = line.style_solid, xloc = xloc.bar_time)
high_50 := line.new(dclose_y, high_50_P, last_bar_time, high_50_P, color = color.new(#5bd50f, 30), style = line.style_solid, xloc = xloc.bar_time)
high_25 := line.new(dclose_y, high_25_p, last_bar_time, high_25_p, color = color.new(#5bd50f, 40), style = line.style_solid, xloc = xloc.bar_time)
low_25 := line.new(dclose_y, low_25_p, last_bar_time, low_25_p, color = color.new(#ea2700, 40), style = line.style_solid, xloc = xloc.bar_time)
low_50 := line.new(dclose_y, low_50_p, last_bar_time, low_50_p, color = color.new(#ea2700, 30), style = line.style_solid, xloc = xloc.bar_time)
low_75 := line.new(dclose_y, low_75_p, last_bar_time, low_75_p, color = color.new(#ea2700, 20), style = line.style_solid, xloc = xloc.bar_time)
low_100 := line.new(dclose_y, low_100_p, last_bar_time, low_100_p, color = color.new(#ea2700, 10), style = line.style_solid, xloc = xloc.bar_time)
//Labels
label_t1_open := label.new(last_bar_time, dopen, size = size.normal, text = ' ' + 'Open | ' + str.tostring(dopen, format.mintick), style = label.style_none, textcolor = color.new(color.white, 10), xloc = xloc.bar_time)
label_high_100 := label.new(last_bar_time, high_100_p, size = size.normal, text = ' ' + '100% | ' + str.tostring(math.round(adr_pips)) + ' Pips' + ' | ' + str.tostring(high_100_p, format.mintick), style = label.style_none, textcolor = color.new(#5bd50f, 10), xloc = xloc.bar_time)
label_high_75 := label.new(last_bar_time, high_75_p, size = size.normal, text = ' ' + '75% | ' + str.tostring(math.round(adr_pips * 0.75)) + ' Pips' + ' | ' + str.tostring(high_75_p, format.mintick), style = label.style_none, textcolor = color.new(#5bd50f, 10), xloc = xloc.bar_time)
label_high_50 := label.new(last_bar_time, high_50_P, size = size.normal, text = ' ' + '50% | ' + str.tostring(math.round(adr_pips * 0.50)) + ' Pips' + ' | ' + str.tostring(high_50_P, format.mintick), style = label.style_none, textcolor = color.new(#5bd50f, 10), xloc = xloc.bar_time)
label_high_25 := label.new(last_bar_time, high_25_p, size = size.normal, text = ' ' + '25% | ' + str.tostring(math.round(adr_pips * 0.25)) + ' Pips' + ' | ' + str.tostring(high_25_p, format.mintick), style = label.style_none, textcolor = color.new(#5bd50f, 10), xloc = xloc.bar_time)
label_low_25 := label.new(last_bar_time, low_25_p, size = size.normal, text = ' ' + '25% | ' + str.tostring(math.round(adr_pips * 0.25)) + ' Pips' + ' | ' + str.tostring(low_25_p, format.mintick), style = label.style_none, textcolor = color.new(#ea2700, 10), xloc = xloc.bar_time)
label_low_50 := label.new(last_bar_time, low_50_p, size = size.normal, text = ' ' + '50% | ' + str.tostring(math.round(adr_pips * 0.50)) + ' Pips' + ' | ' + str.tostring(low_50_p, format.mintick), style = label.style_none, textcolor = color.new(#ea2700, 10), xloc = xloc.bar_time)
label_low_75 := label.new(last_bar_time, low_75_p, size = size.normal, text = ' ' + '75% | ' + str.tostring(math.round(adr_pips * 0.75)) + ' Pips' + ' | ' + str.tostring(low_75_p, format.mintick), style = label.style_none, textcolor = color.new(#ea2700, 10), xloc = xloc.bar_time)
label_low_100 := label.new(last_bar_time, low_100_p, size = size.normal, text = ' ' + '100% | ' + str.tostring(math.round(adr_pips)) + ' Pips' + ' | ' + str.tostring(low_100_p, format.mintick), style = label.style_none, textcolor = color.new(#ea2700, 10), xloc = xloc.bar_time)
//Delete Label
label.delete(label_t1_open[1])
label.delete(label_high_100[1])
label.delete(label_high_75[1])
label.delete(label_high_50[1])
label.delete(label_high_25[1])
label.delete(label_low_25[1])
label.delete(label_low_50[1])
label.delete(label_low_75[1])
label.delete(label_low_100[1])
//Delete Line
line.delete(tl[1])
line.delete(high_100[1])
line.delete(high_75[1])
line.delete(high_50[1])
line.delete(high_25[1])
line.delete(low_25[1])
line.delete(low_50[1])
line.delete(low_75[1])
line.delete(low_100[1])
//#endregion
//#region -------------------- Table Plots
//Plot strategy information in the table
strat_tbl = table.new(position.top_right, 2, 9)
//Colors for table
table.set_border_color(table_id = strat_tbl, border_color = color.white)
table.set_frame_color(strat_tbl, color.white)
//Logic for table info
//Current will be for the current ADR reading
current = res == 'D' ? '5 Day ADR' : res == 'W' ? '5 Week ADR' : res == 'M' ? '5 Month ADR' : na
//Yesterday will be for the previous ADR reading
yesterday = res == 'D' ? 'Yesterdays 5 Day ADR' : res == 'W' ? 'Last Weeks 5 Week ADR' : res == 'M' ? 'Last Months 5 Month ADR' : na
//Move will be the actual movement according to the previous ADR reading
move = res == 'D' ? 'Yesterdays Move' : res == 'W' ? 'Last Weeks Move' : res == 'M' ? 'Last Months Move' : na
//ht is for the recommended high time frame value for scalping
scalp_ht = 'Recommended HT Range'
scalp_ht_v = adr_pips * 0.03
scalp_ht_v := math.round(scalp_ht_v)
//mt is for the recommended medium time frame value for scalping
scalp_mt = 'Recommended MT Range'
scalp_mt_v = scalp_ht_v * 0.5
scalp_mt_v := math.round(scalp_mt_v)
//lt is for the recommended lower time frame value for scalping
scalp_lt = 'Recommended LT Range'
scalp_lt_v = scalp_mt_v * 0.5
scalp_lt_v := math.round(scalp_lt_v)
//ht is for the recommended high time frame value for swings
swing_ht = 'Recommended HT Range'
swing_ht_v = adr_pips * 0.1
swing_ht_v := math.round(swing_ht_v)
//mt is for the recommended medium time frame value for swings
swing_mt = 'Recommended MT Range'
swing_mt_v = swing_ht_v * 0.5
swing_mt_v := math.round(swing_mt_v)
//lt is for the recommended lower time frame value for swings
swing_lt = 'Recommended LT Range'
swing_lt_v = swing_mt_v * 0.5
swing_lt_v := math.round(swing_lt_v)
//Table info
table.cell(strat_tbl, 0, 0, str.tostring(current), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 0, 1, str.tostring(yesterday), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 0, 2, str.tostring(move), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
if show_swing
table.cell(strat_tbl, 0, 3, str.tostring(swing_ht), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 0, 4, str.tostring(swing_mt), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 0, 5, str.tostring(swing_lt), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
else if show_scalp
table.cell(strat_tbl, 0, 3, str.tostring(scalp_ht), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 0, 4, str.tostring(scalp_mt), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 0, 5, str.tostring(scalp_lt), text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
//Table value
//Anything less than 100 pips probably not worth the time, so turns red in these cases
bg_adr = adr_pips > 100 ? color.new(#5bd50f, 40) : color.new(#ea2700, 40)
//If yesterdays value is greater than todays, it will be green
bg_y_move = y_move_p > adr_pips ? color.new(#5bd50f, 40) : color.new(#ea2700, 40)
//Green if price move 75% of yesterdays ADR
bg_y_move_75 = y_move_pips > y_move_75_pips ? color.new(#5bd50f, 40) : color.new(#ea2700, 40)
table.cell(strat_tbl, 1, 0, str.tostring(adr_pips), text_size = size.auto, text_color = color.white, bgcolor = bg_adr, text_halign = text.align_left)
table.cell(strat_tbl, 1, 1, str.tostring(y_move_p), text_size = size.auto, text_color = color.white, bgcolor = bg_y_move, text_halign = text.align_left)
table.cell(strat_tbl, 1, 2, str.tostring(y_move_pips), text_size = size.auto, text_color = color.white, bgcolor = bg_y_move_75, text_halign = text.align_left)
if syminfo.type == 'crypto'
if show_swing
table.cell(strat_tbl, 1, 3, str.tostring(swing_ht_v) + ' R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 4, str.tostring(swing_mt_v) + ' R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 5, str.tostring(swing_lt_v) + ' R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
if show_scalp
table.cell(strat_tbl, 1, 3, str.tostring(scalp_ht_v) + ' R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 4, str.tostring(scalp_mt_v) + ' R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 5, str.tostring(scalp_lt_v) + ' R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
if syminfo.type == 'forex'
if show_swing
table.cell(strat_tbl, 1, 3, str.tostring(swing_ht_v) + '0 R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 4, str.tostring(swing_mt_v) + '0 R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 5, str.tostring(swing_lt_v) + '0 R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
if show_scalp
table.cell(strat_tbl, 1, 3, str.tostring(scalp_ht_v) + '0 R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 4, str.tostring(scalp_mt_v) + '0 R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
table.cell(strat_tbl, 1, 5, str.tostring(scalp_lt_v) + '0 R', text_size = size.auto, text_color = color.white, bgcolor = color.rgb(35, 35, 35), text_halign = text.align_left)
//#endregion
//#region -------------------- Alerts
//Section if you would like to input custom alerts
//#endregion
|
Candlestick - Kicker Pattern | https://www.tradingview.com/script/BUpvLJRy-Candlestick-Kicker-Pattern/ | FxCloudTrader | https://www.tradingview.com/u/FxCloudTrader/ | 41 | 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/
// © FxCloudTrader
//@version=5
indicator("Candlestick - Kicker Pattern", shorttitle = 'Kicker', overlay = true)
_bodyPencLeft = input.int(0, 'Minimum body % for left bar', minval=0, maxval=100, step=5, tooltip = 'Minimum body to range percentage for the left formation')
_bodyPencRight = input.int(0, 'Minimum body % for right bar', minval=0, maxval=100, step=5, tooltip = 'Minimum body to range percentage for the right formation')
getRange(x, y) => math.abs(x - y)
condition_kicker_up_threshold = open[1] > close[1] and
open < close and
open > open[1] and
low > low[1] and
getRange(open[1], close[1])/getRange(high[1], low[1]) * 100> _bodyPencLeft and
getRange(open, close)/getRange(high, low) * 100> _bodyPencRight
condition_kicker_dn_threshold = open[1] < close[1] and
open > close and
open < open[1] and
high < high[1] and
getRange(open[1], close[1])/getRange(high[1], low[1]) * 100> _bodyPencLeft and
getRange(open, close)/getRange(high, low) * 100> _bodyPencRight
plotshape(condition_kicker_up_threshold?close:na, 'kicker up', style = shape.circle, location = location.belowbar, size = size.auto, color = color.green)
plotshape(condition_kicker_dn_threshold?close:na, 'kicker up', style = shape.circle, location = location.abovebar, size = size.auto, color = color.red)
|
Delta Stochastic | https://www.tradingview.com/script/OFRhHXRc-Delta-Stochastic/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 59 | 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/
// © peacefulLizard50262
//@version=5
indicator("Delta Stochastic", overlay = false)
stoch = input.int(14, "Stochastic Length", 1)
stoch_smoothing = input.int(1, "Stochastic Smoothing", 1)
sum_window = input.int(6, "Sum Window")
// Use the EMA for the stochastic calculation
k2 = ta.ema(ta.stoch(close, high, low, stoch), stoch_smoothing) - 50
sum = math.sum(k2,sum_window)
cum = ta.cum(sum - sum[1])
colour = (cum>=0 ? (cum[1] < cum ? color.rgb(89, 255, 186) : color.rgb(167, 255, 215)) : (cum[1] < cum ? color.rgb(255, 183, 183) : color.red))
// Add labels to the x- and y-axes
plot(cum, color = colour, style = plot.style_area,
linewidth = 2, title = "Delta Stochastic")
// Add a signal line to the plot
signal = ta.sma(cum, 5)
plot(signal, color = color.orange, style = plot.style_line,
linewidth = 2, title = "Signal Line")
|
Rolling HTF Liquidity Levels [CHE] | https://www.tradingview.com/script/NX45gAcM/ | chervolino | https://www.tradingview.com/u/chervolino/ | 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/
// © chervolino
// the program code is inspired by sbtnc https://de.tradingview.com/script/PL0iPxy0-HTF-Liquidity-Levels/
// and sbtnc used fixed timeframes
// my version use a rolling time frame modul - so that the functionality is increased and the clarity
//@version=5
indicator("Rolling HTF Liquidity Levels [CHE]", "HTF Liquidity Rolling", overlay=true, max_lines_count=500)
//--------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------
var START_OFFSET = 0
var END_OFFSET = 25
//--------------------------------------------------------------------
// Inputs
//--------------------------------------------------------------------
var g_htf = 'HTF Liquidity :'
var g_purged = 'Liquidity :'
string GRP2 = 'Time Period :'
bool showInfoBoxInput = input.bool(true, "Show time period", group = GRP2)
string infoBoxSizeInput = input.string("small", "Size ", inline = "21", group = GRP2, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", inline = "21", group = GRP2, options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", inline = "21", group = GRP2, options = ["left", "center", "right"])
color infoBoxColorInput = input.color(color.gray, "", inline = "21", group = GRP2)
color infoBoxTxtColorInput = input.color(color.white, "T", inline = "21", group = GRP2)
i_isAutoEnabled = input (true, "Auto", inline="Auto", group=g_htf)
i_AutoAboveLiquidityColor = input (#00ff08, "", inline="Auto", group=g_htf)
i_AutoBelowLiquidityColor = input (#ff061b, "", inline="Auto", group=g_htf)
i_AutoWidth = input (2, "Width", inline="Auto", group=g_htf)
i_purgedLevelColor = input (color.new(color.gray, 60), "Color", group=g_purged)
i_purgedLevelStyle = input.string ("Dashed", "Style", ["Solid", "Dashed", "Dotted"], group=g_purged)
//--------------------------------------------------------------------
// Variables declarations
//--------------------------------------------------------------------
var highsArray = array.new_float()
var lowsArray = array.new_float()
var highLinesArray = array.new_line()
var lowLinesArray = array.new_line()
var purgedLinesArray = array.new_line()
var float dayHigh = na
var float dayLow = na
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
timeStep_translate() =>
int tfInMs = timeframe.in_seconds() * 1000
string step =
switch
tfInMs <= MS_IN_MIN => "60"
tfInMs <= MS_IN_MIN * 5 => "240"
tfInMs <= MS_IN_HOUR => "1D"
tfInMs <= MS_IN_HOUR * 4 => "3D"
tfInMs <= MS_IN_HOUR * 12 => "7D"
tfInMs <= MS_IN_DAY => "1M"
tfInMs <= MS_IN_DAY * 7 => "3M"
=> "12M"
[prevDayHigh, prevDayLow] = request.security(syminfo.tickerid, timeStep_translate(), [high[1], low[1]], lookahead=barmerge.lookahead_on)
//--------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------
f_drawLine(float _y, color _c, int _w=1) => line.new(bar_index, _y, bar_index, _y, color=_c, width=_w)
f_create(float _high, float _low, color _upperColor, color _lowerColor, int _linewidth) =>
array.push(highsArray, _high)
array.push(lowsArray, _low)
array.push(highLinesArray, f_drawLine(_high, _upperColor, _linewidth))
array.push(lowLinesArray, f_drawLine(_low, _lowerColor, _linewidth))
f_updateStickyLevels(array<line> _levels) =>
for _line in _levels
line.set_x1(_line, bar_index + START_OFFSET)
line.set_x2(_line, bar_index + END_OFFSET)
f_moveLevel(array<line> _from, array<line> _to, line _level, int _index) =>
array.push(_to, _level)
array.remove(_from, _index)
f_highlightPurgedLevel(line _level) =>
_style = i_purgedLevelStyle == "Solid" ? line.style_solid : i_purgedLevelStyle == "Dashed" ? line.style_dashed : line.style_dotted
line.set_color(_level, i_purgedLevelColor)
line.set_style(_level, _style)
f_updateUpperLevels(float _high, array<float> _highs, array<line> _levels, array<line> _purgedLevels) =>
while array.min(_highs) < _high
for [_index, _value] in _highs
if _high > _value
_line = array.get(_levels, _index)
f_highlightPurgedLevel(_line)
f_moveLevel(_levels, _purgedLevels, _line, _index)
array.remove(_highs, _index)
f_updateLowerLevels(float _low, array<float> _lows, array<line> _levels, array<line> _purgedLevels) =>
while array.max(_lows) > _low
for [_index, _value] in _lows
if _low < _value
_line = array.get(_levels, _index)
f_highlightPurgedLevel(_line)
f_moveLevel(_levels, _purgedLevels, _line, _index)
array.remove(_lows, _index)
f_clearLevels(array<line> _levels) =>
while array.size(_levels) > 0
for [_index, _line] in _levels
line.delete(array.remove(_levels, _index))
f_isHigherTimeframe(string _timeframe) => timeframe.in_seconds() <= timeframe.in_seconds(_timeframe)
//--------------------------------------------------------------------
// Logic
//--------------------------------------------------------------------
if i_isAutoEnabled and f_isHigherTimeframe(timeStep_translate()) and ta.change(time(timeStep_translate()))
f_create(prevDayHigh, prevDayLow, i_AutoAboveLiquidityColor, i_AutoBelowLiquidityColor, i_AutoWidth)
if barstate.islast
f_updateStickyLevels(highLinesArray)
f_updateStickyLevels(lowLinesArray)
f_updateStickyLevels(purgedLinesArray)
f_updateUpperLevels(high, highsArray, highLinesArray, purgedLinesArray)
f_updateLowerLevels(low, lowsArray, lowLinesArray, purgedLinesArray)
if ta.change(time(timeStep_translate()))
f_clearLevels(purgedLinesArray)
// Display of time period.
var table tfDisplay = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 2, 2)
if showInfoBoxInput and barstate.islastconfirmedhistory
table.cell(tfDisplay, 0, 0, "Timeframe: " + timeStep_translate(), bgcolor = infoBoxColorInput, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput)
|
Close Candles | https://www.tradingview.com/script/b6jfH5i1-Close-Candles/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("Close Candles", overlay = true)
OHLC(src, int len = 4) =>
Open = ta.sma(src[1], len)
High = ta.highest(src, 1)
Low = ta.lowest(src, 1)
Close = ta.wma(src, len)
[Open, High, Low, Close]
src = input.source(close, "Source")
len = input.int(4, "Length")
sel = input.bool(true, "Candle Colour", "Chance how the candles are colored. If this is enabled it will color the candles bassed on the transformed open/close. Otherwise this indicator will use source/source[1]")
red = input.color(color.new(#ef5350, 0), "")
green = input.color(color.new(#26a69a, 0), "")
[Open, High, Low, Close] = OHLC(src, len)
colour = sel ? Open < Close ? green : red : src > src[1] ? green : red
plotcandle(Open, High, Low, Close, "RSI Candle", colour, colour, true, bordercolor = colour)
|
Timeframe Continuity [TFO] | https://www.tradingview.com/script/qECtmYcT-Timeframe-Continuity-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,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/
// © tradeforopp
//@version=5
indicator("Timeframe Continuity [TFO]", "Timeframe Continuity [TFO]", true, max_lines_count = 500, max_labels_count = 500)
// -------------------------------------------------- Inputs --------------------------------------------------
var g1 = "Settings"
table_position = input.string('Top Right', "Table Position", options = ['Bottom Center', 'Bottom Left', 'Bottom Right', 'Middle Center', 'Middle Left', 'Middle Right', 'Top Center', 'Top Left', 'Top Right'], group = g1)
display = input.string('Horizontal', "Table Display", options = ['Horizontal', 'Vertical'], group = g1)
paint_ftfc = input.bool(true, "FTFC Candles", inline = "FTFC", tooltip = "Paint candles as FTFC Up/Down/Neutral", group = g1)
ftfc_up_color = input.color(color.rgb(0, 255, 0), "", inline = "FTFC", group = g1)
ftfc_dn_color = input.color(color.rgb(255, 0, 0), "", inline = "FTFC", group = g1)
ftfc_nu_color = input.color(color.gray, "", inline = "FTFC", group = g1)
ftfc_labels = input.bool(false, "Labels", inline = "LABEL", group = g1)
ftfc_label_type = input.string("Flip", "", inline = "LABEL", options = ['Flip', 'Any'], tooltip = "Flip will only plot labels for the first FTFC Up/Down instance. Any will plot labels for any new indication of FTFC", group = g1)
show_mbhl = input.bool(false, "Show Mother Bar High & Low", tooltip = "If a given timeframe is currently trading as an inside bar, it will plot the previous high and low that must be exceeded to no longer be an inside bar", group = g1)
var g3 = "Table Colors"
text_color = input.color(color.white, "Text", group = g3)
up_close_color = input.color(color.new(color.teal, 0), "Up-Close", group = g3)
dn_close_color = input.color(color.new(color.red, 0), "Down-Close", group = g3)
inside_up_color = input.color(color.new(color.blue, 0), "Inside-Up-Close", group = g3)
inside_dn_color = input.color(color.new(color.purple, 0), "Inside-Down-Close", group = g3)
var g2 = "Timeframes"
tf1 = input.timeframe("D", "TF 1", inline = "1", group = g2)
tf2 = input.timeframe("60", "TF 2", inline = "2", group = g2)
tf3 = input.timeframe("30", "TF 3", inline = "3", group = g2)
tf4 = input.timeframe("15", "TF 4", inline = "4", group = g2)
tf5 = input.timeframe("5", "TF 5", inline = "5", group = g2)
tf6 = input.timeframe("D", "TF 6", inline = "6", group = g2)
tf7 = input.timeframe("60", "TF 7", inline = "7", group = g2)
tf8 = input.timeframe("30", "TF 8", inline = "8", group = g2)
tf9 = input.timeframe("15", "TF 9", inline = "9", group = g2)
tf10 = input.timeframe("5", "TF 10", inline = "10", group = g2)
y1 = input.bool(true, "", inline = "1", group = g2)
y2 = input.bool(true, "", inline = "2", group = g2)
y3 = input.bool(true, "", inline = "3", group = g2)
y4 = input.bool(true, "", inline = "4", group = g2)
y5 = input.bool(true, "", inline = "5", group = g2)
y6 = input.bool(false, "", inline = "6", group = g2)
y7 = input.bool(false, "", inline = "7", group = g2)
y8 = input.bool(false, "", inline = "8", group = g2)
y9 = input.bool(false, "", inline = "9", group = g2)
y10 = input.bool(false, "", inline = "10", group = g2)
// -------------------------------------------------- Inputs --------------------------------------------------
// -------------------------------------------------- Variables --------------------------------------------------
[o1, h1, l1] = request.security(syminfo.tickerid, tf1, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o2, h2, l2] = request.security(syminfo.tickerid, tf2, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o3, h3, l3] = request.security(syminfo.tickerid, tf3, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o4, h4, l4] = request.security(syminfo.tickerid, tf4, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o5, h5, l5] = request.security(syminfo.tickerid, tf5, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o6, h6, l6] = request.security(syminfo.tickerid, tf6, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o7, h7, l7] = request.security(syminfo.tickerid, tf7, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o8, h8, l8] = request.security(syminfo.tickerid, tf8, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o9, h9, l9] = request.security(syminfo.tickerid, tf9, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
[o10, h10, l10] = request.security(syminfo.tickerid, tf10, [open, high, low], barmerge.gaps_off, barmerge.lookahead_on)
var tf1_h = array.new_float()
var tf2_h = array.new_float()
var tf3_h = array.new_float()
var tf4_h = array.new_float()
var tf5_h = array.new_float()
var tf6_h = array.new_float()
var tf7_h = array.new_float()
var tf8_h = array.new_float()
var tf9_h = array.new_float()
var tf10_h = array.new_float()
var tf1_l = array.new_float()
var tf2_l = array.new_float()
var tf3_l = array.new_float()
var tf4_l = array.new_float()
var tf5_l = array.new_float()
var tf6_l = array.new_float()
var tf7_l = array.new_float()
var tf8_l = array.new_float()
var tf9_l = array.new_float()
var tf10_l = array.new_float()
var mbh_1 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_2 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_3 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_4 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_5 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_6 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_7 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_8 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_9 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbh_10 = line.new(na, na, na, na, color = color.new(up_close_color, 0), extend = extend.right)
var mbl_1 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_2 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_3 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_4 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_5 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_6 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_7 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_8 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_9 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbl_10 = line.new(na, na, na, na, color = color.new(dn_close_color, 0), extend = extend.right)
var mbh_label_1 = label.new(na, na, str.tostring(tf1) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_2 = label.new(na, na, str.tostring(tf2) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_3 = label.new(na, na, str.tostring(tf3) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_4 = label.new(na, na, str.tostring(tf4) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_5 = label.new(na, na, str.tostring(tf5) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_6 = label.new(na, na, str.tostring(tf6) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_7 = label.new(na, na, str.tostring(tf7) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_8 = label.new(na, na, str.tostring(tf8) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_9 = label.new(na, na, str.tostring(tf9) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbh_label_10 = label.new(na, na, str.tostring(tf10) + " H", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_down)
var mbl_label_1 = label.new(na, na, str.tostring(tf1) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_2 = label.new(na, na, str.tostring(tf2) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_3 = label.new(na, na, str.tostring(tf3) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_4 = label.new(na, na, str.tostring(tf4) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_5 = label.new(na, na, str.tostring(tf5) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_6 = label.new(na, na, str.tostring(tf6) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_7 = label.new(na, na, str.tostring(tf7) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_8 = label.new(na, na, str.tostring(tf8) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_9 = label.new(na, na, str.tostring(tf9) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
var mbl_label_10 = label.new(na, na, str.tostring(tf10) + " L", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_up)
// -------------------------------------------------- Variables --------------------------------------------------
// -------------------------------------------------- Functions --------------------------------------------------
get_table_pos(pos) =>
result = switch pos
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Top Right" => position.top_right
result
update_hl(_ah, _al, _tf, _h, _l) =>
if timeframe.change(_tf)
_ah.unshift(_h[1])
_al.unshift(_l[1])
if _ah.size() > 3
_ah.pop()
_al.pop()
check_tfc(_tfc, _ah, _al, _h, _l) =>
color table_color = na
if _ah.size() > 0
if _h <= _ah.get(0) and _l >= _al.get(0)
if _tfc
table_color := inside_up_color
else
table_color := inside_dn_color
else
if _tfc
table_color := up_close_color
else
table_color := dn_close_color
table_color
draw_lines(_h, _l, _ah, _al, _mbh, _mbl, _mbhl, _mbll, _idx, _u) =>
i = _idx - 1
if _ah.size() > 0 and _u.get(i)
if _h <= _ah.get(0) and _l >= _al.get(0)
_mbh.set_xy1(bar_index, _ah.get(0))
_mbh.set_xy2(bar_index + 1, _ah.get(0))
_mbhl.set_xy(bar_index, _ah.get(0))
_mbl.set_xy1(bar_index, _al.get(0))
_mbl.set_xy2(bar_index + 1, _al.get(0))
_mbll.set_xy(bar_index, _al.get(0))
else
_mbh.set_xy1(na, na)
_mbh.set_xy2(na, na)
_mbhl.set_xy(na, na)
_mbl.set_xy1(na, na)
_mbl.set_xy2(na, na)
_mbll.set_xy(na, na)
// -------------------------------------------------- Functions --------------------------------------------------
// -------------------------------------------------- Logic --------------------------------------------------
update_hl(tf1_h, tf1_l, tf1, h1, l1)
update_hl(tf2_h, tf2_l, tf2, h2, l2)
update_hl(tf3_h, tf3_l, tf3, h3, l3)
update_hl(tf4_h, tf4_l, tf4, h4, l4)
update_hl(tf5_h, tf5_l, tf5, h5, l5)
update_hl(tf6_h, tf6_l, tf6, h6, l6)
update_hl(tf7_h, tf7_l, tf7, h7, l7)
update_hl(tf8_h, tf8_l, tf8, h8, l8)
update_hl(tf9_h, tf9_l, tf9, h9, l9)
update_hl(tf10_h, tf10_l, tf10, h10, l10)
// Check if up-close
tfc1 = close > o1
tfc2 = close > o2
tfc3 = close > o3
tfc4 = close > o4
tfc5 = close > o5
tfc6 = close > o6
tfc7 = close > o7
tfc8 = close > o8
tfc9 = close > o9
tfc10 = close > o10
use_arr = array.from(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10)
tfc_arr = array.from(tfc1, tfc2, tfc3, tfc4, tfc5, tfc6, tfc7, tfc8, tfc9, tfc10)
// Determine FTFC
ftfc_up = true
ftfc_dn = true
var bool ftfc_up_last = na
for i = 0 to tfc_arr.size() - 1
if use_arr.get(i)
if tfc_arr.get(i)
ftfc_dn := false
else
ftfc_up := false
if ftfc_up and not ftfc_up[1]
ftfc_up_last := true
if ftfc_labels
if ftfc_label_type == 'Flip' ? (ftfc_up_last and not ftfc_up_last[1]) : true
label.new(bar_index, low, "FTFC Up", color = color.new(up_close_color, 0), textcolor = color.white, style = label.style_label_up)
if ftfc_dn and not ftfc_dn[1]
ftfc_up_last := false
if ftfc_labels
if ftfc_label_type == 'Flip' ? (not ftfc_up_last and ftfc_up_last[1]) : true
label.new(bar_index, high, "FTFC Down", color = color.new(dn_close_color, 0), textcolor = color.white, style = label.style_label_down)
// Change bar color according to FTFC
barcolor(not paint_ftfc ? na : ftfc_up ? ftfc_up_color : ftfc_dn ? ftfc_dn_color : ftfc_nu_color)
if show_mbhl
draw_lines(h1, l1, tf1_h, tf1_l, mbh_1, mbl_1, mbh_label_1, mbl_label_1, 1, use_arr)
draw_lines(h2, l2, tf2_h, tf2_l, mbh_2, mbl_2, mbh_label_2, mbl_label_2, 2, use_arr)
draw_lines(h3, l3, tf3_h, tf3_l, mbh_3, mbl_3, mbh_label_3, mbl_label_3, 3, use_arr)
draw_lines(h4, l4, tf4_h, tf4_l, mbh_4, mbl_4, mbh_label_4, mbl_label_4, 4, use_arr)
draw_lines(h5, l5, tf5_h, tf5_l, mbh_5, mbl_5, mbh_label_5, mbl_label_5, 5, use_arr)
draw_lines(h6, l6, tf6_h, tf6_l, mbh_6, mbl_6, mbh_label_6, mbl_label_6, 6, use_arr)
draw_lines(h7, l7, tf7_h, tf7_l, mbh_7, mbl_7, mbh_label_7, mbl_label_7, 7, use_arr)
draw_lines(h8, l8, tf8_h, tf8_l, mbh_8, mbl_8, mbh_label_8, mbl_label_8, 8, use_arr)
draw_lines(h9, l9, tf9_h, tf9_l, mbh_9, mbl_9, mbh_label_9, mbl_label_9, 9, use_arr)
draw_lines(h10, l10, tf10_h, tf10_l, mbh_10, mbl_10, mbh_label_10, mbl_label_10, 10, use_arr)
// -------------------------------------------------- Logic --------------------------------------------------
// -------------------------------------------------- Table --------------------------------------------------
// Create TFC table
var table tfc = table.new(get_table_pos(table_position), 10, 10)
horizontal = display == 'Horizontal'
if barstate.islast
if y1
table.cell(tfc, horizontal ? 0 : 0, horizontal ? 0 : 0, str.tostring(tf1), text_color = text_color, bgcolor = check_tfc(tfc1, tf1_h, tf1_l, h1, l1))
if y2
table.cell(tfc, horizontal ? 1 : 0, horizontal ? 0 : 1, str.tostring(tf2), text_color = text_color, bgcolor = check_tfc(tfc2, tf2_h, tf2_l, h2, l2))
if y3
table.cell(tfc, horizontal ? 2 : 0, horizontal ? 0 : 2, str.tostring(tf3), text_color = text_color, bgcolor = check_tfc(tfc3, tf3_h, tf3_l, h3, l3))
if y4
table.cell(tfc, horizontal ? 3 : 0, horizontal ? 0 : 3, str.tostring(tf4), text_color = text_color, bgcolor = check_tfc(tfc4, tf4_h, tf4_l, h4, l4))
if y5
table.cell(tfc, horizontal ? 4 : 0, horizontal ? 0 : 4, str.tostring(tf5), text_color = text_color, bgcolor = check_tfc(tfc5, tf5_h, tf5_l, h5, l5))
if y6
table.cell(tfc, horizontal ? 5 : 0, horizontal ? 0 : 5, str.tostring(tf6), text_color = text_color, bgcolor = check_tfc(tfc6, tf6_h, tf6_l, h6, l6))
if y7
table.cell(tfc, horizontal ? 6 : 0, horizontal ? 0 : 6, str.tostring(tf7), text_color = text_color, bgcolor = check_tfc(tfc7, tf7_h, tf7_l, h7, l7))
if y8
table.cell(tfc, horizontal ? 7 : 0, horizontal ? 0 : 7, str.tostring(tf8), text_color = text_color, bgcolor = check_tfc(tfc8, tf8_h, tf8_l, h8, l8))
if y9
table.cell(tfc, horizontal ? 8 : 0, horizontal ? 0 : 8, str.tostring(tf9), text_color = text_color, bgcolor = check_tfc(tfc9, tf9_h, tf9_l, h9, l9))
if y10
table.cell(tfc, horizontal ? 9 : 0, horizontal ? 0 : 9, str.tostring(tf10), text_color = text_color, bgcolor = check_tfc(tfc10, tf10_h, tf10_l, h10, l10))
// -------------------------------------------------- Table -------------------------------------------------- |
Heiken Ashi Swing High/Low | https://www.tradingview.com/script/GzuyxnXU-Heiken-Ashi-Swing-High-Low/ | TheBacktestGuy | https://www.tradingview.com/u/TheBacktestGuy/ | 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/
// © wallneradam
//@version=5
indicator("Heiken Ashi Swing High/Low", "HASwing", overlay=true, timeframe="", timeframe_gaps=false)
import wallneradam/TAExt/9
type = input.string("High/Low", "Type", ["High/Low", "HA Open/Close"], tooltip="Which levels to use for upper and lower?")
[o, h, l, c] = TAExt.heiken_ashi()
var float swing_high = na
var float swing_low = na
if c[1] > o[1] and c < o
swing_high := type == "High/Low" ? high[1] : c[1]
else if c[1] < o[1] and c > o
swing_low := type == "High/Low" ? low[1] : o[1]
plot(swing_high, "Swing High", color=color.new(color.green, 40), style=plot.style_stepline)
plot(swing_low, "Swing Low", color=color.new(color.red, 40), style=plot.style_stepline)
|
ATR Table 2.0 | https://www.tradingview.com/script/C5PHFbIY-ATR-Table-2-0/ | gtabachi | https://www.tradingview.com/u/gtabachi/ | 59 | 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/
// © gtabachi
//@version=5
indicator("ATR Table 3.0", overlay=true)
day2_close = request.security(syminfo.tickerid, "D", close[2])
day1_max = request.security(syminfo.tickerid, "D", high[1])
day1_min = request.security(syminfo.tickerid, "D", low[1])
day1_atr = if (day1_min > day2_close)
day1_max - day2_close
else if (day1_max < day2_close)
day2_close - day1_min
else
day1_max - day1_min
day3_close = request.security(syminfo.tickerid, "D", close[3])
day2_max = request.security(syminfo.tickerid, "D", high[2])
day2_min = request.security(syminfo.tickerid, "D", low[2])
day2_atr = if (day2_min > day3_close)
day2_max - day3_close
else if (day2_max < day3_close)
day3_close - day2_min
else
day2_max - day2_min
day4_close = request.security(syminfo.tickerid, "D", close[4])
day3_max = request.security(syminfo.tickerid, "D", high[3])
day3_min = request.security(syminfo.tickerid, "D", low[3])
day3_atr = if (day3_min > day4_close)
day3_max - day4_close
else if (day3_max < day4_close)
day4_close - day3_min
else
day3_max - day3_min
day5_close = request.security(syminfo.tickerid, "D", close[5])
day4_max = request.security(syminfo.tickerid, "D", high[4])
day4_min = request.security(syminfo.tickerid, "D", low[4])
day4_atr = if (day4_min > day5_close)
day4_max - day5_close
else if (day4_max < day5_close)
day5_close - day4_min
else
day4_max - day4_min
day6_close = request.security(syminfo.tickerid, "D", close[6])
day5_max = request.security(syminfo.tickerid, "D", high[5])
day5_min = request.security(syminfo.tickerid, "D", low[5])
day5_atr = if (day5_min > day6_close)
day5_max - day6_close
else if (day5_max < day6_close)
day6_close - day5_min
else
day5_max - day5_min
day7_close = request.security(syminfo.tickerid, "D", close[7])
day6_max = request.security(syminfo.tickerid, "D", high[6])
day6_min = request.security(syminfo.tickerid, "D", low[6])
day6_atr = if (day6_min > day7_close)
day6_max - day7_close
else if (day6_max < day7_close)
day7_close - day6_min
else
day6_max - day6_min
day8_close = request.security(syminfo.tickerid, "D", close[8])
day7_max = request.security(syminfo.tickerid, "D", high[7])
day7_min = request.security(syminfo.tickerid, "D", low[7])
day7_atr = if (day7_min > day8_close)
day7_max - day8_close
else if (day7_max < day8_close)
day8_close - day7_min
else
day7_max - day7_min
day9_close = request.security(syminfo.tickerid, "D", close[9])
day8_max = request.security(syminfo.tickerid, "D", high[8])
day8_min = request.security(syminfo.tickerid, "D", low[8])
day8_atr = if (day8_min > day9_close)
day8_max - day9_close
else if (day8_max < day9_close)
day9_close - day8_min
else
day8_max - day8_min
day10_close = request.security(syminfo.tickerid, "D", close[10])
day9_max = request.security(syminfo.tickerid, "D", high[9])
day9_min = request.security(syminfo.tickerid, "D", low[9])
day9_atr = if (day9_min > day10_close)
day9_max - day10_close
else if (day9_max < day10_close)
day10_close - day9_min
else
day9_max - day9_min
day11_close = request.security(syminfo.tickerid, "D", close[11])
day10_max = request.security(syminfo.tickerid, "D", high[10])
day10_min = request.security(syminfo.tickerid, "D", low[10])
day10_atr = if (day10_min > day11_close)
day10_max - day11_close
else if (day10_max < day11_close)
day11_close - day10_min
else
day10_max - day10_min
avg_atr = (day1_atr+day2_atr+day3_atr+day4_atr+day5_atr+day6_atr+day7_atr+day8_atr+day9_atr+day10_atr)/10
day1_close = request.security(syminfo.tickerid, "D", close[1])
day_max = request.security(syminfo.tickerid, "D", high)
day_min = request.security(syminfo.tickerid, "D", low)
day_atr = if (day_min > day1_close)
day_max - day1_close
else if (day_max < day1_close)
day1_close - day_min
else
day_max - day_min
perc_ma_atr = day_atr/avg_atr
max_zrange = avg_atr*0.12
var ADRTable = table.new(position = position.top_right, columns = 2, rows = 4, frame_color = color.black , frame_width = 2, border_color=color.silver, border_width = 1)
bgcolor_c= input( defval=color.gray, title="Head col color",group="Header columns",inline="Column color")
bgtrans_c= input.float( defval=0,title="transparency",group="Header columns",inline="Column color",minval=0,maxval=100,step=10)
font_color_c= input( defval=color.white, title="Font color",group="Header columns",inline="Column font")
font_trans_c= input.float( defval=0,title="transparency",group="Header columns",inline="Column font",minval=0,maxval=100,step=10)
bgcolor_r= input( defval=color.white, title="Head row color",group="Header rows",inline="Row color")
bgtrans_r= input.float( defval=0,title="transparency",group="Header rows",inline="Row color",minval=0, maxval=100, step=10)
font_color_r= input( defval=color.black, title="Font color",group="Header rows",inline="Row font")
font_trans_r= input.float( defval=0,title="transparency",group="Header rows",inline="Row font",minval=0, maxval=100, step=10)
if barstate.islast
table.cell(table_id = ADRTable, column = 0, row = 0, text = "Day TR:", text_size=size.small, bgcolor = color.new(bgcolor_c,bgtrans_c), text_color=color.new (font_color_c,font_trans_c))
table.cell(table_id = ADRTable, column = 1, row = 0, text = str.tostring(day_atr,'#'), text_size=size.small, bgcolor = color.new(bgcolor_r,bgtrans_r), text_color=color.new (font_color_r,font_trans_r))
table.cell(table_id = ADRTable, column = 0, row = 1, text = "10 Day ATR:", text_size=size.small, bgcolor = color.new(bgcolor_c,bgtrans_c), text_color=color.new (font_color_c,font_trans_c))
table.cell(table_id = ADRTable, column = 1, row = 1, text = str.tostring(avg_atr,'#'), text_size=size.small, bgcolor = color.new(bgcolor_r,bgtrans_r), text_color=color.new (font_color_r,font_trans_r))
table.cell(table_id = ADRTable, column = 0, row = 2, text = "Max ZRange:", text_size=size.small, bgcolor = color.new(bgcolor_c,bgtrans_c), text_color=color.new (font_color_c,font_trans_c))
table.cell(table_id = ADRTable, column = 1, row = 2, text = str.tostring(max_zrange,'#'), text_size=size.small, bgcolor = color.new(bgcolor_r,bgtrans_r), text_color=color.new (font_color_r,font_trans_r))
table.cell(table_id = ADRTable, column = 0, row = 3, text = "Range Consumed:", text_size=size.small, bgcolor = color.new(bgcolor_c,bgtrans_c), text_color=color.new (font_color_c,font_trans_c))
table.cell(table_id = ADRTable, column = 1, row = 3, text = str.tostring(perc_ma_atr,'#.##'), text_size=size.small, bgcolor = color.new(bgcolor_r,bgtrans_r), text_color=color.new (font_color_r,font_trans_r)) |
Time & volume point of control / quantifytools | https://www.tradingview.com/script/nY63MyD9-Time-volume-point-of-control-quantifytools/ | quantifytools | https://www.tradingview.com/u/quantifytools/ | 1,670 | 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/
// © quantifytools
//@version=5
indicator("Time & volume point of control (TPOC & VPOC)", overlay=true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
// Inputs
//POC inputs
groupPoc = "VPOC & TPOC settings"
i_source = input.source(close, "Source for TPOC/VPOC price", group=groupPoc, tooltip="E.g. With close as source, a point of control is calculated using LTF close.")
i_tpocThreshold = input.int(50, "Threshold % for TPOC highlight", maxval=100, minval=1, group=groupPoc, tooltip="E.g. With 50% threshold, a highlight will occur when >= 50% of total time was traded at point of control.")
i_vpocThreshold = input.int(50, "Threshold % for VPOC highlight", maxval=100, minval=1, group=groupPoc)
i_deltaRule = input.string("Standard VPOC", "Show VPOC as", options=["Standard VPOC", "VPOC with delta indication", "VPOCs separately for each side"], group=groupPoc, tooltip="Standard VPOC = volume point of control. VPOC with delta indication = volume point of control with direction indicated as color (buy/sell). VPOCs separately for each side = volume point of control for each side separately with direction indicated as color.")
i_buySellPoc = i_deltaRule == "VPOC with delta indication" or i_deltaRule == "VPOCs separately for each side"
i_addPoc = i_deltaRule == "VPOCs separately for each side"
//Timeframe inputs
groupTf = "Timeframe settings"
i_tf1 = input.timeframe("1", "LTF for charts <= 30 min", group=groupTf, tooltip="E.g. Lower timeframe data is fetched from 1 minute timeframe when viewing charts at or below 30 min. The lower the chosen timeframe, the more precision you get, but with the cost of less historical data and slower loading time.")
i_tf2 = input.timeframe("5", "LTF for charts > 30 min & <= 3 hours", group=groupTf)
i_tf3 = input.timeframe("15", "LTF for charts > 3 hours & <= 8 hours", group=groupTf)
i_tf4 = input.timeframe("60", "LTF for charts > 8 hours & <= 1D", group=groupTf)
i_tf5 = input.timeframe("120", "LTF for charts > 1D & <= 3D", group=groupTf)
i_tf6 = input.timeframe("240", "LTF for charts > 3D", group=groupTf)
//TPOC/VPOC visual inputs
groupVisuals = "TPOC/VPOC visuals"
i_hideChart = input.bool(true, "Hide chart", group=groupVisuals, tooltip="")
i_lineCol = input.color(color.gray, "Line", group=groupVisuals, inline="line")
i_lineColThreshold = input.color(color.orange, "Threshold exceeded", group=groupVisuals, inline="line")
i_vpocCol = input.color(color.yellow, "VPOC", group=groupVisuals, inline="vpoc")
i_vpocThresholdCol = input.color(color.orange, "Threshold exceeded", group=groupVisuals, inline="vpoc")
i_tpocCol = input.color(color.yellow, "TPOC", group=groupVisuals, inline="tpoc")
i_tpocThresholdCol = input.color(color.orange, "Threshold exceeded", group=groupVisuals, inline="tpoc")
i_vpocBuyCol = input.color(color.rgb(31, 97, 249), "Buy side POC", group=groupVisuals, inline="vpocdelta")
i_vpocSellCol = input.color(color.rgb(247, 62, 139), "Sell side POC", group=groupVisuals, inline="vpocdelta")
//TPOC/VPOC anomaly visual inputs
groupAnomalyVisuals = "Anomaly visuals"
i_hideAnomalies = input.bool(true, "Hide anomalies", tooltip="", group=groupAnomalyVisuals)
i_trappedTpocVpoc = input.color(color.rgb(232, 74, 74), "Trapped TPOC/VPOC", group=groupAnomalyVisuals)
i_trendInitiationCol = input.color(color.rgb(232, 74, 74), "Trend initiation", group=groupAnomalyVisuals)
// LTF data
//Delta rules
upVolRule = i_source >= i_source[1]
downVolRule = i_source < i_source[1]
//Current timeframe in minutes
currentTimeframe = timeframe.in_seconds(timeframe.period) / 60
//Dynamic timeframe
dynTf = currentTimeframe <= 30 ? i_tf1 : currentTimeframe > 30 and currentTimeframe <= 180 ? i_tf2 :
currentTimeframe > 180 and currentTimeframe <= 480 ? i_tf3 : currentTimeframe > 480 and currentTimeframe <= 1440 ? i_tf4 :
currentTimeframe > 1440 and currentTimeframe <= 4320 ? i_tf5 : currentTimeframe > 4320 ? i_tf6 : na
//Function to fetch LTF data
ltfStats() =>
vol = na(volume) == false ? volume : 0
volDelta = upVolRule and na(volume) == false ? volume : downVolRule and na(volume) == false ? 0 - volume : na
[i_source, vol, volDelta]
[ltfSrc, ltfVolume, ltfDelta]
= request.security_lower_tf(syminfo.tickerid, dynTf, ltfStats())
// TPOC
//Dividing range into 10 blocks/lots
divBlock = (high - low) / 10
//Blocks separately
tpoBlock1 = low + (divBlock * 1)
tpoBlock2 = low + (divBlock * 2)
tpoBlock3 = low + (divBlock * 3)
tpoBlock4 = low + (divBlock * 4)
tpoBlock5 = low + (divBlock * 5)
tpoBlock6 = low + (divBlock * 6)
tpoBlock7 = low + (divBlock * 7)
tpoBlock8 = low + (divBlock * 8)
tpoBlock9 = low + (divBlock * 9)
tpoBlock10 = low + (divBlock * 10)
//Time counters for blocks
int block1Count = 0
int block2Count = 0
int block3Count = 0
int block4Count = 0
int block5Count = 0
int block6Count = 0
int block7Count = 0
int block8Count = 0
int block9Count = 0
int block10Count = 0
//TPO array size
tpoArrSize = array.size(ltfSrc)
//Looping through TPO array and assigning counts to blocks
for i = 0 to (tpoArrSize > 0 ? tpoArrSize - 1 : na)
recentTpo = array.get(ltfSrc, i)
if recentTpo < tpoBlock1
block1Count += 1
else
if recentTpo > tpoBlock1 and recentTpo <= tpoBlock2
block2Count += 1
else
if recentTpo > tpoBlock2 and recentTpo <= tpoBlock3
block3Count += 1
else
if recentTpo > tpoBlock3 and recentTpo <= tpoBlock4
block4Count += 1
else
if recentTpo > tpoBlock4 and recentTpo <= tpoBlock5
block5Count += 1
if recentTpo > tpoBlock5 and recentTpo <= tpoBlock6
block6Count += 1
else
if recentTpo > tpoBlock6 and recentTpo <= tpoBlock7
block7Count += 1
else
if recentTpo > tpoBlock7 and recentTpo <= tpoBlock8
block8Count += 1
else
if recentTpo > tpoBlock8 and recentTpo <= tpoBlock9
block9Count += 1
else
if recentTpo > tpoBlock9 and recentTpo <= tpoBlock10
block10Count += 1
//TPOC Array
tpoCountArray = array.new_int(0, 0)
//Populating TPOC array with time counts
array.push(tpoCountArray, block1Count)
array.push(tpoCountArray, block2Count)
array.push(tpoCountArray, block3Count)
array.push(tpoCountArray, block4Count)
array.push(tpoCountArray, block5Count)
array.push(tpoCountArray, block6Count)
array.push(tpoCountArray, block7Count)
array.push(tpoCountArray, block8Count)
array.push(tpoCountArray, block9Count)
array.push(tpoCountArray, block10Count)
//Highest time count (TPOC)
maxTpo = array.max(tpoCountArray)
//Array index of TPOC
indexOfMaxTpo = array.indexof(tpoCountArray, maxTpo)
//Finding TPOC block
relevantTpoBlock = indexOfMaxTpo == 0 ? tpoBlock1 : indexOfMaxTpo == 1 ? tpoBlock2 : indexOfMaxTpo == 2 ? tpoBlock3 : indexOfMaxTpo == 3 ? tpoBlock4 :
indexOfMaxTpo == 4 ? tpoBlock5 : indexOfMaxTpo == 5 ? tpoBlock6 : indexOfMaxTpo == 6 ? tpoBlock7 : indexOfMaxTpo == 7 ? tpoBlock8 :
indexOfMaxTpo == 8 ? tpoBlock9 : tpoBlock10
//Forming a plot location for TPOC mark (middle point of block)
tpoBlockPos = relevantTpoBlock == tpoBlock1 ? (low + tpoBlock1) / 2 : relevantTpoBlock == tpoBlock2 ? (tpoBlock1 + tpoBlock2) / 2 : relevantTpoBlock == tpoBlock3 ? (tpoBlock2 + tpoBlock3) / 2 :
relevantTpoBlock == tpoBlock4 ? (tpoBlock3 + tpoBlock4) / 2 : relevantTpoBlock == tpoBlock5 ? (tpoBlock4 + tpoBlock5) / 2 : relevantTpoBlock == tpoBlock6 ? (tpoBlock5 + tpoBlock6) / 2 :
relevantTpoBlock == tpoBlock7 ? (tpoBlock6 + tpoBlock7) / 2 : relevantTpoBlock == tpoBlock8 ? (tpoBlock7 + tpoBlock8) / 2 : relevantTpoBlock == tpoBlock9 ? (tpoBlock8 + tpoBlock9) / 2 : (tpoBlock9 + high) / 2
// VPOC
//Max volume from LTF volume/up volume array
maxVolume = array.max(ltfVolume)
//Array index of max volume
indexOfMaxVolume = array.indexof(ltfVolume, maxVolume)
//Price at max volume (VPOC/bVPOC)
maxVol = array.size(ltfSrc) > 0 ? array.get(ltfSrc, indexOfMaxVolume) : na
//Max volume from LTF down volume array
maxVolumeDelta = array.max(ltfDelta)
minVolumeDelta = array.min(ltfDelta)
//Determining additional POC
addVpoc = maxVolumeDelta > math.abs(minVolumeDelta) ? minVolumeDelta : maxVolumeDelta
//Array index of max sell volume
indexOfAddVpoc = array.indexof(ltfDelta, addVpoc)
//Price at max sell volume (sVPOC)
addVpocPrice = array.size(ltfSrc) > 0 ? array.get(ltfSrc, indexOfAddVpoc) : na
// TPOC/VPOC anomalies
//Trapped time/volume
//Ensuring sufficient distance between close and TPOC/VPOC, equal to or greater than half of bar range.
vpocCloseSpread = close > maxVol ? close - maxVol : maxVol - close
vpocCloseSpreadCond = vpocCloseSpread >= (hl2 - low)
tpocCloseSpread = close > tpoBlockPos ? close - tpoBlockPos : tpoBlockPos - close
tpocCloseSpreadCond = tpocCloseSpread >= (hl2 - low)
//Trapped volume down scenarios
trappedVpocDown = (close > low[1] and maxVol < low[1]) or (close < low[1] and maxVol < close and vpocCloseSpreadCond)
//Trapped volume up scenarios
trappedVpocUp = (close < high[1] and maxVol > high[1]) or (close > high[1] and maxVol > close and vpocCloseSpreadCond)
//Trapped time down scenarios
trappedTpocDown = (close > low[1] and tpoBlockPos < low[1]) or (close < low[1] and tpoBlockPos < close and tpocCloseSpreadCond)
//Trapped time up scenarios
trappedTpocUp = (close < high[1] and tpoBlockPos > high[1]) or (close > high[1] and tpoBlockPos > close and tpocCloseSpreadCond)
//Trapped volume
trappedVolumeDown = trappedVpocDown and maxVol < hl2 and barstate.isconfirmed
trappedVolumeUp = trappedVpocUp and maxVol > hl2 and barstate.isconfirmed
trappedVolumeAny = trappedVolumeDown or trappedVolumeUp
//Trapped time
trappedTimeDown = trappedTpocDown and tpoBlockPos < hl2 and barstate.isconfirmed
trappedTimeUp = trappedTpocUp and tpoBlockPos > hl2 and barstate.isconfirmed
trappedTimeAny = trappedTimeDown or trappedTimeUp
//Trend initiation
//Defining volatility
volatility = high - low
//Ensuring distance between TPOC and VPOC is sufficient, equal to or greater than half of bar range.
tpocVpocSpread = tpoBlockPos > maxVol ? tpoBlockPos - maxVol : maxVol - tpoBlockPos
tpocVpocSpreadCond = tpocVpocSpread >= (hl2 - low)
//Trend initiation up/down
trendInitiationUp = close > high[1] and tpoBlockPos < hl2 and maxVol > hl2 and volatility > volatility[1] * 1.5 and tpocVpocSpreadCond and barstate.isconfirmed
trendInitiationDown = close < low[1] and (maxVol < hl2 and tpoBlockPos > hl2) and volatility > volatility[1] * 1.5 and tpocVpocSpreadCond and barstate.isconfirmed
trendInitiationAny = trendInitiationUp or trendInitiationDown
// Alerts
alertcondition(trappedTimeUp, "Trapped TPOC above", "Potential trapped TPOC above detected.")
alertcondition(trappedTimeDown, "Trapped TPOC below", "Potential trapped TPOC below detected.")
alertcondition(trappedVolumeUp, "Trapped VPOC above", "Potential trapped VPOC above detected.")
alertcondition(trappedVolumeDown, "Trapped VPOC below", "Potential trapped VPOC below detected.")
alertcondition(trappedTimeAny, "Trapped TPOC above/below", "Potential trapped TPOC above/below detected.")
alertcondition(trappedVolumeAny, "Trapped VPOC above/below", "Potential trapped VPOC above/below detected.")
alertcondition(trappedTimeAny or trappedVolumeAny, "Trapped POC (either) above/below", "Potential trapped POC (either) above/below detected.")
alertcondition(trendInitiationUp, "Trend initiation up", "Potential trend initiation up detected.")
alertcondition(trendInitiationDown, "Trend initiation down", "Potential trend initiation down detected.")
alertcondition(trendInitiationAny, "Trend initiation any", "Potential trend initiation up/down detected.")
// Colors
vpocThresholdMet = maxVolume >= (volume * (i_vpocThreshold / 100)) and barstate.isconfirmed
tpocThresholdMet = maxTpo >= (tpoArrSize * (i_tpocThreshold / 100)) and barstate.isconfirmed
vpocColor = (trappedVolumeUp or trappedVolumeDown) and i_hideAnomalies == false ? i_trappedTpocVpoc : vpocThresholdMet ? i_vpocThresholdCol : i_vpocCol
tpocColor = (trappedTimeUp or trappedTimeDown) and i_hideAnomalies == false ? i_trappedTpocVpoc : tpocThresholdMet ? i_tpocThresholdCol : i_tpocCol
lineColor = vpocThresholdMet or tpocThresholdMet ? i_lineColThreshold : i_lineCol
boxColor = vpocThresholdMet[500] or tpocThresholdMet[500] ? i_lineColThreshold : i_lineCol
// Plots
plotVpocCond = tpoArrSize > 0 and na(volume) == false and volume > 0
mainVpocCol = i_buySellPoc ? addVpoc == maxVolumeDelta ? i_vpocSellCol : i_vpocBuyCol : vpocColor
addVpocCond = addVpoc == maxVolumeDelta ? i_vpocBuyCol : i_vpocSellCol
//TPOC and VPOC plots
plotshape(tpoArrSize > 0 ? tpoBlockPos : na, title="TPOC", style=shape.cross, text="", color=tpocColor, location=location.absolute, size=size.small, textcolor=color.white)
plotshape(plotVpocCond ? maxVol : na, title="VPOC #1", style=shape.circle, text="", color=mainVpocCol, location=location.absolute, size=size.tiny, textcolor=color.white)
plotshape(i_buySellPoc and i_addPoc ? addVpocPrice : na, title="VPOC #2", style=shape.cross, text="", color=addVpocCond, location=location.absolute, size=size.small, textcolor=color.white)
plotshape(i_hideAnomalies == false and trendInitiationUp ? low : na, title="Trend initiation up", style=shape.triangleup, text="", color=i_trendInitiationCol, location=location.belowbar, size=size.tiny, textcolor=color.white)
plotshape(i_hideAnomalies == false and trendInitiationDown ? high : na, title="Trend initiation down", style=shape.triangledown, text="", color=i_trendInitiationCol, location=location.abovebar, size=size.tiny, textcolor=color.white)
//Mid-bar line
line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, color=lineColor, width=3)
box.new(left=bar_index[500], top=high[500], right=bar_index[500], bottom=low[500], bgcolor=boxColor, border_color=boxColor, border_width=2)
//Hiding chart
barcolor(i_hideChart == true ? color.new(color.white, 100) : na)
|
Cheat Code's Redemption | https://www.tradingview.com/script/kuOcbPqO-Cheat-Code-s-Redemption/ | CheatCode1 | https://www.tradingview.com/u/CheatCode1/ | 333 | 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/
// © CheatCode1
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CheatCode1
//@version=5
indicator("Cheat Code's Redemption", 'CCR', false)
//WELCOME TO THE REDEMTION OSCILLATOR, HERE YOU WILL FIND THE
////////Important Variable Declaration
o = ta.obv
lR = 1
lL = 5
Upper = 150
Lower = 1
r1 = ta.tsi(o, 1, 9)*100
r2 = ta.rsi(close, 14)
dalma = ta.alma(close, 130, .025, 4.5)
e21 = ta.ema(close, 21)
e55 = ta.ema(close, 55)
//////////////////////////Histogram Executions
fast_ma = e21
slow_ma = e55
CCR = fast_ma - slow_ma
histlen = input.int(title="Histogram Smoothing", minval = 1, maxval = 50, defval = 6, group = 'Histogram Settings')
signal = ta.ema(CCR, histlen)
hist = ta.tsi(CCR - signal, 1, 9)*10
plot(hist, 'CCR histogram', hist>=0 ? (hist[1] < hist ? color.rgb(72, 218, 223) : color.rgb(72, 218, 223, 67)) : (hist[1] < hist ? color.rgb(250, 225, 2, 55) : color.rgb(250, 225, 2)), 2, plot.style_columns)
//////////////////////////OBV Calulations
raycol = e21 < dalma and dalma > close ? color.red: e21 > dalma and dalma < close ? color.green:color.white
fitobv = ((o/(o*.5))/o)*3.14
rate = o+30
//////////////////////////CCR Oscillator Variables and Executions
p1 = math.avg(r1, r2)
e21p = ta.ema(p1, 21)
e9p = ta.ema(p1, 9)
e = e9p > e21p ? e9p : e21p
ecol = e9p > e21p ? color.aqua : color.yellow
plot(e, 'CCR Moving Average', ecol)
plot(p1, 'CCR Oscillator', raycol, 3 )
//////////////////////////Indicator overbought/Oversold levels
hl1 = hline(-25, 'Bottom Hline', color.white, hline.style_dashed)
hl22 = hline(85, 'Top Hline', color.rgb(255, 255, 255, 29), hline.style_dashed)
hl3 = hline(75, 'fibs', color.rgb(0, 187, 212, 54), hline.style_dotted )
hl4 = hline(-15, 'fibs2', color.rgb(255, 235, 59, 47), hline.style_dotted)
fill(hl1, hl4, color = color.rgb(219, 77, 77, 80))
fill(hl22, hl3, color = color.rgb(105, 194, 93, 84))
//////////////////////////Regular & Hidden Divergence Calculations and Executions
pivotlow = na(ta.pivotlow(p1, lL, lR)) ? false : true
Pivothigh = na(ta.pivothigh(p1, lL, lR)) ? false : true
iR(rate) =>
bars = ta.barssince(rate)
Lower <= bars and bars <= Upper
M12 = p1[lR] > ta.valuewhen(pivotlow, p1[lR], 1) and iR(pivotlow[1])
LL = low[lR] < ta.valuewhen(pivotlow, low[lR], 1)
bulld = LL and M12 and pivotlow
plot( pivotlow ? p1[lR] : na, "Regular Bullish", bulld ? color.green : na, 3, plot.style_line, offset = -lR )
LH = p1[lR] < ta.valuewhen(Pivothigh, p1[lR], 1) and iR(Pivothigh[1])
HH = high[lR] > ta.valuewhen(Pivothigh, high[lR], 1)
beard = HH and LH and Pivothigh
plot( Pivothigh ? p1[lR] : na, "Regular Bearish", beard ? color.red : na, 3, offset= -lR)
Ll = p1[lR] < ta.valuewhen(pivotlow, p1[lR], 1) and iR(pivotlow[1])
Hl = low[lR] > ta.valuewhen(pivotlow, low[lR], 1)
priceLH = high[lR] < ta.valuewhen(Pivothigh, high[lR], 1)
hiddenB= Hl and Ll and pivotlow
plot(pivotlow ? p1[lR] : na, 'Hidden bull', hiddenB ? color.rgb(150, 221, 153) : na, 3, plot.style_line, offset = -lR)
Hh = p1[lR] > ta.valuewhen(Pivothigh, p1[lR], 1) and iR(Pivothigh[1])
Lh = high[lR] < ta.valuewhen(Pivothigh, high[lR], 1)
hiddenBe = Lh and Hh and Pivothigh
plot(Pivothigh ? p1[lR] : na, 'Hidden Bear', hiddenBe ? color.rgb(202, 107, 107) : na, 3, plot.style_line, offset = -lR) |
Divergence Backtester - V2 | https://www.tradingview.com/script/4H9jg3DX-Divergence-Backtester-V2/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 582 | 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/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
indicator("Divergence Backtester - V2", "DBv2", overlay=true, max_lines_count = 500, max_labels_count = 500)
import HeWhoMustNotBeNamed/mZigzag/12 as zg
import HeWhoMustNotBeNamed/enhanced_ta/14 as eta
import HeWhoMustNotBeNamed/arrays/1 as pa
//*********************** Debug method *************************//
i_start = 0
i_page = 100
i_maxLogSize = 1000
i_showHistory = false
i_showBarIndex = false
var DebugArray = array.new_string(0)
var DebugBarArray = array.new_string(0)
add_to_debug_array(arr, val, maxItems) =>
array.unshift(arr, str.tostring(val))
if array.size(arr) > maxItems
array.pop(arr)
debug(debugMsg) =>
if barstate.islast or i_showHistory
barTimeString = str.tostring(year, '0000') + '/' + str.tostring(month, '00') + '/' + str.tostring(dayofmonth, '00') + (timeframe.isintraday ? '-' + str.tostring(hour, '00') + ':' + str.tostring(minute, '00') + ':' + str.tostring(second, '00') : '')
add_to_debug_array(DebugBarArray, i_showBarIndex ? str.tostring(bar_index) : barTimeString, i_maxLogSize)
add_to_debug_array(DebugArray, debugMsg, i_maxLogSize)
//*********************** Debug method *************************//
length = input.int(8, 'Length', group='Zigzag')
oscillatorType = input.string("rsi", title="Oscillator", inline="osc", options=["cci", "cmo", "cog", "mfi", "roc", "rsi"], group='Oscillator')
oscLength = input.int(14, title="", inline="osc", group='Oscillator')
supertrendLength = input.int(5, 'History', inline='st', group='Supertrend')
drawSupertrend = input.bool(true, "Draw Zigzag Supertrend", inline='st2', group='Supertrend')
txtSize = input.string(size.tiny, 'Text Size', [size.tiny, size.small, size.normal, size.large, size.huge], inline='txt')
txtColor = input.color(color.white, '', inline='txt')
increment(mtx, row, col, val=1)=>matrix.set(mtx, row, col, matrix.get(mtx, row, col)+val)
gettrendindex(int price, int osc, int trend)=>
trendFactor = trend > 0 ? 0 : 1
priceFactor = math.abs(price) > 1? 1 : 0
oscFactor = math.abs(osc) > 1? 1 : 0
trendFactor*4 + priceFactor*2 + oscFactor
getSentimentDetails(pDir, oDir, sDir) =>
sentiment = pDir == oDir ? sDir == pDir or sDir * 2 == -pDir ? -sDir : sDir * 4 : sDir == pDir or sDir == -oDir ? 0 : (math.abs(oDir) > math.abs(pDir) ? sDir : -sDir) * (sDir == oDir ? 2 : 3)
sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣'
sentimentColor = sentiment == 4 ? color.green : sentiment == -4 ? color.red : sentiment == 3 ? color.lime : sentiment == -3 ? color.orange : sentiment == 2 ? color.rgb(202, 224, 13, 0) : sentiment == -2 ? color.rgb(250, 128, 114, 0) : color.silver
sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I'
[sentimentSymbol, sentimentLabel, sentimentColor]
getStatus(int trendIndex, int pivotDir)=>
trendFactor = int(trendIndex/4)
remainder = trendIndex % 4
priceFactor = int(remainder/2)+1
oscFactor = (remainder % 2)+1
trendChar = (trendFactor == 0)? 'U' : 'D'
priceChar = pivotDir > 0? (priceFactor == 2? 'HH' : 'LH') : (priceFactor == 2? 'LL' : 'HL')
oscChar = pivotDir > 0? (oscFactor == 2? 'HH' : 'LH') : (oscFactor == 2? 'LL' : 'HL')
trendChar + ' - ' + priceChar + '/'+oscChar
draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix,
barArray, trendArray, lineColor, lineWidth, lineStyle) =>
if matrix.rows(valueMatrix) > 2
idxLen1 = matrix.rows(valueMatrix)-idx1
idxLen2 = matrix.rows(valueMatrix)-idx2
lastValues = matrix.row(valueMatrix, idxLen1)
llastValues = matrix.row(valueMatrix, idxLen2)
lastDirections = matrix.row(directionMatrix, idxLen1)
lastRatios = matrix.row(ratioMatrix, idxLen1)
lastDivergence = matrix.row(divergenceMatrix, idxLen1)
lastDoubleDivergence = matrix.row(doubleDivergenceMatrix, idxLen1)
y1 = array.get(lastValues, 0)
y2 = array.get(llastValues, 0)
x1 = array.get(barArray, idxLen1)
x2 = array.get(barArray, idxLen2)
zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=lineColor, width=lineWidth, style=lineStyle)
currentDir = y1 > y2? 1 : -1
priceDir = array.get(lastDirections, 0)
oscDir = array.get(lastDirections, 1)
trendDir = array.get(trendArray, idxLen1)
trendIndex = gettrendindex(priceDir, oscDir, trendDir)
trendLabel = getStatus(trendIndex, currentDir)
[sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(priceDir, oscDir, trendDir)
labelStyle = currentDir > 0? label.style_label_down : label.style_label_up
zlabel = label.new(x=x1, y=y1, yloc=yloc.price, color=sentimentColor, style=labelStyle, text=sentimentSymbol + ' ' + trendLabel,
textcolor=color.black, size = size.small, tooltip=sentimentLabel)
if array.size(zigzaglines) > 0
lastLine = array.get(zigzaglines, array.size(zigzaglines)-1)
if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1
pa.pop(zigzaglines)
pa.pop(zigzaglabels)
pa.push(zigzaglines, zline, 500)
pa.push(zigzaglabels, zlabel, 500)
draw(matrix<float> valueMatrix, matrix<int> directionMatrix, matrix<float> ratioMatrix, matrix<int> divergenceMatrix, matrix<int> doubleDivergenceMatrix, array<int> barArray, array<int> trendArray,
bool newZG, bool doubleZG, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid)=>
var zigzaglines = array.new_line(0)
var zigzaglabels = array.new_label(0)
if(newZG)
if doubleZG
draw_zg_line(2, 3, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
lineColor, lineWidth, lineStyle)
if matrix.rows(valueMatrix) >= 2
draw_zg_line(1, 2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
lineColor, lineWidth, lineStyle)
[valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, zigzaglines, zigzaglabels]
indicatorHigh = array.new_float()
indicatorLow = array.new_float()
indicatorLabels = array.new_string()
[oscHigh, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, high)
[oscLow, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, low)
array.push(indicatorHigh, math.round(oscHigh,2))
array.push(indicatorLow, math.round(oscLow,2))
array.push(indicatorLabels, oscillatorType+str.tostring(oscLength))
[valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, supertrendDir, supertrend, newZG, doubleZG] =
zg.calculate(length, array.from(high, low), indicatorHigh, indicatorLow, supertrendLength = supertrendLength)
nextDirection = matrix.rows(directionMatrix) > 0? matrix.row(directionMatrix, matrix.rows(directionMatrix)-1) : array.new_int()
lastDirection = matrix.rows(directionMatrix) > 1? matrix.row(directionMatrix, matrix.rows(directionMatrix)-2) : array.new_int()
llastDirection = matrix.rows(directionMatrix) > 2? matrix.row(directionMatrix, matrix.rows(directionMatrix)-3) : array.new_int()
lllastDirection = matrix.rows(directionMatrix) > 3? matrix.row(directionMatrix, matrix.rows(directionMatrix)-4) : array.new_int()
var pivotHighStats = matrix.new<int>(64, 3, 0)
var pivotLowStats = matrix.new<int>(64, 3, 0)
var pivotHighRatios = matrix.new<float>(64, 3, 0)
var pivotLowRatios = matrix.new<float>(64, 3, 0)
currentTotalTrendIndex = 0
nextTotalTrendIndex = 0
currentDir = matrix.rows(directionMatrix) > 0? matrix.get(directionMatrix, matrix.rows(directionMatrix)-1, 0) : 0
if(array.size(lllastDirection) > 0)
priceDirection = array.get(lastDirection, 0)
priceRatio = matrix.get(ratioMatrix, matrix.rows(ratioMatrix)-2, 0)
currentPriceDirection = array.get(lastDirection, 0)
currentOscDirection = array.get(lastDirection, 1)
currentTrend = array.get(trendArray, array.size(trendArray)-2)
nextPriceDirection = array.get(nextDirection, 0)
nextOscDirection = array.get(nextDirection, 1)
nextTrend = array.get(trendArray, array.size(trendArray)-1)
lastPriceDirection = array.get(llastDirection, 0)
lastOscDirection = array.get(llastDirection, 1)
lastTrend = array.get(trendArray, array.size(trendArray)-3)
llastPriceDirection = array.get(lllastDirection, 0)
llastOscDirection = array.get(lllastDirection, 1)
llastTrend = array.get(trendArray, array.size(trendArray)-4)
colLast = math.abs(priceDirection) %2
nextTrendIndex = gettrendindex(nextPriceDirection, nextOscDirection, nextTrend)
currentTrendIndex = gettrendindex(currentPriceDirection, currentOscDirection, currentTrend)
lastTrendIndex = gettrendindex(lastPriceDirection, lastOscDirection, lastTrend)
llastTrendIndex = gettrendindex(llastPriceDirection, llastOscDirection, llastTrend)
totalIndex = lastTrendIndex*8 + llastTrendIndex
currentTotalTrendIndex := currentTrendIndex*8 + lastTrendIndex
nextTotalTrendIndex := nextTrendIndex*8 + currentTrendIndex
matrixToSet = math.sign(priceDirection) > 0? pivotHighStats : pivotLowStats
ratioMatrixToSet = math.sign(priceDirection) > 0? pivotHighRatios : pivotLowRatios
increment(matrixToSet, totalIndex, colLast)
increment(ratioMatrixToSet, totalIndex, colLast, priceRatio)
increment(matrixToSet, totalIndex, 2)
increment(ratioMatrixToSet, totalIndex, 2, priceRatio)
if(barstate.islast)
startRow = 2
var statsTable = table.new(position=position.top_right, columns=10, rows=64+startRow, border_color = color.black, border_width = 2)
table.clear(statsTable, 0, 0, 9, 64+startRow-1)
phSortIndices = array.sort_indices(matrix.col(pivotHighStats, 2), order.descending)
phColStart = currentDir > 0 ? 0 : 5
table.cell(statsTable, phColStart, 0, 'Pivot High Projection', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart, 1, 'Last Two Pivots', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart+2, 1, 'HH', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart+3, 1, 'LH', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, phColStart+4, 1, 'T', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.merge_cells(statsTable, phColStart, 0, phColStart+4, 0)
table.merge_cells(statsTable, phColStart, 1, phColStart+1, 1)
hlr = startRow
for i=0 to 63
si = array.get(phSortIndices, i)
lastTrendIndex = int(si/8)
llastTrendIndex = si%8
lastPivotStatus = getStatus(lastTrendIndex, -1)
llastPivotStatus = getStatus(llastTrendIndex, 1)
hhStats = matrix.get(pivotHighStats, si, 0)
lhStats = matrix.get(pivotHighStats, si, 1)
tStats = matrix.get(pivotHighStats, si, 2)
hhRatio = math.round(matrix.get(pivotHighRatios, si, 0)/hhStats, 3)
lhRatio = math.round(matrix.get(pivotHighRatios, si, 1)/lhStats, 3)
tRatio = math.round(matrix.get(pivotHighRatios, si, 2)/tStats, 3)
highlight = math.sign(currentDir) < 0 ? nextTotalTrendIndex == si : currentTotalTrendIndex == si
hhTooltip = 'Average Ratio - '+str.tostring(hhRatio)
lhTooltip = 'Average Ratio - '+str.tostring(lhRatio)
tTooltip = 'Average Ratio - '+str.tostring(tRatio)
if(hhStats != 0 and lhStats != 0)
table.cell(statsTable, phColStart, hlr, llastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.lime, 60))
table.cell(statsTable, phColStart+1, hlr, lastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.orange, 60))
table.cell(statsTable, phColStart+2, hlr, str.tostring(hhStats)+' - '+str.tostring(hhRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.green, highlight ? 50 : 90), tooltip = hhTooltip)
table.cell(statsTable, phColStart+3, hlr, str.tostring(lhStats)+' - '+str.tostring(lhRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.red, highlight? 50 : 90), tooltip = lhTooltip)
table.cell(statsTable, phColStart+4, hlr, str.tostring(tStats)+' - '+str.tostring(tRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.from_gradient(hhStats/tStats, 0, 1, color.red, color.green), tooltip = tTooltip)
hlr+=1
plColStart = currentDir < 0 ? 0 : 5
table.cell(statsTable, plColStart, 0, 'Pivot Low Projection', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart, 1, 'Last Two Pivots', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart+2, 1, 'LL', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart+3, 1, 'HL', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.cell(statsTable, plColStart+4, 1, 'T', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
table.merge_cells(statsTable, plColStart, 0, plColStart+4, 0)
table.merge_cells(statsTable, plColStart, 1, plColStart+1, 1)
plSortIndices = array.sort_indices(matrix.col(pivotLowStats, 2), order.descending)
llr = startRow
for i=0 to 63
si = array.get(plSortIndices, i)
lastTrendIndex = int(si/8)
llastTrendIndex = si%8
lastPivotStatus = getStatus(lastTrendIndex, 1)
llastPivotStatus = getStatus(llastTrendIndex, -1)
llStats = matrix.get(pivotLowStats, si, 0)
hlStats = matrix.get(pivotLowStats, si, 1)
tStats = matrix.get(pivotLowStats, si, 2)
llRatio = math.round(matrix.get(pivotLowRatios, si, 0)/llStats, 3)
hlRatio = math.round(matrix.get(pivotLowRatios, si, 1)/hlStats, 3)
tRatio = math.round(matrix.get(pivotLowRatios, si, 2)/tStats, 3)
highlight = math.sign(currentDir) > 0 ? nextTotalTrendIndex == si : currentTotalTrendIndex == si
llTooltip = 'Average Ratio - '+str.tostring(llRatio)
hlTooltip = 'Average Ratio - '+str.tostring(hlRatio)
tTooltip = 'Average Ratio - '+str.tostring(tRatio)
if(llStats != 0 and hlStats != 0)
table.cell(statsTable, plColStart, llr, llastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.orange, 60))
table.cell(statsTable, plColStart+1, llr, lastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.lime, 60))
table.cell(statsTable, plColStart+2, llr, str.tostring(llStats)+' - '+str.tostring(llRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.red, highlight? 50 : 90), tooltip=llTooltip)
table.cell(statsTable, plColStart+3, llr, str.tostring(hlStats)+' - '+str.tostring(hlRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.green, highlight? 50 : 90), tooltip = hlTooltip)
table.cell(statsTable, plColStart+4, llr, str.tostring(tStats)+' - '+str.tostring(tRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.from_gradient(llStats/tStats, 0, 1, color.green, color.red), tooltip = tTooltip)
llr+=1
draw(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, newZG, doubleZG)
plot(drawSupertrend? supertrend:na, color=supertrendDir>0? color.green:color.red, style=plot.style_linebr)
//************************************************************ Print debug message on table ********************************************************/
var debugTable = table.new(position=position.bottom_left, columns=2, rows=i_page + 1, border_width=1)
if array.size(DebugArray) > 0
table.cell(table_id=debugTable, column=0, row=0, text=i_showBarIndex ? 'Bar Index' : 'Bar Time', bgcolor=color.teal, text_color=txtColor, text_size=size.normal)
table.cell(table_id=debugTable, column=1, row=0, text='Debug Message', bgcolor=color.teal, text_color=txtColor, text_size=size.normal)
for i = 0 to math.min(array.size(DebugArray) - 1 - i_start, i_page - 1) by 1
table.cell(table_id=debugTable, column=0, row=i + 1, text=array.get(DebugBarArray, i + i_start), bgcolor=color.black, text_color=txtColor, text_size=size.normal)
table.cell(table_id=debugTable, column=1, row=i + 1, text=array.get(DebugArray, i + i_start), bgcolor=color.black, text_color=txtColor, text_size=size.normal)
//************************************************************ Finish Printing ********************************************************/
|
RedK Magic Ribbon JeetendraGaur | https://www.tradingview.com/script/oNwx1FNg-RedK-Magic-Ribbon-JeetendraGaur/ | jsrg8955 | https://www.tradingview.com/u/jsrg8955/ | 101 | 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/
// © jeetendra
//@version=5
indicator('RedK Magic Ribbon', shorttitle='MagicRibbon v4.0', overlay=true, timeframe='', timeframe_gaps=false)
//====================================================================
f_LazyLine(_data, _length) =>
w1 = 0, w2 = 0, w3 = 0
L1 = 0.0, L2 = 0.0, L3 = 0.0
w = _length / 3
if _length > 2
w2 := math.round(w)
w1 := math.round((_length - w2) / 2)
w3 := int((_length - w2) / 2)
L1 := ta.wma(_data, w1)
L2 := ta.wma(L1, w2)
L3 := ta.wma(L2, w3)
L3
else
L3 := _data
L3
L3
//=====================================================================
f_CoraWave(source, length, s) =>
numerator = 0.0, denom = 0.0
c_weight = 0.0, r_multi = 2.0
Start_Wt = 0.01 // Start Weight & r_multi are set to basic values here.
End_Wt = length // use length as initial End Weight to calculate base "r"
r = math.pow(End_Wt / Start_Wt, 1 / (length - 1)) - 1
base = 1 + r * r_multi
for i = 0 to length - 1 by 1
c_weight := Start_Wt * math.pow(base, length - i)
numerator += source[i] * c_weight
denom += c_weight
denom
cora_raw = numerator / denom
cora_wave = ta.wma(cora_raw, s)
cora_wave
// ======================================================================
Source_1 = input.source(close, 'Source', inline='CRMA1', group='CoRa Wave (Fast MA)')
Length_1 = input.int(10, 'Length', minval=1, inline='CRMA1', group='CoRa Wave (Fast MA)')
smooth = input.int(3, 'Smooth', minval=1, inline='CRMA2', group='CoRa Wave (Fast MA)')
Source_2 = input.source(close, 'Source', inline='RSSMA', group='RSS_WMA (Slow MA)')
Length_2 = input.int(15, 'Smoothness', minval=1, inline='RSSMA', group='RSS_WMA (Slow MA)')
ShowFill = input.bool(true, 'Ribbon Fill?', group='RSS_WMA (Slow MA)')
FastLine = f_CoraWave(Source_1, Length_1, smooth)
SlowLine = f_LazyLine(Source_2, Length_2)
c_fup = color.new(color.aqua, 30)
c_fdn = color.new(color.orange, 30)
Fast_up = FastLine > FastLine[1]
Fast_dn = FastLine < FastLine[1]
c_sup = color.new(#33ff00, 0)
c_sdn = color.new(#ff1111, 0)
Slow_up = SlowLine > SlowLine[1]
Slow_dn = SlowLine < SlowLine[1]
FastPlot = plot(FastLine, title='Fast Line', color=Fast_up ? c_fup : c_fdn, linewidth=2)
SlowPlot = plot(SlowLine, title='Slow Line', color=Slow_up ? c_sup : c_sdn, linewidth=3)
c_rup = color.new(#33ff00, 70)
c_rdn = color.new(#ff1111, 70)
c_rsw = color.new(color.gray, 70)
Ribbon_up = Fast_up and Slow_up
Ribbon_dn = not Fast_up and not Slow_up
fill(FastPlot, SlowPlot, title='Ribbon Fill', color=ShowFill ? Ribbon_up ? c_rup : Ribbon_dn ? c_rdn : c_rsw : na)
// ======================================================================================================
// v3.0 adds 2 optional MA's - to enable us to track what many other traders are working with
// the below code is based on the built-in MA Ribbon in the TV library - with some modifications
// ======================================================================
f_ma(source, length, type) =>
type == 'SMA' ? ta.sma(source, length) : type == 'EMA' ? ta.ema(source, length) : ta.wma(source, length)
// ======================================================================
gr_ma = 'Optional Moving Averages'
t_ma1 = 'MA #1'
t_ma2 = 'MA #2'
show_ma1 = input.bool(false, t_ma1, inline=t_ma1, group=gr_ma)
ma1_type = input.string('SMA', '', options=['SMA', 'EMA', 'WMA'], inline=t_ma1, group=gr_ma)
ma1_source = input.source(close, '', inline=t_ma1, group=gr_ma)
ma1_length = input.int(50, '', minval=1, inline=t_ma1, group=gr_ma)
ma1_color = color.new(#9c27b0,0)
ma1 = f_ma(ma1_source, ma1_length, ma1_type)
plot(show_ma1 ? ma1 : na, color=ma1_color, title=t_ma1, linewidth=1)
show_ma2 = input.bool(false, t_ma2, inline=t_ma2, group=gr_ma)
ma2_type = input.string('SMA', '', options=['SMA', 'EMA', 'WMA'], inline=t_ma2, group=gr_ma)
ma2_source = input.source(close, '', inline=t_ma2, group=gr_ma)
ma2_length = input.int(100, '', minval=1, inline=t_ma2, group=gr_ma)
ma2_color = color.new(#1163f6,0)
ma2 = f_ma(ma2_source, ma2_length, ma2_type)
plot(show_ma2 ? ma2 : na, color=ma2_color, title=t_ma2, linewidth=1)
// ======================================================================================================
// v4.0 adds alerts for Fast and Slow swinging to a new move up or new move down
// This is easier than looking for the visual signal / color change .. as requested
// The main signal is really when the ribbon "agrees" on a spcific color
// ======================================================================================================
Alert_Fastup = Fast_up and not Fast_up[1]
Alert_Fastdn = Fast_dn and not Fast_dn[1]
Alert_Slowup = Slow_up and not Slow_up[1]
Alert_Slowdn = Slow_dn and not Slow_dn[1]
alertcondition(Alert_Fastup, 'Fast Line Swings Up', 'MagicRibbon - Fast Line Swing Up Detected!')
alertcondition(Alert_Fastdn, 'Fast Line Swings Down', 'MagicRibbon - Fast Line Swing Down Detected!')
alertcondition(Alert_Slowup, 'Slow Line Swings Up', 'MagicRibbon - Slow Line Swing Up Detected!')
alertcondition(Alert_Slowdn, 'Slow Line Swings Down', 'MagicRibbon - Slow Line Swing Down Detected!')
|
Stochastic Moving Average Delta Oscillator (SMADO) | https://www.tradingview.com/script/eOcuSo1z-Stochastic-Moving-Average-Delta-Oscillator-SMADO/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("SMADO")
back = input.int(25, "Window", 1)
len = input.int(200, "Length", 1)
smooth = input.int(4, "Smoothing", 1)
lag = input.int(10, 'Lag Line', 1)
del = array.new<float>(len)
for i = 1 to len by 1
array.push(del, ta.cum(ta.sma(close, i) - ta.sma(close, i)[1]))
delta_sum = ta.sma(array.sum(del), smooth)
scale = ta.stoch(delta_sum, delta_sum, delta_sum, back)
mom = ta.sma(scale, lag)
colour = scale >= mom ? color.new(color.blue, 10) : color.new(color.orange, 10)
u = plot(scale, color = colour)
d = plot(mom, color = colour)
fill(u, d, color = colour) |
Traders Reality PVSRA Volume Suite | https://www.tradingview.com/script/UcbR9FIH-Traders-Reality-PVSRA-Volume-Suite/ | TradersReality | https://www.tradingview.com/u/TradersReality/ | 1,373 | 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 by infernix, library integration by peshocore
// Please note while the code is open source and you are free to use it however you like - the 'Traders Reality' name is not - ie if you produce derivatives of this
// source code you to name those scripts using "Traders Reality", "Pattern Watchers" or any other name that relates to Traders Reality in any way.
//@version=5
indicator(title = 'Traders Reality PVSRA Volume Suite', shorttitle='TR_PVSRA_VS', format=format.volume)
import TradersReality/Traders_Reality_Lib/1 as trLib
color redVectorColor = input.color(title='Vector: Red', group='PVSRA Colors', defval=color.red, inline='vectors')
color greenVectorColor = input.color(title='Green', group='PVSRA Colors', defval=color.lime, inline='vectors')
color violetVectorColor = input.color(title='Violet', group='PVSRA Colors', defval=color.fuchsia, inline='vectors')
color blueVectorColor = input.color(title='Blue', group='PVSRA Colors', defval=color.blue, inline='vectors', tooltip='Bull bars are green and bear bars are red when the bar is with volume >= 200% of the average volume of the 10 previous bars, or bars where the product of candle spread x candle volume is >= the highest for the 10 previous bars.\n Bull bars are blue and bear are violet when the bar is with with volume >= 150% of the average volume of the 10 previous bars.')
color regularCandleUpColor = input.color(title='Regular: Up Candle', group='PVSRA Colors', defval=#999999, inline='nonVectors')
color regularCandleDownColor = input.color(title='Down Candle', group='PVSRA Colors', defval=#4d4d4d, inline='nonVectors', tooltip='Bull bars are light gray and bear are dark gray when none of the red/green/blue/violet vector conditions are met.')
bool setCandleColors = input.bool(false, title='Set PVSRA candle colors?', group='PVSRA Colors', inline='setCandle')
bool overrideSym = input.bool(group='PVSRA Override', title='Override chart symbol?', defval=false, inline='pvsra')
string pvsraSym = input.string(group='PVSRA Override', title='', defval='INDEX:BTCUSD', tooltip='You can use INDEX:BTCUSD or you can combine multiple feeds, for example BINANCE:BTCUSDT+COINBASE:BTCUSD. Note that adding too many will slow things down.', inline='pvsra')
bool displayMa = input.bool(false, 'Volume MA', inline="vma")
color maColor = input.color(color.blue, "MA Color", inline="vma")
int maPeriod = input.int(20,"MA Period", minval=1, maxval=2000, step=1, inline="vma")
pvsraVolume(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', volume, barmerge.gaps_off, barmerge.lookahead_off)
pvsraHigh(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', high, barmerge.gaps_off, barmerge.lookahead_off)
pvsraLow(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', low, barmerge.gaps_off, barmerge.lookahead_off)
pvsraClose(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', close, barmerge.gaps_off, barmerge.lookahead_off)
pvsraOpen(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', open, barmerge.gaps_off, barmerge.lookahead_off)
pvsraVolume = pvsraVolume(overrideSym, pvsraSym, syminfo.tickerid)
pvsraHigh = pvsraHigh(overrideSym, pvsraSym, syminfo.tickerid)
pvsraLow = pvsraLow(overrideSym, pvsraSym, syminfo.tickerid)
pvsraClose = pvsraClose(overrideSym, pvsraSym, syminfo.tickerid)
pvsraOpen = pvsraOpen(overrideSym, pvsraSym, syminfo.tickerid)
[pvsraColor, alertFlag, averageVolume, volumeSpread, highestVolumeSpread] = trLib.calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleDownColor, regularCandleUpColor)
plot(pvsraVolume, style=plot.style_columns, color=pvsraColor,title="PVSRA Volume")
barcolor(setCandleColors ? pvsraColor : na)
alertcondition(alertFlag, title='Vector Candle Alert', message='Vector Candle Alert')
plot(displayMa ? ta.sma(pvsraVolume,maPeriod) : na, title="Volume MA", color=maColor, editable=true) |
VOLQ Sigma Table | https://www.tradingview.com/script/7BTOLUJ1-VOLQ-Sigma-Table/ | Cube_Lee | https://www.tradingview.com/u/Cube_Lee/ | 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/
// © Cube_Lee
//@version=5
indicator("VOLQ Sigma Table", overlay = true)
// Function
truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
// Input
showtable = input.bool(true, "Show Table", tooltip = "VOLQ를 반영한 가격을 테이블에 표시합니다.", group = "VOLQ Table")
trunc = input.int(0, "Decimal display", tooltip = "테이블에 나타나는 가격의 소수점 자리수를 선택하세요", group = "VOLQ Table")
showline = input.bool(true, "Show VOLQ Line", tooltip = "예상 VOLQ를 선으로 표시합니다.", group = "VOLQ Line")
showplot = input.bool(false, "Show historic VOLQ band", tooltip = "과거 VOLQ 밴드를 차트에 표시합니다.")
src = input.string("last week close", "price source", options = ["week close", "last week close"], tooltip = "VOLQ % 를 이번 주 종가로 할 것인지 지난 주 종가로 할 것인지 선택합니다.")
// Get Data
vol1 = request.security("VOLQ", "W", close)
vol2 = request.security("VOLQ", "W", close[1])
// close1 = truncate(request.security(syminfo.tickerid, "D", close), trunc)
// close2 = truncate(request.security(syminfo.tickerid, "D", close[1]), trunc)
// close3 = truncate(request.security(syminfo.tickerid, "W", close), trunc)
// close4 = truncate(request.security(syminfo.tickerid, "W", close[1]), trunc)
//━━━━━━━━━━━━━━━━━━━━━//
// 마지막 금요일 구하기 //
//━━━━━━━━━━━━━━━━━━━━//
var float last_fri_close = 0.0
var int last_friday = 0
if dayofweek == dayofweek.friday and time(timeframe.period, "1600-1630")
last_fri_close := truncate(close, trunc)
last_friday := time
// 마지막 금요일 구하기 끝 //
float volq = switch src
"week close" => vol1
"last week close" => vol2
// float sym_close = switch src
// "day close" => close1
// "last day close" => close2
// "week close" => close3
// "last week close" => close4
// 변동성 반영한 주가지수 산출
sigma2_high_1day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(250) * 2 / 100), trunc)
sigma2_high_2day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(125) * 2 / 100), trunc)
sigma2_high_3day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(83) * 2 / 100), trunc)
sigma2_high_4day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(62.5) * 2 / 100), trunc)
sigma2_high_5day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(50) * 2 / 100), trunc)
sigma1_high_1day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(250) / 100), trunc)
sigma1_high_2day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(125) / 100), trunc)
sigma1_high_3day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(83) / 100), trunc)
sigma1_high_4day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(62.5) / 100), trunc)
sigma1_high_5day = truncate(last_fri_close + (last_fri_close * volq / math.sqrt(50) / 100), trunc)
sigma1_low_1day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(250) / 100), trunc)
sigma1_low_2day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(125) / 100), trunc)
sigma1_low_3day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(83) / 100), trunc)
sigma1_low_4day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(62.5) / 100), trunc)
sigma1_low_5day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(50) / 100), trunc)
sigma2_low_1day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(250) * 2 / 100), trunc)
sigma2_low_2day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(125) * 2 / 100), trunc)
sigma2_low_3day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(83) * 2 / 100), trunc)
sigma2_low_4day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(62.5) * 2 / 100), trunc)
sigma2_low_5day = truncate(last_fri_close - (last_fri_close * volq / math.sqrt(50) * 2 / 100), trunc)
// 테이블 컬러
bg_color_volq = color.rgb(0, 0, 0)
bg_color_title = color.rgb(0, 0, 0)
bg_color_high2 = color.rgb(129, 199, 132)
bg_color_high1 = color.rgb(200, 230, 201)
bg_color_close = color.rgb(255, 255, 255)
bg_color_low1 = color.rgb(252, 203, 205)
bg_color_low2 = color.rgb(247, 124, 128)
text_color_volq = color.red
text_color_title = color.rgb(216, 216, 216)
text_color_high = color.rgb(0, 0, 0)
text_color_close = color.blue
text_color_low = color.rgb(0, 0, 0)
// Draw Table
string close_text = switch src
"week close" => "주간 종가"
"last week close" => "지난 주 종가"
_textsize = size.normal
if barstate.islastconfirmedhistory and showtable
t = table.new(position = position.top_right, columns = 7, rows = 6, border_color = color.white, border_width = 2)
table.cell(table_id = t, column = 6, row = 0, text = "blank", bgcolor = color.rgb(54, 58, 69, 100), text_color = color.rgb(54, 58, 69, 100), text_size = _textsize)
table.merge_cells(table_id = t, start_column = 6, start_row = 0, end_column = 6, end_row = 5)
table.cell(table_id = t, column = 0, row = 0, text = "VOLQ:" + "\n" + str.tostring(volq) + "%", bgcolor = bg_color_volq, text_color = text_color_volq, text_size = _textsize)
table.cell(table_id = t, column = 1, row = 0, text = "1 day", bgcolor = bg_color_title, text_color = text_color_title, text_size = _textsize)
table.cell(table_id = t, column = 2, row = 0, text = "2 day", bgcolor = bg_color_title, text_color = text_color_title, text_size = _textsize)
table.cell(table_id = t, column = 3, row = 0, text = "3 day", bgcolor = bg_color_title, text_color = text_color_title, text_size = _textsize)
table.cell(table_id = t, column = 4, row = 0, text = "4 day", bgcolor = bg_color_title, text_color = text_color_title, text_size = _textsize)
table.cell(table_id = t, column = 5, row = 0, text = "5 day", bgcolor = bg_color_title, text_color = text_color_title, text_size = _textsize)
table.cell(table_id = t, column = 0, row = 1, text = "High 2σ", bgcolor = bg_color_high2, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 1, row = 1, text = str.tostring(sigma2_high_1day), bgcolor = bg_color_high2, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 2, row = 1, text = str.tostring(sigma2_high_2day), bgcolor = bg_color_high2, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 3, row = 1, text = str.tostring(sigma2_high_3day), bgcolor = bg_color_high2, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 4, row = 1, text = str.tostring(sigma2_high_4day), bgcolor = bg_color_high2, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 5, row = 1, text = str.tostring(sigma2_high_5day), bgcolor = bg_color_high2, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 0, row = 2, text = "High 1σ", bgcolor = bg_color_high1, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 1, row = 2, text = str.tostring(sigma1_high_1day), bgcolor = bg_color_high1, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 2, row = 2, text = str.tostring(sigma1_high_2day), bgcolor = bg_color_high1, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 3, row = 2, text = str.tostring(sigma1_high_3day), bgcolor = bg_color_high1, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 4, row = 2, text = str.tostring(sigma1_high_4day), bgcolor = bg_color_high1, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 5, row = 2, text = str.tostring(sigma1_high_5day), bgcolor = bg_color_high1, text_color = text_color_high, text_size = _textsize)
table.cell(table_id = t, column = 0, row = 3, text = str.tostring(close_text), bgcolor = bg_color_close, text_color = text_color_close, text_size = _textsize)
table.cell(table_id = t, column = 1, row = 3, text = str.tostring(last_fri_close), bgcolor = bg_color_close, text_color = text_color_close, text_size = _textsize)
table.merge_cells(table_id = t, start_column = 1, start_row = 3, end_column = 5, end_row = 3)
table.cell(table_id = t, column = 0, row = 4, text = "Low 1σ", bgcolor = bg_color_low1, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 1, row = 4, text = str.tostring(sigma1_low_1day), bgcolor = bg_color_low1, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 2, row = 4, text = str.tostring(sigma1_low_2day), bgcolor = bg_color_low1, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 3, row = 4, text = str.tostring(sigma1_low_3day), bgcolor = bg_color_low1, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 4, row = 4, text = str.tostring(sigma1_low_4day), bgcolor = bg_color_low1, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 5, row = 4, text = str.tostring(sigma1_low_5day), bgcolor = bg_color_low1, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 0, row = 5, text = "Low 2σ", bgcolor = bg_color_low2, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 1, row = 5, text = str.tostring(sigma2_low_1day), bgcolor = bg_color_low2, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 2, row = 5, text = str.tostring(sigma2_low_2day), bgcolor = bg_color_low2, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 3, row = 5, text = str.tostring(sigma2_low_3day), bgcolor = bg_color_low2, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 4, row = 5, text = str.tostring(sigma2_low_4day), bgcolor = bg_color_low2, text_color = text_color_low, text_size = _textsize)
table.cell(table_id = t, column = 5, row = 5, text = str.tostring(sigma2_low_5day), bgcolor = bg_color_low2, text_color = text_color_low, text_size = _textsize)
// volq line location
// day1 = input.time(timestamp("2022-10-30"), title = "VOLQ Line 표시 시작 날짜", confirm = true, group = "VOLQ Line")
day1 = last_friday + 235800 * 1000
day2 = day1 + 86400 * 1000
day3 = day2 + 86400 * 1000
day4 = day3 + 86400 * 1000
day5 = day4 + 86400 * 1000
day6 = day5 + 86400 * 1000
// Draw VOLQ Line
linecolor = color.yellow
LblBR = color.black
txtColor = color.white
if barstate.islast and showline
if timeframe.isintraday or timeframe.isdaily
// baseline
line_base = line.new(x1=day1, y1 = last_fri_close, x2 = day6, y2 = last_fri_close, xloc = xloc.bar_time, extend = extend.none, color = color.gray, style = line.style_dotted)
// 1 day
line_h2_day1 = line.new(x1=day1, y1=sigma2_high_1day, x2=day2, y2=sigma2_high_1day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_h2_day1[1])
line_h1_day1 = line.new(x1=day1, y1=sigma1_high_1day, x2=day2, y2=sigma1_high_1day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_h1_day1[1])
line_l1_day1 = line.new(x1=day1, y1=sigma1_low_1day, x2=day2, y2=sigma1_low_1day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_l1_day1[1])
line_l2_day1 = line.new(x1=day1, y1=sigma2_low_1day, x2=day2, y2=sigma2_low_1day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_l2_day1[1])
// 2 day
line_h2_day2 = line.new(x1=day2, y1=sigma2_high_2day, x2=day3, y2=sigma2_high_2day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_h2_day2[1])
line_h1_day2 = line.new(x1=day2, y1=sigma1_high_2day, x2=day3, y2=sigma1_high_2day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_h1_day2[1])
line_l1_day2 = line.new(x1=day2, y1=sigma1_low_2day, x2=day3, y2=sigma1_low_2day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_l1_day2[1])
line_l2_day2 = line.new(x1=day2, y1=sigma2_low_2day, x2=day3, y2=sigma2_low_2day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_l2_day2[1])
// 3 day
line_h2_day3 = line.new(x1=day3, y1=sigma2_high_3day, x2=day4, y2=sigma2_high_3day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_h2_day3[1])
line_h1_day3 = line.new(x1=day3, y1=sigma1_high_3day, x2=day4, y2=sigma1_high_3day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_h1_day3[1])
line_l1_day3 = line.new(x1=day3, y1=sigma1_low_3day, x2=day4, y2=sigma1_low_3day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_l1_day3[1])
line_l2_day3 = line.new(x1=day3, y1=sigma2_low_3day, x2=day4, y2=sigma2_low_3day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_l2_day3[1])
// 4 day
line_h2_day4 = line.new(x1=day4, y1=sigma2_high_4day, x2=day5, y2=sigma2_high_4day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_h2_day4[1])
line_h1_day4 = line.new(x1=day4, y1=sigma1_high_4day, x2=day5, y2=sigma1_high_4day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_h1_day4[1])
line_l1_day4 = line.new(x1=day4, y1=sigma1_low_4day, x2=day5, y2=sigma1_low_4day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_l1_day4[1])
line_l2_day4 = line.new(x1=day4, y1=sigma2_low_4day, x2=day5, y2=sigma2_low_4day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_l2_day4[1])
// 5 day
line_h2_day5 = line.new(x1=day5, y1=sigma2_high_5day, x2=day6, y2=sigma2_high_5day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_h2_day5[1])
line_h1_day5 = line.new(x1=day5, y1=sigma1_high_5day, x2=day6, y2=sigma1_high_5day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_h1_day5[1])
line_l1_day5 = line.new(x1=day5, y1=sigma1_low_5day, x2=day6, y2=sigma1_low_5day, xloc=xloc.bar_time, extend=extend.none, color=linecolor)
line.delete(line_l1_day5[1])
line_l2_day5 = line.new(x1=day5, y1=sigma2_low_5day, x2=day6, y2=sigma2_low_5day, xloc=xloc.bar_time, extend=extend.none, color=linecolor, width=2)
line.delete(line_l2_day5[1])
// label
label_h2_day5 = label.new(x=day6, y=sigma2_high_5day, text='High 2σ', xloc=xloc.bar_time, color=LblBR, textcolor = txtColor, style=label.style_label_left)
label.delete(label_h2_day5[1])
label_h1_day5 = label.new(x=day6, y=sigma1_high_5day, text='High 1σ', xloc=xloc.bar_time, color=LblBR, textcolor = txtColor, style=label.style_label_left)
label.delete(label_h1_day5[1])
label_l1_day5 = label.new(x=day6, y=sigma1_low_5day, text='Low 1σ', xloc=xloc.bar_time, color=LblBR, textcolor = txtColor, style=label.style_label_left)
label.delete(label_l1_day5[1])
label_l2_day5 = label.new(x=day6, y=sigma2_low_5day, text='Low 2σ', xloc=xloc.bar_time, color=LblBR, textcolor = txtColor, style=label.style_label_left)
label.delete(label_l2_day5[1])
// VOLQ band plot
plot(sigma2_high_1day, "High 2σ", style = plot.style_line, color = showplot ? color.rgb(0, 255, 0, 50) : color.rgb(33, 149, 243, 100))
plot(sigma1_high_1day, "High 1σ", style = plot.style_line, color = showplot ? color.rgb(0, 255, 0, 70) : color.rgb(33, 149, 243, 100))
plot(sigma1_low_1day, "Low 1σ", style = plot.style_line, color = showplot ? color.rgb(255, 0, 0, 70) : color.rgb(33, 149, 243, 100))
plot(sigma2_low_1day, "Low 2σ", style = plot.style_line, color = showplot ? color.rgb(255, 0, 0, 50) : color.rgb(33, 149, 243, 100)) |
Traders Reality Vector Candle Zones | https://www.tradingview.com/script/I604sNNd-Traders-Reality-Vector-Candle-Zones/ | TradersReality | https://www.tradingview.com/u/TradersReality/ | 1,418 | 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 by infernix, library integration by peshocore
// Please note while the code is open source and you are free to use it however you like - the 'Traders Reality' name is not - ie if you produce derivatives of this
// source code you to name those scripts using "Traders Reality", "Pattern Watchers" or any other name that relates to Traders Reality in any way.
//@version=5
indicator(title='Traders Reality Vector Candle Zones', shorttitle='TR_VCZ', overlay=true)
import TradersReality/Traders_Reality_Lib/1 as trLib
color redVectorColor = input.color(title='Vector: Red', group='PVSRA Colors', defval=color.red, inline='vectors')
color greenVectorColor = input.color(title='Green', group='PVSRA Colors', defval=color.lime, inline='vectors')
color violetVectorColor = input.color(title='Violet', group='PVSRA Colors', defval=color.fuchsia, inline='vectors')
color blueVectorColor = input.color(title='Blue', group='PVSRA Colors', defval=color.blue, inline='vectors', tooltip='Bull bars are green and bear bars are red when the bar is with volume >= 200% of the average volume of the 10 previous bars, or bars where the product of candle spread x candle volume is >= the highest for the 10 previous bars.\n Bull bars are blue and bear are violet when the bar is with with volume >= 150% of the average volume of the 10 previous bars.')
color regularCandleUpColor = input.color(title='Regular: Up Candle', group='PVSRA Colors', defval=#999999, inline='nonVectors')
color regularCandleDownColor = input.color(title='Down Candle', group='PVSRA Colors', defval=#4d4d4d, inline='nonVectors', tooltip='Bull bars are light gray and bear are dark gray when none of the red/green/blue/violet vector conditions are met.')
bool setcandlecolors = input.bool(false, title='Set PVSRA candle colors?', group='PVSRA Colors', inline='setCandle')
int zonesMax = input.int(500, 'Maximum zones to draw', group='Vector Candle Zones')
string zoneType = input.string(group='Vector Candle Zones', defval='Body only', title='Zone top/bottom is defined with: ', options=['Body only', 'Body with wicks'])
string zoneUpdateType = input.string(group='Vector Candle Zones', defval='Body with wicks', title='Zones are cleared using candle: ', options=['Body only', 'Body with wicks'])
int borderWidth = input.int(0, 'Zone border width', group='Vector Candle Zones')
bool colorOverride = input.bool(true, 'Override color?' , group='Vector Candle Zones', inline="vcz1")
color zoneColor = input.color(title='Color', group='Vector Candle Zones', defval=color.rgb(255, 230, 75, 90), inline="vcz1", tooltip='the vector candle zones color to use if you dont not want to use the PVSRA Candle Colors.')
int transperancy = input.int(90, 'Zone Transperancy', minval = 0, maxval = 100, group='Vector Candle Zones', tooltip='If the vector candle zones color is not overriden, then we want to set the transparancy of the vector candle colors as defined by the PBSRA candle colors. This setting only affects the candle zone colors not the candle colors themselves.')
bool overrideSym = input.bool(group='PVSRA Override', title='Override chart symbol?', defval=false, inline='pvsra')
string pvsraSym = input.string(group='PVSRA Override', title='', defval='INDEX:BTCUSD', tooltip='You can use INDEX:BTCUSD or you can combine multiple feeds, for example BINANCE:BTCUSDT+COINBASE:BTCUSD. Note that adding too many will slow things down.', inline='pvsra')
pvsraVolume(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', volume, barmerge.gaps_off, barmerge.lookahead_off)
pvsraHigh(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', high, barmerge.gaps_off, barmerge.lookahead_off)
pvsraLow(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', low, barmerge.gaps_off, barmerge.lookahead_off)
pvsraClose(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', close, barmerge.gaps_off, barmerge.lookahead_off)
pvsraOpen(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', open, barmerge.gaps_off, barmerge.lookahead_off)
pvsraVolume = pvsraVolume(overrideSym, pvsraSym, syminfo.tickerid)
pvsraHigh = pvsraHigh(overrideSym, pvsraSym, syminfo.tickerid)
pvsraLow = pvsraLow(overrideSym, pvsraSym, syminfo.tickerid)
pvsraClose = pvsraClose(overrideSym, pvsraSym, syminfo.tickerid)
pvsraOpen = pvsraOpen(overrideSym, pvsraSym, syminfo.tickerid)
[pvsraColor, alertFlag, averageVolume, volumeSpread, highestVolumeSpread] = trLib.calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleDownColor, regularCandleUpColor)
var zoneBoxesAbove = array.new_box()
var zoneBoxesBelow = array.new_box()
barcolor(setcandlecolors ? pvsraColor : na)
pvsra = trLib.getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleUpColor)
trLib.updateZones(pvsra, 0, zoneBoxesBelow, zonesMax, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneUpdateType, zoneColor, zoneType, borderWidth, colorOverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
trLib.updateZones(pvsra, 1, zoneBoxesAbove, zonesMax, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneUpdateType, zoneColor, zoneType, borderWidth, colorOverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
trLib.cleanarr(zoneBoxesAbove)
trLib.cleanarr(zoneBoxesBelow)
|
Liquidity Levels MTF - Sonarlab | https://www.tradingview.com/script/xr4eVwH4-Liquidity-Levels-MTF-Sonarlab/ | Sonarlab | https://www.tradingview.com/u/Sonarlab/ | 2,626 | 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/
// © Sonarlab
//@version=5
indicator("Liquidity Levels - Sonarlab", overlay=true)
_tfSettings = "TimeFrame Settings"
currentTF = input.bool(true, title = "Liquidity Levels", group=_tfSettings)
htfBool = input.bool(false, title = "Higher Timeframe",inline="1", group=_tfSettings)
htfTF = input.timeframe("", title = "", inline="1",group=_tfSettings, tooltip="Display Liquidity Levels for a Higher Timeframe")
// --
_lvlsGrp = "Liquidity Levels"
leftBars = input.int(15, title = "Left Bars", group=_lvlsGrp, tooltip="Set the lookback point for what determines a Liquidity Level")
rightBars = input.int(5, title = "Right Bars", group=_lvlsGrp, tooltip="Set the number of bars to confirm a Liquidity Level")
// --
_removeGrp = "Mitigation Settings"
removeMitigated = input.bool(true, title = "Mitigated", inline="1", group=_removeGrp)
mitiOptions = input.string("Show", title = " ", inline="1", options=["Remove", "Show"], group=_removeGrp, tooltip="Show: Liquidity Levels will stop printing when mitigated and remain on the chart.\nRemove: Liquidity Levels will be removed from the chart when mitigated.")
_candleType = input.string("Close", title = "Candle type", options=["Close", "Wick"], group=_removeGrp, tooltip="Choose whether a candle close or a candles high/low is needed to determine a mitigated Liquidity Level")
// --
_displayStyleGrp = "Display Styles"
displayStyle = input.string("Lines", title = "Display Style", options=["Lines", "Boxes"], group=_displayStyleGrp, tooltip="Choose how Liquidity Levels are displayed on the chart")
extentionOptions = input.string("Current", title = "Extention Options", options=["Short", "Current", "Max"], group=_displayStyleGrp, tooltip="Choose how Liquidity Levels are extended on the chart")
extentionMax = extentionOptions=="Max" ? true : false
extentionCurrent = extentionOptions=="Current" ? true : false
displayLimit = input.int(5, title = "Display Limit", group=_displayStyleGrp, tooltip="")
// --
_styleGrp = "Line Styles and Colors"
_highLineStyle = input.string("Solid", title = "High Line Style", options=["Solid", "Dashed", "Dotted"], group=_styleGrp)
highLineStyle = _highLineStyle=="Solid" ? line.style_solid : _highLineStyle=="Dashed" ? line.style_dashed : line.style_dotted
_lowLineStyle = input.string("Solid", title = "Low Line Style", options=["Solid", "Dashed", "Dotted"], group=_styleGrp)
lowLineStyle = _lowLineStyle=="Solid" ? line.style_solid : _lowLineStyle=="Dashed" ? line.style_dashed : line.style_dotted
lineWidth = input.int(1, title = "Line Width", group=_styleGrp, tooltip="")
// --
highLineColor = input.color(#1f4ef5, "High Line ", group = _styleGrp, inline = "1")
lowLineColor = input.color(#fd441c, "Low Line", group = _styleGrp, inline = "1")
highBoxBgColor = input.color(color.new(#1f4ef5, 80), "High Box Bg ", group = _styleGrp, inline = "2")
highBoxBorderColor = input.color(color.new(#1f4ef5, 80), "Box Border", group = _styleGrp, inline = "2")
lowBoxBgColor = input.color(color.new(#fd441c, 80), "Low Box Bg ", group = _styleGrp, inline = "3")
lowBoxBorderColor = input.color(color.new(#fd441c, 80), "Box Border", group = _styleGrp, inline = "3")
// --
// --
_styleGrpHTF = "Line Styles and Colors - Higher TimeFrame"
_highLineStyleHTF = input.string("Solid", title = "High Line HTF", options=["Solid", "Dashed", "Dotted"], group=_styleGrpHTF)
highLineStyleHTF = _highLineStyleHTF=="Solid" ? line.style_solid : _highLineStyleHTF=="Dashed" ? line.style_dashed : line.style_dotted
_lowLineStyleHTF = input.string("Solid", title = "Low Line HTF", options=["Solid", "Dashed", "Dotted"], group=_styleGrpHTF)
lowLineStyleHTF = _lowLineStyleHTF=="Solid" ? line.style_solid : _lowLineStyleHTF=="Dashed" ? line.style_dashed : line.style_dotted
lineWidthHTF = input.int(1, title = "Line Width HTF", group=_styleGrpHTF, tooltip="")
// --
highLineColorHTF = input.color(#4c9650, "High Line ", group = _styleGrpHTF, inline = "1")
lowLineColorHTF = input.color(#fd1c49, "Low Line", group = _styleGrpHTF, inline = "1")
highBoxBgColorHTF = input.color(color.new(#4c9650, 80), "High Box Bg ", group = _styleGrpHTF, inline = "2")
highBoxBorderColorHTF = input.color(color.new(#4c9650, 80), "Box Border", group = _styleGrpHTF, inline = "2")
lowBoxBgColorHTF = input.color(color.new(#fd1c49, 80), "Low Box Bg ", group = _styleGrpHTF, inline = "3")
lowBoxBorderColorHTF = input.color(color.new(#fd1c49, 80), "Box Border", group = _styleGrpHTF, inline = "3")
// --
// --
// Alerts
alertNewHigh = input.bool(true, title = "New High", inline="1", group="Alerts")
alertNewHighTxt = input.string("Break out!", title="", inline="1", group="Alerts")
alertNewLow = input.bool(true, title = "New Low", inline="2", group="Alerts")
alertNewLowTxt = input.string("Break down!", title="", inline="2", group="Alerts")
alertNewHighHTF = input.bool(true, title = "New HTF High", inline="3", group="Alerts")
alertNewHighHTFTxt = input.string("Break out!", title="", inline="3", group="Alerts")
alertNewLowHTF = input.bool(true, title = "New HTF Low", inline="4", group="Alerts")
alertNewLowHTFTxt = input.string("Break down!", title="", inline="4", group="Alerts")
// --
// ----------------------------------------------------
// Functions
// ----------------------------------------------------
tf_multi(tf) =>
ts = timeframe.in_seconds("")
htfs = timeframe.in_seconds(tf)
htfs/ts
display_limit_line(_array) =>
if array.size(_array) > displayLimit/2
a = array.shift(_array)
line.delete(a)
display_limit_box(_array) =>
if array.size(_array) > displayLimit/2
a = array.shift(_array)
box.delete(a)
remove_mitigated_lines(_array, _hl) =>
m = false
if array.size(_array) > 0 and removeMitigated
for i = array.size(_array) - 1 to 0 by 1
l = array.get(_array, i)
hh = _candleType == "Close" ? close[1] : high
ll = _candleType == "Close" ? close[1] : low
if _hl == "High" and hh > line.get_y1(l)
array.remove(_array, i)
if mitiOptions == "Show"
line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = color.new(highLineColor, 70))
line.delete(l)
m := true
if _hl == "Low" and ll < line.get_y1(l)
array.remove(_array, i)
if mitiOptions == "Show"
line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = color.new(lowLineColor, 70))
line.delete(l)
m := true
display_limit_line(_array)
m
remove_mitigated_boxes(_array, _hl) =>
m = false
if array.size(_array) > 0 and removeMitigated
for i = array.size(_array) - 1 to 0 by 1
l = array.get(_array, i)
hh = _candleType == "Close" ? close[1] : high
ll = _candleType == "Close" ? close[1] : low
if _hl == "High" and hh > box.get_top(l)
array.remove(_array, i)
if mitiOptions == "Show"
box.new(box.get_left(l),box.get_top(l),time,box.get_bottom(l), xloc=xloc.bar_time, bgcolor = color.new(highBoxBgColor, 90), border_color = color.new(highBoxBorderColor, 90), border_style = highLineStyle)
box.delete(l)
m := true
if _hl == "Low" and ll < box.get_top(l)
array.remove(_array, i)
if mitiOptions == "Show"
box.new(box.get_left(l),box.get_top(l),time,box.get_bottom(l), xloc=xloc.bar_time, bgcolor = color.new(lowBoxBgColor, 90), border_color = color.new(lowBoxBorderColor, 90), border_style = lowLineStyle)
box.delete(l)
m := true
display_limit_box(_array)
m
extend_line_to_current(lineArray) =>
if array.size(lineArray) > 0
for i = array.size(lineArray) - 1 to 0 by 1
l = array.get(lineArray, i)
timeExt = time + ((time[1]-time[2])*20)
line.set_x2(l, timeExt)
extend_box_to_current(boxArray) =>
if array.size(boxArray) > 0
for i = array.size(boxArray) - 1 to 0 by 1
b = array.get(boxArray, i)
timeExt = time + ((time[1]-time[2])*20)
box.set_right(b, timeExt)
// ----------------------------------------------------
// Current TimeFrame
// ----------------------------------------------------
// Varibles
// Lines
var highLineArray = array.new_line()
var lowLineArray = array.new_line()
// Boxes
var highBoxArray = array.new_box()
var lowBoxArray = array.new_box()
// Pivots
pivotHigh = ta.pivothigh(leftBars, rightBars)[1]
pivotLow = ta.pivotlow(leftBars, rightBars)[1]
// Run Calculations
if currentTF
if pivotHigh
if displayStyle == "Lines"
array.push(highLineArray, line.new(time[rightBars+1],high[rightBars+1],time[+1],high[rightBars+1],color = highLineColor, style=highLineStyle, xloc=xloc.bar_time, extend=extentionMax?extend.right:extend.none, width = lineWidth))
else
y1 = math.max(open[rightBars+1], close[rightBars+1])
array.push(highBoxArray, box.new(time[rightBars+1],high[rightBars+1],time[+1],y1,bgcolor = highBoxBgColor, border_color=highBoxBorderColor, xloc=xloc.bar_time, border_style = highLineStyle, extend=extentionMax?extend.right:extend.none, border_width = lineWidth))
if pivotLow
if displayStyle == "Lines"
array.push(lowLineArray, line.new(time[rightBars+1],low[rightBars+1],time[+1],low[rightBars+1],color = lowLineColor, style=lowLineStyle, xloc=xloc.bar_time, extend=extentionMax?extend.right:extend.none, width = lineWidth))
else
y1 = math.min(open[rightBars+1], close[rightBars+1])
array.push(lowBoxArray, box.new(time[rightBars+1],low[rightBars+1],time[+1],y1,bgcolor = lowBoxBgColor, border_color=lowBoxBorderColor, xloc=xloc.bar_time, border_style = lowLineStyle, extend=extentionMax?extend.right:extend.none, border_width = lineWidth))
// ----------------------------------------------------
// Run Functions
// ----------------------------------------------------
highLineAlert = remove_mitigated_lines(highLineArray, "High")
lowLineAlert = remove_mitigated_lines(lowLineArray, "Low")
highBoxAlert = remove_mitigated_boxes(highBoxArray, "High")
lowBoxAlert = remove_mitigated_boxes(lowBoxArray, "Low")
if extentionCurrent
extend_line_to_current(highLineArray)
extend_line_to_current(lowLineArray)
extend_box_to_current(highBoxArray)
extend_box_to_current(lowBoxArray)
// Alerts
alertcondition(highLineAlert or highBoxAlert, "New High", "Price is breaking out!")
alertcondition(lowLineAlert or lowBoxAlert, "New Low", "Price is breaking down!")
//
if (highLineAlert or highBoxAlert) and alertNewHigh
alert(alertNewHighTxt, alert.freq_once_per_bar)
if (lowLineAlert or lowBoxAlert) and alertNewLow
alert(alertNewLowTxt, alert.freq_once_per_bar)
// ----------------------------------------------------
// Higher TimeFrame
// ----------------------------------------------------
// Varibles
// Lines
var highLineArrayHTF = array.new_line()
var lowLineArrayHTF = array.new_line()
// Boxes
var highBoxArrayHTF = array.new_box()
var lowBoxArrayHTF = array.new_box()
// Get HTF
[_time, _open, _high, _low, _close] = request.security(syminfo.tickerid, htfTF, [time, open, high, low, close])
// Pivots
pivotHighHTF = ta.pivothigh(_high, leftBars*tf_multi(htfTF), rightBars+tf_multi(htfTF))
pivotLowHTF = ta.pivotlow(_low, leftBars*tf_multi(htfTF), rightBars+tf_multi(htfTF))
if htfBool
timeExt = time+((time[1]-time[2])*10)
dis = rightBars+tf_multi(htfTF)
if pivotHighHTF
if displayStyle == "Lines"
array.push(highLineArrayHTF, line.new(_time[dis],_high[dis],_time[+1],_high[dis],color = highLineColorHTF, style=highLineStyleHTF, xloc=xloc.bar_time, extend=extentionMax?extend.right:extend.none, width = lineWidthHTF))
else
y1 = math.max(_open[dis], _close[dis])
array.push(highBoxArrayHTF, box.new(_time[dis],_high[dis],_time[+1],y1,bgcolor = highBoxBgColorHTF, border_color=highBoxBorderColorHTF, xloc=xloc.bar_time, border_style = highLineStyleHTF, extend=extentionMax?extend.right:extend.none, border_width = lineWidthHTF))
if pivotLowHTF
if displayStyle == "Lines"
array.push(lowLineArrayHTF, line.new(_time[dis],_low[dis],_time[+1],_low[dis],color = lowLineColorHTF, style=lowLineStyleHTF, xloc=xloc.bar_time, extend=extentionMax?extend.right:extend.none, width = lineWidthHTF))
else
y1 = math.min(_open[dis], _close[dis])
array.push(lowBoxArrayHTF, box.new(_time[dis],_low[dis],_time[+1],y1,bgcolor = lowBoxBgColorHTF, border_color=lowBoxBorderColorHTF, xloc=xloc.bar_time, border_style = lowLineStyleHTF, extend=extentionMax?extend.right:extend.none, border_width = lineWidthHTF))
// ----------------------------------------------------
// Run Functions
// ----------------------------------------------------
highLineAlertHTF = remove_mitigated_lines(highLineArrayHTF, "High")
lowLineAlertHTF = remove_mitigated_lines(lowLineArrayHTF, "Low")
highBoxAlertHTF = remove_mitigated_boxes(highBoxArrayHTF, "High")
lowBoxAlertHTF = remove_mitigated_boxes(lowBoxArrayHTF, "Low")
if extentionCurrent
extend_line_to_current(highLineArrayHTF)
extend_line_to_current(lowLineArrayHTF)
extend_box_to_current(highBoxArrayHTF)
extend_box_to_current(lowBoxArrayHTF)
// Alerts
alertcondition(highLineAlertHTF or highBoxAlertHTF, "New HTF High", "Price is breaking out!")
alertcondition(lowLineAlertHTF or lowBoxAlertHTF, "New HTF Low", "Price is breaking down!")
//
if (highLineAlertHTF or highBoxAlertHTF) and alertNewHighHTF
alert(alertNewHighHTFTxt, alert.freq_once_per_bar)
if (lowLineAlertHTF or lowBoxAlertHTF) and alertNewLowHTF
alert(alertNewLowHTFTxt, alert.freq_once_per_bar)
|
Heiken Ashi Swing Range Filter | https://www.tradingview.com/script/bVOiJyrs-Heiken-Ashi-Swing-Range-Filter/ | TheBacktestGuy | https://www.tradingview.com/u/TheBacktestGuy/ | 45 | 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/
// © wallneradam
//@version=5
indicator("Heiken Ashi Swing Range Filter", "HARF", overlay=true, timeframe="", timeframe_gaps=false)
import wallneradam/TAExt/10
swing_use_ha = input.bool(false, "Use HA Open/Close as swing high/low", group="Range")
// Heiken-ashi candles
[o, h, l, c] = TAExt.heiken_ashi()
// Calculate swing range
var float swing_high = na
var float swing_low = na
if c[1] > o[1] and c < o
swing_high := swing_use_ha ? c[1] : high[1]
else if c[1] < o[1] and c > o
swing_low := swing_use_ha ? o[1] : low[1]
// Check if bar is inside the range
in_range = (high > swing_high and low < swing_low) or (high < swing_high and low > swing_low)
if not in_range
// Check if bar is more inside than outside
if high > swing_high
in_range := high - swing_high <= swing_high - low
else
in_range := swing_low - low <= high - swing_low
barcolor(in_range ? #444444 : na)
bgcolor(in_range ? color.new(color.gray, 98) : na)
plot(swing_high, "Swing High", color=color.new(color.green, 30), style=plot.style_stepline, display=display.none)
plot(swing_low, "Swing Low", color=color.new(color.red, 30), style=plot.style_stepline, display=display.none) |
Top 40 constituents of S&P 500 Index | https://www.tradingview.com/script/clYkX85H-Top-40-constituents-of-S-P-500-Index/ | iravan | https://www.tradingview.com/u/iravan/ | 52 | 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/
// © iravan
//@version=5
indicator("Top 40 constituents of S&P 500 Index", shorttitle="S&P 500 Constituents", overlay=false, max_boxes_count=100, max_lines_count=100, max_labels_count=100)
box_space = timeframe.isdwm ? 5 : 5
box_width = timeframe.isdwm ? 2 : 2
var sym_len = 40
var sym_names = array.new<string>(sym_len)
var sym_changes = array.new<float>(sym_len)
var boxes1 = array.new<box>(sym_len)
var boxes2 = array.new<box>(sym_len)
var labels1 = array.new<label>(sym_len)
var lowest = array.from(1000.0)
setBox(id, l, t, r, b, c) =>
box.set_left(id, l)
box.set_top(id, t)
box.set_right(id, r)
box.set_bottom(id, b)
box.set_bgcolor(id, c)
box.set_border_color(id, c)
setLabel(id, x, y, t, c) =>
label.set_x(id, x)
label.set_y(id, y)
label.set_text(id, t)
label.set_textcolor(id, c)
ohlc(s, i) =>
if not barstate.islast
[0, 0, 0, 0]
[s_open, s_high, s_low, s_close] = request.security(s, timeframe.period, [open, high, low, close])
o = (s_open[0] - s_close[1])/s_close[1] * 100
h = (s_high[0] - s_close[1])/s_close[1] * 100
l = (s_low[0] - s_close[1])/s_close[1] * 100
c = (s_close[0] - s_close[1])/s_close[1] * 100
if barstate.islast
_l = array.get(lowest, 0)
if(l < _l)
array.set(lowest, 0, l)
box_index = bar_index - (sym_len - i) * box_space
setBox(array.get(boxes1, i - 1), box_index + box_width / 2, c, box_index - box_width / 2, o, c > o ? color.teal: color.red)
setBox(array.get(boxes2, i - 1), box_index, h, box_index, l, c > o ? color.teal: color.red)
ex_index = str.pos(s, ":")
name_index = ex_index >= 0? ex_index + 1: 0
name = str.substring(s, name_index, name_index + 3)
array.set(sym_names, i - 1, name)
array.set(sym_changes, i - 1, c)
if(i == sym_len)
__l = array.get(lowest, 0)
for j = 1 to sym_len
__name = array.get(sym_names, j - 1)
__change = math.round(array.get(sym_changes, j - 1), 2)
__change_text = __name + "\n" + str.tostring(__change) + "%"
lbl_index = bar_index - (sym_len - j) * box_space
setLabel(array.get(labels1, j - 1), lbl_index, __l - 1, __change_text, __change < 0? color.red: color.green)
[o, h, l, c]
if barstate.isfirst
for i = 0 to sym_len - 1
array.set(boxes1, i, box.new(0, 0, 0, 0, border_width=1))
array.set(boxes2, i, box.new(0, 0, 0, 0, border_width=0))
array.set(labels1, i, label.new(0, 0, "", style=label.style_none, size=size.small))
hline(0)
sym1 = input.symbol("NASDAQ:AAPL", "Symbol 1")
sym2 = input.symbol("NASDAQ:MSFT", "Symbol 2")
sym3 = input.symbol("NASDAQ:AMZN", "Symbol 3")
sym4 = input.symbol("NASDAQ:TSLA", "Symbol 4")
sym5 = input.symbol("NASDAQ:GOOGL", "Symbol 5")
sym6 = input.symbol("NYSE:BRK.B", "Symbol 6")
sym7 = input.symbol("NYSE:UNH", "Symbol 7")
sym8 = input.symbol("NASDAQ:GOOG", "Symbol 8")
sym9 = input.symbol("NYSE:XOM", "Symbol 9")
sym10 = input.symbol("NYSE:JNJ", "Symbol 10")
sym11 = input.symbol("NYSE:JPM", "Symbol 11")
sym12 = input.symbol("NASDAQ:NVDA", "Symbol 12")
sym13 = input.symbol("NYSE:V", "Symbol 13")
sym14 = input.symbol("NYSE:CVX", "Symbol 14")
sym15 = input.symbol("NYSE:PG", "Symbol 15")
sym16 = input.symbol("NYSE:HD", "Symbol 16")
sym17 = input.symbol("NYSE:MA", "Symbol 17")
sym18 = input.symbol("NYSE:LLY", "Symbol 18")
sym19 = input.symbol("NYSE:PFE", "Symbol 19")
sym20 = input.symbol("NYSE:ABBV", "Symbol 20")
sym21 = input.symbol("NYSE:BAC", "Symbol 21")
sym22 = input.symbol("NYSE:MRK", "Symbol 22")
sym23 = input.symbol("NASDAQ:PEP", "Symbol 23")
sym24 = input.symbol("NYSE:KO", "Symbol 24")
sym25 = input.symbol("NASDAQ:COST", "Symbol 25")
sym26 = input.symbol("NASDAQ:META", "Symbol 26")
sym27 = input.symbol("NYSE:TMO", "Symbol 27")
sym28 = input.symbol("NYSE:WMT", "Symbol 28")
sym29 = input.symbol("NYSE:MCD", "Symbol 29")
sym30 = input.symbol("NYSE:DIS", "Symbol 30")
sym31 = input.symbol("NASDAQ:AVGO", "Symbol 31")
sym32 = input.symbol("NASDAQ:CSCO", "Symbol 32")
sym33 = input.symbol("NYSE:WFC", "Symbol 33")
sym34 = input.symbol("NYSE:ACN", "Symbol 34")
sym35 = input.symbol("NYSE:ABT", "Symbol 35")
sym36 = input.symbol("NYSE:DHR", "Symbol 36")
sym37 = input.symbol("NYSE:BMY", "Symbol 37")
sym38 = input.symbol("NYSE:COP", "Symbol 38")
sym39 = input.symbol("NYSE:CRM", "Symbol 39")
sym40 = input.symbol("NYSE:VZ", "Symbol 40")
ohlc(sym1, 1)
ohlc(sym2, 2)
ohlc(sym3, 3)
ohlc(sym4, 4)
ohlc(sym5, 5)
ohlc(sym6, 6)
ohlc(sym7, 7)
ohlc(sym8, 8)
ohlc(sym9, 9)
ohlc(sym10, 10)
ohlc(sym11, 11)
ohlc(sym12, 12)
ohlc(sym13, 13)
ohlc(sym14, 14)
ohlc(sym15, 15)
ohlc(sym16, 16)
ohlc(sym17, 17)
ohlc(sym18, 18)
ohlc(sym19, 19)
ohlc(sym20, 20)
ohlc(sym21, 21)
ohlc(sym22, 22)
ohlc(sym23, 23)
ohlc(sym24, 24)
ohlc(sym25, 25)
ohlc(sym26, 26)
ohlc(sym27, 27)
ohlc(sym28, 28)
ohlc(sym29, 29)
ohlc(sym30, 30)
ohlc(sym31, 31)
ohlc(sym32, 32)
ohlc(sym33, 33)
ohlc(sym34, 34)
ohlc(sym35, 35)
ohlc(sym36, 36)
ohlc(sym37, 37)
ohlc(sym38, 38)
ohlc(sym39, 39)
ohlc(sym40, 40)
|
AJ's Position Size Calculator for Forex and Stocks | https://www.tradingview.com/script/Y3rPjP9n-AJ-s-Position-Size-Calculator-for-Forex-and-Stocks/ | Algo_Jo | https://www.tradingview.com/u/Algo_Jo/ | 114 | 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/
// © Algo_Jo
//@version=5
//Version 2.0
//I can't guarentee the output of this caculator is correct, use at your own risk
indicator("AJ's Position Size Calculator for Forex and Stocks", shorttitle = "AJ's PSC", overlay = true, precision = 4)
//User Input
//Account Statistics
Acc_Stats = "Account Stats"
Acount_Size = input.float(title = "Account Value", defval = 100000.00, confirm = true, group = Acc_Stats)
Account_Cur = input.string(title = "Account Currency", defval = "USD", confirm = true, group = Acc_Stats, options = ["USD", "CAD", "EUR", "AUD", "NZD", "CHF", "GBP", "SGD", "JPY"])
T_Direction = input.string(title = "Trade Direction", defval = "Long", options = ["Long", "Short"])
risk_Amnt = input.float(title = "Risk % Per Trade", defval = 1.0)
use_ATR = input.bool(title = "Use Atr To Calculate Stop Loss?", defval = true, group = "ATR")
use_rtp = input.bool(title = "Use Real Time Price?", defval = false, tooltip = "Use real time price to calculate SL & TP, If false, will use the previous close.", group = "Price Source")
ATRper = input.int(title = "ATR Period", defval = 14, group = "ATR")
ATRMult = input.float(title = "ATR Multiplier for SL", defval = 1.5, group = "Stop Loss")
SLtype = input.string(title = "SL value Type", defval = "Ratio", options = ["Ratio","Manual"], tooltip = "Choose whether Stop Loss is manual or a ratio of stop loss distance from price", group = "Stop Loss")
SL_Price = input.float(title = "Stop Loss Price", defval = 0.00, group = "Stop Loss", tooltip = "Choose 'Manual' for Stop Loss price placment then enter price")
TPtype = input.string(title = "TP value Type", defval = "Ratio", options = ["Ratio","Manual"], tooltip = "Choose whether Profit Target is manual or a ratio of stop loss distance from price", group = "Profit Target")
TP_ratio = input.float(title = "Profit Target Ratio", defval = 1.5, group = "Profit Target", tooltip = "Reward to Risk Ratio")
TP_price = input.float(title = "Profit Target Price", defval = 0.00, group = "Profit Target", tooltip = "Choose 'Manual' for Profit Target price placment then enter price")
Chart_settings = "Chart Settings"
p_table = input.bool(title = "Plot Table to Chart", defval = true, group = Chart_settings)
show_LL = input.bool(title = "Show Line Labels", defval = true, tooltip = "Show distance and $ value for TP/SL near lines?", group = Chart_settings)
txt_color = input.color(title = "Tabel Text Color", defval = color.white, group = Chart_settings)
add_SLL = input.string(title = "Show SL Distance", defval = " $ ", options = [" $ ", " % "], group = Chart_settings)
theme_color = input.color(title = "Chart Border Color", defval = color.gray, group = Chart_settings)
bgcolor = input.color(title = "Table and label background colors", defval = color.black, group = Chart_settings)
sl_color = input.color(title = "Stop Loss Color", defval = color.red, group = Chart_settings)
tp_color = input.color(title = "Profit Target Color", defval = color.green, group = Chart_settings)
eLine_C = input.color(title = "Entry Line Color", defval = color.blue, group = Chart_settings)
plotSL = input.bool(title = "Plot Stop Loss and Profit line?", defval = true, group = Chart_settings)
fillSL = input.float(title = "Fill Stop Loss and Profit Level Transperency", defval = 70.0, group = Chart_settings)
LSL = "Lot Sizes and Leverage"
LT_size = input.float(title = "Standard Forex Lot Size in $", defval = 100000.00, group = LSL)
FXleverage = input.float(title = "Forex Leverage, ( ____ :1)", defval = 500.0, group = LSL)
//Crleverage = input.float(title = "Crypto Leverage, ( ____ :1)", defval = 10.0, group = LSL)
Stleverage = input.float(title = "Stocks & ETF's Leverage, ( ____ :1)", defval = 3.0, group = LSL)
//cfdlev = input.float(title = "CFD's Leverage ( ____ :1)", defval = 500.0, group = LSL)
min_Lot = input.float(title = "Minimum Lot Size (Forex)", defval = 0.01, group = LSL)
//Truncate Function (get value to desired decimal place)
truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
//Add ATR For stop loss calculations
atr = ta.atr(ATRper)
//Get Risk amount in dollars of account currrency
risk = risk_Amnt/100
risk_dollars = risk*Acount_Size
//Get Current Price
float C_price = 0.0
if use_rtp
C_price := close
else if use_rtp == false
C_price := close[1]
//Get minimum point move
float P_value = syminfo.mintick
//Get Type of symbol (forex,crypto,stock,cfd,etc..)
Tckr_Type = syminfo.type
// Dollar amount per pip per Lot in account currency
float dollar_PPpl = syminfo.pointvalue
//Declare Stop loss and profit levels
float sl_Val = 0.00
float tp_Val = 0.00
//Get Stop and Profit levels
if SLtype == "Manual"
sl_Val := SL_Price
if SLtype == "Ratio"
if T_Direction == "Long"
sl_Val := C_price - (atr * ATRMult)
if T_Direction == "Short"
sl_Val := C_price + (atr * ATRMult)
if TPtype == "Manual"
tp_Val := TP_price
if TPtype == "Ratio"
if T_Direction == "Long"
tp_Val := C_price + (atr * (TP_ratio * ATRMult))
if T_Direction == "Short"
tp_Val := C_price - (atr * (TP_ratio * ATRMult))
//Get Stop and Profit Distance from current price
float slDistace = 0.00
float tpDistance = 0.00
//Get stop and profit in $ or %
if add_SLL == " $ "
slDistace := math.abs(C_price - sl_Val)
tpDistance := math.abs(C_price - tp_Val)
if add_SLL == " % "
slDistace := ((math.abs(C_price - sl_Val))/C_price) * 100
tpDistance := ((math.abs(C_price - tp_Val))/C_price) * 100
//Declare Variables for used for getting correct lot size and margin
float rr_Ratio = tpDistance/slDistace //Reward to Risk Ratio
float pip = P_value // Value of a single point for a standard lot in account currency
string point_id = "Points" //Identifier if a "Point" movment ("Pip" for CFD's and forex)
string c_id = "Lots" //Identifier of units ("Shares" for stocks and ETF's)
float lot = 1 //Number of Units in a Lot (forex = "100000")
float mnLTssz = 0.01 //Minimum Lot Size(Micro Lot for forex, shares for stocks)
int tvalue = 2//truncate value (decimal places)
string quoteCurrency = syminfo.currency //Get the qouted currency of the current symbol
float m_factor = 0 //multiplication factor to get correct lot size
float margin = 0.00 //Withheld margin according to your brokers leverage
int rval = 0
//Get Values for Forex tickers
if Tckr_Type == "forex"
pip := P_value //* 10//0.0001
point_id := "PIPS"
lot := 100000
rval := 2
if P_value == 0.00001
m_factor := 1
tvalue := 5
//Get Correct sizes for JPY pairs
if P_value == 0.001
m_factor := .01
tvalue := 3
//Get Values for CFD Tickers
else if Tckr_Type == "cfd"
pip := P_value //* 10//0.0001
point_id := "PIPS"
//Values for Silver CFD
if syminfo.ticker == "XAGUSD"
lot := 5000
m_factor := 1000
//Values for Oil CFD's
if syminfo.ticker == "USOIL" or syminfo.ticker == "USOILSPOT"
lot := 1000
if P_value == 0.001
m_factor := 10
if P_value == 0.01
m_factor := 1
//Values for Gold CFD
if syminfo.ticker == "XAUUSD"
lot := 100
m_factor := 100
else
if P_value == 0.00001
tvalue := 5
m_factor := 1000
if P_value == 0.0001
m_factor := 100
if P_value == 0.001
tvalue := 3
m_factor := 10
if P_value == 0.01
m_factor := 10
//Get Values for Stocks or ETF's
else if Tckr_Type == "stock" or Tckr_Type == "fund"
pip := P_value //0.01
dollar_PPpl := syminfo.pointvalue * syminfo.mintick //Update Tick value
point_id := "Points"
c_id := "Shares"
tvalue := 2
lot := 1
min_Lot := 1
rval := 0
m_factor := 1
//Get Values for Crypto
else if Tckr_Type =="crypto"
dollar_PPpl := syminfo.pointvalue * syminfo.mintick
lot := 1
tvalue := 5
point_id := "Points"
c_id := "Lots"
else
pip := P_value//0.01
point_id := "Points"
c_id := "Lots"
mnLTssz := 1.0
tvalue := 2
lot := 1
//Convert Account Currency to USD (to increase accuracy because most currencies are qouted against USD)
float gbpUSDrate = request.security('GBPUSD', 'D', close)
float audUSDrate = request.security('AUDUSD', 'D', close)
float nzdUSDrate = request.security('NZDUSD', 'D', close)
float cadUSDrate = request.security('CADUSD', 'D', close)
float chfUSDrate = request.security('CHFUSD', 'D', close)
float eurUSDrate = request.security('EURUSD', 'D', close)
float jpyUSDrate = request.security('JPYUSD', 'D', close)
float sgdUSDrate = request.security('SGDUSD', 'D', close)
//declare variables for getting account values
float ex_rate = 1.0
float USD_val = Acount_Size
float pointVal = 0.0
//Convert Account Value to USD
if Account_Cur == "CAD"
ex_rate := cadUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "EUR"
ex_rate := eurUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "AUD"
ex_rate := audUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "NZD"
ex_rate := nzdUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "CHF"
ex_rate := chfUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "GBP"
ex_rate := gbpUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "SGD"
ex_rate := sgdUSDrate
USD_val := ex_rate * Acount_Size
if Account_Cur == "JPY"
ex_rate := jpyUSDrate
USD_val := ex_rate * Acount_Size
//Get $USD per point per lot
float sl_Distance = math.abs(C_price - sl_Val)
float point_value = risk_dollars / (sl_Distance/pip)
float USD_dppPL = 0.0
//Convert Quote Currency amount per lot per pip to USD (to increase accuracy because most currencies are quoted against USD)
if quoteCurrency == "USD"
USD_dppPL := dollar_PPpl
if quoteCurrency == "CAD"
USD_dppPL := (dollar_PPpl * cadUSDrate)
if quoteCurrency == "EUR"
USD_dppPL := (dollar_PPpl * eurUSDrate)
if quoteCurrency == "AUD"
USD_dppPL := (dollar_PPpl * audUSDrate)
if quoteCurrency == "NZD"
USD_dppPL := (dollar_PPpl * nzdUSDrate)
if quoteCurrency == "CHF"
USD_dppPL := (dollar_PPpl * chfUSDrate)
if quoteCurrency == "GBP"
USD_dppPL := (dollar_PPpl * gbpUSDrate)
if quoteCurrency == "SGD"
USD_dppPL := (dollar_PPpl * sgdUSDrate)
if quoteCurrency == "JPY"
USD_dppPL := ((dollar_PPpl* 100) * jpyUSDrate)
//Get Lot size in USD
USD_risk = risk_dollars * ex_rate//Convert Risk amount to USD
TicksSL = sl_Distance / syminfo.mintick // Stop loss in ticks
fullLotV = TicksSL * USD_dppPL //Get risk amount for a full lot
USD_lotsize = math.round((USD_risk/fullLotV),rval) //Get ideal lot size
Actual_Risk = USD_lotsize * (TicksSL * USD_dppPL) // Get actual risk in USD for ideal lot size
ffLotv = Actual_Risk > USD_risk and USD_lotsize > min_Lot ? USD_lotsize - min_Lot : USD_lotsize // If risk for ideal lot size is greater than desired risk, reduce lot size by minimum lot size amount
final_lot = ffLotv < min_Lot ? min_Lot : ffLotv // IF lot size is smaller than minimum lot size, use minimum lot size
clotvalue = fullLotV / ex_rate // Full lot value in account currency
//Final Risk dollars and percent outcome for lot size
friskdollars = final_lot * clotvalue //Get Risked dollars amount in account currency
friskper = friskdollars / Acount_Size // Get risked dollars percent value of account
riskpercent = friskper * 100 //multiply by 100 to get percentage value
//Get Margin amount for trade lot size
if Tckr_Type == "forex"
margin := (final_lot * ((lot*m_factor) * C_price)) / FXleverage
if Tckr_Type == "stock" or Tckr_Type == "fund"
margin := (final_lot * ((lot*m_factor) * C_price)) / Stleverage
//if Tckr_Type == "crypto"
//margin := (final_lot * ((lot*m_factor) * C_price)) / Crleverage
//if Tckr_Type == "cfd"
//margin := (final_lot * ((lot*m_factor) * C_price)) / cfdleverage
marPerc = (margin / Acount_Size) * 100
//Create Labels and plots for stop and profit targets
sl_label = "SL: " + str.tostring(truncate(sl_Val, tvalue)) + "\n" + "SL Distance: " + add_SLL + str.tostring(truncate(slDistace,tvalue))
tp_label = "TP: " + str.tostring(truncate(tp_Val, tvalue)) + "\n" + "TP Distance: " + add_SLL + str.tostring(truncate(tpDistance,tvalue))
//Set TP and SL label style
Syloc = label.style_label_up
tyloc = label.style_label_down
if T_Direction == "Short"
Syloc := label.style_label_down
tyloc := label.style_label_up
//Plot Stop Loss and Take Profit
sl_Line = plotSL ? line.new(x1 = bar_index[1], y1 = sl_Val, x2 = bar_index + 10, y2 = sl_Val, extend = extend.none, color = sl_color, style = line.style_solid, width = 2) : na
tp_Line = plotSL ? line.new(x1 = bar_index[1], y1 = tp_Val, x2 = bar_index + 10, y2 = tp_Val, extend = extend.none, color = tp_color, style = line.style_solid, width = 2) : na
en_Line = plotSL ? line.new(x1 = bar_index[1], y1 = C_price, x2 = bar_index + 10, y2 = C_price, extend = extend.none, color = eLine_C, style = line.style_solid, width = 2) : na
line.delete(sl_Line[1])
line.delete(tp_Line[1])
line.delete(en_Line[1])
//Fill stop and profit lines
slfill = linefill.new(en_Line, sl_Line, color = color.new(sl_color, fillSL))
tpfill = linefill.new(en_Line, tp_Line, color = color.new(tp_color, fillSL))
//plot stop and profit labels
slLabl = show_LL ? label.new(x = bar_index + 10, y = sl_Val, text = sl_label, color = bgcolor, textcolor = sl_color, style = Syloc) : na
tpLabl = show_LL ? label.new(x = bar_index + 10, y = tp_Val, text = tp_label, color = bgcolor, textcolor = tp_color, style = tyloc) : na
label.delete(slLabl[1])
label.delete(tpLabl[1])
//Check if Caclulator has been configured for current Symbols
tckrconfig = syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "forex" ? true : false
//Dislay Text for non configured symbols
string nconfigtxt = "Current Ticker has \n not yet been configured \n and added to postion sizing \n Updates may come \n in the future \n to support current \n ticker."
//Declare Table stats
var table testTable1 = table.new(position.middle_right, 2, 20, frame_color = theme_color, frame_width = 2, border_color = theme_color, border_width = 2)
f_fillCell1(_table, _column, _row, _value, _bgcolor, _txtcolor, _txtSize) =>
_cellText = _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=_txtSize)
if p_table
// Update table
f_fillCell1(testTable1, 0, 0, "Position Size", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 0, str.tostring(truncate(final_lot,2)) + " " + c_id, bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 0, 1, "Stop Loss", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 1, "$ " + str.tostring(truncate(sl_Val,tvalue)), bgcolor, color.red, size.small)
f_fillCell1(testTable1, 0, 2, "Profit Target", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 2, "$ " + str.tostring(truncate(tp_Val,tvalue)), bgcolor, color.lime, size.small)
f_fillCell1(testTable1, 0, 3, "Stop Loss Distance", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 3, add_SLL + str.tostring(truncate(slDistace,tvalue)), bgcolor, color.red, size.small)
f_fillCell1(testTable1, 0, 4, "Profit Target Distance ", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 4, add_SLL + str.tostring(truncate(tpDistance,tvalue)), bgcolor, color.lime, size.small)
f_fillCell1(testTable1, 0, 5, "Reward:Risk Ratio", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 5, str.tostring(truncate(rr_Ratio,2)), bgcolor, color.green, size.small)
f_fillCell1(testTable1, 0, 6, "Actual Risk $", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 6, tckrconfig ? "$ " + str.tostring(truncate(friskdollars,2)) : "", bgcolor, riskpercent < (risk* 100) ? color.lime : color.red, size.small)
f_fillCell1(testTable1, 0, 7, "Actual Risk %", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 7, tckrconfig ? str.tostring(truncate(riskpercent,2)) + "%" : "", bgcolor, riskpercent < (risk * 100) ? color.lime : color.red, size.small)
f_fillCell1(testTable1, 0, 8, "Account Balance", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 8, "$ " + str.tostring(truncate(Acount_Size,2)) + " " + Account_Cur, bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 0, 9, "Margin $", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 9, tckrconfig ? "$ " + str.tostring(truncate(margin,2)) : "", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 0, 10, "Margin % of Entire Account", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 10, tckrconfig ? str.tostring(truncate(marPerc,2)) + "%" : "", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 0, 11, "Trade Direction", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 11, T_Direction, bgcolor, T_Direction == "Long" ? color.green : color.red, size.small)
f_fillCell1(testTable1, 0, 12, "ATR Period", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 12, str.tostring(ATRper), bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 0, 13, "ATR Value", bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 1, 13, "$ " + str.tostring(truncate(atr,tvalue)), bgcolor, txt_color, size.small)
f_fillCell1(testTable1, 0, 14, "Alog_Jo's Position Size & Stop Loss Calulator \n for Forex and Stocks", bgcolor, txt_color, size.tiny)
f_fillCell1(testTable1, 1, 14, tckrconfig != true ? nconfigtxt : "", bgcolor, color.red, size.tiny)
|
LazyScalp Volume in Currency AVG | https://www.tradingview.com/script/JEsJNrwS-lazyscalp-volume-in-currency-avg/ | Aleksandr400 | https://www.tradingview.com/u/Aleksandr400/ | 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/
// © Aleksandr400
//@version=5
indicator("LazyScalp Volume in Currency AVG", shorttitle = "Volume in Currency AVG", overlay = false, format = format.volume)
avgType = input.string("SMA", "Avg type", options = ["SMA", "EMA", "RMA", "WMA"], group="PARAMETERS")
length = input.int(30, "Length of avg", minval=5, maxval=1000, step=1, group="PARAMETERS")
barCoef = input.float(4, "Avg size coef:", minval=-0.1, maxval=100, step=1, group="PARAMETERS")
barFilter = input.float(1.0, "Candle size filter (%)", minval=0.1, maxval=10, step=0.1, group="PARAMETERS")
candleMeasureType = input.string("Open / Close", "Candle measure type", options = ["Open / Close", "High / Low"], group="PARAMETERS")
longColor = input.color(#26a69a, "Long color", group="COLUMN STYLE")
shortColor = input.color(#ef5350, "Short color", group="COLUMN STYLE")
columnTransp = input.int(50, "Column transparency", minval=0, maxval=100, step=1, group="COLUMN STYLE")
avgLineColor = input.color(#ffffff, "Avg line color", group="AVG LINE STYLE")
avgLineTransp = input.int(50, "Avg line transparency", minval=0, maxval=100, step=1, group="AVG LINE STYLE")
multipAvgLineColor = input.color(#ffb74d, "Avg line color", group="AVG LINE STYLE")
multipAvgLineTransp = input.int(50, "Avg line transparency", minval=0, maxval=100, step=1, group="AVG LINE STYLE")
highlightBars = input.bool(true, "Highlight candles", group="ALERT STYLE")
alertBarColor = input.color(#ffb74d, "Candle color", group="ALERT STYLE")
highlightColumns = input.bool(true, "Highlight columns", group="ALERT STYLE")
alertColor = input.color(#ffb74d, "Column color", group="ALERT STYLE")
alertTransp = input.int(0, "Column transparency", minval=0, maxval=100, step=1, group="ALERT STYLE")
vol = close * volume
volAvg = ta.sma(vol, length)
if avgType == "EMA"
volAvg := ta.ema(vol, length)
if avgType == "RMA"
volAvg := ta.rma(vol, length)
if avgType == "WMA"
volAvg := ta.wma(vol, length)
multipVolAvg = volAvg * barCoef
barSize = math.abs(math.round((open - close)/open * 100, 2))
if candleMeasureType == "High / Low"
barSize := math.round((high - low)/high * 100, 2)
palette = close[1] > close ? shortColor : longColor
volColor = vol > multipVolAvg and barSize > barFilter and highlightColumns ? color.new(alertColor, alertTransp) : color.new(palette, columnTransp)
barcolor(vol > multipVolAvg and barSize > barFilter and highlightBars ? color.new(alertBarColor, 0) : na)
plot(vol, style = plot.style_columns, color = volColor)
plot(multipVolAvg, color = color.new(multipAvgLineColor, multipAvgLineTransp))
plot(volAvg, color = color.new(avgLineColor, avgLineTransp))
if vol > multipVolAvg and barSize > barFilter
alert("BIG VOL " + syminfo.ticker, alert.freq_once_per_bar)
|
Market sessions and Volume profile - By Leviathan | https://www.tradingview.com/script/tV3rCaJ9-Market-sessions-and-Volume-profile-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 6,535 | 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/
// © Leviathan
// Some Volume Profile elements are inspired by @LonesomeTheBlue's volume profile script
//@version=5
indicator("Market sessions and Volume profile - By Leviathan", overlay=true, max_boxes_count=500, max_bars_back=1000)
//==========================
//Inputs
//==========================
sessionType = input.string('Daily', 'Session Type', options=['Tokyo','London','New York','Daily','Weekly', 'Monthly', 'Quarterly', 'Yearly'])
showProf = input.bool(true, 'Show Volume Profile', group='Display')
showSbox = input.bool(true, 'Show Session Box', group='Display')
showPoc = input.bool(true, 'Show POC', group='Display')
showVA = input.bool(true, 'Show VAH and VAL', group='Display')
showVAb = input.bool(false, 'Show Value Area Box', group='Display')
showCur = input.bool(true, 'Show Live Zone', group='Display')
showLabels = input.bool(true, 'Show Session Lables', group='Display')
showFx = input.bool(false, 'Show Forex Sessions (no profile)', group='Display')
resolution = input.int(30, 'Resolution', minval=5, tooltip='The higher the value, the more refined of a profile, but less profiles shown on chart', group='Volume Profile Settings')
VAwid = input.int(70, 'Value Area Volume %', minval=1, maxval=100, group='Volume Profile Settings')
dispMode = input.string('Mode 2', 'Bar Mode', ['Mode 1', 'Mode 2', 'Mode 3'], group='Volume Profile Settings')
volType = input.string('Volume', 'Profile Data Type', options=['Volume', 'Open Interest'], group='Volume Profile Settings')
smoothVol = input.bool(false, 'Smooth Volume Data', tooltip='Useful for assets that have very large spikes in volume over large bars - helps create better profiles', group='Volume Profile Settings')
dataTf = ''
bullCol = input.color(color.rgb(76, 175, 79, 50), 'Up Volume', group='Appearance')
bearCol = input.color(color.rgb(255, 82, 82, 50), 'Down Volume', group='Appearance')
VAbCol = input.color(color.rgb(107, 159, 255, 90), 'Value Area Box', group='Appearance' )
pocCol = input.color(color.red, 'POC', inline='p', group='Appearance')
pocWid = input.int(1, 'Thickness', inline='p', group='Appearance')
vahCol = input.color(color.aqua, 'VAH', inline='h', group='Appearance')
vahWid = input.int(1, 'Thickness', inline='h', group='Appearance')
valCol = input.color(color.aqua, 'VAL', inline='l', group='Appearance')
valWid = input.int(1, 'Thickness', inline='l', group='Appearance')
boxBg = input.color(color.rgb(255, 153, 0, 100), 'Box', inline='m', group='Appearance')
boxWid = input.int(1, 'Thickness', inline='m', group='Appearance')
//==========================
//Constants / Variable Declaration
//==========================
var int zoneStart = 0
var int tokyoStart = 0
var int londonStart = 0
var int nyStart = 0
int lookback = bar_index - zoneStart
var activeZone = false
// Defining arrays that store the information
var vpGreen = array.new_float(resolution, 0) // Sum of volume on long bars
var vpRed = array.new_float(resolution, 0) // Same thing but with red bars
var zoneBounds = array.new_float(resolution, 0) // array that stores the highest value that can be in a zone
//Values to store current intra bar data
var float[] ltfOpen = array.new_float(0)
var float[] ltfClose = array.new_float(0)
var float[] ltfHigh = array.new_float(0)
var float[] ltfLow = array.new_float(0)
var float[] ltfVolume = array.new_float(0)
//Getting OI Data
string userSymbol = syminfo.prefix + ":" + syminfo.ticker
string openInterestTicker = str.format("{0}_OI", userSymbol)
string timeframe = syminfo.type == "futures" and timeframe.isintraday ? "1D" : timeframe.period
deltaOi = request.security(openInterestTicker, timeframe, close-close[1], ignore_invalid_symbol = true)
//Selecting what vol type to use
vol() =>
out = smoothVol ? ta.ema(volume, 5) : volume
if volType == 'Open Interest'
out := deltaOi
out
//Getting intrabar intial data
[dO, dC, dH, dL, dV] = request.security_lower_tf(syminfo.tickerid, dataTf, [open, close, high, low, vol()])
//==========================
//Functions
//==========================
resetProfile(enable) =>
if enable
array.fill(vpGreen, 0)
array.fill(vpRed, 0)
array.clear(ltfOpen)
array.clear(ltfHigh)
array.clear(ltfLow)
array.clear(ltfClose)
array.clear(ltfVolume)
profHigh = ta.highest(high, lookback+1)[1]
profLow = ta.lowest(low, lookback+1)[1]
tr = ta.atr(1)
atr = ta.atr(14)
get_vol(y11, y12, y21, y22, height, vol) =>
nz(math.max(math.min(math.max(y11, y12), math.max(y21, y22)) - math.max(math.min(y11, y12), math.min(y21, y22)), 0) * vol / height)
profileAdd(o, h, l, c, v, g, w) =>
//Array to store how much to distribute in each zone, on scale of 1 for full gap size to 0
zoneDist = array.new_float(resolution, 0)
distSum = 0.0
// Going over each zone
for i = 0 to array.size(vpGreen) - 1
// Checking to see if cur bar is in zone
zoneTop = array.get(zoneBounds, i)
zoneBot = zoneTop - g
body_top = math.max(c, o)
body_bot = math.min(c, o)
itsgreen = c >= o
topwick = h - body_top
bottomwick = body_bot - l
body = body_top - body_bot
bodyvol = body * v / (2 * topwick + 2 * bottomwick + body)
topwickvol = 2 * topwick * v / (2 * topwick + 2 * bottomwick + body)
bottomwickvol = 2 * bottomwick * v / (2 * topwick + 2 * bottomwick + body)
if volType == 'Volume'
array.set(vpGreen, i, array.get(vpGreen, i) + (itsgreen ? get_vol(zoneBot, zoneTop, body_bot, body_top, body, bodyvol) : 0) + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
array.set(vpRed, i, array.get(vpRed, i) + (itsgreen ? 0 : get_vol(zoneBot, zoneTop, body_bot, body_top, body, bodyvol)) + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
else if volType == 'Open Interest'
if v > 0
array.set(vpGreen, i, array.get(vpGreen, i) + get_vol(zoneBot, zoneTop, body_bot, body_top, body, v))// + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
if v < 0
array.set(vpRed, i, array.get(vpRed, i) + get_vol(zoneBot, zoneTop, body_bot, body_top, body, -v))// + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
calcSession(update) =>
array.fill(vpGreen, 0)
array.fill(vpRed, 0)
if bar_index > lookback and update
gap = (profHigh - profLow) / resolution
// Defining profile bounds
for i = 0 to resolution - 1
array.set(zoneBounds, i, profHigh - gap * i)
// Putting each bar inside zone into the volume profile array
if array.size(ltfOpen) > 0
for j = 0 to array.size(ltfOpen) - 1
profileAdd(array.get(ltfOpen, j), array.get(ltfHigh, j), array.get(ltfLow, j), array.get(ltfClose, j), array.get(ltfVolume, j), gap, 1)
pocLevel() =>
float maxVol = 0
int levelInd = 0
for i = 0 to array.size(vpRed) - 1
if array.get(vpRed, i) + array.get(vpGreen, i) > maxVol
maxVol := array.get(vpRed, i) + array.get(vpGreen, i)
levelInd := i
float outLevel = na
if levelInd != array.size(vpRed) - 1
outLevel := array.get(zoneBounds, levelInd) - (array.get(zoneBounds, levelInd) - array.get(zoneBounds, levelInd+1)) / 2
outLevel
valueLevels(poc) =>
float gap = (profHigh - profLow) / resolution
float volSum = array.sum(vpRed) + array.sum(vpGreen)
float volCnt = 0
float vah = profHigh
float val = profLow
//Finding poc index
int pocInd = 0
for i = 0 to array.size(zoneBounds)-2
if array.get(zoneBounds, i) >= poc and array.get(zoneBounds, i + 1) < poc
pocInd := i
volCnt += (array.get(vpRed, pocInd) + array.get(vpGreen, pocInd))
for i = 1 to array.size(vpRed)
if pocInd + i >= 0 and pocInd + i < array.size(vpRed)
volCnt += (array.get(vpRed, pocInd + i) + array.get(vpGreen, pocInd + i))
if volCnt >= volSum * (VAwid/100)
break
else
val := array.get(zoneBounds, pocInd + i) - gap
if pocInd - i >= 0 and pocInd - i < array.size(vpRed)
volCnt += (array.get(vpRed, pocInd - i) + array.get(vpGreen, pocInd - i))
if volCnt >= volSum * (VAwid/100)
break
else
vah := array.get(zoneBounds, pocInd - i)
[val, vah]
drawNewZone(update) =>
if bar_index > lookback and update and array.sum(vpGreen) + array.sum(vpRed) > 0
gap = (profHigh - profLow) / resolution
float leftMax = bar_index[lookback]
float rightMax = bar_index[int(lookback / 1.4)]
float rightMaxVol = array.max(vpGreen)+array.max(vpRed)
float buffer = gap / 10
if showLabels
label.new((bar_index - 1 + int(leftMax))/2, profHigh, sessionType, color=color.rgb(0,0,0,100), textcolor=chart.fg_color)
if showProf
for i = 0 to array.size(vpRed) - 1
greenEnd = int(leftMax + (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol))
redEnd = int(greenEnd + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
if dispMode == 'Mode 2'
box.new(int(leftMax), array.get(zoneBounds, i) - buffer, greenEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bullCol, border_width=0)
box.new(greenEnd, array.get(zoneBounds, i) - buffer, redEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bearCol, border_width=0)
else if dispMode == 'Mode 1'
box.new(int(leftMax), array.get(zoneBounds, i) - buffer, greenEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bullCol, border_width=0)
else
box.new(int(leftMax), array.get(zoneBounds, i) - buffer, greenEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bullCol, border_width=0)
box.new(int(leftMax)-redEnd+greenEnd, array.get(zoneBounds, i) - buffer, int(leftMax), array.get(zoneBounds, i) - gap + buffer, bgcolor=bearCol, border_width=0)
box.new(int(leftMax), profHigh, bar_index-1, profLow, chart.fg_color, boxWid, line.style_dashed, bgcolor=boxBg)
poc = pocLevel()
[val, vah] = valueLevels(poc)
if showPoc
line.new(int(leftMax), poc, bar_index-1, poc, color=pocCol, width=pocWid)
if showVA
line.new(int(leftMax), vah, bar_index-1, vah, color=vahCol, width=vahWid)
line.new(int(leftMax), val, bar_index-1, val, color=valCol, width=valWid)
if showVAb
box.new(int(leftMax), vah, bar_index-1, val, border_color=color.rgb(54, 58, 69, 100), bgcolor=VAbCol)
//if update
// resetProfile(true)
drawCurZone(update, delete) =>
var line pocLine = na
var line vahLine = na
var line valLine = na
var box outBox = na
var label sessionLab = na
var redBoxes = array.new_box(array.size(vpRed), na)
var greenBoxes = array.new_box(array.size(vpRed), na)
if bar_index > lookback and update and array.sum(vpGreen) + array.sum(vpRed) > 0
//Clearing the previous boxes and array
if not na(pocLine)
line.delete(pocLine)
if not na(vahLine)
line.delete(vahLine)
if not na(valLine)
line.delete(valLine)
if not na(outBox)
box.delete(outBox)
if not na(sessionLab)
label.delete(sessionLab)
for i = 0 to array.size(redBoxes) - 1
if not na(array.get(redBoxes, i))
box.delete(array.get(redBoxes, i))
box.delete(array.get(greenBoxes, i))
gap = (profHigh - profLow) / resolution
float leftMax = bar_index[lookback]
float rightMax = bar_index[int(lookback / 1.4)]
float rightMaxVol = array.max(vpGreen)+array.max(vpRed)
float buffer = gap / 10
if showLabels
sessionLab := label.new((bar_index - 1 + int(leftMax))/2, profHigh, sessionType, color=color.rgb(0,0,0,100), textcolor=chart.fg_color)
if showProf
for i = 0 to array.size(vpRed) - 1
greenEnd = int(leftMax + (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol))
redEnd = int(greenEnd + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
if dispMode == 'Mode 2'
array.set(greenBoxes, i, box.new(int(leftMax), array.get(zoneBounds, i) - buffer, greenEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bullCol, border_width=0))
array.set(redBoxes, i, box.new(greenEnd, array.get(zoneBounds, i) - buffer, redEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bearCol, border_width=0))
else if dispMode == 'Mode 1'
array.set(greenBoxes, i, box.new(int(leftMax), array.get(zoneBounds, i) - buffer, greenEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bullCol, border_width=0))
else
array.set(greenBoxes, i, box.new(int(leftMax), array.get(zoneBounds, i) - buffer, greenEnd, array.get(zoneBounds, i) - gap + buffer, bgcolor=bullCol, border_width=0))
array.set(redBoxes, i, box.new(int(leftMax)-redEnd+greenEnd, array.get(zoneBounds, i) - buffer, int(leftMax), array.get(zoneBounds, i) - gap + buffer, bgcolor=bearCol, border_width=0))
outBox := box.new(int(leftMax), profHigh, bar_index-1, profLow, chart.fg_color, boxWid, line.style_dashed, bgcolor=boxBg)
poc = pocLevel()
[val, vah] = valueLevels(poc)
if showPoc
line.delete(pocLine)
pocLine := line.new(int(leftMax), poc, bar_index-1, poc, color=pocCol, width=pocWid)
if showVA
line.delete(vahLine)
line.delete(valLine)
vahLine := line.new(int(leftMax), vah, bar_index-1, vah, color=vahCol, width=vahWid)
valLine := line.new(int(leftMax), val, bar_index-1, val, color=valCol, width=valWid)
if showVAb
box.new(int(leftMax), vah, bar_index-1, val, border_color=color.rgb(54, 58, 69, 100), bgcolor=VAbCol)
if delete
box.delete(outBox)
line.delete(pocLine)
line.delete(vahLine)
line.delete(valLine)
for i = 0 to array.size(greenBoxes)-1
box.delete(array.get(greenBoxes, i))
for i = 0 to array.size(redBoxes)-1
box.delete(array.get(redBoxes, i))
drawForexBox(startBar, title, top, bottom) =>
box.new(int(startBar), top, bar_index-1, bottom, chart.fg_color, boxWid, line.style_dashed, bgcolor=boxBg)
if showLabels
label.new((bar_index - 1 + int(startBar))/2, top, title, color=color.rgb(0,0,0,100), textcolor=chart.fg_color)
combArray(arr1, arr2) =>
out = array.copy(arr1)
if array.size(arr2) > 0
for i = 0 to array.size(arr2) - 1
array.push(out, array.get(arr2, i))
out
updateIntra(o, h, l, c, v) =>
if array.size(o) > 0
for i = 0 to array.size(o) - 1
array.push(ltfOpen, array.get(o, i))
array.push(ltfHigh,array.get(h, i))
array.push(ltfLow,array.get(l, i))
array.push(ltfClose,array.get(c, i))
array.push(ltfVolume,array.get(v, i))
//==========================
//Calculations
//==========================
//Detecting different start dates
newDaily = dayofweek != dayofweek[1]
newWeekly = weekofyear != weekofyear[1]
newMonthly = (dayofmonth != dayofmonth[1] + 1) and (dayofmonth != dayofmonth[1])
newYearly = year != year[1]
newQuarterly = month != month[1] and (month - 1) % 3 == 0
utcHour = hour(time(timeframe.period, '0000-2400', 'GMT'), 'GMT')
newTokyo = utcHour != utcHour[1] + 1 and utcHour != utcHour[1]
endTokyo = utcHour >= 9 and utcHour[1] < 9
newLondon = utcHour >= 7 and utcHour[1] < 7
endLondon = utcHour >= 16 and utcHour[1] < 16
newNewYork = utcHour >= 13 and utcHour[1] < 13
endNewYork = utcHour >= 22 and utcHour[1] < 22
newSession = switch sessionType
'Tokyo' => newTokyo
'London' => newLondon
'New York' => newNewYork
'Daily' => newDaily
'Weekly' => newWeekly
'Monthly' => newMonthly
'Yearly' => newYearly
'Quarterly' => newQuarterly
=> newDaily
zoneEnd = switch sessionType
'Tokyo' => endTokyo
'London' => endLondon
'New York' => endNewYork
'Daily' => newDaily
'Weekly' => newWeekly
'Monthly' => newMonthly
'Yearly' => newYearly
'Quarterly' => newQuarterly
=> newDaily
isForex = showFx
//Re calculating and drawing zones
calcSession(zoneEnd or (barstate.islast and showCur))
drawNewZone(zoneEnd)
drawCurZone(barstate.islast and not zoneEnd and showCur and activeZone, zoneEnd)
//Reseting profie at start of new zone
resetProfile(newSession)
//Updating data arrays
updateIntra(dO, dH, dL, dC, dV)
//Reseting zone start value
if zoneEnd
activeZone := false
if newSession
zoneStart := bar_index
activeZone := true
if newLondon
londonStart := bar_index
if newTokyo
tokyoStart := bar_index
if newNewYork
nyStart := bar_index
londonHigh = ta.highest(high, bar_index-londonStart+1)
tokyoHigh = ta.highest(high, bar_index-tokyoStart+1)
nyHigh = ta.highest(high, bar_index-nyStart+1)
londonLow = ta.lowest(low, bar_index-londonStart+1)
tokyoLow = ta.lowest(low, bar_index-tokyoStart+1)
nyLow = ta.lowest(low, bar_index-nyStart+1)
if endLondon and isForex
drawForexBox(londonStart, 'London', londonHigh, londonLow)
if endNewYork and isForex
drawForexBox(nyStart, 'New York', nyHigh, nyLow)
if endTokyo and isForex
drawForexBox(tokyoStart, 'Tokyo', tokyoHigh, tokyoLow)
|
SOS/SOW Scores | https://www.tradingview.com/script/VGTtMS24-SOS-SOW-Scores/ | benheller21 | https://www.tradingview.com/u/benheller21/ | 105 | 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/
// © benheller21
//@version=5
indicator("SOS/SOW Scores", overlay=true, precision=2, max_labels_count=500)
////////// SOS/SOW ////////////
var display = "SOS/SOW Display Settings"
var vol = "Volume Settings"
var candles = "Candle Settings"
var swing = "Swing Level Settings"
var alerts = "Alert Management"
//Display Settings
displayWeakSOS = input.bool(title="Display Weak SOS/SOW?", defval=true, group = display)
displayModerateSOS = input.bool(title="Display Moderate SOS/SOW?", defval=true, group = display)
displayStrongSOS = input.bool(title="Display Strong SOS/SOW?", defval=true, group = display)
minWeakSOS = input.float(title="Minimum value for weak SOS/SOW", defval=1.5, step = 0.1, minval = 0, group = display)
minModerateSOS = input.float(title="Minimum value for moderate SOS/SOW", defval=4, step = 0.1, group = display)
minStrongSOS = input.float(title="Minimum value for strong SOS/SOW", defval=6.5, step= 0.1, group = display)
displayLabels = input.bool(title="Display Score Labels?", defval=true, group = display)
//Volume
volMALen = input.int(defval=200, title="Volume Moving Average Length", step=1, group=vol, minval=1,
tooltip= "Moving average length used to compare volume to")
volWeight = input.float(title="Volume Weight", defval=2, step = 0.1, group = vol,
tooltip = "Volume MA multiple is multiplied by this number and added to SOS/SOW score")
//Candles
hammerFibLevel = input.float(title="Hammer Body % Level", defval=0.66, minval=0, maxval=1, step=0.01, group=candles,
tooltip= "Entire candle body must be below this value from bottom to top wick")
hammerWeight = input.float(title="Hammer Weight", defval=0.5, step=0.1, group = candles,
tooltip = "Score that a candle gets for qualifying as a hammer")
wickSizeWeight = input.float(title="Wick Size Weight", defval=2, step = 0.1, group = candles,
tooltip = "Size of the wick (as a % of ATR) is multiplied by this number")
colorBoostWeight = input.float(title="Color Boost Weight", defval=0.5, step = 0.1, group=candles,
tooltip = "Additional score that a hammer candle gets if it closes green (bullish hammer) or red (bearish hammer)")
engulfingWeight = input.float(title="Engulfing Weight", defval=1.5, step = 0.1, group=candles,
tooltip = "Score that a candle gets for qualifying as an engulfing candle")
//Swing Levels
swingLookback = input.int(title="Swing High/Low Period", defval=8, minval=1, step=1, group=swing,
tooltip= "Current candle must be highest/lowest in this number of most recent candles")
prevCandleSwing = input.bool(title="Swing High/Low on either of last 2 candles?", defval=true, group=swing)
//Alert Options
alertWeakSOS = input.bool(title = "Send alerts for Weak SOS", defval = false, group = alerts)
alertModSOS = input.bool(title = "Send alerts for Moderate SOS", defval = false, group = alerts)
alertStrongSOS = input.bool(title = "Send alerts for Strong SOS", defval = true, group = alerts)
alertWeakSOW = input.bool(title = "Send alerts for Weak SOW", defval = false, group = alerts)
alertModSOW = input.bool(title = "Send alerts for Moderate SOW", defval = false, group = alerts)
alertStrongSOW = input.bool(title = "Send alerts for Strong SOW", defval = true, group = alerts)
////////////// SOS/SOW Calculations ///////////////
//Swing Levels
swingHigh = high == ta.highest(high, swingLookback) or (prevCandleSwing ? high[1] == ta.highest(high, swingLookback) : na)
swingLow = low == ta.lowest(low, swingLookback) or (prevCandleSwing ? low[1] == ta.lowest(low, swingLookback) : na)
//Valid volume SOS/SOW?
volAvg = (volMALen > 1) ? ta.sma(volume, volMALen) : volume[1]
//Volume Score
volScore = (volume / volAvg) * volWeight
//Hammer candle fib calculations
bullFib = (low - high) * hammerFibLevel + high
bearFib = (high - low) * hammerFibLevel + low
//Determine which price source closes or opens highest/lowest for hammers
lowestBody = close < open ? close : open
highestBody = close > open ? close : open
//Hammer ATR filter
atr = ta.atr(14)
//Valid hammer candle?
bullHammer = lowestBody >= bullFib
bearHammer = highestBody <= bearFib
//Wick Size Score
bearHammerWickScore = ((high - highestBody) / atr) * wickSizeWeight
bullHammerWickScore = ((math.abs(low - lowestBody)) / atr) * wickSizeWeight
//Color Filter
bullHammerColorBoost = (close > open) ? colorBoostWeight: 0
bearHammerColorBoost = (close < open) ? colorBoostWeight: 0
//Hammer Score
bullHammerScore = (bullHammer ? hammerWeight: 0) + bullHammerWickScore + bullHammerColorBoost
bearHammerScore = (bearHammer ? hammerWeight: 0) + bearHammerWickScore + bearHammerColorBoost
//Gapping calculations for engulfing candles
gap = math.abs(open - close[1])
var gapList = array.new_float()
array.push(gapList, gap)
stDev = array.stdev(gapList)
allowance = stDev * 2
//Valid engulfing candle?
bull_ec = close[1] < open[1] and open <= (close[1] + allowance) and close >= open[1]
bear_ec = close[1] > open[1] and open >= (close[1] - allowance) and close <= open[1]
//Engulfing Score
bull_ecScore = bull_ec ? engulfingWeight: 0
bear_ecScore = bear_ec ? engulfingWeight: 0
//Total Candle Score
bullCandleScore = bull_ecScore + bullHammerScore + bullHammerColorBoost + bullHammerWickScore
bearCandleScore = bear_ecScore + bearHammerScore + bearHammerColorBoost + bearHammerWickScore
//SOS/SOW Logic
validSOS = (bull_ec or bullHammer) and swingLow
validSOW = (bear_ec or bearHammer) and swingHigh
if validSOS and validSOW
validSOS := false
validSOW := false
bodySize = math.abs(open-close)
if bodySize / atr > 2.5
validSOS := false
validSOW := false
sosScore = bullCandleScore + volScore
sowScore = bearCandleScore + volScore
weakSOS = sosScore >= minWeakSOS and sosScore < minModerateSOS
moderateSOS = sosScore >= minModerateSOS and sosScore < minStrongSOS
strongSOS = sosScore >= minStrongSOS
weakSOW = sowScore >= minWeakSOS and sowScore < minModerateSOS
moderateSOW = sowScore >= minModerateSOS and sowScore < minStrongSOS
strongSOW = sowScore >= minStrongSOS
bool sos_toDisplay = false
if validSOS and displayWeakSOS and weakSOS
sos_toDisplay := true
else if validSOS and displayModerateSOS and moderateSOS
sos_toDisplay := true
else if validSOS and displayStrongSOS and strongSOS
sos_toDisplay := true
bool sow_toDisplay = false
if validSOW and displayWeakSOS and weakSOW
sow_toDisplay := true
else if validSOW and displayModerateSOS and moderateSOW
sow_toDisplay := true
else if validSOW and displayStrongSOS and strongSOW
sow_toDisplay := true
color sosColor = strongSOS ? color.new(color.green, 0) : moderateSOS ? color.new(color.green, 50) : color.new(color.green, 80)
color sowColor = strongSOW ? color.new(color.red, 0) : moderateSOW ? color.new(color.red, 50) : color.new(color.red, 80)
plotshape(sos_toDisplay, title="SOS", style=shape.circle, color=sosColor, location=location.belowbar, size=size.tiny)
plotshape(sow_toDisplay, title="SOW", style=shape.circle, color=sowColor, location=location.abovebar, size=size.tiny)
if sos_toDisplay and displayLabels
label.new(x=bar_index, y=low, yloc=yloc.belowbar, text=str.tostring(sosScore, '#.#'),
style=label.style_label_up, color=sosColor, textcolor=color.white, size=size.normal)
else if sow_toDisplay and displayLabels
label.new(x=bar_index, y=high, yloc=yloc.abovebar, text=str.tostring(sowScore, '#.#'),
style=label.style_label_down, color=sowColor, textcolor=color.white, size=size.normal)
//Alerts
bool sos_alert = false
bool sow_alert = false
if alertWeakSOS and weakSOS and validSOS
sos_alert := true
else if alertModSOS and moderateSOS and validSOS
sos_alert := true
else if alertStrongSOS and strongSOS and validSOS
sos_alert := true
if alertWeakSOW and weakSOW and validSOW
sow_alert := true
else if alertModSOW and moderateSOW and validSOW
sow_alert := true
else if alertStrongSOW and strongSOW and validSOW
sow_alert := true
alertcondition(sos_alert, "SOS Alert", "SOS detected on {{ticker}} {{interval}}")
alertcondition(sow_alert, "SOW Alert", "SOW detected on {{ticker}} {{interval}}")
// |
Volatility Inverse Correlation Candle | https://www.tradingview.com/script/6ZsWQtZx-Volatility-Inverse-Correlation-Candle/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 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/
// © exlux99
//@version=5
indicator("Volatility Inverse Correlation Candle", overlay=true)
fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Time Condition')
fromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12, group='Time Condition')
fromYear = input.int(defval=2000, title='From Year', minval=1970, group='Time Condition')
//monday and session
// To Date Inputs
toDay = input.int(defval=31, title='To Day', minval=1, maxval=31, group='Time Condition')
toMonth = input.int(defval=12, title='To Month', minval=1, maxval=12, group='Time Condition')
toYear = input.int(defval=2029, title='To Year', minval=1970, group='Time Condition')
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
// plot(close)
input_symbol = input.symbol("TVC:VIX")
ha = input.bool(true,title="Allow HA Mode Calulation")
security_candle_open = ha ? request.security(ticker.heikinashi(input_symbol), timeframe.period, open) : request.security((input_symbol), timeframe.period, open)
security_candle_close = ha ? request.security(ticker.heikinashi(input_symbol), timeframe.period, close) : request.security((input_symbol), timeframe.period, close)
chart_candle_open = ha ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open) : request.security((syminfo.tickerid), timeframe.period, open)
chart_candle_close = ha ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close) : request.security((syminfo.tickerid), timeframe.period, close)
var int total_positive = 0
var int total_negative = 0
var int count_positive = 0
var int count_negative = 0
if(time_cond)
//long vix => short spx
if(security_candle_open > security_candle_close[1] and chart_candle_open <chart_candle_close )
count_positive:= count_positive +1
if(security_candle_open > security_candle_close[1] )
total_positive := total_positive+1
//short vix => long spx
if(security_candle_open < security_candle_close[1] and chart_candle_open > chart_candle_close )
count_negative:= count_negative +1
if(security_candle_open < security_candle_close[1] )
total_negative:=total_negative+1
//with moving average
// ma_out = ta.sma(open, input(2))
// plot(ma_out, color=color.white, linewidth=4)
// plot_short_spx = (security_candle_open > security_candle_close and open >close and open < ma_out)
// plotshape(plot_short_spx, style=shape.xcross, color=color.red, location=location.abovebar)
// plot_long_spx = (security_candle_open < security_candle_close and open < close and open > ma_out)
// plotshape(plot_long_spx, style=shape.xcross, color=color.green, location=location.belowbar)
// //long vix => short spx
// if(security_candle_open > security_candle_close and open >close and open < ma_out)
// count_positive:= count_positive +1
// if(security_candle_open > security_candle_close and open < ma_out)
// total_positive := total_positive+1
// //short vix => long spx
// if(security_candle_open < security_candle_close and open < close and open > ma_out)
// count_negative:= count_negative +1
// if(security_candle_open < security_candle_close and open > ma_out)
// total_negative:=total_negative+1
////////////////////////////////////////////////////////////////////////////
posInput = input.string(title='Position', defval='Middle Right', options=['Bottom Left', 'Bottom Right', 'Top Left', 'Top Right', 'Middle Right'])
var pos = posInput == 'Bottom Left' ? position.bottom_left : posInput == 'Bottom Right' ? position.bottom_right : posInput == 'Top Left' ? position.top_left : posInput == 'Top Right' ? position.top_right : posInput == 'Middle Right' ? position.middle_right: na
var table table_atr = table.new(pos, 15, 15, border_width=1)
table_fillCell(_table, _column, _row, _value, _timeframe, _c_color) =>
_transp = 70
_cellText = str.tostring(_value, '#.###')
table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_c_color, _transp), text_color=_c_color, width=5)
//table.cell_set_text_size(table_atr, 0, 2, text)
if barstate.islast
table.cell(table_atr, 0, 0, 'Total Candles VIX Long', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 0, 1, total_positive, 'Text', color.white)
table.cell(table_atr, 1, 0, 'Total Correlation VIX LONG SPX SHORT', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 1, 1, count_positive, 'Text', color.white)
table.cell(table_atr, 2, 0, '% Correlation VIX LONG SPX SHORT', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 2, 1, count_positive/total_positive, 'Text', color.white)
table.cell(table_atr, 0, 2, 'Total Candles VIX Short', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
table_fillCell(table_atr, 0, 3, total_negative, 'Text', color.white)
table.cell(table_atr, 1, 2, 'Total Correlation VIX SHORT SPX LONG', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
table_fillCell(table_atr, 1, 3, count_negative, 'Text', color.white)
table.cell(table_atr, 2, 2, '% Correlation VIX SHORT SPX LONG', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
table_fillCell(table_atr, 2, 3, count_negative/total_negative, 'Text', color.white)
|
Change of Volatility | https://www.tradingview.com/script/veXegTLF-Change-of-Volatility/ | bjr117 | https://www.tradingview.com/u/bjr117/ | 127 | 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/
// © bjr117
//@version=5
indicator(title = "Change of Volatility", shorttitle = "CHGVOLT", timeframe = "", timeframe_gaps = false)
//==============================================================================
// Function: Calculate a given type of moving average
//==============================================================================
get_ma_out(type, src, len, alma_offset, alma_sigma, kama_fastLength, kama_slowLength, vama_vol_len, vama_do_smth, vama_smth, mf_beta, mf_feedback, mf_z, eit_alpha, ssma_pow, ssma_smooth, rsrma_pw, svama_method, svama_vol_or_volatility, wrma_smooth) =>
float baseline = 0.0
if type == 'SMA | Simple MA'
baseline := ta.sma(src, len)
else if type == 'EMA | Exponential MA'
baseline := ta.ema(src, len)
else if type == 'DEMA | Double Exponential MA'
e = ta.ema(src, len)
baseline := 2 * e - ta.ema(e, len)
else if type == 'TEMA | Triple Exponential MA'
e = ta.ema(src, len)
baseline := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
else if type == 'TMA | Triangular MA' // by everget
baseline := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1)
else if type == 'WMA | Weighted MA'
baseline := ta.wma(src, len)
else if type == 'VWMA | Volume-Weighted MA'
baseline := ta.vwma(src, len)
else if type == 'SMMA | Smoothed MA'
w = ta.wma(src, len)
baseline := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len
else if type == 'RMA | Rolling MA'
baseline := ta.rma(src, len)
else if type == 'HMA | Hull MA'
baseline := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
else if type == 'LSMA | Least Squares MA'
baseline := ta.linreg(src, len, 0)
else if type == 'Kijun' //Kijun-sen
kijun = math.avg(ta.lowest(len), ta.highest(len))
baseline := kijun
else if type == 'MD | McGinley Dynamic'
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
baseline := mg
else if type == 'JMA | Jurik MA' // by everget
DEMAe1 = ta.ema(src, len)
DEMAe2 = ta.ema(DEMAe1, len)
baseline := 2 * DEMAe1 - DEMAe2
else if type == 'ALMA | Arnaud Legoux MA'
baseline := ta.alma(src, len, alma_offset, alma_sigma)
else if type == 'VAR | Vector Autoregression MA'
valpha = 2 / (len+1)
vud1 = (src > src[1]) ? (src - src[1]) : 0
vdd1 = (src < src[1]) ? (src[1] - src) : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz( (vUD - vDD) / (vUD + vDD) )
baseline := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(baseline[1])
else if type == 'ZLEMA | Zero-Lag Exponential MA' // by HPotter
xLag = (len) / 2
xEMAData = (src + (src - src[xLag]))
baseline := ta.ema(xEMAData, len)
else if type == 'AHMA | Ahrens Moving Average' // by everget
baseline := nz(baseline[1]) + (src - (nz(baseline[1]) + nz(baseline[len])) / 2) / len
else if type == 'EVWMA | Elastic Volume Weighted MA'
volumeSum = math.sum(volume, len)
baseline := ( (volumeSum - volume) * nz(baseline[1]) + volume * src ) / volumeSum
else if type == 'SWMA | Sine Weighted MA' // by everget
sum = 0.0
weightSum = 0.0
for i = 0 to len - 1
weight = math.sin(i * math.pi / (len + 1))
sum := sum + nz(src[i]) * weight
weightSum := weightSum + weight
baseline := sum / weightSum
else if type == 'LMA | Leo MA'
baseline := 2 * ta.wma(src, len) - ta.sma(src, len)
else if type == 'VIDYA | Variable Index Dynamic Average' // by KivancOzbilgic
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), len)
downSum = math.sum(-math.min(mom, 0), len)
out = (upSum - downSum) / (upSum + downSum)
cmo = math.abs(out)
alpha = 2 / (len + 1)
baseline := src * alpha * cmo + nz(baseline[1]) * (1 - alpha * cmo)
else if type == 'FRAMA | Fractal Adaptive MA'
length2 = math.floor(len / 2)
hh2 = ta.highest(length2)
ll2 = ta.lowest(length2)
N1 = (hh2 - ll2) / length2
N2 = (hh2[length2] - ll2[length2]) / length2
N3 = (ta.highest(len) - ta.lowest(len)) / len
D = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
factor = math.exp(-4.6 * (D - 1))
baseline := factor * src + (1 - factor) * nz(baseline[1])
else if type == 'VMA | Variable MA' // by LazyBear
k = 1.0/len
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
pdmS = float(0.0)
mdmS = float(0.0)
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
pdiS = float(0.0)
mdiS = float(0.0)
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS = float(0.0)
iS := ((1 - k)*nz(iS[1]) + k*d/s1)
hhv = ta.highest(iS, len)
llv = ta.lowest(iS, len)
d1 = hhv - llv
vI = (iS - llv)/d1
baseline := (1 - k*vI)*nz(baseline[1]) + k*vI*src
else if type == 'GMMA | Geometric Mean MA'
lmean = math.log(src)
smean = math.sum(lmean, len)
baseline := math.exp(smean / len)
else if type == 'CMA | Corrective MA' // by everget
sma = ta.sma(src, len)
baseline := sma
v1 = ta.variance(src, len)
v2 = math.pow(nz(baseline[1], baseline) - baseline, 2)
v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
var tolerance = math.pow(10, -5)
float err = 1
// Gain Factor
float kPrev = 1
float k = 1
for i = 0 to 5000 by 1
if err > tolerance
k := v3 * kPrev * (2 - kPrev)
err := kPrev - k
kPrev := k
kPrev
baseline := nz(baseline[1], src) + k * (sma - nz(baseline[1], src))
else if type == 'MM | Moving Median' // by everget
baseline := ta.percentile_nearest_rank(src, len, 50)
else if type == 'QMA | Quick MA' // by everget
peak = len / 3
num = 0.0
denom = 0.0
for i = 1 to len + 1
mult = 0.0
if i <= peak
mult := i / peak
else
mult := (len + 1 - i) / (len + 1 - peak)
num := num + src[i - 1] * mult
denom := denom + mult
baseline := (denom != 0.0) ? (num / denom) : src
else if type == 'KAMA | Kaufman Adaptive MA' // by everget
mom = math.abs(ta.change(src, len))
volatility = math.sum(math.abs(ta.change(src)), len)
// Efficiency Ratio
er = volatility != 0 ? mom / volatility : 0
fastAlpha = 2 / (kama_fastLength + 1)
slowAlpha = 2 / (kama_slowLength + 1)
alpha = math.pow(er * (fastAlpha - slowAlpha) + slowAlpha, 2)
baseline := alpha * src + (1 - alpha) * nz(baseline[1], src)
else if type == 'VAMA | Volatility Adjusted MA' // by Joris Duyck (JD)
mid = ta.ema(src, len)
dev = src - mid
vol_up = ta.highest(dev, vama_vol_len)
vol_down = ta.lowest(dev, vama_vol_len)
vama = mid + math.avg(vol_up, vol_down)
baseline := vama_do_smth ? ta.wma(vama, vama_smth) : vama
else if type == 'Modular Filter' // by alexgrover
//----
b = 0.0, c = 0.0, os = 0.0, ts = 0.0
//----
alpha = 2/(len+1)
a = mf_feedback ? mf_z*src + (1-mf_z)*nz(baseline[1],src) : src
//----
b := a > alpha*a+(1-alpha)*nz(b[1],a) ? a : alpha*a+(1-alpha)*nz(b[1],a)
c := a < alpha*a+(1-alpha)*nz(c[1],a) ? a : alpha*a+(1-alpha)*nz(c[1],a)
os := a == b ? 1 : a == c ? 0 : os[1]
//----
upper = mf_beta*b+(1-mf_beta)*c
lower = mf_beta*c+(1-mf_beta)*b
baseline := os*upper+(1-os)*lower
else if type == 'EIT | Ehlers Instantaneous Trendline' // by Franklin Moormann (cheatcountry)
baseline := bar_index < 7 ? (src + (2 * nz(src[1])) + nz(src[2])) / 4 : ((eit_alpha - (math.pow(eit_alpha, 2) / 4)) * src) + (0.5 * math.pow(eit_alpha, 2) * nz(src[1])) -
((eit_alpha - (0.75 * math.pow(eit_alpha, 2))) * nz(src[2])) + (2 * (1 - eit_alpha) * nz(baseline[1])) - (math.pow(1 - eit_alpha, 2) * nz(baseline[2]))
else if type == 'ESD | Ehlers Simple Decycler' // by everget
// High-pass Filter
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])
baseline := src - hp
else if type == 'SSMA | Shapeshifting MA' // by alexgrover
//----
ssma_sum = 0.0
ssma_sumw = 0.0
alpha = ssma_smooth ? 2 : 1
power = ssma_smooth ? ssma_pow - ssma_pow % 2 : ssma_pow
//----
for i = 0 to len-1
x = i/(len-1)
n = ssma_smooth ? -1 + x*2 : x
w = 1 - 2*math.pow(n,alpha)/(math.pow(n,power) + 1)
ssma_sumw := ssma_sumw + w
ssma_sum := ssma_sum + src[i] * w
baseline := ssma_sum/ssma_sumw
//----
else if type == 'RSRMA | Right Sided Ricker MA' // by alexgrover
//----
rsrma_sum = 0.0
rsrma_sumw = 0.0
rsrma_width = rsrma_pw/100*len
for i = 0 to len-1
w = (1 - math.pow(i/rsrma_width,2))*math.exp(-(i*i/(2*math.pow(rsrma_width,2))))
rsrma_sumw := rsrma_sumw + w
rsrma_sum := rsrma_sum + src[i] * w
baseline := rsrma_sum/rsrma_sumw
//----
else if type == 'DSWF | Damped Sine Wave Weighted Filter' // by alexgrover
//----
dswf_sum = 0.0
dswf_sumw = 0.0
for i = 1 to len
w = math.sin(2.0*math.pi*i/len)/i
dswf_sumw := dswf_sumw + w
dswf_sum := dswf_sum + w*src[i-1]
//----
baseline := dswf_sum/dswf_sumw
else if type == 'BMF | Blackman Filter' // by alexgrover
//----
bmf_sum = 0.0
bmf_sumw = 0.0
for i = 0 to len-1
k = i/len
w = 0.42 - 0.5 * math.cos(2 * math.pi * k) + 0.08 * math.cos(4 * math.pi * k)
bmf_sumw := bmf_sumw + w
bmf_sum := bmf_sum + w*src[i]
//----
baseline := bmf_sum/bmf_sumw
else if type == 'HCF | Hybrid Convolution Filter' // by alexgrover
//----
sum = 0.
for i = 1 to len
sgn = .5*(1 - math.cos((i/len)*math.pi))
sum := sum + (sgn*(nz(baseline[1],src)) + (1 - sgn)*src[i-1]) * ( (.5*(1 - math.cos((i/len)*math.pi))) - (.5*(1 - math.cos(((i-1)/len)*math.pi))) )
baseline := sum
//----
else if type == 'FIR | Finite Response Filter' // by alexgrover
//----
var b = array.new_float(0)
if barstate.isfirst
for i = 0 to len-1
w = len-i
array.push(b,w)
den = array.sum(b)
//----
sum = 0.0
for i = 0 to len-1
sum := sum + src[i]*array.get(b,i)
baseline := sum/den
else if type == 'FLSMA | Fisher Least Squares MA' // by alexgrover
//----
b = 0.0
//----
e = ta.sma(math.abs(src - nz(b[1])),len)
z = ta.sma(src - nz(b[1],src),len)/e
r = (math.exp(2*z) - 1)/(math.exp(2*z) + 1)
a = (bar_index - ta.sma(bar_index,len))/ta.stdev(bar_index,len) * r
b := ta.sma(src,len) + a*ta.stdev(src,len)
baseline := b
else if type == 'SVAMA | Non-Parametric Volume Adjusted MA' // by alexgrover and bjr117
//----
h = 0.0
l = 0.0
c = 0.0
//----
a = svama_vol_or_volatility == 'Volume' ? volume : ta.tr
h := a > nz(h[1], a) ? a : nz(h[1], a)
l := a < nz(l[1], a) ? a : nz(l[1], a)
//----
b = svama_method == 'Max' ? a / h : l / a
c := b * close + (1 - b) * nz(c[1], close)
baseline := c
else if type == 'RPMA | Repulsion MA' // by alexgrover
baseline := ta.sma(close, len*3) + ta.sma(close, len*2) - ta.sma(close, len)
else if type == 'WRMA | Well Rounded MA' // by alexgrover
//----
alpha = 2/(len+1)
p1 = wrma_smooth ? len/4 : 1
p2 = wrma_smooth ? len/4 : len/2
//----
a = float(0.0)
b = float(0.0)
y = ta.ema(a + b,p1)
A = src - y
B = src - ta.ema(y,p2)
a := nz(a[1]) + alpha*nz(A[1])
b := nz(b[1]) + alpha*nz(B[1])
baseline := y
baseline
//==============================================================================
//==============================================================================
// Inputs
//==============================================================================
// Histogram calculation inputs
chgvolt_short_len = input.int(title = "CHGVOLT Short Length", defval = 6, minval = 1, group = "Main Calculation Settings")
chgvolt_long_len = input.int(title = "CHGVOLT Long Length", defval = 100, minval = 1, group = "Main Calculation Settings")
// Histogram momentum calculation inputs
chgvolt_mom_len = input.int(title = "CHGVOLT Momentum Calculation Length", defval = 1, minval = 1, group = "Main Calculation Settings")
chgvolt_mom_src = input.source(title = "CHGVOLT Momentum Calculation Source", defval = close, group = "Main Calculation Settings")
// Histogram deadzone calculation inputs
chgvolt_dz_ma_type = input.string("EMA | Exponential MA", "CHGVOLT Deadzone MA Type", options=[ "EMA | Exponential MA", "SMA | Simple MA",
"WMA | Weighted MA", "DEMA | Double Exponential MA",
"TEMA | Triple Exponential MA", "TMA | Triangular MA",
"VWMA | Volume-Weighted MA", "SMMA | Smoothed MA",
"HMA | Hull MA", "LSMA | Least Squares MA",
"Kijun", "MD | McGinley Dynamic",
"RMA | Rolling MA", "JMA | Jurik MA",
"ALMA | Arnaud Legoux MA", "VAR | Vector Autoregression MA",
"ZLEMA | Zero-Lag Exponential MA",
"AHMA | Ahrens Moving Average", "EVWMA | Elastic Volume Weighted MA",
"SWMA | Sine Weighted MA", "LMA | Leo MA",
"VIDYA | Variable Index Dynamic Average", "FRAMA | Fractal Adaptive MA",
"VMA | Variable MA", "GMMA | Geometric Mean MA",
"CMA | Corrective MA", "MM | Moving Median",
"QMA | Quick MA", "KAMA | Kaufman Adaptive MA",
"VAMA | Volatility Adjusted MA", "Modular Filter",
"EIT | Ehlers Instantaneous Trendline", "ESD | Ehlers Simple Decycler",
"SSMA | Shapeshifting MA", "RSRMA | Right Sided Ricker MA",
"DSWF | Damped Sine Wave Weighted Filter", "BMF | Blackman Filter",
"HCF | Hybrid Convolution Filter", "FIR | Finite Response Filter",
"FLSMA | Fisher Least Squares MA", "SVAMA | Non-Parametric Volume Adjusted MA",
"RPMA | Repulsion MA", "WRMA | Well Rounded MA"
], group = "Main Calculation Settings")
chgvolt_dz_len = input.int(title = "CHGVOLT Deadzone Length", defval = 55, minval = 1, group = "Main Calculation Settings")
chgvolt_do_barcolor = input.bool(title = "CHGVOLT Show Bar Color", defval = false)
// Specific ma settings
chgvolt_dz_alma_offset = input.float(title = "Offset", defval = 0.85, step = 0.05, group = "Deadzone ALMA Settings")
chgvolt_dz_alma_sigma = input.int(title = "Sigma", defval = 6, group = "Deadzone ALMA Settings")
chgvolt_dz_kama_fastLength = input(title = "Fast EMA Length", defval=2, group = "Deadzone KAMA Settings")
chgvolt_dz_kama_slowLength = input(title = "Slow EMA Length", defval=30, group = "Deadzone KAMA Settings")
chgvolt_dz_vama_vol_len = input.int(title = "Volatality Length", defval = 51, group = "Deadzone VAMA Settings")
chgvolt_dz_vama_do_smth = input.bool(title = "Do Smoothing?", defval = false, group = "Deadzone VAMA Settings")
chgvolt_dz_vama_smth = input.int(title = "Smoothing length", defval = 5, minval = 1, group = "Deadzone VAMA Settings")
chgvolt_dz_mf_beta = input.float(title = "Beta", defval = 0.8, step = 0.1, minval = 0, maxval=1, group = "Deadzone Modular Filter Settings")
chgvolt_dz_mf_feedback = input.bool(title = "Feedback?", defval = false, group = "Deadzone Modular Filter Settings")
chgvolt_dz_mf_z = input.float(title = "Feedback Weighting", defval = 0.5, step = 0.1, minval = 0, maxval = 1, group = "Deadzone Modular Filter Settings")
chgvolt_dz_eit_alpha = input.float(title = "Alpha", defval = 0.07, step = 0.01, minval = 0.0, group = "Deadzone Ehlers Instantaneous Trendline Settings")
chgvolt_dz_ssma_pow = input.float(title = "Power", defval = 4.0, step = 0.5, minval = 0.0, group = "Deadzone SSMA Settings")
chgvolt_dz_ssma_smooth = input.bool(title = "Smooth", defval = false, group = "Deadzone SSMA Settings")
chgvolt_dz_rsrma_pw = input.float(title = "Percent Width", defval = 60.0, step = 10.0, minval = 0.0, maxval = 100.0, group = "Deadzone RSRMA Settings")
chgvolt_dz_svama_method = input.string(title = "Max", options=["Max", "Min"], defval = "Max", group = "Deadzone SVAMA Settings")
chgvolt_dz_svama_vol_or_volatility = input.string(title = "Use Volume or Volatility?", options = ["Volume", "Volatility"], defval = "Volatility", group = "Deadzone SVAMA Settings")
chgvolt_dz_wrma_smooth = input.bool(title = "Extra Smoothing?", defval = false, group = "Deadzone WRMA Settings")
//==============================================================================
//==============================================================================
// Function: Default MT4/MT5 Momentum calculation method
//==============================================================================
get_mom_mt(mom_length, mom_src) =>
mom_src * 100 / mom_src[mom_length]
//==============================================================================
//==============================================================================
// Calculating the change of volatility histogram
//==============================================================================
chgvolt_momentum = get_mom_mt(chgvolt_mom_len, chgvolt_mom_src)
chgvolt = ta.stdev(chgvolt_momentum, chgvolt_short_len, true) / ta.stdev(chgvolt_momentum, chgvolt_long_len, true)
//==============================================================================
//==============================================================================
// Calculating the deadzone (long term ma of the change of volatility histogram)
//==============================================================================
chgvolt_dz = get_ma_out(chgvolt_dz_ma_type, chgvolt, chgvolt_dz_len, chgvolt_dz_alma_offset, chgvolt_dz_alma_sigma, chgvolt_dz_kama_fastLength, chgvolt_dz_kama_slowLength, chgvolt_dz_vama_vol_len, chgvolt_dz_vama_do_smth, chgvolt_dz_vama_smth, chgvolt_dz_mf_beta, chgvolt_dz_mf_feedback, chgvolt_dz_mf_z, chgvolt_dz_eit_alpha, chgvolt_dz_ssma_pow, chgvolt_dz_ssma_smooth, chgvolt_dz_rsrma_pw, chgvolt_dz_svama_method, chgvolt_dz_svama_vol_or_volatility, chgvolt_dz_wrma_smooth)
//==============================================================================
//==============================================================================
// Coloring and plotting the change of volatility line and the deadzone
//==============================================================================
chgvolt_plot_color = chgvolt > chgvolt_dz ? color.green : color.gray
plot(chgvolt, title = "Change of Volatility Histogram", color = chgvolt_plot_color, style = plot.style_columns)
plot(chgvolt_dz, title = "Change of Volatility Deadzone Line", color = color.black)
//==============================================================================
//==============================================================================
// Calculating and plotting the change of volatility bar coloring
//==============================================================================
barcolor(chgvolt_do_barcolor ? chgvolt_plot_color : na, title = "Change of Volatility Bar Color")
//============================================================================== |
Q-Trend | https://www.tradingview.com/script/2vRdxyjm-q-trend/ | tarasenko_ | https://www.tradingview.com/u/tarasenko_/ | 702 | 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/
// © tarasenko_
//@version=5
indicator("Q-Trend", overlay = 1)
// Inputs
src = input(close, "Source", group = "Main settings")
p = input.int(200, "Trend period", group = "Main settings", tooltip = "Changes STRONG signals' sensitivity.", minval = 1)
atr_p = input.int(14, "ATR Period", group = "Main settings", minval = 1)
mult = input.float(1.0, "ATR Multiplier", step = 0.1, group = "Main settings", tooltip = "Changes sensitivity: higher period = higher sensitivty.")
mode = input.string("Type A", "Signal mode", options = ["Type A", "Type B"], group = "Mode")
use_ema_smoother = input.string("No", "Smooth source with EMA?", options = ["Yes", "No"], group = "Source")
src_ema_period = input(3, "EMA Smoother period", group = "Source")
color_bars = input(true, "Color bars?", group = "Addons")
show_tl = input(true, "Show trend line?", group = "Addons")
signals_view = input.string("All", "Signals to show", options = ["All", "Buy/Sell", "Strong", "None"], group = "Signal's Addon")
signals_shape = input.string("Labels", "Signal's shape", options = ["Labels", "Arrows"], group = "Signal's Addon")
buy_col = input(color.green, "Buy colour", group = "Signal's Addon", inline = "BS")
sell_col = input(color.red, "Sell colour", group = "Signal's Addon", inline = "BS")
// Calculations
src := use_ema_smoother == "Yes" ? ta.ema(src, src_ema_period) : src // Source;
h = ta.highest(src, p) // Highest of src p-bars back;
l = ta.lowest(src, p) // Lowest of src p-bars back.
d = h - l
ls = "" // Tracker of last signal
m = (h + l) / 2 // Initial trend line;
m := bar_index > p ? m[1] : m
atr = ta.atr(atr_p)[1] // ATR;
epsilon = mult * atr // Epsilon is a mathematical variable used in many different theorems in order to simplify work with mathematical object. Here it used as sensitivity measure.
change_up = (mode == "Type B" ? ta.cross(src, m + epsilon) : ta.crossover(src, m + epsilon)) or src > m + epsilon // If price breaks trend line + epsilon (so called higher band), then it is time to update the value of a trend line;
change_down = (mode == "Type B" ? ta.cross(src, m - epsilon) : ta.crossunder(src, m - epsilon)) or src < m - epsilon // If price breaks trend line - epsilon (so called higher band), then it is time to update the value of a trend line.
sb = open < l + d / 8 and open >= l
ss = open > h - d / 8 and open <= h
strong_buy = sb or sb[1] or sb[2] or sb[3] or sb[4]
strong_sell = ss or ss[1] or ss[2] or ss[3] or ss[4]
m := (change_up or change_down) and m != m[1] ? m : change_up ? m + epsilon : change_down ? m - epsilon : nz(m[1], m) // Updating the trend line.
ls := change_up ? "B" : change_down ? "S" : ls[1] // Last signal. Helps avoid multiple labels in a row with the same signal;
colour = ls == "B" ? buy_col : sell_col // Colour of the trend line.
buy_shape = signals_shape == "Labels" ? shape.labelup : shape.triangleup
sell_shape = signals_shape == "Labels" ? shape.labeldown : shape.triangledown
// Plottings
plot(show_tl ? m : na, "trend line", colour, 3) // Plotting the trend line.
// Signals with label shape
plotshape(signals_shape == "Labels" and (signals_view == "All" or signals_view == "Buy/Sell") and change_up and ls[1] != "B" and not strong_buy, "Buy signal" , color = colour, style = buy_shape , location = location.belowbar, size = size.normal, text = "BUY", textcolor = color.white) // Plotting the BUY signal;
plotshape(signals_shape == "Labels" and (signals_view == "All" or signals_view == "Buy/Sell") and change_down and ls[1] != "S" and not strong_sell, "Sell signal" , color = colour, style = sell_shape, size = size.normal, text = "SELL", textcolor = color.white) // Plotting the SELL signal.
plotshape(signals_shape == "Labels" and (signals_view == "All" or signals_view == "Strong") and change_up and ls[1] != "B" and strong_buy, "Strong Buy signal" , color = colour, style = buy_shape , location = location.belowbar, size = size.normal, text = "STRONG", textcolor = color.white) // Plotting the STRONG BUY signal;
plotshape(signals_shape == "Labels" and (signals_view == "All" or signals_view == "Strong") and change_down and ls[1] != "S" and strong_sell, "Strong Sell signal" , color = colour, style = sell_shape, size = size.normal, text = "STRONG", textcolor = color.white) // Plotting the STRONG SELL signal.
// Signal with arrow shape
plotshape(signals_shape == "Arrows" and (signals_view == "All" or signals_view == "Buy/Sell") and change_up and ls[1] != "B" and not strong_buy, "Buy signal" , color = colour, style = buy_shape , location = location.belowbar, size = size.tiny) // Plotting the BUY signal;
plotshape(signals_shape == "Arrows" and (signals_view == "All" or signals_view == "Buy/Sell") and change_down and ls[1] != "S" and not strong_sell, "Sell signal" , color = colour, style = sell_shape, size = size.tiny) // Plotting the SELL signal.
plotshape(signals_shape == "Arrows" and (signals_view == "All" or signals_view == "Strong") and change_up and ls[1] != "B" and strong_buy, "Strong Buy signal" , color = colour, style = buy_shape , location = location.belowbar, size = size.tiny) // Plotting the STRONG BUY signal;
plotshape(signals_shape == "Arrows" and (signals_view == "All" or signals_view == "Strong") and change_down and ls[1] != "S" and strong_sell, "Strong Sell signal" , color = colour, style = sell_shape, size = size.tiny) // Plotting the STRONG SELL signal.
barcolor(color_bars ? colour : na) // Bar coloring
// Alerts
alertcondition(change_up and ls[1] != "B", "Q-Trend BUY", "Q-Trend BUY signal were given.") // Buy alert.
alertcondition(change_down and ls[1] != "S", "Q-Trend SELL", "Q-Trend SELL signal were given.") // Sell alert.
alertcondition((change_up and ls[1] != "B") or (change_down and ls[1] != "S"), "Q-Trend Signal", "Q-Trend gave you a signal!")
alertcondition(change_up and ls[1] != "B" and strong_buy, "Strong BUY signal", "Q-Trend gave a Strong Buy signal!")
alertcondition(change_down and ls[1] != "S" and strong_sell, "Strong SELL signal", "Q-Trend gave a Strong Sell signal!") |
Moving Averages Selection | https://www.tradingview.com/script/CuP8GhRD/ | fabio11fcv | https://www.tradingview.com/u/fabio11fcv/ | 13 | 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/
// © fabio11fcv
//@version=5
indicator("Moving Averages Selection", overlay = true, timeframe = "")
ema1lenght = input.int(defval = 45,title = "EMA1")
ema1 = ta.ema(close,ema1lenght)
ema2lenght = input.int(defval = 90,title = "EMA2")
ema2 = ta.ema(close,ema2lenght)
ema3lenght = input.int(defval = 180,title = "EMA3")
ema3 = ta.ema(close,ema3lenght)
sma1lenght = input.int(defval = 45,title = "SMA1")
sma1 = ta.sma(close,sma1lenght)
sma2lenght = input.int(defval = 90,title = "SMA2")
sma2 = ta.sma(close, sma2lenght)
sma3lenght = input.int(defval = 180,title = "SMA3")
sma3 = ta.sma(close,sma3lenght)
hma1lenght = input.int(defval = 45,title = "HMA1")
hma1 = ta.hma(close,hma1lenght)
hma2lenght = input.int(defval = 90,title = "HMA2")
hma2 = ta.hma(close,hma2lenght)
hma3lenght = input.int(defval = 180,title = "HMA3")
hma3 = ta.hma(close,hma3lenght)
rma1lenght = input.int(defval = 45,title = "RMA1")
rma1 = ta.rma(close,rma1lenght)
rma2lenght = input.int(defval = 90,title = "RMA2")
rma2 = ta.rma(close,rma2lenght)
rma3lenght = input.int(defval = 180,title = "RMA3")
rma3 = ta.rma(close,rma3lenght)
wma1lenght = input.int(defval = 45,title = "WMA1")
wma1 = ta.wma(close,wma1lenght)
wma2lenght = input.int(defval = 90,title = "WMA2")
wma2 = ta.wma(close,wma2lenght)
wma3lenght = input.int(defval = 180,title = "WMA3")
wma3 = ta.wma(close,wma3lenght)
Length1 = input.int(45, title = "kAMA1")
xPrice1 = close
xvnoise1 = math.abs(xPrice1 - xPrice1[1])
nAMA1 = 0.0
nfastend1 = 0.666
nslowend1 = 0.0645
nsignal1 = math.abs(xPrice1 - xPrice1[Length1])
nnoise1 = math.sum(xvnoise1, Length1)
nefratio1 = nnoise1 != 0 ? nsignal1 / nnoise1 : 0
nsmooth1 = math.pow(nefratio1 * (nfastend1 - nslowend1) + nslowend1, 2)
nAMA1 := nz(nAMA1[1]) + nsmooth1 * (xPrice1 - nz(nAMA1[1]))
Length2 = input.int(90, title = "kAMA2")
xPrice2 = close
xvnoise2 = math.abs(xPrice2 - xPrice2[1])
nAMA2 = 0.0
nfastend2 = 0.666
nslowend2 = 0.0645
nsignal2 = math.abs(xPrice2 - xPrice2[Length2])
nnoise2 = math.sum(xvnoise2, Length2)
nefratio2 = nnoise2 != 0 ? nsignal2 / nnoise2 : 0
nsmooth2 = math.pow(nefratio2 * (nfastend2 - nslowend2) + nslowend2, 2)
nAMA2 := nz(nAMA2[1]) + nsmooth2 * (xPrice2 - nz(nAMA2[1]))
Length3 = input.int(180, title = "kAMA3")
xPrice3 = close
xvnoise3 = math.abs(xPrice3 - xPrice3[1])
nAMA3 = 0.0
nfastend3 = 0.666
nslowend3 = 0.0645
nsignal3 = math.abs(xPrice3 - xPrice3[Length3])
nnoise3 = math.sum(xvnoise3, Length3)
nefratio3 = nnoise3 != 0 ? nsignal3 / nnoise3 : 0
nsmooth3 = math.pow(nefratio3 * (nfastend3 - nslowend3) + nslowend3, 2)
nAMA3 := nz(nAMA3[1]) + nsmooth3 * (xPrice3 - nz(nAMA3[1]))
plot(ema1,"EMA1",color = color.rgb(50,50,50,0))
plot(ema2,"EMA2",color = color.rgb(55,55,55,0))
plot(ema3,"EMA3",color = color.rgb(60,60,60,0))
plot(sma1,"SMA1",color = color.rgb(65,65,65,0))
plot(sma2,"SMA2",color = color.rgb(70,70,70,0))
plot(sma3,"SMA3",color = color.rgb(75,75,75,0))
plot(hma1,"HMA1",color = color.rgb(80,80,80,0))
plot(hma2,"HMA2",color = color.rgb(85,85,85,0))
plot(hma3,"HMA3",color = color.rgb(90,90,90,0))
plot(rma1,"RMA1",color = color.rgb(95,95,95,0))
plot(rma2,"RMA2",color = color.rgb(100,100,100,0))
plot(rma3,"RMA3",color = color.rgb(110,110,110,0))
plot(wma1,"WMA1",color = color.rgb(120,120,120,0))
plot(wma2,"WMA2",color = color.rgb(130,130,130,0))
plot(wma3,"WMA3",color = color.rgb(140,140,140,0))
plot(nAMA1,"KAMA1",color = color.rgb(150,150,150,0))
plot(nAMA2,"KAMA2",color = color.rgb(160,160,160,0))
plot(nAMA3,"KAMA3",color = color.rgb(170,170,170,0)) |
Portfolio Tracker For Stocks & Crypto | https://www.tradingview.com/script/awMm3eHA-Portfolio-Tracker-For-Stocks-Crypto/ | FriendOfTheTrend | https://www.tradingview.com/u/FriendOfTheTrend/ | 198 | 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/
// © FriendOfTheTrend
//@version=5
indicator("Portfolio Tracker", shorttitle="Portfolio Tracker", overlay=true)
//Tables On/Off
dataTableOn = input.bool(true, title="Info Table On/Off", group="Info Table")
//Table Positions
bright = position.bottom_right
bleft = position.bottom_left
bcenter = position.bottom_center
tright = position.top_right
tleft = position.top_left
tcenter = position.top_center
mright = position.middle_right
mleft = position.middle_left
mcenter = position.middle_center
tablePosition = input.string(tright, title="Info Table Position", options=[bright, bleft, bcenter, tright, tleft, tcenter, mright, mleft, mcenter], group="Info Table")
//Ticker #1
ticker1On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #1")
ticker1 = input.symbol("BATS:AAPL", title="Ticker", group="Portfolio Asset #1")
ticker1OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #1")
ticker1EntryPrice = input.float(135, title="Entry Price", group="Portfolio Asset #1")
ticker1Price = request.security(ticker1, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker1PriceClose = request.security(ticker1, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker1Pnl = ticker1Price > ticker1EntryPrice ? ((ticker1Price - ticker1EntryPrice) / ticker1EntryPrice) : ((ticker1EntryPrice - ticker1Price) / ticker1EntryPrice)
ticker1PnlText = ticker1Price > ticker1EntryPrice ? str.tostring(ticker1Pnl*100, format.percent) : "-" +str.tostring(ticker1Pnl*100, format.percent)
ticker1Value = ticker1Price * ticker1OrderSize
ticker1ValueText = "$" + str.tostring(ticker1Value)
if not ticker1On
ticker1OrderSize := 0.0
ticker1Value := 0.0
//Ticker #2
ticker2On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #2")
ticker2 = input.symbol("BATS:AMZN", title="Ticker", group="Portfolio Asset #2")
ticker2OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #2")
ticker2EntryPrice = input.float(104, title="Entry Price", group="Portfolio Asset #2")
ticker2Price = request.security(ticker2, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker2PriceClose = request.security(ticker2, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker2Pnl = ticker2Price > ticker2EntryPrice ? ((ticker2Price - ticker2EntryPrice) / ticker2EntryPrice) : ((ticker2EntryPrice - ticker2Price) / ticker2EntryPrice)
ticker2PnlText = ticker2Price > ticker2EntryPrice ? str.tostring(ticker2Pnl*100, format.percent) : "-" +str.tostring(ticker2Pnl*100, format.percent)
ticker2Value = ticker2Price * ticker2OrderSize
ticker2ValueText = "$" + str.tostring(ticker2Value)
if not ticker2On
ticker2OrderSize := 0.0
ticker2Value := 0.0
//Ticker #3
ticker3On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #3")
ticker3 = input.symbol("BATS:META", title="Ticker", group="Portfolio Asset #3")
ticker3OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #3")
ticker3EntryPrice = input.float(128, title="Entry Price", group="Portfolio Asset #3")
ticker3Price = request.security(ticker3, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker3PriceClose = request.security(ticker3, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker3Pnl = ticker3Price > ticker3EntryPrice ? ((ticker3Price - ticker3EntryPrice) / ticker3EntryPrice) : ((ticker3EntryPrice - ticker3Price) / ticker3EntryPrice)
ticker3PnlText = ticker3Price > ticker3EntryPrice ? str.tostring(ticker3Pnl*100, format.percent) : "-" +str.tostring(ticker3Pnl*100, format.percent)
ticker3Value = ticker3Price * ticker3OrderSize
ticker3ValueText = "$" + str.tostring(ticker3Value)
if not ticker3On
ticker3OrderSize := 0.0
ticker3Value := 0.0
//Ticker #4
ticker4On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #4")
ticker4 = input.symbol("BATS:TSLA", title="Ticker", group="Portfolio Asset #4")
ticker4OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #4")
ticker4EntryPrice = input.float(212, title="Entry Price", group="Portfolio Asset #4")
ticker4Price = request.security(ticker4, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker4PriceClose = request.security(ticker4, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker4Pnl = ticker4Price > ticker4EntryPrice ? ((ticker4Price - ticker4EntryPrice) / ticker4EntryPrice) : ((ticker4EntryPrice - ticker4Price) / ticker4EntryPrice)
ticker4PnlText = ticker4Price > ticker4EntryPrice ? str.tostring(ticker4Pnl*100, format.percent) : "-" +str.tostring(ticker4Pnl*100, format.percent)
ticker4Value = ticker4Price * ticker4OrderSize
ticker4ValueText = "$" + str.tostring(ticker4Value)
if not ticker4On
ticker4OrderSize := 0.0
ticker4Value := 0.0
//Ticker #5
ticker5On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #5")
ticker5 = input.symbol("BATS:NFLX", title="Ticker", group="Portfolio Asset #5")
ticker5OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #5")
ticker5EntryPrice = input.float(247, title="Entry Price", group="Portfolio Asset #5")
ticker5Price = request.security(ticker5, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker5PriceClose = request.security(ticker5, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker5Pnl = ticker5Price > ticker5EntryPrice ? ((ticker5Price - ticker5EntryPrice) / ticker5EntryPrice) : ((ticker5EntryPrice - ticker5Price) / ticker5EntryPrice)
ticker5PnlText = ticker5Price > ticker5EntryPrice ? str.tostring(ticker5Pnl*100, format.percent) : "-" +str.tostring(ticker5Pnl*100, format.percent)
ticker5Value = ticker5Price * ticker5OrderSize
ticker5ValueText = "$" + str.tostring(ticker5Value)
if not ticker5On
ticker5OrderSize := 0.0
ticker5Value := 0.0
//Ticker #6
ticker6On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #6")
ticker6 = input.symbol("BATS:WMT", title="Ticker", group="Portfolio Asset #6")
ticker6OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #6")
ticker6EntryPrice = input.float(118, title="Entry Price", group="Portfolio Asset #6")
ticker6Price = request.security(ticker6, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker6PriceClose = request.security(ticker6, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker6Pnl = ticker6Price > ticker6EntryPrice ? ((ticker6Price - ticker6EntryPrice) / ticker6EntryPrice) : ((ticker6EntryPrice - ticker6Price) / ticker6EntryPrice)
ticker6PnlText = ticker6Price > ticker6EntryPrice ? str.tostring(ticker6Pnl*100, format.percent) : "-" +str.tostring(ticker6Pnl*100, format.percent)
ticker6Value = ticker6Price * ticker6OrderSize
ticker6ValueText = "$" + str.tostring(ticker6Value)
if not ticker6On
ticker6OrderSize := 0.0
ticker6Value := 0.0
//Ticker #7
ticker7On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #7")
ticker7 = input.symbol("BATS:SPY", title="Ticker", group="Portfolio Asset #7")
ticker7OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #7")
ticker7EntryPrice = input.float(346, title="Entry Price", group="Portfolio Asset #7")
ticker7Price = request.security(ticker7, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker7PriceClose = request.security(ticker7, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker7Pnl = ticker7Price > ticker7EntryPrice ? ((ticker7Price - ticker7EntryPrice) / ticker7EntryPrice) : ((ticker7EntryPrice - ticker7Price) / ticker7EntryPrice)
ticker7PnlText = ticker7Price > ticker7EntryPrice ? str.tostring(ticker7Pnl*100, format.percent) : "-" +str.tostring(ticker7Pnl*100, format.percent)
ticker7Value = ticker7Price * ticker7OrderSize
ticker7ValueText = "$" + str.tostring(ticker7Value)
if not ticker7On
ticker7OrderSize := 0.0
ticker7Value := 0.0
//Ticker #8
ticker8On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #8")
ticker8 = input.symbol("BATS:QQQ", title="Ticker", group="Portfolio Asset #8")
ticker8OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #8")
ticker8EntryPrice = input.float(233, title="Entry Price", group="Portfolio Asset #8")
ticker8Price = request.security(ticker8, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker8PriceClose = request.security(ticker8, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker8Pnl = ticker8Price > ticker8EntryPrice ? ((ticker8Price - ticker8EntryPrice) / ticker8EntryPrice) : ((ticker8EntryPrice - ticker8Price) / ticker8EntryPrice)
ticker8PnlText = ticker8Price > ticker8EntryPrice ? str.tostring(ticker8Pnl*100, format.percent) : "-" +str.tostring(ticker8Pnl*100, format.percent)
ticker8Value = ticker8Price * ticker8OrderSize
ticker8ValueText = "$" + str.tostring(ticker8Value)
if not ticker8On
ticker8OrderSize := 0.0
ticker8Value := 0.0
//Ticker #9
ticker9On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #9")
ticker9 = input.symbol("BATS:AMD", title="Ticker", group="Portfolio Asset #9")
ticker9OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #9")
ticker9EntryPrice = input.float(52, title="Entry Price", group="Portfolio Asset #9")
ticker9Price = request.security(ticker9, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker9PriceClose = request.security(ticker9, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker9Pnl = ticker9Price > ticker9EntryPrice ? ((ticker9Price - ticker9EntryPrice) / ticker9EntryPrice) : ((ticker9EntryPrice - ticker9Price) / ticker9EntryPrice)
ticker9PnlText = ticker9Price > ticker9EntryPrice ? str.tostring(ticker9Pnl*100, format.percent) : "-" +str.tostring(ticker9Pnl*100, format.percent)
ticker9Value = ticker9Price * ticker9OrderSize
ticker9ValueText = "$" + str.tostring(ticker9Value)
if not ticker9On
ticker9OrderSize := 0.0
ticker9Value := 0.0
//Ticker #10
ticker10On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #10")
ticker10 = input.symbol("BATS:NVDA", title="Ticker", group="Portfolio Asset #10")
ticker10OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #10")
ticker10EntryPrice = input.float(134, title="Entry Price", group="Portfolio Asset #10")
ticker10Price = request.security(ticker10, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker10PriceClose = request.security(ticker10, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker10Pnl = ticker10Price > ticker10EntryPrice ? ((ticker10Price - ticker10EntryPrice) / ticker10EntryPrice) : ((ticker10EntryPrice - ticker10Price) / ticker10EntryPrice)
ticker10PnlText = ticker10Price > ticker10EntryPrice ? str.tostring(ticker10Pnl*100, format.percent) : "-" +str.tostring(ticker10Pnl*100, format.percent)
ticker10Value = ticker10Price * ticker10OrderSize
ticker10ValueText = "$" + str.tostring(ticker10Value)
if not ticker10On
ticker10OrderSize := 0.0
ticker10Value := 0.0
//Ticker #11
ticker11On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #11")
ticker11 = input.symbol("BATS:BA", title="Ticker", group="Portfolio Asset #11")
ticker11OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #11")
ticker11EntryPrice = input.float(137, title="Entry Price", group="Portfolio Asset #11")
ticker11Price = request.security(ticker11, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker11PriceClose = request.security(ticker11, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker11Pnl = ticker11Price > ticker11EntryPrice ? ((ticker11Price - ticker11EntryPrice) / ticker11EntryPrice) : ((ticker11EntryPrice - ticker11Price) / ticker11EntryPrice)
ticker11PnlText = ticker11Price > ticker11EntryPrice ? str.tostring(ticker11Pnl*100, format.percent) : "-" +str.tostring(ticker11Pnl*100, format.percent)
ticker11Value = ticker11Price * ticker11OrderSize
ticker11ValueText = "$" + str.tostring(ticker11Value)
if not ticker11On
ticker11OrderSize := 0.0
ticker11Value := 0.0
//Ticker #12
ticker12On = input.bool(true, title="Turn Ticker On/Off", group="Portfolio Asset #12")
ticker12 = input.symbol("BATS:MSFT", title="Ticker", group="Portfolio Asset #12")
ticker12OrderSize = input.float(1, title="# Of Shares/Coins Bought", group="Portfolio Asset #12")
ticker12EntryPrice = input.float(248, title="Entry Price", group="Portfolio Asset #12")
ticker12Price = request.security(ticker12, "", close, barmerge.gaps_off, ignore_invalid_symbol=true)
ticker12PriceClose = request.security(ticker12, "D", close[1], barmerge.gaps_off, ignore_invalid_symbol=true)
ticker12Pnl = ticker12Price > ticker12EntryPrice ? ((ticker12Price - ticker12EntryPrice) / ticker12EntryPrice) : ((ticker12EntryPrice - ticker12Price) / ticker12EntryPrice)
ticker12PnlText = ticker12Price > ticker12EntryPrice ? str.tostring(ticker12Pnl*100, format.percent) : "-" +str.tostring(ticker12Pnl*100, format.percent)
ticker12Value = ticker12Price * ticker12OrderSize
ticker12ValueText = "$" + str.tostring(ticker12Value)
if not ticker12On
ticker12OrderSize := 0.0
ticker12Value := 0.0
//Change Background Color Of Cells For Positive/Negative Percentages
ticker1Color = color.blue
ticker2Color = color.blue
ticker3Color = color.blue
ticker4Color = color.blue
ticker5Color = color.blue
ticker6Color = color.blue
ticker7Color = color.blue
ticker8Color = color.blue
ticker9Color = color.blue
ticker10Color = color.blue
ticker11Color = color.blue
ticker12Color = color.blue
ticker1ValueColor = color.blue
ticker2ValueColor = color.blue
ticker3ValueColor = color.blue
ticker4ValueColor = color.blue
ticker5ValueColor = color.blue
ticker6ValueColor = color.blue
ticker7ValueColor = color.blue
ticker8ValueColor = color.blue
ticker9ValueColor = color.blue
ticker10ValueColor = color.blue
ticker11ValueColor = color.blue
ticker12ValueColor = color.blue
if ticker1Price > ticker1EntryPrice
ticker1Color := color.green
ticker1ValueColor := color.green
else if ticker1Price < ticker1EntryPrice
ticker1Color := color.red
ticker1ValueColor := color.red
if ticker2Price > ticker2EntryPrice
ticker2Color := color.green
ticker2ValueColor := color.green
else if ticker2Price < ticker2EntryPrice
ticker2Color := color.red
ticker2ValueColor := color.red
if ticker3Price > ticker3EntryPrice
ticker3Color := color.green
ticker3ValueColor := color.green
else if ticker3Price < ticker3EntryPrice
ticker3Color := color.red
ticker3ValueColor := color.red
if ticker4Price > ticker4EntryPrice
ticker4Color := color.green
ticker4ValueColor := color.green
else if ticker4Price < ticker4EntryPrice
ticker4Color := color.red
ticker4ValueColor := color.red
if ticker5Price > ticker5EntryPrice
ticker5Color := color.green
ticker5ValueColor := color.green
else if ticker5Price < ticker5EntryPrice
ticker5Color := color.red
ticker5ValueColor := color.red
if ticker6Price > ticker6EntryPrice
ticker6Color := color.green
ticker6ValueColor := color.green
else if ticker6Price < ticker6EntryPrice
ticker6Color := color.red
ticker6ValueColor := color.red
if ticker7Price > ticker7EntryPrice
ticker7Color := color.green
ticker7ValueColor := color.green
else if ticker7Price < ticker7EntryPrice
ticker7Color := color.red
ticker7ValueColor := color.red
if ticker8Price > ticker8EntryPrice
ticker8Color := color.green
ticker8ValueColor := color.green
else if ticker8Price < ticker8EntryPrice
ticker8Color := color.red
ticker8ValueColor := color.red
if ticker9Price > ticker9EntryPrice
ticker9Color := color.green
ticker9ValueColor := color.green
else if ticker9Price < ticker9EntryPrice
ticker9Color := color.red
ticker9ValueColor := color.red
if ticker10Price > ticker10EntryPrice
ticker10Color := color.green
ticker10ValueColor := color.green
else if ticker10Price < ticker10EntryPrice
ticker10Color := color.red
ticker10ValueColor := color.red
if ticker11Price > ticker11EntryPrice
ticker11Color := color.green
ticker11ValueColor := color.green
else if ticker11Price < ticker11EntryPrice
ticker11Color := color.red
ticker11ValueColor := color.red
if ticker12Price > ticker12EntryPrice
ticker12Color := color.green
ticker12ValueColor := color.green
else if ticker12Price < ticker12EntryPrice
ticker12Color := color.red
ticker12ValueColor := color.red
//Calculate Portfolio Percentages
ticker1PortfolioPercent = ticker1Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker2PortfolioPercent = ticker2Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker3PortfolioPercent = ticker3Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker4PortfolioPercent = ticker4Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker5PortfolioPercent = ticker5Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker6PortfolioPercent = ticker6Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker7PortfolioPercent = ticker7Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker8PortfolioPercent = ticker8Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker9PortfolioPercent = ticker9Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker10PortfolioPercent = ticker10Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker11PortfolioPercent = ticker11Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker12PortfolioPercent = ticker12Value / (ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value)
ticker1PortfolioPercentText = str.tostring(ticker1PortfolioPercent*100, format.percent)
ticker2PortfolioPercentText = str.tostring(ticker2PortfolioPercent*100, format.percent)
ticker3PortfolioPercentText = str.tostring(ticker3PortfolioPercent*100, format.percent)
ticker4PortfolioPercentText = str.tostring(ticker4PortfolioPercent*100, format.percent)
ticker5PortfolioPercentText = str.tostring(ticker5PortfolioPercent*100, format.percent)
ticker6PortfolioPercentText = str.tostring(ticker6PortfolioPercent*100, format.percent)
ticker7PortfolioPercentText = str.tostring(ticker7PortfolioPercent*100, format.percent)
ticker8PortfolioPercentText = str.tostring(ticker8PortfolioPercent*100, format.percent)
ticker9PortfolioPercentText = str.tostring(ticker9PortfolioPercent*100, format.percent)
ticker10PortfolioPercentText = str.tostring(ticker10PortfolioPercent*100, format.percent)
ticker11PortfolioPercentText = str.tostring(ticker11PortfolioPercent*100, format.percent)
ticker12PortfolioPercentText = str.tostring(ticker12PortfolioPercent*100, format.percent)
//Today % Gain Calculations
ticker1TodayGain = ticker1Price >= ticker1PriceClose ? ((ticker1Price - ticker1PriceClose) / ticker1PriceClose) * 100 : ((ticker1PriceClose - ticker1Price) / ticker1PriceClose) * -100
ticker1TodayGainText = str.tostring(ticker1TodayGain, "#.##") + "%"
ticker1TodayGainColor = ticker1Price > ticker1PriceClose ? color.green : ticker1Price < ticker1PriceClose ? color.red : color.blue
ticker2TodayGain = ticker2Price >= ticker2PriceClose ? ((ticker2Price - ticker2PriceClose) / ticker2PriceClose) * 100 : ((ticker2PriceClose - ticker2Price) / ticker2PriceClose) * -100
ticker2TodayGainText = str.tostring(ticker2TodayGain, "#.##") + "%"
ticker2TodayGainColor = ticker2Price > ticker2PriceClose ? color.green : ticker2Price < ticker2PriceClose ? color.red : color.blue
ticker3TodayGain = ticker3Price >= ticker3PriceClose ? ((ticker3Price - ticker3PriceClose) / ticker3PriceClose) * 100 : ((ticker3PriceClose - ticker3Price) / ticker3PriceClose) * -100
ticker3TodayGainText = str.tostring(ticker3TodayGain, "#.##") + "%"
ticker3TodayGainColor = ticker3Price > ticker3PriceClose ? color.green : ticker3Price < ticker3PriceClose ? color.red : color.blue
ticker4TodayGain = ticker4Price >= ticker4PriceClose ? ((ticker4Price - ticker4PriceClose) / ticker4PriceClose) * 100 : ((ticker4PriceClose - ticker4Price) / ticker4PriceClose) * -100
ticker4TodayGainText = str.tostring(ticker4TodayGain, "#.##") + "%"
ticker4TodayGainColor = ticker4Price > ticker4PriceClose ? color.green : ticker4Price < ticker4PriceClose ? color.red : color.blue
ticker5TodayGain = ticker5Price >= ticker5PriceClose ? ((ticker5Price - ticker5PriceClose) / ticker5PriceClose) * 100 : ((ticker5PriceClose - ticker5Price) / ticker5PriceClose) * -100
ticker5TodayGainText = str.tostring(ticker5TodayGain, "#.##") + "%"
ticker5TodayGainColor = ticker5Price > ticker5PriceClose ? color.green : ticker5Price < ticker5PriceClose ? color.red : color.blue
ticker6TodayGain = ticker6Price >= ticker6PriceClose ? ((ticker6Price - ticker6PriceClose) / ticker6PriceClose) * 100 : ((ticker6PriceClose - ticker6Price) / ticker6PriceClose) * -100
ticker6TodayGainText = str.tostring(ticker6TodayGain, "#.##") + "%"
ticker6TodayGainColor = ticker6Price > ticker6PriceClose ? color.green : ticker6Price < ticker6PriceClose ? color.red : color.blue
ticker7TodayGain = ticker7Price >= ticker7PriceClose ? ((ticker7Price - ticker7PriceClose) / ticker7PriceClose) * 100 : ((ticker7PriceClose - ticker7Price) / ticker7PriceClose) * -100
ticker7TodayGainText = str.tostring(ticker7TodayGain, "#.##") + "%"
ticker7TodayGainColor = ticker7Price > ticker7PriceClose ? color.green : ticker7Price < ticker7PriceClose ? color.red : color.blue
ticker8TodayGain = ticker8Price >= ticker8PriceClose ? ((ticker8Price - ticker8PriceClose) / ticker8PriceClose) * 100 : ((ticker8PriceClose - ticker8Price) / ticker8PriceClose) * -100
ticker8TodayGainText = str.tostring(ticker8TodayGain, "#.##") + "%"
ticker8TodayGainColor = ticker8Price > ticker8PriceClose ? color.green : ticker8Price < ticker8PriceClose ? color.red : color.blue
ticker9TodayGain = ticker9Price >= ticker9PriceClose ? ((ticker9Price - ticker9PriceClose) / ticker9PriceClose) * 100 : ((ticker9PriceClose - ticker9Price) / ticker9PriceClose) * -100
ticker9TodayGainText = str.tostring(ticker9TodayGain, "#.##") + "%"
ticker9TodayGainColor = ticker9Price > ticker9PriceClose ? color.green : ticker9Price < ticker9PriceClose ? color.red : color.blue
ticker10TodayGain = ticker10Price >= ticker10PriceClose ? ((ticker10Price - ticker10PriceClose) / ticker10PriceClose) * 100 : ((ticker10PriceClose - ticker10Price) / ticker10PriceClose) * -100
ticker10TodayGainText = str.tostring(ticker10TodayGain, "#.##") + "%"
ticker10TodayGainColor = ticker10Price > ticker10PriceClose ? color.green : ticker10Price < ticker10PriceClose ? color.red : color.blue
ticker11TodayGain = ticker11Price >= ticker11PriceClose ? ((ticker11Price - ticker11PriceClose) / ticker11PriceClose) * 100 : ((ticker11PriceClose - ticker11Price) / ticker11PriceClose) * -100
ticker11TodayGainText = str.tostring(ticker11TodayGain, "#.##") + "%"
ticker11TodayGainColor = ticker11Price > ticker11PriceClose ? color.green : ticker11Price < ticker11PriceClose ? color.red : color.blue
ticker12TodayGain = ticker12Price >= ticker12PriceClose ? ((ticker12Price - ticker12PriceClose) / ticker12PriceClose) * 100 : ((ticker12PriceClose - ticker12Price) / ticker12PriceClose) * -100
ticker12TodayGainText = str.tostring(ticker12TodayGain, "#.##") + "%"
ticker12TodayGainColor = ticker12Price > ticker12PriceClose ? color.green : ticker12Price < ticker12PriceClose ? color.red : color.blue
//Overall Portfolio Calculations
startingCapital = (ticker1OrderSize * ticker1EntryPrice) + (ticker2OrderSize * ticker2EntryPrice) + (ticker3OrderSize * ticker3EntryPrice) + (ticker4OrderSize * ticker4EntryPrice) + (ticker5OrderSize * ticker5EntryPrice) + (ticker6OrderSize * ticker6EntryPrice) + (ticker7OrderSize * ticker7EntryPrice) + (ticker8OrderSize * ticker8EntryPrice) + (ticker9OrderSize * ticker9EntryPrice) + (ticker10OrderSize * ticker10EntryPrice) + (ticker11OrderSize * ticker11EntryPrice) + (ticker12OrderSize * ticker12EntryPrice)
startingCapitalText = "$" + str.tostring(startingCapital, "#.##")
currentCapital = ticker1Value + ticker2Value + ticker3Value + ticker4Value + ticker5Value + ticker6Value + ticker7Value + ticker8Value + ticker9Value + ticker10Value + ticker11Value + ticker12Value
currentCapitalText = "$" + str.tostring(currentCapital, "#.##")
currentCapitalColor = currentCapital > startingCapital ? color.green : currentCapital < startingCapital ? color.red : color.blue
overallProfitDollars = currentCapital >= startingCapital ? currentCapital - startingCapital : startingCapital - currentCapital
overallProfitDollarsText = currentCapital >= startingCapital ? "$" + str.tostring(overallProfitDollars, "#.##") : "-$" + str.tostring(overallProfitDollars, "#.##")
overallProfitDollarsColor = currentCapital > startingCapital ? color.green : currentCapital < startingCapital ? color.red : color.blue
overallProfitPercent = currentCapital >= startingCapital ? ((currentCapital - startingCapital) / startingCapital) * 100 : ((startingCapital - currentCapital) / startingCapital) * 100
overallProfitPercentText = currentCapital >= startingCapital ? str.tostring(overallProfitPercent, "#.##") + "%" : "-" + str.tostring(overallProfitPercent, "#.##") + "%"
overallProfitPercentColor = currentCapital > startingCapital ? color.green : currentCapital < startingCapital ? color.red : color.blue
overallGainToday = (((ticker1Price - ticker1PriceClose) * ticker1OrderSize) - (ticker1PriceClose * ticker1OrderSize)) + (((ticker2Price - ticker2PriceClose) * ticker2OrderSize) - (ticker2PriceClose * ticker2OrderSize)) + (((ticker3Price - ticker3PriceClose) * ticker3OrderSize) - (ticker3PriceClose * ticker3OrderSize)) + (((ticker4Price - ticker4PriceClose) * ticker4OrderSize) - (ticker4PriceClose * ticker4OrderSize)) + (((ticker5Price - ticker5PriceClose) * ticker5OrderSize) - (ticker5PriceClose * ticker5OrderSize)) + (((ticker6Price - ticker6PriceClose) * ticker6OrderSize) - (ticker6PriceClose * ticker6OrderSize)) + (((ticker7Price - ticker7PriceClose) * ticker7OrderSize) - (ticker7PriceClose * ticker7OrderSize)) + (((ticker8Price - ticker8PriceClose) * ticker8OrderSize) - (ticker8PriceClose * ticker8OrderSize)) + (((ticker9Price - ticker9PriceClose) * ticker9OrderSize) - (ticker9PriceClose * ticker9OrderSize)) + (((ticker10Price - ticker10PriceClose) * ticker10OrderSize) - (ticker10PriceClose * ticker10OrderSize)) + (((ticker11Price - ticker11PriceClose) * ticker11OrderSize) - (ticker11PriceClose * ticker11OrderSize)) + (((ticker12Price - ticker12PriceClose) * ticker12OrderSize) - (ticker12PriceClose * ticker12OrderSize))
overallValueYesterday = (ticker1PriceClose * ticker1OrderSize) + (ticker2PriceClose * ticker2OrderSize) + (ticker3PriceClose * ticker3OrderSize) + (ticker4PriceClose * ticker4OrderSize) + (ticker5PriceClose * ticker5OrderSize) + (ticker6PriceClose * ticker6OrderSize) + (ticker7PriceClose * ticker7OrderSize) + (ticker8PriceClose * ticker8OrderSize) + (ticker9PriceClose * ticker9OrderSize) + (ticker10PriceClose * ticker10OrderSize) + (ticker11PriceClose * ticker11OrderSize) + (ticker12PriceClose * ticker12OrderSize)
overallProfitTodayNumber = ((currentCapital - overallValueYesterday) / overallValueYesterday) * 100
overallProfitTodayText = str.tostring(overallProfitTodayNumber, "#.##") + "%"
overallProfitTodayColor = overallProfitTodayNumber > 0 ? color.green : overallProfitTodayNumber < 0 ? color.red : color.blue
//Plot Data To Table
dataTable = table.new(tablePosition, columns=5, rows=20, bgcolor=color.blue, frame_color=color.white, frame_width=1, border_color=color.white, border_width=1)
if dataTableOn and barstate.islast
table.cell(table_id=dataTable, column=0, row=0, text="Asset Name", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=3, row=0, text="PnL %", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=2, row=0, text="$ Value", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=1, row=0, text="Weight", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=4, row=0, text="Today", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=0, row=1, text=ticker1On ? ticker1 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=1, text=ticker1On ? ticker1PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker1Color)
table.cell(table_id=dataTable, column=2, row=1, text=ticker1On ? ticker1ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker1ValueColor)
table.cell(table_id=dataTable, column=1, row=1, text=ticker1On ? ticker1PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=1, text=ticker1On ? ticker1TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker1TodayGainColor)
table.cell(table_id=dataTable, column=0, row=2, text=ticker2On ? ticker2 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=2, text=ticker2On ? ticker2PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker2Color)
table.cell(table_id=dataTable, column=2, row=2, text=ticker2On ? ticker2ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker2ValueColor)
table.cell(table_id=dataTable, column=1, row=2, text=ticker2On ? ticker2PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=2, text=ticker2On ? ticker2TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker2TodayGainColor)
table.cell(table_id=dataTable, column=0, row=3, text=ticker3On ? ticker3 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=3, text=ticker3On ? ticker3PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker3Color)
table.cell(table_id=dataTable, column=2, row=3, text=ticker3On ? ticker3ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker3ValueColor)
table.cell(table_id=dataTable, column=1, row=3, text=ticker3On ? ticker3PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=3, text=ticker3On ? ticker3TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker3TodayGainColor)
table.cell(table_id=dataTable, column=0, row=4, text=ticker4On ? ticker4 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=4, text=ticker4On ? ticker4PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker4Color)
table.cell(table_id=dataTable, column=2, row=4, text=ticker4On ? ticker4ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker4ValueColor)
table.cell(table_id=dataTable, column=1, row=4, text=ticker4On ? ticker4PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=4, text=ticker4On ? ticker4TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker4TodayGainColor)
table.cell(table_id=dataTable, column=0, row=5, text=ticker5On ? ticker5 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=5, text=ticker5On ? ticker5PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker5Color)
table.cell(table_id=dataTable, column=2, row=5, text=ticker5On ? ticker5ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker5ValueColor)
table.cell(table_id=dataTable, column=1, row=5, text=ticker5On ? ticker5PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=5, text=ticker5On ? ticker5TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker5TodayGainColor)
table.cell(table_id=dataTable, column=0, row=6, text=ticker6On ? ticker6 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=6, text=ticker6On ? ticker6PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker6Color)
table.cell(table_id=dataTable, column=2, row=6, text=ticker6On ? ticker6ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker6ValueColor)
table.cell(table_id=dataTable, column=1, row=6, text=ticker6On ? ticker6PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=6, text=ticker6On ? ticker6TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker6TodayGainColor)
table.cell(table_id=dataTable, column=0, row=7, text=ticker7On ? ticker7 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=7, text=ticker7On ? ticker7PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker7Color)
table.cell(table_id=dataTable, column=2, row=7, text=ticker7On ? ticker7ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker7ValueColor)
table.cell(table_id=dataTable, column=1, row=7, text=ticker7On ? ticker7PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=7, text=ticker7On ? ticker7TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker7TodayGainColor)
table.cell(table_id=dataTable, column=0, row=8, text=ticker8On ? ticker8 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=8, text=ticker8On ? ticker8PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker8Color)
table.cell(table_id=dataTable, column=2, row=8, text=ticker8On ? ticker8ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker8ValueColor)
table.cell(table_id=dataTable, column=1, row=8, text=ticker8On ? ticker8PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=8, text=ticker8On ? ticker8TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker8TodayGainColor)
table.cell(table_id=dataTable, column=0, row=9, text=ticker9On ? ticker9 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=9, text=ticker9On ? ticker9PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker9Color)
table.cell(table_id=dataTable, column=2, row=9, text=ticker9On ? ticker9ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker9ValueColor)
table.cell(table_id=dataTable, column=1, row=9, text=ticker9On ? ticker9PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=9, text=ticker9On ? ticker9TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker9TodayGainColor)
table.cell(table_id=dataTable, column=0, row=10, text=ticker10On ? ticker10 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=10, text=ticker10On ? ticker10PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker10Color)
table.cell(table_id=dataTable, column=2, row=10, text=ticker10On ? ticker10ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker10ValueColor)
table.cell(table_id=dataTable, column=1, row=10, text=ticker10On ? ticker10PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=10, text=ticker10On ? ticker10TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker10TodayGainColor)
table.cell(table_id=dataTable, column=0, row=11, text=ticker11On ? ticker11 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=11, text=ticker11On ? ticker11PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker11Color)
table.cell(table_id=dataTable, column=2, row=11, text=ticker11On ? ticker11ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker11ValueColor)
table.cell(table_id=dataTable, column=1, row=11, text=ticker11On ? ticker11PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=11, text=ticker11On ? ticker11TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker11TodayGainColor)
table.cell(table_id=dataTable, column=0, row=12, text=ticker12On ? ticker12 : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=3, row=12, text=ticker12On ? ticker12PnlText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker12Color)
table.cell(table_id=dataTable, column=2, row=12, text=ticker12On ? ticker12ValueText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker12ValueColor)
table.cell(table_id=dataTable, column=1, row=12, text=ticker12On ? ticker12PortfolioPercentText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=4, row=12, text=ticker12On ? ticker12TodayGainText : na, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=ticker12TodayGainColor)
table.cell(table_id=dataTable, column=0, row=13, text="Total Cost", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=0, row=14, text=startingCapitalText, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center)
table.cell(table_id=dataTable, column=1, row=13, text="Value", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=1, row=14, text=currentCapitalText, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=currentCapitalColor)
table.cell(table_id=dataTable, column=2, row=13, text="PnL $", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=2, row=14, text=overallProfitDollarsText, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=overallProfitDollarsColor)
table.cell(table_id=dataTable, column=3, row=13, text="PnL %", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=3, row=14, text=overallProfitPercentText, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=overallProfitPercentColor)
table.cell(table_id=dataTable, column=4, row=13, text="Today", height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.navy)
table.cell(table_id=dataTable, column=4, row=14, text=overallProfitTodayText, height=0, text_color=color.white, text_halign=text.align_left, text_valign=text.align_center, bgcolor=overallProfitTodayColor) |
Limited MACD | https://www.tradingview.com/script/i4SySiwl/ | faytterro | https://www.tradingview.com/u/faytterro/ | 160 | 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("Limited MACD", timeframe = "", timeframe_gaps = false, max_bars_back = 500)
src=input(close, title="source")
len=math.min(bar_index+1,200)//input.int(200, title="sensitivity lenght")
lenshortema=input.int(12,title="short ema lenght")
lenlongema=input.int(26, title="long ema lenght")
lensignal=input.int(9, title="signal lenght")
macd=ta.ema(src,lenshortema)-ta.ema(src,lenlongema)
macd:= 100*ta.ema(src,lenshortema)/ta.ema(src,lenlongema)-100
signal = ta.ema(macd,lensignal)
y = math.abs(macd)
n = bar_index
m = n<lenlongema? 1 : math.min(n-lenlongema+1,500)
t = ta.wma(y,m)//ta.cum(y)/n
f = 100-200/(math.pow(1+1/(t*1),macd)+1)
plot(f, color= #2962ff)
y2 = math.abs(signal)
t2 = ta.wma(y,m)//ta.cum(y)/n
f2 = 100-200/(math.pow(1+1/(t*1),signal)+1)
plot(f2, color=color.orange)
buy=ta.crossover(f,-50) or ta.crossover(f,50)
sell=ta.crossunder(f,50) or ta.crossunder(f,-50)
hline(50)
hline(-50)
bgcolor(color= buy? color.green : sell? color.red : na)
z=(f2/2+50)*2.55
barcolor(color=color.rgb(math.min(255+255-z*2,255),z, 0), display = display.none)
alertcondition(buy or sell)
col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
hline(0, "Zero Line", color=color.new(#787B86, 50))
hist = f-f2
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below))) |
Swing Oscillator [AstrideUnicorn] | https://www.tradingview.com/script/i4F21wvI-Swing-Oscillator-AstrideUnicorn/ | AstrideUnicorn | https://www.tradingview.com/u/AstrideUnicorn/ | 135 | 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/
// © AstrideUnicorn
//@version=5
indicator("Swing Oscillator [AstrideUnicorn]", overlay=false)
LENGTH = input(7, title="Period")
bar_range = close-open
bar_range_ema = ta.ema(bar_range, LENGTH)
treshold= ta.ema(math.abs(bar_range_ema),10*LENGTH)
conditional_color = (bar_range_ema > treshold)?color.green:(bar_range_ema > 0.5*treshold)?
color.new(color.green,55):(bar_range_ema < -treshold)?color.red:(bar_range_ema < -0.5*treshold)?
color.new(color.red,55):color.blue
average_return = plot(bar_range_ema,color=conditional_color)
zero_line = plot(0,color = conditional_color)
fill(average_return,zero_line, color = conditional_color)
plot(treshold, color=color.purple)
plot(-treshold, color=color.purple)
plot(0.5*treshold, color=color.purple)
plot(-0.5*treshold, color=color.purple)
|
Macro Directional Index | https://www.tradingview.com/script/tSBJg6pQ-Macro-Directional-Index/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 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/
// © jordanfray
//@version=5
// About This Indicator
// The default settings for this indicator are for BTC/USDT and intended to be used on the 3D timeframe to identify market trends.
// This indicator does a great job identifying whether the market is bullish, bearish, or consolidating.
// This can also work well on lower time frames to help identify when a trend is strong or when it's reversing.
indicator("Simplified Macro Directional Index", shorttitle="Macro Directional Index")
import jordanfray/threengine_global_automation_library/89 as bot
// Colors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
green = color.new(#2DBD85,0)
lightGreen = color.new(#2DBD85,70)
red = color.new(#E02A4A,0)
lightRed = color.new(#E02A4A,70)
purple = color.new(#5A00FF,0)
black = color.new(#000000,0)
lightBlack = color.new(#000000,90)
// Tooltips
diDistanceRocLengthTip = "Core to this indicator is the rate at which DI+ and DI- are moving away or towards each other. This is called The Rate of Change (ROC)." + "\n \n"
+ "The ROC length dictates how many bars back you want to compare to the current bar to see how much it has changed." + "\n \n"
+ "It is calculated like this:" + "\n"
+ "(source - source[length]/source[length]) * 100" + "\n \n"
+ "This indicator has 4 values in the status line: " + "\n"
+ " 1: DI+" + "\n"
+ " 2: DI-" + "\n"
+ " 3: Distance between DI+ and DI-" + "\n"
+ " 4: DI Rate of Change" + "\n \n"
+ "Default: 1"
diDistanceRocEmaLengthTip = "The rate of change is smoothed using an EMA. A shorter EMA length will cause the ROC to flip back and forth between positive and negative while a larger EMA length will cause the ROC to change less often." + "\n \n"
+ "Since the rate of change is used to indicate periods of 'consolidation', you want to find a setting that doesn't flip back and forth too often." + "\n \n"
+ "Default: 5"
diMidlineChannelWidthTip = "Between the DI+ and DI- is a black centerline. Offset from this centerline is a channel that is used to filter out false crosses of the DI+ and DI-. "
+ "Sometimes, the DI+ and DI- lines will come together in this channel and cross momentarily before resuming the direction prior to the cross. "
+ "When this happens, you don't want to flip your bias too soon. The wider the channel, the later the indicator will signal a DI reversal. A narrower channel will call it sooner but risks being more choppy and indicating a false cross." + "\n \n"
+ "Default: 5"
// Indicator Settings
diLength = input.int(defval=23, minval=1, step=1, title="DI Length", group="Directional Index (DI)")
diDistanceRocLength = input.int(defval=1, title="DI Distance ROC Length", group="Directional Index (DI)", tooltip=diDistanceRocLengthTip)
diDistanceRocEmaLength = input.int(defval=5, title="DI Distance ROC Smoothing", group="Directional Index (DI)", tooltip=diDistanceRocEmaLengthTip)
diMidlineChannelWidth = input.float(defval=12, title="DI Midline Channel Width (%)", group="Directional Index (DI)", tooltip=diMidlineChannelWidthTip)
// Directional Index
TrueRange = math.max(math.max(high-low, math.abs(high-nz(close[1]))), math.abs(low-nz(close[1])))
DMPlus = high-nz(high[1]) > nz(low[1])-low ? math.max(high-nz(high[1]), 0): 0
DMMinus = nz(low[1])-low > high-nz(high[1]) ? math.max(nz(low[1])-low, 0): 0
SmoothedTR = 0.0
SmoothedTR := nz(SmoothedTR[1]) - (nz(SmoothedTR[1])/diLength) + TrueRange
SmoothedDMPlus = 0.0
SmoothedDMPlus := nz(SmoothedDMPlus[1]) - (nz(SmoothedDMPlus[1])/diLength) + DMPlus
SmoothedDMMinus = 0.0
SmoothedDMMinus := nz(SmoothedDMMinus[1]) - (nz(SmoothedDMMinus[1])/diLength) + DMMinus
diPlus = SmoothedDMPlus / SmoothedTR * 100
diMinus = SmoothedDMMinus / SmoothedTR * 100
distanceBetweenDi = (diPlus - diMinus) < 0 ? (diPlus - diMinus)*-1 : (diPlus - diMinus)
distanceBetweenDiRoc = bot.getRateOfChange(distanceBetweenDi, diDistanceRocLength)
distanceBetweenDiRocEma = bot.taGetEma("EMA", distanceBetweenDiRoc, diDistanceRocEmaLength)
diCenterLine = (diPlus + diMinus)/2
diCenterLineChannelTop = diCenterLine + (diCenterLine*(diMidlineChannelWidth/100))
diCenterLineChannelBottom = diCenterLine - (diCenterLine*(diMidlineChannelWidth/100))
bool diDistanceRocEmaTrendingDown = distanceBetweenDiRocEma < 0
bool diPlusAboveDiMinus = diPlus > diMinus
bool diPlusAboveCenterChannel = diPlus > diCenterLineChannelTop
bool diMinusAboveDiPlus = diMinus > diPlus
bool diMinusAboveCenterChannel = diMinus > diCenterLineChannelTop
bool bullMarket = diPlusAboveDiMinus
bool bearMarket = diMinusAboveDiPlus
bool bullishConsolidation = diPlusAboveDiMinus and diPlusAboveCenterChannel and diDistanceRocEmaTrendingDown
bool bearishConsolidation = diMinusAboveDiPlus and diPlusAboveCenterChannel and diDistanceRocEmaTrendingDown
var string macroMarketStatus = na
if diPlusAboveDiMinus and diPlusAboveCenterChannel
macroMarketStatus := "bullish"
else
if diMinusAboveDiPlus and diMinusAboveCenterChannel
macroMarketStatus := "bearish"
// Plots
diPlusPlot = plot(series=diPlus, title="DI+", color=green, linewidth=2, editable=false, display=display.pane + display.status_line)
diMinusPlot = plot(series=diMinus, title="DI-", color=red, linewidth=2, editable=false, display=display.pane + display.status_line)
diDistancePlot = plot(series=distanceBetweenDi, title="Distance Between DI", color=purple, editable=false, display=display.status_line)
diDistanceRocPlot = plot(series=distanceBetweenDiRocEma, title="DI Distance Rate of Change", color=purple, editable=false, display=display.status_line)
diCenterLineChannelTopPlot = plot(series=diCenterLineChannelTop, title="DI Center Channel Top", color=black, editable=false, display=display.none)
diCenterLinePlot = plot(series=diCenterLine, title="DI Center Line", color=black, editable=false, linewidth=2, display=display.pane)
diCenterLineChannelBottomPlot = plot(series=diCenterLineChannelBottom, title="DI Center Channel Bottom", color=black, editable=false, display=display.none)
bgcolor(macroMarketStatus == "bullish" ? lightGreen : lightRed, editable = false, title = "Background Colors (Market Status)")
fill(diCenterLineChannelTopPlot, diCenterLineChannelBottomPlot, editable = false, title = "DI Center Channel", color = lightBlack)
// Alert Conditions
alertcondition(condition = diPlusAboveDiMinus and diPlusAboveCenterChannel, title = "Macro DI - Long", message = "Directional Index Plus crossed above the center channel.")
alertcondition(condition = diMinusAboveDiPlus and diMinusAboveCenterChannel, title = "Macro DI - Short", message = "Directional Index Minus crossed above the center channel.") |
Signs of the Times [LucF] | https://www.tradingview.com/script/ZKF0qji2-Signs-of-the-Times-LucF/ | LucF | https://www.tradingview.com/u/LucF/ | 611 | 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/
// © LucF
//@version=5
indicator("Signs of the Times [LucF]", "SOTT", timeframe = "", timeframe_gaps = false, precision = 2)
// Signs of the Times [LucF]
// v2, 2022.11.06 12:54 — LucF
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import LucF/ta/2 as LucfTa
//#region ———————————————————— Constants and inputs
// Key levels
float LEVEL_MID = 0.0
float LEVEL_HI = 0.3
float LEVEL_LO = -0.3
// Colors
color BLUE = #3179f5
color BLUE_DK = #013bca
color GRAY = #434651
color GRAY_LT = #9598a1
color GREEN = #006200
color LIME = #3CEB14
color MAROON = #800000
color ORANGE = #e65100
color PINK = #FF0080
color PURPLE = #C314EB
color YELLOW = #fbc02d
// MAs
string MA01 = "Simple MA"
string MA02 = "Exponential MA"
string MA03 = "Wilder MA"
string MA04 = "Weighted MA"
string MA05 = "Volume-weighted MA"
string MA06 = "Arnaud Legoux MA"
string MA07 = "Hull MA"
string MA08 = "Symmetrically-weighted MA"
// Bar coloring modes
string CB1 = "SOTT MA"
string CB2 = "MA of MA"
string CB3 = "Channel fill"
string CB4 = "MA fill"
// Tooltips
string TT_SIGNAL = "You specify here the type and length of the MA you want applied to the instant SOTT value.
You can view the instant value by using a length of 1.
\n\nNOTE: The length of this MA must be smaller than that of the second MA defined below.
\n\n'🡑' and '🡓' indicate bull/bear conditions, which occur when the line is above/below the centerline."
string TT_MA = "You specify here the type and length of the MA you want applied to the MA of SOTT defined above, so this is an MA of an MA.
\n\n'🡑' and '🡓' indicate bull/bear conditions, which occur when the line is above/below the centerline."
string TT_CHANNEL = "'🡑' and '🡓' indicate bull/bear conditions, which occur when the first MA is above/below the second MA while not also being above/below the centerline.
\n\n'🡑🡑' and '🡓🡓' indicate strong bull/bear conditions, which require the first MA to be above/below the second MA, and above/below the centerline."
string TT_MAFILL = "'🡑' and '🡓' indicate bull/bear conditions, which occur when the second MA is above/below the centerline."
// Inputs
bool signalShowInput = input.bool(true, "SOTT MA", inline = "signal")
color signalUpColorInput = input.color(GREEN, " 🡑", inline = "signal")
color signalDnColorInput = input.color(MAROON, "🡓", inline = "signal")
string signalTypeInput = input.string(MA06, "", inline = "signal", options = [MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08])
int signalLengthInput = input.int(20, "Length", inline = "signal", minval = 1, tooltip = TT_SIGNAL)
bool maShowInput = input.bool(false, "MA of MA", inline = "ma")
color maUpColorInput = input.color(YELLOW, " 🡑", inline = "ma")
color maDnColorInput = input.color(BLUE_DK, "🡓", inline = "ma")
string maTypeInput = input.string(MA01, "", inline = "ma", options = [MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08])
int maLengthInput = input.int(20, "Length", inline = "ma", minval = 2, tooltip = TT_MA)
bool channelShowInput = input.bool(true, "Channel", inline = "channel")
color channelUpColorInput = input.color(GREEN, " 🡑", inline = "channel")
color channelDnColorInput = input.color(MAROON, "🡓", inline = "channel")
color channelUpUpColorInput = input.color(LIME, "🡑🡑", inline = "channel")
color channelDnDnColorInput = input.color(PURPLE, "🡓🡓", inline = "channel", tooltip = TT_CHANNEL)
bool maFillShowInput = input.bool(true, "MA fill", inline = "maFill")
color maFillUpColorInput = input.color(YELLOW, " 🡑", inline = "maFill")
color maFillDnColorInput = input.color(BLUE, "🡓", inline = "maFill", tooltip = TT_MAFILL)
bool colorBarsInput = input.bool(false, "Color chart bars using the color of", inline = "bars")
string colorBarsModeInput = input.string(CB3, "", inline = "bars", options = [CB1, CB2, CB3, CB4])
//#endregion
//#region ———————————————————— Calculations
// Validate MA lengths.
if signalLengthInput > maLengthInput
runtime.error("The length of the SOTT MA must be less than or equal to that of the second MA.")
// Instant SOTT
float sott = LucfTa.sott()
// MAs
float signal = LucfTa.ma(signalTypeInput, sott, signalLengthInput)
float ma = LucfTa.ma(maTypeInput, signal, maLengthInput)
// States
bool maIsBull = ma > LEVEL_MID
bool signalIsBull = signal > LEVEL_MID
bool channelIsBull = signal > ma
//#endregion
//#region ———————————————————— Plots
// Plotting colors
color channelColor = channelIsBull ? signalIsBull ? channelUpUpColorInput : channelUpColorInput : signalIsBull ? channelDnColorInput : channelDnDnColorInput
color signalColor = signalIsBull ? signalUpColorInput : signalDnColorInput
color maColor = maIsBull ? maUpColorInput : maDnColorInput
color maChannelTopColor = maIsBull ? maFillUpColorInput : color.new(maFillDnColorInput, 95)
color maChannelBotColor = maIsBull ? color.new(maFillUpColorInput, 95) : maFillDnColorInput
// Plots
signalPlot = plot(signalShowInput or channelShowInput ? signal : na, "SOTT MA", signalShowInput ? signalColor : na, 2)
maPlot = plot(ma, "MA of MA", maShowInput ? maColor : na)
zeroPlot = plot(LEVEL_MID, "Phantom Mid Level", display = display.none)
// Fill the MA channel (the space between the middle level and the MA).
fill(maPlot, zeroPlot, not maFillShowInput ? na : maIsBull ? LEVEL_HI * 0.7 : LEVEL_MID, maIsBull ? LEVEL_MID : LEVEL_LO * 0.7, maChannelTopColor, maChannelBotColor)
// Fill the signal channel (between the two MAs).
fill(maPlot, signalPlot, ma, not channelShowInput ? na : signal, color.new(channelColor, 70), channelColor)
// Levels
hline(LEVEL_HI, "High level", signalUpColorInput, hline.style_dotted)
hline(LEVEL_MID, "Mid level", color.gray, hline.style_dotted)
hline(LEVEL_LO, "Low level", signalDnColorInput, hline.style_dotted)
// Instant SOTT for Data Window.
plot(sott, "Instant SOTT", display = display.data_window)
// Color bars
color barColor =
switch colorBarsModeInput
CB1 => signalColor
CB2 => maColor
CB3 => channelColor
CB4 => maIsBull ? maFillUpColorInput : maFillDnColorInput
=> na
barcolor(colorBarsInput ? barColor : na)
//#endregion
|
Dashboard With Strength Trend & Phase Market | https://www.tradingview.com/script/TflARuxc/ | salahbelidong | https://www.tradingview.com/u/salahbelidong/ | 270 | 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/
// © salahbelidong
//-------------Original--------------
// autor original : @KP_House, @JustInNovel, @jdehorty
// Remake @salahbelidong
//@version=5
indicator("Dashboard", overlay=true, scale=scale.none, max_lines_count=500)
//Start dashboard
import jdehorty/EconomicCalendar/1 as calendar
// ---- Table Settings Start ----//
max = 160 //Maximum Length
min = 10 //Minimum Length
// Input setting page start
dash_loc = input.session("Bottom Right","Dashboard Posision" ,["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"], group='Style Settings')
text_size = input.session('Small',"Dashboard Size" ,options=["Tiny","Small","Normal","Large"] ,group='Style Settings')
cell_up = input.color(color.green,'Up Cell Color' ,group='Style Settings')
cell_dn = input.color(color.red,'Down Cell Color' ,group='Style Settings')
cell_Neut = input.color(color.gray,'Nochange Cell Color' ,group='Style Settings')
row_col = color.blue
col_col = color.white
txt_col = color.white
cell_transp = input.int(60,'Cell Transparency' ,minval=0 ,maxval=100 ,group='Style Settings')
Header_col = color.rgb(35, 94, 255)
//MACDV color
cell_MACDV1 = input.color(color.teal,'Continue/Reversal ', group='MACD COLOR')
cell_MACDV2 = input.color(color.green,'Buy G0 ', group='MACD COLOR')
cell_MACDV3 = input.color(color.red,'Buy Retest ', group='MACD COLOR')
cell_MACDV4 = input.color(color.rgb(194, 179, 47),'Sideway ', group='MACD COLOR')
cell_MACDV5 = input.color(color.green,'Short go', group='MACD COLOR')
cell_MACDV6 = input.color(color.red,'Short Retest ' , group='MACD COLOR')
cell_MACDV7 = input.color(color.rgb(204, 8, 24),'Wait Continue/Reversal ', group='MACD COLOR')
//Momentum color
cell_phase1 = input.color(color.green,'Phase1:Accumulation', group='Momentum')
cell_phase2 = input.color(color.teal,'Phase2:Runing' , group='Momentum')
cell_phase3 = input.color(color.red,'Phase3:Re-Accumulation' , group='Momentum')
cell_phase4 = input.color(color.red,'Phase4:Distribution' , group='Momentum')
cell_phase5 = input.color(color.orange,'Phase5:Bearish' , group='Momentum')
cell_phase6 = input.color(color.green,'Phase6:Rev/Continue' , group='Momentum')
// ---- Table Settings End ----}//
// ---- Indicators Show/Hide Settings Start ----//
showCls = input.bool(defval=true, title="Show Price Close", group="Colum On/Off")
showMA01 = input.bool(defval=true, title="Show MA01", group="Colum On/Off")
showMA02 = input.bool(defval=true, title="Show MA02", group="Colum On/Off")
showMACross = input.bool(defval=true, title="Show Trend", group="Colum On/Off")
showRSI = input.bool(defval=true, title="Show RSI ", group="Colum On/Off")
showMACDV = input.bool(defval=true, title="Show MACDV", group="Colum On/Off")
showSignalV = input.bool(defval=true, title="Show SignalV", group="Colum On/Off")
showMACDV_Status = input.bool(defval=true, title="Show Condition", group="Colum On/Off")
showmomentum = input.bool(defval=true, title="Show Momentum", group="Colum On/Off")
//---- MACD-V code start ----//
MACD_fast_length = input(title="MACD-V Fast", defval=14, group="MACD-V Settings")
MACD_slow_length = input(title="MACD-V Slow", defval=26, group="MACD-V Settings")
MACD_signal_length = input.int(title="MACD-V Signal ", minval = 1, maxval = 50, defval = 9, group="MACD-V Settings")
MACD_atr_length = input(title="ATR", defval=26, group="MACD-V Settings")
// ---- Indicators Show/Hide Settings end ----}//
// ==================
// ==== Settings ====
// ==================
//------Seting Color Calender Economi------
color1 = color.red
color2 = color.orange
color3 = color.yellow
color4 = color.lime
color5 = color.aqua
color6 = color.fuchsia
color7 = color.silver
show_fomc_meetings = input.bool(defval = false, title = "📅 FOMC", inline = "FOMC", group="⚙️ Settings", tooltip="The FOMC meets eight times a year to determine the course of monetary policy. The FOMC's decisions are announced in a press release at 2:15 p.m. ET on the day of the meeting. The press release is followed by a press conference at 2:30 p.m. ET. The FOMC's decisions are based on a review of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
c_fomcMeeting = input.color(color.new(color1, 50), title = "Color", group="⚙️ Settings", inline = "FOMC")
show_fomc_minutes = input.bool(defval = false, title = "📅 FOMC Minutes", inline = "FOMCMinutes", group="⚙️ Settings", tooltip="The FOMC minutes are released three weeks after each FOMC meeting. The minutes provide a detailed account of the FOMC's discussion of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
c_fomcMinutes = input.color(color.new(color2, 50), title = "Color", group="⚙️ Settings", inline = "FOMCMinutes")
show_ppi = input.bool(defval = false, title = "📅 Producer Price Index (PPI)", inline = "PPI", group="⚙️ Settings", tooltip="The Producer Price Index (PPI) measures changes in the price level of goods and services sold by domestic producers. The PPI is a weighted average of prices of a basket of goods and services, such as transportation, food, and medical care. The PPI is a leading indicator of CPI.")
c_ppi = input.color(color.new(color3, 50), title = "Color", group="⚙️ Settings", inline = "PPI")
show_cpi = input.bool(defval = false, title = "📅 Consumer Price Index (CPI)", inline = "CPI", group="⚙️ Settings", tooltip="The Consumer Price Index (CPI) measures changes in the price level of goods and services purchased by households. The CPI is a weighted average of prices of a basket of consumer goods and services, such as transportation, food, and medical care. The CPI-U is the most widely used measure of inflation. The CPI-U is based on a sample of about 87,000 households and measures the change in the cost of a fixed market basket of goods and services purchased by urban consumers.")
c_cpi = input.color(color.new(color4, 50), title = "Color", group="⚙️ Settings", inline = "CPI")
show_csi = input.bool(defval = false, title = "📅 Consumer Sentiment Index (CSI)", inline = "CSI", group="⚙️ Settings", tooltip="The University of Michigan's Consumer Sentiment Index (CSI) is a measure of consumer attitudes about the economy. The CSI is based on a monthly survey of 500 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CSI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_csi = input.color(color.new(color5, 50), title = "Color", group="⚙️ Settings", inline = "CSI")
show_cci = input.bool(defval = false, title = "📅 Consumer Confidence Index (CCI)", inline = "CCI", group="⚙️ Settings", tooltip="The Conference Board's Consumer Confidence Index (CCI) is a measure of consumer attitudes about the economy. The CCI is based on a monthly survey of 5,000 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CCI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_cci = input.color(color.new(color6, 50), title = "Color", group="⚙️ Settings", inline = "CCI")
show_nfp = input.bool(defval = false, title = "📅 Non-Farm Payroll (NFP)", inline = "NFP", group="⚙️ Settings", tooltip="The Non-Farm Payroll (NFP) is a measure of the change in the number of employed persons, excluding farm workers and government employees. The NFP is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_nfp = input.color(color.new(color7, 50), title = "Color", group="⚙️ Settings", inline = "NFP")
show_legend = input.bool(true, "Show Legend", group="⚙️ Settings", inline = "Legend", tooltip="Show the color legend for the economic calendar events.")
// =======================
// ==== Dates & Times ====
// =======================
getUnixTime(_eventArr, _index) =>
switch
timeframe.isdaily => array.get(_eventArr, _index) - timeframe.multiplier*86400000 // -n day(s)
timeframe.isweekly => array.get(_eventArr, _index) - timeframe.multiplier*604800000 // -n week(s)
timeframe.ismonthly => array.get(_eventArr, _index) - timeframe.multiplier*2592000000 // -n month(s)
timeframe.isminutes and timeframe.multiplier > 59 => array.get(_eventArr, _index) - timeframe.multiplier*60000 // -n minute(s)
=> array.get(_eventArr, _index)
if barstate.islastconfirmedhistory
// Note: An offset of -n units is needed to realign events with the timeframe in which they occurred
if show_fomc_meetings
fomcMeetingsArr = calendar.fomcMeetings()
for i = 0 to array.size(fomcMeetingsArr) - 1
unixTime = getUnixTime(fomcMeetingsArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMeeting, width=2, xloc=xloc.bar_time)
if show_fomc_minutes
fomcMinutesArr = calendar.fomcMinutes()
for i = 0 to array.size(fomcMinutesArr) - 1
unixTime = getUnixTime(fomcMinutesArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMinutes, width=2, xloc=xloc.bar_time)
if show_ppi
ppiArr = calendar.ppiReleases()
for i = 0 to array.size(ppiArr) - 1
unixTime = getUnixTime(ppiArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_ppi, width=2, xloc=xloc.bar_time)
if show_cpi
cpiArr = calendar.cpiReleases()
for i = 0 to array.size(cpiArr) - 1
unixTime = getUnixTime(cpiArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cpi, width=2, xloc=xloc.bar_time)
if show_csi
csiArr = calendar.csiReleases()
for i = 0 to array.size(csiArr) - 1
unixTime = getUnixTime(csiArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_csi, width=2, xloc=xloc.bar_time)
if show_cci
cciArr = calendar.cciReleases()
for i = 0 to array.size(cciArr) - 1
unixTime = getUnixTime(cciArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cci, width=2, xloc=xloc.bar_time)
if show_nfp
nfpArr = calendar.nfpReleases()
for i = 0 to array.size(nfpArr) - 1
unixTime = getUnixTime(nfpArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_nfp, width=2, xloc=xloc.bar_time)
// ================
// ==== Legend ====
// ================
if show_legend
var tbl = table.new(position.top_right, columns=8, rows=8, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.black, 100))
units = timeframe.isminutes ? "m" : ""
table.cell(tbl, 1, 0, syminfo.ticker + ' => ' + str.tostring(timeframe.period)+ units, text_halign=text.align_center, text_color=color.gray, text_size=size.small)
table.cell(tbl, 2, 0, 'FOMC Meeting', text_halign=text.align_center, bgcolor=color.black, text_color=color1, text_size=size.small)
table.cell(tbl, 3, 0, 'FOMC Minutes', text_halign=text.align_center, bgcolor=color.black, text_color=color2, text_size=size.small)
table.cell(tbl, 4, 0, 'Producer Price Index (PPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color3, text_size=size.small)
table.cell(tbl, 1, 1, 'Consumer Price Index (CPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color4, text_size=size.small)
table.cell(tbl, 2, 1, 'Consumer Sentiment Index (CSI)', text_halign=text.align_center, bgcolor=color.black, text_color=color5, text_size=size.small)
table.cell(tbl, 3, 1, 'Consumer Confidence Index (CCI)', text_halign=text.align_center, bgcolor=color.black, text_color=color6, text_size=size.small)
table.cell(tbl, 4, 1, 'Non-Farm Payrolls (NFP)', text_halign=text.align_center, bgcolor=color.black, text_color=color7, text_size=size.small)
// =======================
// ==== CE And ===========
// =======================
// ---- Timeframe Row Show/Hide Settings Start ----//
showTF1 = input.bool(defval=true, title="Show TF MN", inline='indicator1',group="Rows Settings")
f_MACDV(_close) =>
//---- Indicators code Start ----//
CLS= _close[1]
//---- RSI code start ----//
rsiPeriod = 14
RSI = ta.rsi(_close, rsiPeriod)
//---- RSI code end ----//
//---- EMA 1 code start----//
length_MA1 = input.int(title="MA1",defval=50, minval=1)
MA1 = ta.ema(_close, length_MA1)
//plot(MA01, color=color.red, title="MA1")
//---- EMA 1 code end ----//
//---- EMA 2 code start---//
length_MA2 = input.int(title="MA2",defval=200, minval=1)
MA2 = ta.ema(_close, length_MA2)
//plot(MA02, color=color.blue, title="MA2")
//---- EMA 2 code end ----//
// Input seeting page end
// Calculating
fast_ma = ta.ema(_close, MACD_fast_length)
slow_ma = ta.ema(_close, MACD_slow_length)
atr = ta.atr(MACD_atr_length)
MACDV = (((fast_ma - slow_ma)/atr)*100)//[( 12 bar EMA - 26 bar EMA) / ATR(26) ] * 100
SignalV = ta.ema(MACDV, MACD_signal_length)
//---- MACD-V code end ----//
//---- Indicators code end ----//
//-----Condition start
stringmacdv =(MACDV>150) ? "Wait Continue/Reversal" :(MACDV>50 and MACDV<150 and MACDV>SignalV ) ? "Buy G0" :(MACDV>50 and MACDV<150 and MACDV<SignalV ) ? "Buy Retest":(MACDV<50) and (MACDV>-50) ? "Sideway" :(MACDV<-50 and MACDV>-150 and MACDV>SignalV ) ? "Short go":(MACDV<-50 and MACDV>-150 and MACDV<SignalV ) ? "Short Retest":(MACDV<150) ? "Wait Continue/Reversal" :na
//momentum
stringmomentum =(CLS>MA1 and CLS>MA2 and MA1<MA2) ? "Accumulation:Stop Sell - Setup Buy" :(CLS>MA1 and CLS>MA2 and MA1>MA2) ? "Runing Up: Buy Runing":(CLS<MA1 and CLS>MA2 and MA1>MA2) ? "Re-Acumulasi: Continue Up":(CLS<MA1 and CLS<MA2 and MA1>MA2) ? "Distribution: Stop Buy-Setup Short":(CLS<MA1 and CLS<MA2 and MA1<MA2) ? "Re-Distribusi: Continue Down":(CLS>MA1 and CLS<MA2 and MA1<MA2) ? "Accumulation-Distribusi: Don't Trade Wait Break":na
//-----Condition end
// Return values
[CLS, MA1, MA2, RSI, MACDV, SignalV, stringmacdv, stringmomentum]
// ] -------- Alerts ----------------- [
//---- Table Position & Size code start {----//
var table_position = dash_loc == 'Bottom Right' ? position.bottom_right :
dash_loc == 'Bottom Left' ? position.bottom_left :
dash_loc == 'Middle Right' ? position.middle_right :
dash_loc == 'Bottom Center' ? position.bottom_center :
dash_loc == 'Top Left' ? position.top_right : position.bottom_right
var table_text_size = text_size == 'Normal' ? size.normal :
text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small :
text_size == 'Normal' ? size.normal : size.large
var t = table.new(table_position,15,math.abs(max-min)+2,
frame_color =color.new(#f1ff2a, 0),
frame_width =1,
border_color =color.new(#f1ff2a,0),
border_width =1)
//---- Table Position & Size code end ----//
// get values for table
[CLS_chart, MA1_chart, MA2_chart, RSI_chart, MACDV_chart, SignalV_chart, stringmacdv_chart, stringmomentum_chart] = f_MACDV(close)
[CLS_5_min, MA1_5_min, MA2_5_min, RSI_5_min, MACDV_5_min, SignalV_5_min, stringmacdv_5_min, stringmomentum_5_min] = request.security(syminfo.tickerid, "5", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_15_min, MA1_15_min, MA2_15_min, RSI_15_min, MACDV_15_min, SignalV_15_min, stringmacdv_15_min, stringmomentum_15_min] = request.security(syminfo.tickerid, "15", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_1_hour, MA1_1_hour, MA2_1_hour, RSI_1_hour, MACDV_1_hour, SignalV_1_hour, stringmacdv_1_hour, stringmomentum_1_hour] = request.security(syminfo.tickerid, "60", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_4_hour, MA1_4_hour, MA2_4_hour, RSI_4_hour, MACDV_4_hour, SignalV_4_hour, stringmacdv_4_hour, stringmomentum_4_hour] = request.security(syminfo.tickerid, "240", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_1_day, MA1_1_day, MA2_1_day, RSI_1_day, MACDV_1_day, SignalV_1_day, stringmacdv_1_day, stringmomentum_1_day] = request.security(syminfo.tickerid, "D", f_MACDV(close), lookahead=barmerge.lookahead_on)
//---- Table Column & Rows code start ----//
if (barstate.islast)
//---- Table Main Column Headers code start ----//
table.cell(t,1,1,'TimeFrem',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showCls
table.cell(t,2,1,'L.Close',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMA01
table.cell(t,3,1,'MA01',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMA02
table.cell(t,4,1,'MA02',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMACross
table.cell(t,5,1,'Trend',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showRSI
table.cell(t,6,1,'RSI',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMACDV
table.cell(t,7,1,'MACDV',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showSignalV
table.cell(t,8,1,'SignalV',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMACDV_Status
table.cell(t,9,1,'Condition',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showmomentum
table.cell(t,10,1,'Phase Market',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
//---- Table Main Column Headers code end ----//
//---- Display data code start ----//
//---------------------- Chart period ----------------------------------
table.cell(t,1,2, "Chart",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255))
if showCls
table.cell(t,2,2, str.tostring(CLS_chart, '#.###'),text_color=color.new(CLS_chart >CLS_chart[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_chart >CLS_chart[2] ? cell_up : cell_dn ,cell_transp))
if showMA01
table.cell(t,3,2, str.tostring(MA1_chart, '#.###'),text_color=color.new(MA1_chart >MA1_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_chart >MA1_chart[1] ? cell_up : cell_dn ,cell_transp))
if showMA02
table.cell(t,4,2, str.tostring(MA2_chart, '#.###'),text_color=color.new(MA2_chart >MA2_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_chart >MA2_chart[1] ? cell_up : cell_dn ,cell_transp))
if showMACross
table.cell(t,5,2, MA1_chart > MA2_chart ? "Bullish" : "Bearish",text_color=color.new(MA1_chart > MA2_chart ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_chart > MA2_chart ? cell_up : cell_dn ,cell_transp))
if showRSI
table.cell(t,6,2, str.tostring(RSI_chart, '#.###'),text_color=color.new(RSI_chart > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_chart > 50 ? cell_up : cell_dn ,cell_transp))
if showMACDV
table.cell(t,7,2,str.tostring(MACDV_chart, '#.###'),text_color=color.new(MACDV_chart > MACDV_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_chart > MACDV_chart[1] ? cell_up : cell_dn ,cell_transp))
if showSignalV
table.cell(t,8,2,str.tostring(SignalV_chart, '#.###'),text_color=color.new(SignalV_chart > SignalV_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_chart> SignalV_chart[1] ? cell_up : cell_dn ,cell_transp))
if showMACDV_Status
table.cell(t,9,2,stringmacdv_chart,text_color=color.rgb(0, 0, 0),text_size=table_text_size, bgcolor=color.new(MACDV_chart>50 ? cell_up :MACDV_chart<-50 ? cell_dn:cell_MACDV4 ,cell_transp))
if showmomentum
table.cell(t,10,2,stringmomentum_chart,text_color=color.rgb(2, 2, 2),text_size=table_text_size, bgcolor=color.new(CLS_chart>MA1_chart and CLS_chart>MA2_chart and MA1_chart<MA2_chart ? cell_phase1 : (CLS_chart>MA1_chart and CLS_chart>MA2_chart and MA1_chart>MA2_chart) ? cell_phase2 : (CLS_chart<MA1_chart and CLS_chart>MA2_chart and MA1_chart>MA2_chart) ?cell_phase3 :(CLS_chart<MA1_chart and CLS_chart<MA2_chart and MA1_chart>MA2_chart) ? cell_phase4:(CLS_chart<MA1_chart and CLS_chart<MA2_chart and MA1_chart<MA2_chart) ? cell_phase5:(CLS_chart>MA1_chart and CLS_chart<MA2_chart and MA1_chart<MA2_chart) ? cell_phase6:col_col,cell_transp))
// alert("\nRSI =(" + str.tostring(CLS_chart, '#.###') + ")\n Momentum = (" + str.tostring(stringmomentum_chart) + ")\n Trend =("+ str.tostring(MA1_chart > MA2_chart ? "Bullish" : "Bearish")+").", alert.freq_once_per_bar_close)
//---------------------- 5 minute chart ----------------------------------
table.cell(t,1,3, "5 minute",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255))
if showCls
table.cell(t,2,3, str.tostring(CLS_5_min, '#.###'),text_color=color.new(CLS_5_min >CLS_5_min[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_5_min >CLS_5_min[2] ? cell_up : cell_dn ,cell_transp))
if showMA01
table.cell(t,3,3, str.tostring(MA1_5_min, '#.###'),text_color=color.new(MA1_5_min >MA1_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_5_min >MA1_5_min[1] ? cell_up : cell_dn ,cell_transp))
if showMA02
table.cell(t,4,3, str.tostring(MA2_5_min, '#.###'),text_color=color.new(MA2_5_min >MA2_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_5_min >MA2_5_min[1] ? cell_up : cell_dn ,cell_transp))
if showMACross
table.cell(t,5,3, MA1_5_min > MA2_5_min ? "Bullish" : "Bearish",text_color=color.new(MA1_5_min > MA2_5_min ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_5_min > MA2_5_min ? cell_up : cell_dn ,cell_transp))
if showRSI
table.cell(t,6,3, str.tostring(RSI_5_min, '#.###'),text_color=color.new(RSI_5_min > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_5_min > 50 ? cell_up : cell_dn ,cell_transp))
if showMACDV
table.cell(t,7,3,str.tostring(MACDV_5_min, '#.###'),text_color=color.new(MACDV_5_min > MACDV_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_5_min > MACDV_5_min[1] ? cell_up : cell_dn ,cell_transp))
if showSignalV
table.cell(t,8,3,str.tostring(SignalV_5_min, '#.###'),text_color=color.new(SignalV_5_min > SignalV_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_5_min> SignalV_5_min[1] ? cell_up : cell_dn ,cell_transp))
if showMACDV_Status
table.cell(t,9,3,stringmacdv_5_min,text_color=color.rgb(5, 5, 5),text_size=table_text_size, bgcolor=color.new(MACDV_5_min>50 ? cell_up :MACDV_5_min<-50 ? cell_dn:cell_MACDV4 ,cell_transp))
if showmomentum
table.cell(t,10,3,stringmomentum_5_min,text_color=color.rgb(5, 5, 5),text_size=table_text_size, bgcolor=color.new(CLS_5_min>MA1_5_min and CLS_5_min>MA2_5_min and MA1_5_min<MA2_5_min ? cell_phase1 : (CLS_5_min>MA1_5_min and CLS_5_min>MA2_5_min and MA1_5_min>MA2_5_min) ? cell_phase2 : (CLS_5_min<MA1_5_min and CLS_5_min>MA2_5_min and MA1_5_min>MA2_5_min) ?cell_phase3 :(CLS_5_min<MA1_5_min and CLS_5_min<MA2_5_min and MA1_5_min>MA2_5_min) ? cell_phase4:(CLS_5_min<MA1_5_min and CLS_5_min<MA2_5_min and MA1_5_min<MA2_5_min) ? cell_phase5:(CLS_5_min>MA1_5_min and CLS_5_min<MA2_5_min and MA1_5_min<MA2_5_min) ? cell_phase6:col_col,cell_transp))
//---------------------- 15 minute chart ----------------------------------
table.cell(t,1,4, "15 minute",text_color=color.rgb(245, 243, 243),text_size=table_text_size, bgcolor=color.rgb(0, 68, 255))
if showCls
table.cell(t,2,4, str.tostring(CLS_15_min, '#.###'),text_color=color.new(CLS_15_min >CLS_15_min[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_15_min >CLS_15_min[2] ? cell_up : cell_dn ,cell_transp))
if showMA01
table.cell(t,3,4, str.tostring(MA1_15_min, '#.###'),text_color=color.new(MA1_15_min >MA1_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_15_min >MA1_15_min[1] ? cell_up : cell_dn ,cell_transp))
if showMA02
table.cell(t,4,4, str.tostring(MA2_15_min, '#.###'),text_color=color.new(MA2_15_min >MA2_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_15_min >MA2_15_min[1] ? cell_up : cell_dn ,cell_transp))
if showMACross
table.cell(t,5,4, MA1_15_min > MA2_15_min ? "Bullish" : "Bearish",text_color=color.new(MA1_15_min > MA2_15_min ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_15_min > MA2_15_min ? cell_up : cell_dn ,cell_transp))
if showRSI
table.cell(t,6,4, str.tostring(RSI_15_min, '#.###'),text_color=color.new(RSI_15_min > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_15_min > 50 ? cell_up : cell_dn ,cell_transp))
if showMACDV
table.cell(t,7,4,str.tostring(MACDV_15_min, '#.###'),text_color=color.new(MACDV_15_min > MACDV_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_15_min > MACDV_15_min[1] ? cell_up : cell_dn ,cell_transp))
if showSignalV
table.cell(t,8,4,str.tostring(SignalV_15_min, '#.###'),text_color=color.new(SignalV_15_min > SignalV_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_15_min> SignalV_15_min[1] ? cell_up : cell_dn ,cell_transp))
if showMACDV_Status
table.cell(t,9,4,stringmacdv_15_min,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(MACDV_15_min>50 ? cell_up :MACDV_15_min<-50 ? cell_dn:cell_MACDV4 ,cell_transp))
if showmomentum
table.cell(t,10,4,stringmomentum_15_min,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(CLS_15_min>MA1_15_min and CLS_15_min>MA2_15_min and MA1_15_min<MA2_15_min ? cell_phase1 : (CLS_15_min>MA1_15_min and CLS_15_min>MA2_15_min and MA1_15_min>MA2_15_min) ? cell_phase2 : (CLS_15_min<MA1_15_min and CLS_15_min>MA2_15_min and MA1_15_min>MA2_15_min) ?cell_phase3 :(CLS_15_min<MA1_15_min and CLS_15_min<MA2_15_min and MA1_15_min>MA2_15_min) ? cell_phase4:(CLS_15_min<MA1_15_min and CLS_15_min<MA2_15_min and MA1_15_min<MA2_15_min) ? cell_phase5:(CLS_15_min>MA1_15_min and CLS_15_min<MA2_15_min and MA1_15_min<MA2_15_min) ? cell_phase6:col_col,cell_transp))
//---------------------- 1 Hour chart ----------------------------------
table.cell(t,1,6, "1 Hour",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255))
if showCls
table.cell(t,2,6, str.tostring(CLS_1_hour, '#.###'),text_color=color.new(CLS_1_hour >CLS_1_hour[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_1_hour >CLS_1_hour[2] ? cell_up : cell_dn ,cell_transp))
if showMA01
table.cell(t,3,6, str.tostring(MA1_1_hour, '#.###'),text_color=color.new(MA1_1_hour >MA1_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_hour >MA1_1_hour[1] ? cell_up : cell_dn ,cell_transp))
if showMA02
table.cell(t,4,6, str.tostring(MA2_1_hour, '#.###'),text_color=color.new(MA2_1_hour >MA2_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_1_hour >MA2_1_hour[1] ? cell_up : cell_dn ,cell_transp))
if showMACross
table.cell(t,5,6, MA1_1_hour > MA2_1_hour ? "Bullish" : "Bearish",text_color=color.new(MA1_1_hour > MA2_1_hour ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_hour > MA2_1_hour ? cell_up : cell_dn ,cell_transp))
if showRSI
table.cell(t,6,6, str.tostring(RSI_1_hour, '#.###'),text_color=color.new(RSI_1_hour > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_1_hour > 50 ? cell_up : cell_dn ,cell_transp))
if showMACDV
table.cell(t,7,6,str.tostring(MACDV_1_hour, '#.###'),text_color=color.new(MACDV_1_hour > MACDV_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_1_hour > MACDV_1_hour[1] ? cell_up : cell_dn ,cell_transp))
if showSignalV
table.cell(t,8,6,str.tostring(SignalV_1_hour, '#.###'),text_color=color.new(SignalV_1_hour > SignalV_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_1_hour> SignalV_1_hour[1] ? cell_up : cell_dn ,cell_transp))
if showMACDV_Status
table.cell(t,9,6,stringmacdv_1_hour,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(MACDV_1_hour>50 ? cell_up :MACDV_1_hour<-50 ? cell_dn:cell_MACDV4 ,cell_transp))
if showmomentum
table.cell(t,10,6,stringmomentum_1_hour,text_color=color.rgb(8, 8, 8),text_size=table_text_size, bgcolor=color.new(CLS_1_hour>MA1_1_hour and CLS_1_hour>MA2_1_hour and MA1_1_hour<MA2_1_hour ? cell_phase1 : (CLS_1_hour>MA1_1_hour and CLS_1_hour>MA2_1_hour and MA1_1_hour>MA2_1_hour) ? cell_phase2 : (CLS_1_hour<MA1_1_hour and CLS_1_hour>MA2_1_hour and MA1_1_hour>MA2_1_hour) ?cell_phase3 :(CLS_1_hour<MA1_1_hour and CLS_1_hour<MA2_1_hour and MA1_1_hour>MA2_1_hour) ? cell_phase4:(CLS_1_hour<MA1_1_hour and CLS_1_hour<MA2_1_hour and MA1_1_hour<MA2_1_hour) ? cell_phase5:(CLS_1_hour>MA1_1_hour and CLS_1_hour<MA2_1_hour and MA1_1_hour<MA2_1_hour) ? cell_phase6:col_col,cell_transp))
//---------------------- 4 Hour chart ----------------------------------
table.cell(t,1,7, "4 Hour",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255))
if showCls
table.cell(t,2,7, str.tostring(CLS_4_hour, '#.###'),text_color=color.new(CLS_4_hour >CLS_4_hour[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_4_hour >CLS_4_hour[2] ? cell_up : cell_dn ,cell_transp))
if showMA01
table.cell(t,3,7, str.tostring(MA1_4_hour, '#.###'),text_color=color.new(MA1_4_hour >MA1_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_4_hour >MA1_4_hour[1] ? cell_up : cell_dn ,cell_transp))
if showMA02
table.cell(t,4,7, str.tostring(MA2_4_hour, '#.###'),text_color=color.new(MA2_4_hour >MA2_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_4_hour >MA2_4_hour[1] ? cell_up : cell_dn ,cell_transp))
if showMACross
table.cell(t,5,7, MA1_4_hour > MA2_4_hour ? "Bullish" : "Bearish",text_color=color.new(MA1_4_hour > MA2_4_hour ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_4_hour > MA2_4_hour ? cell_up : cell_dn ,cell_transp))
if showRSI
table.cell(t,6,7, str.tostring(RSI_4_hour, '#.###'),text_color=color.new(RSI_4_hour > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_4_hour > 50 ? cell_up : cell_dn ,cell_transp))
if showMACDV
table.cell(t,7,7,str.tostring(MACDV_4_hour, '#.###'),text_color=color.new(MACDV_4_hour > MACDV_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_4_hour > MACDV_4_hour[1] ? cell_up : cell_dn ,cell_transp))
if showSignalV
table.cell(t,8,7,str.tostring(SignalV_4_hour, '#.###'),text_color=color.new(SignalV_4_hour > SignalV_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_4_hour> SignalV_4_hour[1] ? cell_up : cell_dn ,cell_transp))
if showMACDV_Status
table.cell(t,9,7,stringmacdv_4_hour,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(MACDV_4_hour>50 ? cell_up :MACDV_4_hour<-50 ? cell_dn:cell_MACDV4 ,cell_transp))
if showmomentum
table.cell(t,10,7,stringmomentum_4_hour,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(CLS_4_hour>MA1_4_hour and CLS_4_hour>MA2_4_hour and MA1_4_hour<MA2_4_hour ? cell_phase1 : (CLS_4_hour>MA1_4_hour and CLS_4_hour>MA2_4_hour and MA1_4_hour>MA2_4_hour) ? cell_phase2 : (CLS_4_hour<MA1_4_hour and CLS_4_hour>MA2_4_hour and MA1_4_hour>MA2_4_hour) ?cell_phase3 :(CLS_4_hour<MA1_4_hour and CLS_4_hour<MA2_4_hour and MA1_4_hour>MA2_4_hour) ? cell_phase4:(CLS_4_hour<MA1_4_hour and CLS_4_hour<MA2_4_hour and MA1_4_hour<MA2_4_hour) ? cell_phase5:(CLS_4_hour>MA1_4_hour and CLS_4_hour<MA2_4_hour and MA1_4_hour<MA2_4_hour) ? cell_phase6:col_col,cell_transp))
//---------------------- 1 Day chart ----------------------------------
table.cell(t,1,9, "1 Day",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 253))
if showCls
table.cell(t,2,9, str.tostring(CLS_1_day, '#.###'),text_color=color.new(CLS_1_day >CLS_1_day[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_1_day >CLS_1_day[2] ? cell_up : cell_dn ,cell_transp))
if showMA01
table.cell(t,3,9, str.tostring(MA1_1_day, '#.###'),text_color=color.new(MA1_1_day >MA1_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_day >MA1_1_day[1] ? cell_up : cell_dn ,cell_transp))
if showMA02
table.cell(t,4,9, str.tostring(MA2_1_day, '#.###'),text_color=color.new(MA2_1_day >MA2_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_1_day >MA2_1_day[1] ? cell_up : cell_dn ,cell_transp))
if showMACross
table.cell(t,5,9, MA1_1_day > MA2_1_day ? "Bullish" : "Bearish",text_color=color.new(MA1_1_day > MA2_1_day ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_day > MA2_1_day ? cell_up : cell_dn ,cell_transp))
if showRSI
table.cell(t,6,9, str.tostring(RSI_1_day, '#.###'),text_color=color.new(RSI_1_day > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_1_day > 50 ? cell_up : cell_dn ,cell_transp))
if showMACDV
table.cell(t,7,9,str.tostring(MACDV_1_day, '#.###'),text_color=color.new(MACDV_1_day > MACDV_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_1_day > MACDV_1_day[1] ? cell_up : cell_dn ,cell_transp))
if showSignalV
table.cell(t,8,9,str.tostring(SignalV_1_day, '#.###'),text_color=color.new(SignalV_1_day > SignalV_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_1_day> SignalV_1_day[1] ? cell_up : cell_dn ,cell_transp))
if showMACDV_Status
table.cell(t,9,9,stringmacdv_1_day,text_color=color.rgb(5, 5, 5),text_size=table_text_size, bgcolor=color.new(MACDV_1_day>50 ? cell_up :MACDV_1_day<-50 ? cell_dn:cell_MACDV4 ,cell_transp))
if showmomentum
table.cell(t,10,9,stringmomentum_1_day,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(CLS_1_day>MA1_1_day and CLS_1_day>MA2_1_day and MA1_1_day<MA2_1_day ? cell_phase1 : (CLS_1_day>MA1_1_day and CLS_1_day>MA2_1_day and MA1_1_day>MA2_1_day) ? cell_phase2 : (CLS_1_day<MA1_1_day and CLS_1_day>MA2_1_day and MA1_1_day>MA2_1_day) ?cell_phase3 :(CLS_1_day<MA1_1_day and CLS_1_day<MA2_1_day and MA1_1_day>MA2_1_day) ? cell_phase4:(CLS_1_day<MA1_1_day and CLS_1_day<MA2_1_day and MA1_1_day<MA2_1_day) ? cell_phase5:(CLS_1_day>MA1_1_day and CLS_1_day<MA2_1_day and MA1_1_day<MA2_1_day) ? cell_phase6:col_col,cell_transp))
//---- Display data code end ----//
//End dahs board
|
QQE Student's T-Distribution Bollinger Bands Screener | https://www.tradingview.com/script/ZqSC5pcs-QQE-Student-s-T-Distribution-Bollinger-Bands-Screener/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 48 | 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/
// © peacefulLizard50262
//@version=5
indicator("QQETSBB Screener", overlay = true, precision = 0, max_bars_back = 1000)
// The number 2 * sqrt(e / pi) number:
var float math_TwoSqrtEOverPi = 1.8603827342052657173362492472666631120594218414085755
// The order of the Log Gamma aproximation:
var int GammaN = 10
// Auxiliary variable when evaluating the Log Gamma function:
var float GammaR = 10.900511
// Series of Polynomial coefficients for the Gamma approximation:
var float[] series_GammaDk =
array.from(2.48574089138753565546e-5,
1.05142378581721974210,
-3.45687097222016235469,
4.51227709466894823700,
-2.98285225323576655721,
1.05639711577126713077,
-1.95428773191645869583e-1,
1.70970543404441224307e-2,
-5.71926117404305781283e-4,
4.63399473359905636708e-6,
-2.71994908488607703910e-9)
gamma(input) =>
// <needs> : Precision.Constants
//
// <param> input : Any float input as argument of the Gamma Function.
//
// <returns> : The Gamma Function.
float z = input
if z < 0.5
float s = array.get(series_GammaDk, 0)
for int i = 1 to GammaN by 1
s += array.get(series_GammaDk, i) / (i - z)
s
return_Gamma = math.pi / math.sin(math.pi * z) * s * math_TwoSqrtEOverPi * math.pow((0.5 - z + GammaR) / math.e, 0.5 - z)
return_Gamma
else
float s = array.get(series_GammaDk, 0)
for int i = 1 to GammaN by 1
s += array.get(series_GammaDk, i) / (z + i - 1.0)
s
return_Gamma = s * math_TwoSqrtEOverPi * math.pow((z - 0.5 + GammaR) / math.e, z - 0.5)
return_Gamma
// EndOf: function_Gamma() }
ha_close(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = (Open + High + Low + Close) / 4
out = enable == true ? ha_close : Close
ha_open(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_open = float(na)
ha_close = ha_close(Open, High, Low, Close)
ha_open := na(ha_open[1]) ? (Open + Close) / 2 : (nz(ha_open[1]) + nz(ha_close[1])) / 2
out = enable == true ? ha_open : Open
diff(_src, _N) =>
float derivative = 0.0
if _N == 2
derivative := (_src - _src[2]) / 2
derivative
else if _N == 3
derivative := (_src + _src[1] - _src[2] - _src[3]) / 4
derivative
else if _N == 4
derivative := (_src + 2 * _src[1] - 2 * _src[3] - _src[4]) / 8
derivative
else if _N == 5
derivative := (_src + 3 * _src[1] + 2 * _src[2] - 2 * _src[3] - 3 * _src[4] - _src[5]) / 16
derivative
else if _N == 6
derivative := (_src + 4 * _src[1] + 5 * _src[2] - 5 * _src[4] - 4 * _src[5] - _src[6]) / 32
derivative
else if _N == 7
derivative := (_src + 5 * _src[1] + 9 * _src[2] + 5 * _src[3] - 5 * _src[4] - 9 * _src[5] - 5 * _src[6] - _src[7]) / 64
derivative
else if _N == 8
derivative := (_src + 6 * _src[1] + 14 * _src[2] + 14 * _src[3] - 14 * _src[5] - 14 * _src[6] - 6 * _src[7] - _src[8]) / 128
derivative
else if _N == 9
derivative := (_src + 7 * _src[1] + 20 * _src[2] + 28 * _src[3] + 14 * _src[4] - 14 * _src[5] - 28 * _src[6] - 20 * _src[7] - 7 * _src[8] - _src[9]) / 256
derivative
else if _N == 10
derivative := (_src + 8 * _src[1] + 27 * _src[2] + 48 * _src[3] + 42 * _src[4] - 42 * _src[6] - 48 * _src[7] - 27 * _src[8] - 8 * _src[9] - _src[10]) / 512
derivative
derivative
t_dist_pdf(float x, int v) =>
gamma((v + 1) / 2) / (math.sqrt(v * math.pi) * gamma(v / 2)) * math.pow(1 + x * x / v, -(v + 1) / 2)
rising_factorial(float c, int n) =>
float product = 1.0
if n > 0
for i = 0 to n - 1
product *= (c + i)
product
style = input.string("QQE", "Moving Average", ["QQE","SMA","EMA","WMA"], group="Deviation")
location = input.string("Middle Center", "Position",
["Bottom Left","Bottom Middle","Bottom Right","Middle Left","Middle Center","Middle Right",
"Top Left","Top Middle","Top Right"])
len = input.int(200, title="Length", minval=2, tooltip="How long the rolling window for lookback calculations should be", group="Deviation")
itter = input.int(0, "Cumulative Distribution Function Iterations", 0, group="Deviation")
geometric = input.bool(true, 'Log-space', group="Features")
diff_n = input.int(2, "Direction Look Back", 2, 10, group="Features")
smoothing = input.int(title='QQE Smoothing (when QQE is used as signal line)', defval=5, minval=1, group="QQE")
qqe_factor = input.float(title='QQE Factor (when QQE is used as signal line)', defval=5, minval=1, group="QQE")
custom = input.bool(false, "Custom Time Frame", inline = "Time", tooltip = "When using custom time frame use the minimum time on your chart.")
ctime = input.timeframe("D", "", inline = "Time")
txt_col = input.color(color.new(#c8d7ff, 0), "Title Color", inline = "bull", group = "Settings")
box_col = input.color(color.new(#202236, 10), "", inline = "bull", group = "Settings")
location() =>
switch location
"Bottom Left" => position.bottom_left
"Bottom Middle" => position.bottom_center
"Bottom Right" => position.bottom_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Top Left" => position.top_left
"Top Middle" => position.top_center
"Top Right" => position.top_right
hypergeometric(float a, float b, float c, float z) =>
float sum = 0.0
for i = 0 to itter
sum += rising_factorial(a, i) * rising_factorial(b, i) * math.pow(z, i) / (rising_factorial(c, i) * rising_factorial(i, i))
sum
t_dist_cdf(float x, int v) =>
// I hate myself for doing this
1/2. + x * gamma((v+1)/2.) * (hypergeometric(1/2., (v+1)/2., 3./2, x*x/v) / (math.sqrt(v * math.pi)* gamma(v/2)))
ext1 = input.symbol('BTCUSD', 'Symbol 1', group = "Symbols")
ext2 = input.symbol('ETHUSD', 'Symbol 2', group = "Symbols")
ext3 = input.symbol('BNBUSD', 'Symbol 3', group = "Symbols")
ext4 = input.symbol('XRPUSD', 'Symbol 4', group = "Symbols")
ext5 = input.symbol('DOGEUSD', 'Symbol 5', group = "Symbols")
ext6 = input.symbol('ETCUSD', 'Symbol 6', group = "Symbols")
ext7 = input.symbol('LTCUSD', 'Symbol 7', group = "Symbols")
ext8 = input.symbol('XLMUSD', 'Symbol 8', group = "Symbols")
ext9 = input.symbol('XMRUSD', 'Symbol 9', group = "Symbols")
ext10 = input.symbol('TRXUSD', 'Symbol 10', group = "Symbols")
ext11 = input.symbol('AAPL', 'Symbol 11', group = "Symbols")
ext12 = input.symbol('MSFT', 'Symbol 12', group = "Symbols")
ext13 = input.symbol('GOOG', 'Symbol 13', group = "Symbols")
ext14 = input.symbol('AMZN', 'Symbol 14', group = "Symbols")
ext15 = input.symbol('TSLA', 'Symbol 15', group = "Symbols")
ext16 = input.symbol('UNH', 'Symbol 16', group = "Symbols")
ext17 = input.symbol('META', 'Symbol 17', group = "Symbols")
ext18 = input.symbol('NVDA', 'Symbol 18', group = "Symbols")
ext19 = input.symbol('V', 'Symbol 19', group = "Symbols")
ext20 = input.symbol('MA', 'Symbol 20', group = "Symbols")
timep = custom ? ctime : timeframe.period
var tbl = table.new(location(), 7, 21)
if barstate.islast
table.cell(tbl, 0, 0, "Symbol", text_color = txt_col, bgcolor = box_col, tooltip = "Symbol for that line.")
table.cell(tbl, 1, 0, "Price", text_color = txt_col, bgcolor = box_col, tooltip = "Price of Symbol")
table.cell(tbl, 2, 0, "Band Spread", text_color = txt_col, bgcolor = box_col, tooltip = "The volitility range in %.")
table.cell(tbl, 3, 0, "Segment Spread", text_color = txt_col, bgcolor = box_col, tooltip = "1/4 the volitility range in %.")
table.cell(tbl, 4, 0, "Level", text_color = txt_col, bgcolor = box_col, tooltip = "What quarter of the band the price is currently at.")
table.cell(tbl, 5, 0, "Sentiment", text_color = txt_col, bgcolor = box_col, tooltip = "A score bassed on all of the popular indicators. If the score is high, the popular indicators are showing over baught and visa versa. This is a combination of rsi, macd, stochastic, cci, mfi, and otheres.")
table.cell(tbl, 6, 0, "Direction", text_color = txt_col, bgcolor = box_col, tooltip = "This is the direction the price is moving in.")
qqe(source) =>
wilders_period = len * 2 - 1
ma = ta.ema(source, smoothing)
atr = math.abs(nz(ma[1]) - ma)
ma_atr = ta.ema(atr, wilders_period)
delta_fast_atr = ta.ema(ma_atr, wilders_period) * qqe_factor
result = 0.0
result := ma > nz(result[1]) ? ma - delta_fast_atr < result[1] ? result[1] : ma - delta_fast_atr : ma + delta_fast_atr > result[1] ? result[1] : ma + delta_fast_atr
// Return
result
ma(source) =>
switch style
"SMA" => ta.sma(source, len)
"EMA" => ta.ema(source, len)
"WMA" => ta.wma(source, len)
"QQE" => qqe(source)
main(source, n) =>
exn = str.tostring(source)
ex = request.security(source , timep, close)
exh = ta.highest(ex, 1)
exl = ta.lowest(ex, 1)
// Calculate p-value given the confidence
p = (1 - 0.9999) / 2
// We need to find the value of x such that t_dist_cdf(x, length - 1) = p
// We do this by using a binary search
src = geometric ? math.log(ex) : ex
float lower = -100
float upper = 100
float mid = (lower + upper) / 2
while math.abs(t_dist_cdf(mid, len - 1) - p) > 0.000001
if t_dist_cdf(mid, len - 1) > p
upper := mid
else
lower := mid
mid := (lower + upper) / 2.
float t_value = mid
// t-value for the p-value
if t_value < 0
t_value := -t_value
x_bar = ma(src)
squared_diff = math.pow(src-x_bar, 2)
summed_squares = math.sum(squared_diff, len)
// length - 1 because we're using a sample rather than whole population
mean_squared_error = summed_squares / (len-1)
rmse = math.sqrt(mean_squared_error)
root_standard_error = math.sqrt(1 + 1/len + squared_diff/summed_squares)
offset = t_value * rmse * root_standard_error
// The midline
mid_line = x_bar
// Calculate the upper and lower bounds
upper_bound = x_bar + offset
lower_bound = x_bar - offset
Bottom = geometric ? math.exp(lower_bound) : lower_bound
Top = geometric ? math.exp(upper_bound) : upper_bound
Center = geometric ? math.exp(x_bar) : x_bar
Signal = geometric ? math.exp(src) : src
Half_Bottom = Bottom - ((Bottom-Center)/2)
Half_Top = Top - ((Top-Center)/2)
mean_diff = diff(Center, diff_n)
Diff_Score = mean_diff < 0 ? "↓" : mean_diff > 0 ? "↑" : "→"
Score = Signal >= Top ? 5 : Signal > Half_Top ? 4 : Signal > Center ? 3 : Signal > Half_Bottom ? 2 : Signal > Bottom ? 1 : Signal <= Bottom ? 0 : -1
Band = (((Top - Bottom) / Bottom) - (((Top - Bottom) / Top) % 0.001)) * 100
Segment = (((Half_Top - Center) / Center) - (((Half_Top - Center) / Center) % 0.001)) * 100
oc_trend = ta.sma(ta.ema(ex, 20) - ta.ema(ex[1], 20), 2)
oc_score = oc_trend > 0 ? 1 : 0
fast_e = ta.ema(ex, 9)
slow_e = ta.ema(ex, 21)
ema_cross = fast_e > slow_e ? 1 : 0
fast_s = ta.sma(ex, 13)
slow_s = ta.sma(ex, 48)
sma_cross = fast_s > slow_s ? 1 : 0
rsi = ta.rsi(ex, 14)
rsi_score = rsi < 30 ? 0 : rsi > 30 and rsi < 70 ? 0.5 : rsi > 70 ? 1 : 0
[macd1, macd2, hist] = ta.macd(ex, 12, 26, 9)
macd_score = macd1 > macd2 ? 0.5 : macd1 < macd2 ? 0 : 0
hist_score = (hist >=0 ? (hist[1] < hist ? 0.5 : 0.25) : (hist[1] < hist ? 0.25 : 0))
stoch = ta.sma(ta.stoch(ex, exh, exl, 14), 2)
stoch_score = stoch < 20 ? 0 : stoch > 20 and stoch < 80 ? 0.5 : stoch > 80 ? 1 : 0
ma200 = ta.sma(ex, 200)
ma200_score = ex > ma200 ? 1 : ex <= ma200 ? 0 : 0
mfi = ta.mfi(ex, 14)
mfi_score = mfi < 20 ? 0 : mfi > 20 and mfi < 80 ? 0.5 : mfi > 80 ? 1 : 0
cci = ta.cci(ex, 20)
cci_score = cci < -100 ? 0 : cci > -100 and cci < 100 ? 0.5 : cci > 100 ? 1 : 0
ha_open = ha_open(ex[1], exh, exl, ex)
ha_close = ha_close(ex[1], exh, exl, ex)
ha_score = ha_open < ha_close ? 1 : 0
sent = ema_cross + sma_cross + rsi_score + macd_score + hist_score + stoch_score + ma200_score + mfi_score + cci_score + oc_score + ha_score
sentiment = sent
if barstate.islast
table.cell(tbl, 0, n, exn, text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, n, str.tostring(ex), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 2, n, str.tostring(Band - (Band % 0.1)) + "%", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 3, n, str.tostring(Segment - (Segment % 0.1)) + "%", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 4, n, str.tostring(Score) + "/5", text_color = txt_col, bgcolor = box_col )
table.cell(tbl, 5, n, str.tostring(sentiment) + "/10", text_color = txt_col, bgcolor = box_col )
table.cell(tbl, 6, n, Diff_Score, text_color = txt_col, bgcolor = box_col)
main(ext1, 1)
main(ext2, 2)
main(ext3, 3)
main(ext4, 4)
main(ext5, 5)
main(ext6, 6)
main(ext7, 7)
main(ext8, 8)
main(ext9, 9)
main(ext10, 10)
main(ext11, 11)
main(ext12, 12)
main(ext13, 13)
main(ext14, 14)
main(ext15, 15)
main(ext16, 16)
main(ext17, 17)
main(ext18, 18)
main(ext19, 19)
main(ext20, 20) |
Public Sentiment Oscillator | https://www.tradingview.com/script/HSaGbJdP-Public-Sentiment-Oscillator/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 76 | 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/
// © peacefulLizard50262
//@version=5
indicator("Public Sentiment", overlay = false)
ha_close(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = (Open + High + Low + Close) / 4
out = enable == true ? ha_close : Close
ha_open(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_open = float(na)
ha_close = ha_close(Open, High, Low, Close)
ha_open := na(ha_open[1]) ? (Open + Close) / 2 : (nz(ha_open[1]) + nz(ha_close[1])) / 2
out = enable == true ? ha_open : Open
ha_high(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = ha_close(Open, High, Low, Close)
ha_open = ha_open(Open, High, Low, Close)
ha_high = math.max(High, math.max(ha_open, ha_close))
out = enable == true ? ha_high : High
ha_low(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = ha_close(Open, High, Low, Close)
ha_open = ha_open(Open, High, Low, Close)
ha_low = math.min(Low, math.min(ha_open, ha_close))
out = enable == true ? ha_low : Low
candle = input.bool(true, "Candle View", inline = "cn")
can_smoothing = input.int(4, "Candle Transform", 1, tooltip = "This lets you get proper candles. This modifies the internal moving average in the candle transformation.")
ha_enable = input.bool(true, "Heikin Ashi")
smoothing_enable = input.bool(false, "Smoothing", inline = "sm")
smoothing = input.int(4, "", 1, inline = "sm")
red = input.color(color.new(#ef5350, 0), "", group="", inline = "can")
green = input.color(color.new(#26a69a, 0), "", group="", inline = "can")
high_thresh = input.float(8 , "Threshold", 0)
low_thresh = input.float(3 , "Threshold", 0)
ha_close = ha_close()
ha_open = ha_open()
ha_score = ha_open < ha_close ? 1 : 0
oc_trend = ta.sma(ta.ema(close, 20) - ta.ema(close[1], 20), 2)
oc_score = oc_trend > 0 ? 1 : 0
fast_e = ta.ema(close, 9)
slow_e = ta.ema(close, 21)
ema_cross = fast_e > slow_e ? 1 : 0
fast_s = ta.sma(close, 13)
slow_s = ta.sma(close, 48)
sma_cross = fast_s > slow_s ? 1 : 0
rsi = ta.rsi(close, 14)
rsi_score = rsi < 30 ? 0 : rsi > 30 and rsi < 70 ? 0.5 : rsi > 70 ? 1 : 0
[macd1, macd2, hist] = ta.macd(close, 12, 26, 9)
macd_score = macd1 > macd2 ? 0.5 : macd1 < macd2 ? 0 : 0
hist_score = (hist >=0 ? (hist[1] < hist ? 0.5 : 0.25) : (hist[1] < hist ? 0.25 : 0))
stoch = ta.sma(ta.stoch(close, high, low, 14), 2)
stoch_score = stoch < 20 ? 0 : stoch > 20 and stoch < 80 ? 0.5 : stoch > 80 ? 1 : 0
ma200 = ta.sma(close, 200)
ma200_score = close > ma200 ? 1 : close <= ma200 ? 0 : 0
mfi = ta.mfi(close, 14)
mfi_score = mfi < 20 ? 0 : mfi > 20 and mfi < 80 ? 0.5 : mfi > 80 ? 1 : 0
cci = ta.cci(close, 20)
cci_score = cci < -100 ? 0 : cci > -100 and cci < 100 ? 0.5 : cci > 100 ? 1 : 0
sent = ema_cross + sma_cross + rsi_score + macd_score + hist_score + stoch_score + ma200_score + mfi_score + cci_score + oc_score + ha_score
sentiment = smoothing_enable ? ta.wma(sent, smoothing) : sent
// signal = plot(sentiment, "Signal", color.new(color.orange, 1))
signal = plot(not candle ? sentiment : na, "Signal", color.new(color.orange, 1))
top = hline(10, "Top Line", color.new(color.gray, 50), hline.style_solid)
bot = hline(5, "Center Line", color.new(color.gray, 50), hline.style_solid)
center = hline(0, "Bottom Line", color.new(color.gray, 50), hline.style_solid)
H = hline(high_thresh, "High", color.new(color.gray, 50))
L = hline(low_thresh, "High", color.new(color.gray, 50))
fill(H, L, color.new(color.blue, 90))
Open = ta.sma(sentiment[1], can_smoothing)
High = ta.highest(sentiment, 1)
Low = ta.lowest(sentiment, 1)
Close = ta.sma(sentiment, can_smoothing)
colour = candle ? sentiment[1] > sentiment ? red : green : na
plotcandle(ha_open(Open, High, Low, Close, ha_enable), ha_high(Open, High, Low, Close, ha_enable), ha_low(Open, High, Low, Close, ha_enable), ha_close(Open, High, Low, Close, ha_enable), "Candles", colour, colour, true, bordercolor = colour) |
Fibonacci Plot [ABA Invest]] | https://www.tradingview.com/script/hsmtOleu-Fibonacci-Plot-ABA-Invest/ | abainvest | https://www.tradingview.com/u/abainvest/ | 400 | 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/
// © ABA Invest
//@version=5
indicator("Fibonacci Plot [ABA Invest]]", overlay=true, max_lines_count=500)
versi = input.string('Standard','Fibonacci Type',options=['Musang', 'Standard'])
endpoints = input.string('Wick-Wick','Drawing point',options=['Wick-Wick', 'Wick-Body', 'Body-Body'])
time_start = input.time(0,'Time Start',confirm=true)
time_end = input.time(0,'Time End',confirm=true)
//----
fib_0 = input.bool(true, '0 ',inline='inline1',group='Fibonacci')
fib_0_level = 1
fib_0_color = input(#e91e63,'',inline='inline1',group='Fibonacci')
fib_0_text = '0'
fib_0236 = input.bool(true, '0.236',inline='inline2',group='Fibonacci')
fib_0236_level = 0.236
fib_0236_color = input(#ff5d00,'',inline='inline2',group='Fibonacci')
fib_0236_text = '0.236'
fib_0382 = input.bool(true, '0.382',inline='inline2',group='Fibonacci')
fib_0382_level = 0.382
fib_0382_color = input(#ff5d00,'',inline='inline2',group='Fibonacci')
fib_0382_text = '0.382'
fib_05 = input.bool(true, '0.5',inline='inline2',group='Fibonacci')
fib_05_level = 0.5
fib_05_color = input(#ff5d00,'',inline='inline2',group='Fibonacci')
fib_05_text = '0.5'
fib_0618 = input.bool(true, '0.618',inline='inline2',group='Fibonacci')
fib_0618_level = 0.618
fib_0618_color = input(#ff5d00,'',inline='inline2',group='Fibonacci')
fib_0618_text = '0.618'
fib_0786 = input.bool(true, '0.786',inline='inline2',group='Fibonacci')
fib_0786_level = 0.786
fib_0786_color = input(#ff5d00,'',inline='inline2',group='Fibonacci')
fib_0786_text = '0.786'
fib_1 = input.bool(true, '1',inline='inline1',group='Fibonacci')
fib_1_level = 0.
fib_1_color = input(#e91e63,'',inline='inline1',group='Fibonacci')
fib_1_text = '1'
fib_1618 = input.bool(true, '1.618',inline='inline5',group='Fibonacci')
fib_1618_level = -.618
fib_1618_color = input(#0cb51a,'',inline='inline5',group='Fibonacci')
fib_1618_text = versi == "Standard" ? "1.618" : 'TP1'
fib_188 = input.bool(true, '1.88',inline='inline5',group='Fibonacci')
fib_188_level = -.88
fib_188_color = input(#0cb51a,'',inline='inline5',group='Fibonacci')
fib_188_text = 'TP1'
fib_2618 = input.bool(true, '2.618',inline='inline6',group='Fibonacci')
fib_2618_level = -1.618
fib_2618_color = input(#423ab7,'',inline='inline6',group='Fibonacci')
fib_2618_text = versi == "Standard" ? "2.618" : 'TP2'
fib_288 = input.bool(true, '2.88',inline='inline6',group='Fibonacci')
fib_288_level = -1.88
fib_288_color = input(#673ab7,'',inline='inline6',group='Fibonacci')
fib_288_text = 'TP2'
fib_3618 = input.bool(true, '3.618',inline='inline7',group='Fibonacci')
fib_3618_level = -2.618
fib_3618_color = input(#673ab7,'',inline='inline7',group='Fibonacci')
fib_3618_text = '3.618'
fib_4618 = input.bool(true, '4.618',inline='inline8',group='Fibonacci')
fib_4618_level = -3.618
fib_4618_color = input(#64b5f6,'',inline='inline8',group='Fibonacci')
fib_4618_text = '4.618'
fib_323 = input.bool(true, '3.23',inline='inline8',group='Fibonacci')
fib_323_level = -3.23
fib_323_color = input(#64b5f6,'',inline='inline8',group='Fibonacci')
fib_323_text = 'CC'
fib_388 = input.bool(true, '3.88',inline='inline8',group='Fibonacci')
fib_388_level = -3.88
fib_388_color = input(#673ab7,'',inline='inline8',group='Fibonacci')
fib_388_text = 'CC'
connecting_line = input(true,'Retrace Line',inline='inline7',group='Fibonacci')
line_color = input(color.gray,'',inline='inline7',group='Fibonacci')
//----
var fib = array.new_float(0)
var fib_color = array.new_color(0)
var fib_str = array.new_string()
if barstate.isfirst
if versi == 'Musang'
if fib_1618
array.push(fib,fib_1618_level)
array.push(fib_color,fib_1618_color)
array.push(fib_str,fib_1618_text)
if fib_188
array.push(fib,fib_188_level)
array.push(fib_color,fib_188_color)
array.push(fib_str,fib_188_text)
if fib_05
array.push(fib,fib_05_level)
array.push(fib_color,fib_05_color)
array.push(fib_str,fib_05_text)
if fib_2618
array.push(fib,fib_2618_level)
array.push(fib_color,fib_2618_color)
array.push(fib_str,fib_2618_text)
if fib_288
array.push(fib,fib_288_level)
array.push(fib_color,fib_288_color)
array.push(fib_str,fib_288_text)
if fib_1
array.push(fib,fib_1_level)
array.push(fib_color,fib_1_color)
array.push(fib_str,fib_1_text)
if fib_323
array.push(fib,fib_323_level)
array.push(fib_color,fib_323_color)
array.push(fib_str,fib_323_text)
if fib_388
array.push(fib,fib_388_level)
array.push(fib_color,fib_388_color)
array.push(fib_str,fib_388_text)
if versi == 'Standard'
if fib_05
array.push(fib,fib_05_level)
array.push(fib_color,fib_05_color)
array.push(fib_str,fib_05_text)
if fib_1
array.push(fib,fib_1_level)
array.push(fib_color,fib_1_color)
array.push(fib_str,fib_1_text)
if fib_0618
array.push(fib,fib_0618_level)
array.push(fib_color,fib_0618_color)
array.push(fib_str,fib_0618_text)
if fib_0382
array.push(fib,fib_0382_level)
array.push(fib_color,fib_0382_color)
array.push(fib_str,fib_0382_text)
if fib_0786
array.push(fib,fib_0786_level)
array.push(fib_color,fib_0786_color)
array.push(fib_str,fib_0786_text)
if fib_0236
array.push(fib,fib_0236_level)
array.push(fib_color,fib_0236_color)
array.push(fib_str,fib_0236_text)
if fib_0
array.push(fib,fib_0_level)
array.push(fib_color,fib_0_color)
array.push(fib_str,fib_0_text)
if fib_1618
array.push(fib,fib_1618_level)
array.push(fib_color,fib_1618_color)
array.push(fib_str,fib_1618_text)
if fib_2618
array.push(fib,fib_2618_level)
array.push(fib_color,fib_2618_color)
array.push(fib_str,fib_2618_text)
if fib_3618
array.push(fib,fib_3618_level)
array.push(fib_color,fib_3618_color)
array.push(fib_str,fib_3618_text)
if fib_4618
array.push(fib,fib_4618_level)
array.push(fib_color,fib_4618_color)
array.push(fib_str,fib_4618_text)
//----
n = bar_index
dt = time-time[1]
start_n = ta.valuewhen(time == time_start,n,0)
end_n = ta.valuewhen(time == time_end,n,0)
y_1 = ta.valuewhen(time == time_start,close,0)
y_2 = ta.valuewhen(time == time_end,close,0)
diff = y_2 > y_1
is_ekor_ekor = endpoints == "Wick-Wick"
is_ekor_body = endpoints == "Wick-Body"
is_body_body = endpoints == "Body-Body"
start_high_y = ta.valuewhen(time == time_start,high,0)
start_low_y = ta.valuewhen(time == time_start,low,0)
start_open_y = ta.valuewhen(time == time_start,open,0)
start_close_y = ta.valuewhen(time == time_start,close,0)
end_high_y = ta.valuewhen(time == time_end,high,0)
end_low_y = ta.valuewhen(time == time_end,low,0)
end_open_y = ta.valuewhen(time == time_end,open,0)
end_close_y = ta.valuewhen(time == time_end,close,0)
start_y = 0.0
end_y = 0.0
if is_ekor_body
start_y := diff ? start_low_y : start_high_y
end_y := ta.valuewhen(time == time_end,close,0)
if is_ekor_ekor
start_y := diff ? start_low_y : start_high_y
end_y := diff ? end_high_y : end_low_y
if is_body_body
start_y := diff ? start_open_y : start_close_y
end_y := diff ? end_close_y : end_open_y
diff_n = end_n - start_n
diff_y = start_y - end_y
//----
if n == math.max(start_n,end_n)
if connecting_line
line.new(start_n,start_y,end_n,end_y,color=line_color)
for i = 0 to array.size(fib)-1
level = end_y + array.get(fib,i)*diff_y
line.new(start_n,level,end_n,level,color=array.get(fib_color,i))
start_ext = math.max(start_n,end_n)
line.new(start_ext,level,start_ext+1,level,color=array.get(fib_color,i),extend=extend.right,style=line.style_dashed)
sty = label.style_label_right
label.new(math.min(start_n,end_n),level,str.tostring(array.get(fib_str,i)),color=#00000000, style=sty,textcolor=array.get(fib_color,i),textalign=text.align_center,size=size.small)
|
TMO Scalper | https://www.tradingview.com/script/LOPtZGaw-TMO-Scalper/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 1,567 | 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
//
// TMO (T)rue (M)omentum (O)scillator) MTF Special Scapler Version
//
// TMO Scalper is a special custom version that was designed exclusively for lower time frame scalps (1-5min charts)
//
// This version of the TMO Oscillator print the signals ONLY when the higher aggregation is aligned with the current (lower aggregation)
//
// Created by L&L Capital
//
indicator("TMO Scalper", shorttitle="TMO Scalper", overlay=false)
// Inputs
TimeFrame1 = input.timeframe('1', "TMO 1", options = ['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'], group = "Time Frames")
TimeFrame2 = input.timeframe('5', "TMO 2", options = ['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'], group = "Time Frames")
TimeFrame3 = input.timeframe('30', "TMO 3", options = ['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'], group = "Time Frames")
tmolength = input.int(14,title = "Length", group = "Settings")
calcLength = input(5, title = "Calc Length", group = "Settings")
smoothLength = input(3, title = "Smooth Length", group = "Settings")
dotsize = input(3, title = "Signal Size", group = "Signal Settings")
offset = input(2,title = "Signal Offset", group = "Signal Settings")
oblevel = input(9,title = "OB Extreme Threshold", group = "Signal Settings")
oslevel = input(-9,title = "OS Extreme Threshold", group = "Signal Settings")
ShowTMO1 = input(defval = true, title = "Show TMO 1", group = "True Momentum Oscillator 1")
TMO1Bullish = input(#27c22e, title = "Bullish", group = "True Momentum Oscillator 1")
TMO1Bearish = input(#ff0000, title = "Bearish", group = "True Momentum Oscillator 1")
TMO1CloudUp = input(color.new(#27c22e, 75), title = "Fill Bullish", group = "True Momentum Oscillator 1")
TMO1CloudDn = input(color.new(#ff0000, 75), title = "Fill Bearish", group = "True Momentum Oscillator 1")
ShowTMO2 = input(defval = true, title = "Show TMO 2", group = "True Momentum Oscillator 2")
TMO2Bullish = input(#27c22e, title = "Bullish", group = "True Momentum Oscillator 2")
TMO2Bearish = input(#ff0000, title = "Bearish", group = "True Momentum Oscillator 2")
TMO2CloudUp = input(color.new(#27c22e, 75), title = "Fill Bullish", group = "True Momentum Oscillator 2")
TMO2CloudDn = input(color.new(#ff0000, 75), title = "Fill Bearish", group = "True Momentum Oscillator 2")
ShowTMO3 = input(defval=true, title = "Show TMO 3", group = "True Momentum Oscillator 3")
TMO3Bullish = input(#006400, title = "Bullish", group = "True Momentum Oscillator 3")
TMO3Bearish = input(#800000, title = "Bearish", group = "True Momentum Oscillator 3")
TMO3CloudUp = input(color.new(#27c22e, 75), title = "Fill Bullish", group = "True Momentum Oscillator 3")
TMO3CloudDn = input(color.new(#ff0000, 75), title = "Fill Bearish", group = "True Momentum Oscillator 3")
ShowTMOS1 = input(defval = true, title = "Show TMO 1 Signals", group = "True Momentum Oscillator 1 Signals")
ShowTMOS11 = input(defval = false, title = "Show TMO 1 Signals (Extremes Only)", group = "True Momentum Oscillator 1 Signals")
TMO1UpSignal = input(#27c22e, title = "TMO 1 Up Signal", group = "True Momentum Oscillator 1 Signals")
TMO1DnSignal = input(#ff0000, title = "TMO 1 Down Signal", group = "True Momentum Oscillator 1 Signals")
TMO1CharUp = input('▴',title = "TMO 1 Up", group = "True Momentum Oscillator 1 Signals")
TMO1CharDn = input('▾',title = "TMO 1 Down", group = "True Momentum Oscillator 1 Signals")
ShowTMOS2 = input(defval = true, title = "Show TMO 2 Signals", group = "True Momentum Oscillator 2 Signals")
ShowTMOS22 = input(defval = false, title = "Show TMO 2 Signals (Extremes Only)", group = "True Momentum Oscillator 2 Signals")
TMO2UpSignal = input(#006400, title = "TMO 2 Up Signal", group = "True Momentum Oscillator 2 Signals")
TMO2DnSignal = input(#800000, title = "TMO 2 Down Signal", group = "True Momentum Oscillator 2 Signals")
TMO2CharUp = input('▴',title = "TMO 2 Up", group = "True Momentum Oscillator 2 Signals")
TMO2CharDn = input('▾',title = "TMO 2 Down", group = "True Momentum Oscillator 2 Signals")
ShowUpperL = input(defval = false, title = "Show OB Line", group = "Oscillator Settings")
UpperLineColor = input(#ff0000, title = "OB Line Color", group = "Oscillator Settings")
ShowLowerL = input(defval = false, title = "Show OS Line", group = "Oscillator Settings")
LowerLineColor = input(#27c22e, title = "OS Line Color", group = "Oscillator Settings")
ShowObLine = input(defval = true, title = "Show OB Cutoff Line", group = "Oscillator Settings")
ObLineColor = input(#ff0000, title = "OB Cutoff Line Color", group = "Oscillator Settings")
ShowOsLine = input(defval = true, title = "Show OS Cutoff Line", group = "Oscillator Settings")
OsLineColor = input(#27c22e, title = "OS Cutoff Line Color", group = "Oscillator Settings")
ShowObFill = input(defval = true, title = "Show OB Fill", group = "Oscillator Settings")
OBFillColor = input(color.new(#ff0000, 75), title = "OB Fill Color", group = "Oscillator Settings")
ShowOsFill = input(defval = true, title = "Show OS Fill", group = "Oscillator Settings")
OSFillColor = input(color.new(#27c22e, 75), title = "OS Fill Color", group = "Oscillator Settings")
ShowZeroLine = input(defval = true, title = "Show Zero Line", group = "Oscillator Settings")
ZeroLineColor = input(color.new(#2a2e39, 0), title = "Zero Line Color", group = "Oscillator Settings")
// TMO 1 Calculations
srcc1 = request.security(syminfo.tickerid, TimeFrame1, close)
srco1 = request.security(syminfo.tickerid, TimeFrame1, open)
o1 = srco1
c1 = srcc1
data1 = 0
for i1 = 1 to tmolength -1
if c1 > o1[i1]
data1 := data1 + 1
if c1 < o1[i1]
data1 := data1 - 1
EMA1 = ta.ema(data1,calcLength)
Main1 = request.security(syminfo.tickerid, TimeFrame1, ta.ema(EMA1, smoothLength))
Signal1 = request.security(syminfo.tickerid, TimeFrame1, ta.ema(Main1, smoothLength))
// TMO 2 Calculations
srcc2 = request.security(syminfo.tickerid, TimeFrame2, close)
srco2 = request.security(syminfo.tickerid, TimeFrame2, open)
o2 = srco2
c2 = srcc2
data2 = 0
for i2 = 1 to tmolength -1
if c2 > o2[i2]
data2 := data2 + 1
if c2 < o2[i2]
data2 := data2 - 1
EMA2 = ta.ema(data2,calcLength)
Main2 = request.security(syminfo.tickerid, TimeFrame2, ta.ema(EMA2, smoothLength))
Signal2 = request.security(syminfo.tickerid, TimeFrame2, ta.ema(Main2, smoothLength))
// TMO 3 Calculations
srcc3 = request.security(syminfo.tickerid, TimeFrame3, close)
srco3 = request.security(syminfo.tickerid, TimeFrame3, open)
o3 = srco3
c3 = srcc3
data3 = 0
for i3 = 1 to tmolength -1
if c3 > o3[i3]
data3 := data3 + 1
if c3 < o3[i3]
data3 := data3 - 1
EMA3 = ta.ema(data3,calcLength)
Main3 = request.security(syminfo.tickerid, TimeFrame3, ta.ema(EMA3, smoothLength))
Signal3 = request.security(syminfo.tickerid, TimeFrame3, ta.ema(Main3, smoothLength))
// TMO Scalper Signals
mainln = (15*Main1/tmolength)
signaln = (15*Signal1/tmolength)
mainln2 = (15*Main2/tmolength)
signaln2 = (15*Signal2/tmolength)
mainln3 = (15*Main3/tmolength)
signaln3 = (15*Signal3/tmolength)
// TMO 1 Bullish Signal
plotchar(ShowTMOS1 and ta.crossover(mainln, signaln) and (mainln2 > signaln2) ? (mainln-offset) : na, title = "TMO 1 Up Signal", char = TMO1CharUp, location = location.absolute, size = size.small, color = TMO1UpSignal, editable = false)
// TMO 1 Bearish Signal
plotchar(ShowTMOS1 and ta.crossover(signaln, mainln) and (mainln2 < signaln2) ? (mainln+offset) : na, title = "TMO 1 Down Signal", char = TMO1CharDn, location = location.absolute, size = size.small, color = TMO1DnSignal, editable = false)
// TMO 1 Bullish Signal (Oversolds Only)
plotchar(ShowTMOS11 and ta.crossover(mainln, signaln) and (mainln < oslevel) and (mainln2 > signaln2) ? (mainln-offset) : na, title = "TMO 1 Up (Oversolds Only)", char = TMO1CharUp, location = location.absolute, size = size.small, color = TMO1UpSignal, editable = false)
// TMO 1 Bearish Signal (Overboughts Only)
plotchar(ShowTMOS11 and ta.crossover(signaln, mainln) and (mainln > oblevel) and (mainln2 < signaln2) ? (mainln+offset) : na, title = "TMO 1 Down (Overboughts Only)", char = TMO1CharDn, location = location.absolute, size = size.small, color = TMO1DnSignal, editable = false)
// TMO 2 Bullish Signal
plotchar(ShowTMOS2 and ta.crossover(mainln2, signaln2) and (mainln3 > signaln3) ? (mainln2-offset) : na, title = "TMO 2 Up Signal", char = TMO2CharUp, location = location.absolute, size = size.normal, color = TMO2UpSignal, editable = false)
// TMO 2 Bearish Signal
plotchar(ShowTMOS2 and ta.crossover(signaln2, mainln2) and (mainln3 < signaln3) ? (mainln2+offset) : na, title = "TMO 2 Down Signal", char = TMO2CharDn, location = location.absolute, size = size.normal, color = TMO2DnSignal, editable = false)
// TMO 2 Bullish Signal (Oversolds Only)
plotchar(ShowTMOS22 and ta.crossover(mainln2, signaln2) and (mainln2 < oslevel) and (mainln3 > signaln3) ? (mainln2-offset) : na, title = "TMO 2 Up (Oversolds Only)", char = TMO2CharUp, location = location.absolute, size = size.normal, color = TMO2UpSignal, editable = false)
// TMO 2 Bearish Signal (Overboughts Only)
plotchar(ShowTMOS22 and ta.crossover(signaln2, mainln2) and (mainln2 > oblevel) and (mainln3 < signaln3) ? (mainln2+offset) : na, title = "TMO 2 Down (Overboughts Only)", char = TMO2CharDn, location = location.absolute, size = size.normal, color = TMO2DnSignal, editable = false)
// TMO 1 Plots
color1 = ShowTMO1 and Main1 > Signal1 ? TMO1Bullish : ShowTMO1 ? TMO1Bearish : na
mainLine1 = plot(15*Main1/tmolength, title="TMO 1 Main", color=color1, editable = false)
signalLine1 = plot(15*Signal1/tmolength, title="TMO 1 Signal", color=color1, editable = false)
cloudcolor1 = ShowTMO1 and Main1 > Signal1 ? TMO1CloudUp : ShowTMO1 ? TMO1CloudDn : na
fill(mainLine1, signalLine1, title="TMO 1 Fill", color=cloudcolor1, editable = false)
// TMO 2 Plots
color2 = ShowTMO2 and Main2 > Signal2 ? TMO2Bullish : ShowTMO2 ? TMO2Bearish : na
mainLine2 = plot(15*Main2/tmolength, title="TMO 2 Main", color=color2, editable = false)
signalLine2 = plot(15*Signal2/tmolength, title="TMO 2 Signal", color=color2, editable = false)
cloudcolor2 = ShowTMO2 and Main2 > Signal2 ? TMO2CloudUp : ShowTMO2 ? TMO2CloudDn : na
fill(mainLine2, signalLine2, title="TMO 2 Fill", color=cloudcolor2, editable = false)
// TMO 3 Plots
color3 = ShowTMO3 and Main3 > Signal3 ? TMO3Bullish : ShowTMO3 ? TMO3Bearish : na
mainLine3 = plot(15*Main3/tmolength, title="TMO 3 Main", color=color3, editable = false)
signalLine3 = plot(15*Signal3/tmolength, title="TMO 3 Signal", color=color3, editable = false)
cloudcolor3 = ShowTMO3 and Main3 > Signal3 ? TMO3CloudUp : ShowTMO3 ? TMO3CloudDn : na
fill(mainLine3, signalLine3, title="TMO 3 Fill", color=cloudcolor3, editable = false)
// Background & Colors
upperlcolor = ShowUpperL ? UpperLineColor : na
upper = hline(10, title="OB Line", color= upperlcolor, linestyle=hline.style_solid, editable = false)
lowerlcolor = ShowLowerL ? LowerLineColor : na
lower = hline(-10, title="OS Line", color= lowerlcolor, linestyle=hline.style_solid, editable = false)
obcolor = ShowObLine ? ObLineColor : na
ob = hline(math.round(15), title="OB Cutoff Line", color= obcolor, linestyle=hline.style_solid, editable = false)
oscolor = ShowOsLine ? OsLineColor : na
os = hline(-math.round(15), title="OS Cutoff Line", color= oscolor, linestyle=hline.style_solid, editable = false)
zerol = ShowZeroLine ? ZeroLineColor : na
zero = hline(0, title="Zero Line", color=zerol, linestyle=hline.style_solid, editable = false)
fill(ob, upper, title="OB Fill", color= color.new(#ff0000, 75), editable = false)
fill(os, lower, title="OS Fill", color= color.new(#27c22e, 75), editable = false) |
Line Break Heikin Ashi | https://www.tradingview.com/script/shd9G15i-Line-Break-Heikin-Ashi/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("Line Break Heikin Ashi", "LBHA", overlay = true)
green = input.color(color.new(#26a69a, 0), "Bullish Candle Color")
red = input.color(color.new(#ef5350, 0), "Bearish Candle Color")
ha_close(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = (Open + High + Low + Close) / 4
out = enable == true ? ha_close : Close
ha_open(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_open = float(na)
ha_close = ha_close(Open, High, Low, Close)
ha_open := na(ha_open[1]) ? (Open + Close) / 2 : (nz(ha_open[1]) + nz(ha_close[1])) / 2
out = enable == true ? ha_open : Open
ha_high(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = ha_close(Open, High, Low, Close)
ha_open = ha_open(Open, High, Low, Close)
ha_high = math.max(High, math.max(ha_open, ha_close))
out = enable == true ? ha_high : High
ha_low(float Open = open, float High = high, float Low = low, float Close = close, bool enable = true) =>
ha_close = ha_close(Open, High, Low, Close)
ha_open = ha_open(Open, High, Low, Close)
ha_low = math.min(Low, math.min(ha_open, ha_close))
out = enable == true ? ha_low : Low
Open = ha_open(close[1], ta.highest(close, 1), ta.lowest(close, 1), close)
High = ha_high(close[1], ta.highest(close, 1), ta.lowest(close, 1), close)
Low = ha_low(close[1], ta.highest(close, 1), ta.lowest(close, 1), close)
Close = ha_close(close[1], ta.highest(close, 1), ta.lowest(close, 1), close)
ha_score = Open < Close ? green : red
plotcandle(Open, High, Low, Close, "Test", ha_score, ha_score, true, bordercolor = ha_score)
|
Improved Chaikin Money Flow | https://www.tradingview.com/script/xrakkNuS-Improved-Chaikin-Money-Flow/ | Morogan | https://www.tradingview.com/u/Morogan/ | 121 | 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/
// © Morogan
//@version=5
indicator(title="Improved Chaikin Money Flow", shorttitle="ICMF", format=format.price, timeframe="D", timeframe_gaps=true, precision=2)
length = input.int(21, minval=1)
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
h = open < low[1] and close < close[1] ? close[1] : high
l = open > high[1] and close > close[1] ? close[1] : low
ad = close==h and close==l or h==l ? 0 : ((2*close-l-h)/(h-l))*volume
mf = math.sum(ad, length) / math.sum(volume, length)
cmf = 100 * mf
plot(cmf, "CMF", color=(cmf > 0 ? color.green : color.red), style=plot.style_area)
hline(0, color=color.new(color.white, 25), title="Zero", linestyle=hline.style_solid) |
Opening Range with Infinite Price Targets | https://www.tradingview.com/script/TNrkhVQk-Opening-Range-with-Infinite-Price-Targets/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 238 | 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/
// © SamRecio
//@version=5
indicator("Opening Range with Infinite Price Targets",shorttitle = "|OR|", overlay = true, max_labels_count = 500, max_lines_count = 500, max_bars_back = 5000)
tog_hist = input.bool(false,"Display Historical Data?", inline = "1", group = "Settings")
start_hour = input.int(9,minval = 0,maxval = 23, group = "Range Time", title ="Start Time:", inline = "1")
start_min = input.int(30,minval = 0,maxval = 59, group = "Range Time", title ="", inline = "1")
end_hour = input.int(9,minval = 0,maxval = 23, group = "Range Time", title = "End Time: ", inline = "2")
end_min = input.int(45,minval = 0,maxval = 59, group = "Range Time", title ="", inline = "2")
target_p = input.float(50,title = " Price Target %", minval = 0, tooltip = "Percent(%) of Range to use for Price Targets.")*0.01
color1 = input.color(#0c3299, title = "High", group = "Colors", inline = "1")
color2 = input.color(#0c3299, title = "Low", group = "Colors", inline = "1")
color3 = input.color(#3179f5, title = "Mean", group = "Colors", inline = "1")
colorf = input.color(color.new(#3179f5,95), title = "Fill", group = "Colors", inline = "1")
colorg = color.rgb(0,255,0)
colorr = color.rgb(255,0,0)
color4 = input.color(#bbd9fb, title = "Targets", group = "Colors", inline = "2")
start_time = start_hour + (start_min*0.01)
end_time = end_hour + (end_min*0.01)
t_time = hour + (minute*0.01)
get_or(_start_time,_end_time) =>
var float or_hi = na
var float or_lo = na
or_t = (t_time >= start_time and t_time < end_time)
or_f = or_t == false
or_o = or_t and not or_t[1]
if or_o
or_hi := high
or_lo := low
if or_t and high > or_hi
or_hi := high
if or_t and low < or_lo
or_lo := low
[or_hi,or_lo,or_t,or_f,or_o]
[or_high,or_low,or_true,or_false,or_open] = get_or(start_time,end_time)
or_range = or_high - or_low
or_mean = math.avg(or_high,or_low)
or_end = or_false and (or_false[1] == false)
eod = (ta.valuewhen(or_open,bar_index,0) - ta.valuewhen(or_end,bar_index,1)) - 1
ba_or = ta.valuewhen(or_end,bar_index,0)
var long_count = 0
var short_count = 0
if or_open
long_count := 0
short_count := 0
pt_step = or_range*target_p
pt_1 = or_high + pt_step
pt_1b = or_low - pt_step
pt_2 = or_high + pt_step*2
pt_2b = or_low - pt_step*2
var float pt_x1 = na
var float pt_x2 = na
var int scount = na
var int lcount = na
var line l1 = na
var line l2 = na
var line l3 = na
var line l4 = na
var line l5 = na
var line l6 = na
var line l7 = na
var line lx = na
var label lab1 = na
var label lab2 = na
var label pt1 = na
var label pt2 = na
var label pt3 = na
var label pt4 = na
var label ptx = na
if or_true
scount := 1
lcount := 1
if or_end
pt_x1 := or_high + pt_step
pt_x2 := or_low - pt_step
if tog_hist == false
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(a_allLabels, i))
l1 := line.new(ba_or,or_high,ba_or + eod, or_high, color = color1, width = 2)
l2 := line.new(ba_or,or_low,ba_or + eod, or_low, color = color2, width = 2)
l3 := line.new(ba_or,or_mean,ba_or + eod, or_mean, color = color3)
l4 := line.new(ba_or,pt_x1,ba_or + eod, pt_x1, color = color4, style = line.style_dotted)
pt1 := label.new(ba_or + eod + 1, pt_x1, style = label.style_label_left, text = "PT1", tooltip = str.tostring(str.format("{0, number, currency}",math.round(pt_x1,2))), textcolor = color4, color = color.new(color4,100), size = size.tiny)
l5 := line.new(ba_or,pt_x2,ba_or + eod, pt_x2, color = color4, style = line.style_dotted)
pt2 := label.new(ba_or + eod + 1, pt_x2, style = label.style_label_left, text = "PT1", tooltip = str.tostring(str.format("{0, number, currency}",math.round(pt_x2,2))), textcolor = color4, color = color.new(color4,100), size = size.tiny)
linefill.new(l1, l2,colorf)
//One a Day Alerts
alertcondition(close > or_high and close[1] <= or_high and or_false and long_count == 0,title = "First Break Above Range")
alertcondition(close < or_low and close[1] >= or_low and or_false and short_count == 0, title = "First Break Below Range")
//Breakout Alerts
alertcondition(close > or_high and close[1] <= or_high and or_false,title = "Break Above Range")
alertcondition(close < or_low and close[1] >= or_low and or_false, title = "Break Below Range")
//BREAKOUT LABELS///////////////////////////////////////////////////////////////
if close > or_high and close[1] <= or_high and or_false and long_count == 0
lab1 := label.new(bar_index,or_high, style = label.style_triangleup, size = size.auto, color = colorg, yloc = yloc.abovebar)
long_count := 1
if close < or_low and close[1] >= or_low and or_false and short_count == 0
lab2 := label.new(bar_index,or_low, style = label.style_triangledown, size = size.auto, color = colorr, yloc = yloc.belowbar)
short_count := 1
////////////////////////////////////////////////////////////////////////////////
//To infinity and beyond!//////////////////////////////////////////////////////
alertcondition(close > pt_x1 and or_false, title = "New Long PT Hit")
if close > pt_x1 and or_false
lcount := math.floor((close - or_high)/pt_step) + 1
for i = (lcount[1] + 1) to lcount
pt_x1 := or_high + (i*pt_step)
lx := line.new(bar_index,pt_x1,ba_or + eod, pt_x1, color = color4)
ptx := label.new(ba_or + eod + 1,pt_x1, style = label.style_label_left, text = "PT" + str.tostring(i), tooltip = str.tostring(str.format("{0, number, currency}",math.round(pt_x1,2))), textcolor = color4, color = color.new(color4,100), size = size.tiny)
alertcondition(close < pt_x2 and or_false, title = "New Short PT Hit")
if close < pt_x2 and or_false
scount := math.floor((or_low - close)/pt_step) + 1
for i = (scount[1] + 1) to scount
pt_x2 := or_low - (i*pt_step)
lx := line.new(bar_index,pt_x2, ba_or + eod, pt_x2, color = color4)
ptx := label.new(ba_or + eod + 1,pt_x2, style = label.style_label_left, text = "PT" + str.tostring(i), tooltip = str.tostring(str.format("{0, number, currency}",math.round(pt_x2,2))), textcolor = color4, color = color.new(color4,100), size = size.tiny)
plot(or_high, title = "OR High", display = display.none, editable = false)
plot(or_mean, title = "OR Mean", display = display.none, editable = false)
plot(or_low, title = "OR Low", display = display.none, editable = false) |
swami_rsi | https://www.tradingview.com/script/oTfNZshU-swami-rsi/ | palitoj_endthen | https://www.tradingview.com/u/palitoj_endthen/ | 59 | 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 = 'ehlers_swami_rsi', shorttitle = 'rsi', overlay = false)
// input
apply_hp_filter = input.bool(defval = false, title = 'High-pass Filter', group = 'Options', tooltip = 'Determines whether to apply high-pass filter')
show_initial = input.bool(defval = false, title = 'Initial Level', group = 'Options', tooltip = 'Determines whether to display initial level')
show_confirmation = input.bool(defval = false, title = 'Confirmation Line', group = 'Options', tooltip = 'Determines whether to display confirmation line')
show_continuation = input.bool(defval = false, title = 'Continuation Line', group = 'Options', tooltip = 'Determines whether to display continuation line')
hp_period = input.int(defval = 48, title = 'High-pass Period', group = 'Value')
// variable
alpha1 = 0.00
hp = 0.00
a1 = 0.00
b1 = 0.00
c1 = 0.00
c2 = 0.00
c3 = 0.00
filt = 0.00
lookback = 0
close_up = 0.00
close_down = 0.00
denom = 0.00
// arrays
var ratio1 = array.new_float(50)
var ratio2 = array.new_float(50)
var rsi1 = array.new_float(50)
var rsi2 = array.new_float(50)
var rsi3 = array.new_float(50)
// highpass filter cyclic components whose periods are shorter than 48 bars
pi = 2*math.asin(1)
alpha1 := (math.cos(.707*2*pi/hp_period) + math.sin(.707*2*pi/hp_period) - 1) / math.cos(.707*2*pi/hp_period)
hp := (1-alpha1/2)*(1-alpha1/2)*(close-2*nz(close[1])+nz(close[2]))+2*(1-alpha1)*nz(hp[1])-(1-alpha1)*(1-alpha1)*nz(hp[2])
// smooth with a Super Smoother Filter
a1 := math.exp(-1.414*3.14159/10)
b1 := 2*a1*math.cos(1.414*180/10)
c2 := b1
c3 := -a1*a1
c1 := 1-c2-c3
filt := c1*((apply_hp_filter ? hp : close) + (apply_hp_filter ? hp[1] : close[1]))/2+c2*nz(filt[1])+c3*nz(filt[2])
// swami-rsi
for lookback = 2 to 48
// range includes half the shortest periods of interest
array.set(ratio2, lookback, nz(array.get(ratio1, lookback)))
array.set(rsi3, lookback, nz(array.get(rsi2, lookback)))
array.set(rsi2, lookback, nz(array.get(rsi1, lookback)))
close_up := 0.0
close_down := 0.0
for count = 0 to lookback-1
if filt[count] > filt[count+1]
close_up := close_up+(filt[count]-filt[count+1])
if filt[count] < filt[count+1]
close_down := close_down+(filt[count+1]-filt[count])
denom := close_up+close_down
if denom != 0
array.set(ratio1, lookback, close_up/denom)
// smooth rsi with a 10 bar super smoother
array.set(rsi1, lookback, c1*(nz(array.get(ratio1, lookback))+nz(array.get(ratio2, lookback)))/2+c2*nz(array.get(rsi2, lookback))+c3*nz(array.get(rsi3, lookback)))
// ensure rsi doesnt fall outside color limits
if nz(array.get(rsi1, lookback)) < 0
array.set(rsi1, lookback, 0)
if nz(array.get(rsi1, lookback)) > 1
array.set(rsi1, lookback, 1)
// visualize as heatmap
col(n)=>
if array.get(rsi1,n) > .5
color.rgb(255*(2-2*array.get(rsi1, n)), 255, 0)
else if array.get(rsi1, n) < .5
color.rgb(255, 2*255*array.get(rsi1, n), 0)
n = 0
n := 1
plot(1, color = col(n), linewidth = 8)
n := 2
plot(2, color = col(n), linewidth = 8)
n := 4
plot(4, color = col(n), linewidth = 8)
n := 6
plot(6, color = col(n), linewidth = 8)
n := 8
plot(8, color = col(n), linewidth = 8)
n := 10
plot(10, color = col(n), linewidth = 8)
n := 11
plot(11, color = col(n), linewidth = 8)
n := 12
plot(12, color = col(n), linewidth = 8)
n := 14
plot(14, color = col(n), linewidth = 8)
n := 16
plot(16, color = col(n), linewidth = 8)
n := 18
plot(18, color = col(n), linewidth = 8)
n := 20
plot(20, color = col(n), linewidth = 8)
n := 21
plot(21, color = col(n), linewidth = 8)
n := 22
plot(22, color = col(n), linewidth = 8)
n := 24
plot(24, color = col(n), linewidth = 8)
n := 26
plot(26, color = col(n), linewidth = 8)
n := 28
plot(28, color = col(n), linewidth = 8)
n := 30
plot(30, color = col(n), linewidth = 8)
n := 31
plot(31, color = col(n), linewidth = 8)
n := 32
plot(32, color = col(n), linewidth = 8)
n := 34
plot(34, color = col(n), linewidth = 8)
n := 36
plot(36, color = col(n), linewidth = 8)
n := 38
plot(38, color = col(n), linewidth = 8)
n := 40
plot(40, color = col(n), linewidth = 8)
n := 41
plot(41, color = col(n), linewidth = 8)
n := 42
plot(42, color = col(n), linewidth = 8)
n := 44
plot(44, color = col(n), linewidth = 8)
n := 46
plot(46, color = col(n), linewidth = 8)
n := 48
plot(48, color = col(n), linewidth = 8)
// confrimation line
line.new((bar_index-4), 3, (bar_index+2), 3, color = show_initial ? color.blue : na, width = 2)
line.new((bar_index-4), 25, (bar_index+2), 25, color = show_confirmation ? color.blue : na, width = 2)
line.new((bar_index-4), 46, (bar_index+2), 46, color = show_continuation ? color.blue : na, width = 2) |
CROCE | https://www.tradingview.com/script/7udcXOde/ | formy76 | https://www.tradingview.com/u/formy76/ | 10 | 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/
//
//
// This is a rough version of the Return on Capital Employed
//@version=4
study("CROCE", precision=2)
//
var fcf_ttm = float(na)
var fcf_q1 = 0.0
var fcf_q2 = 0.0
var fcf_q3 = 0.0
var fcf_q4 = 0.0
fcf_series_filled = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FQ", false)
fcf_series_fq = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FQ", true)
fcf_series_fy = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FY", false)
if not na(fcf_series_fq[0])
fcf_q4 := fcf_q3
fcf_q3 := fcf_q2
fcf_q2 := fcf_q1
fcf_q1 := fcf_series_fq[0]
fcf_ttm := fcf_q1 + fcf_q2 + fcf_q3 + fcf_q4
else if na(fcf_series_filled[0]) and not na(fcf_series_fy[0])
fcf_ttm := fcf_series_fy[0]
cur_assets = na(financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FQ")) ? financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FY") : financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FQ")
cur_liabilities = na(financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")) ? financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FY") : financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")
cash_stinv = na(financial(syminfo.tickerid, "CASH_N_SHORT_TERM_INVEST", "FQ")) ? financial(syminfo.tickerid, "CASH_N_SHORT_TERM_INVEST", "FY") : financial(syminfo.tickerid, "CASH_N_SHORT_TERM_INVEST", "FQ")
st_debt = na(financial(syminfo.tickerid, "SHORT_TERM_DEBT", "FQ")) ? financial(syminfo.tickerid, "SHORT_TERM_DEBT", "FY") : financial(syminfo.tickerid, "SHORT_TERM_DEBT", "FQ")
ppe = na(financial(syminfo.tickerid, "PPE_TOTAL_NET", "FQ")) ? financial(syminfo.tickerid, "PPE_TOTAL_NET", "FY") : financial(syminfo.tickerid, "PPE_TOTAL_NET", "FQ")
debt = na(financial(syminfo.tickerid, "TOTAL_DEBT", "FQ")) ? financial(syminfo.tickerid, "TOTAL_DEBT", "FY") : financial(syminfo.tickerid, "TOTAL_DEBT", "FQ")
min_interest = na(financial(syminfo.tickerid, "MINORITY_INTEREST", "FQ")) ? financial(syminfo.tickerid, "MINORITY_INTEREST", "FY") : financial(syminfo.tickerid, "MINORITY_INTEREST", "FQ")
cash = na(financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FQ")) ? financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FY") : financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FQ")
tot_shares = na(financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")) ? financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FY") : financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
capital_employed = max(0 , ((cur_assets[0]-cash_stinv[0]) - (cur_liabilities[0]-st_debt))) + ppe[0]
croce = (fcf_ttm / capital_employed)*100
mkt_cap = tot_shares * close
ev = mkt_cap + debt + min_interest - cash
cash_yield = (fcf_ttm / ev)*100
c = if croce >= 25
color.new(color.green, 75)
else if croce > 0
color.new(color.yellow, 75)
else
color.new(color.red, 75)
plot(croce, color=c, style=plot.style_area, histbase=0)
plot(cash_yield, linewidth=2)
|
Moving Average - fade when crossed [cajole] | https://www.tradingview.com/script/oObu892x-Moving-Average-fade-when-crossed-cajole/ | cajole | https://www.tradingview.com/u/cajole/ | 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/
// A moving average that fades away (wanes) when crossed, then grows again (waxes) afterwards.
// © cajole
// v34 - published
//@version=5
indicator('Moving Average - fade when crossed [cajole]', shorttitle= "Fade MA [cj]", overlay=true)
// INPUTS
src = input(close, "Source", inline='MA')
maType = input.string("EMA", "", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], inline='MA')
waneRate = input.float(50, 'Fade rate [alpha%/bar]', tooltip='How quickly should the line fade when crossed repeatedly?')
waxRate = input.float(5 , 'Wax rate [alpha%/bar]', tooltip='How quickly should the MA become visible again?')
ma_length = input.int(13, "Length", minval=1, inline='MA')
ma_color = input(#fffd74, "", inline="MA")
waxwane(ma, prev_transp) =>
crossed = (ma < high and ma > low) // cross bar/wick
or (ma[1] > high[1] and ma < low ) // gap up
or (ma[1] < low[1] and ma > high) // gap down
new_transp = crossed ? math.min(100, nz(prev_transp) + waneRate)
: math.max( 0, nz(prev_transp) - waxRate)
ma(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
na
ma0 = ma(src, ma_length, maType)
transp = 0.
transp := waxwane(ma0, transp[1])
plot(ma0, color = color.new(ma_color, transp), title="Fade-MA")
// Text label on the fast EMA (last completed bar).
labelThreshold = input.int(90, minval=1, title="Add label if transp. <", inline= "label",
tooltip='For labels at right only.')
labelOffset = input.int(10, minval=1, title="with offset", inline= "label",
tooltip='For labels at right only.')
vline(BarIndex, Color, LineStyle, LineWidth) =>
line.new(BarIndex, low, BarIndex, high, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)
sessionClosed = barstate.islast ? (timenow > time_close ? 1 : 0) : 1
lastcEMA = sessionClosed ? ma0 : ma0[1]
this_bar_xloc = sessionClosed ? bar_index : bar_index - 1
this_bar_yloc = lastcEMA > high ? yloc.abovebar : yloc.belowbar
emaLabStr0 = str.tostring(math.round_to_mintick(lastcEMA)) + ' (' + str.tostring(ma_length) + ') '
emaLabStr1 = lastcEMA > high ? emaLabStr0 + "\n↓" : "↑\n" + emaLabStr0
var emaLabel = label.new(bar_index, na, na, xloc.bar_index, yloc.abovebar,
color(na), label.style_none, ma_color, size.normal, text.align_center)
var fEMAline = line.new(na, na, na, na)
line.delete(fEMAline), label.delete(emaLabel)
if transp[0] < labelThreshold
label.set_yloc(emaLabel, this_bar_yloc), label.set_x( emaLabel, this_bar_xloc)
emaLabel := label.new(bar_index + labelOffset,
lastcEMA,style=label.style_none, textcolor=color.new(ma_color, 20),
textalign=text.align_right, text=str.tostring(emaLabStr0), xloc=xloc.bar_index)
fEMAline := line.new(this_bar_xloc, lastcEMA, this_bar_xloc + labelOffset, lastcEMA,
color=ma_color, style=line.style_dotted, extend=extend.right, width=1)
|
[MAD] Fibonacci retracement | https://www.tradingview.com/script/imZaWvs9-MAD-Fibonacci-retracement/ | djmad | https://www.tradingview.com/u/djmad/ | 408 | 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/
// © djmad
//@version=5
indicator('[MAD] Fib retracement', overlay=true)
int Starttime = input.time(timestamp("2020-02-19"),title= "B O T T O M - L E F T", inline="B O T T O M - L E F T", confirm = true,group='Line 1')
var Bottom = input.price(defval=100, title= "B O T T O M L E F T", inline="B O T T O M - L E F T", confirm = true,group='Line 1')
var Top = input.price(defval=100, title='T O P',confirm = true)
var tracking = input.bool(false,"Active Tracking",group="Global", inline="11a")
var fibreverse = input.bool(false,'Reverse Fib',group="Global", inline="11a")
var decimals_price = input.int(2,"Price decimals",group="decimals trimming",inline="1")
var decimals_percent = input.int(2,"Percent decimals",group="decimals trimming",inline="1")
textcolor1 = input.color(color.white,"Text color",group="Global",inline="1a")
size1 = input.string(size.small,"size", options = [size.tiny,size.small,size.normal,size.large],group="Global",inline="1a")
Linecolor_Global = input.color(color.white,"Linecolor",inline="1a")
var transp = input.int(60,"Transparency fillings",group="Fillings")
fib_01 = input.float(1.0 ,"Level 0",group="Fiblevels 01",step=0.001)
fib_02 = input.float(0.786 ,"Level 1",group="Fiblevels 01",step=0.001,inline="1a")
fib_03 = input.float(0.65 ,"Level 2",group="Fiblevels 23",step=0.001 )
fib_04 = input.float(0.618 ,"Level 3",group="Fiblevels 23",step=0.001,inline="1b")
fib_05 = input.float(0.5 ,"Level 4",group="Fiblevels 4",step=0.001)
fib_06 = input.float(0.382 ,"Level 5",group="Fiblevels 56",step=0.001 )
fib_07 = input.float(0.35 ,"Level 6",group="Fiblevels 56",step=0.001,inline="1c")
fib_08 = input.float(0.236 ,"Level 7",group="Fiblevels 78",step=0.001 )
fib_09 = input.float(0.0 ,"Level 8",group="Fiblevels 78",step=0.001,inline="1d")
channels = array.new<float>(0,na)
if fibreverse
channels := array.from(
fib_01,fib_02,fib_03,fib_04,fib_05,fib_06,fib_07,fib_08,fib_09
)
else
channels := array.from(
1-fib_09,1-fib_08,1-fib_07,1-fib_06,1-fib_05,1-fib_04,1-fib_03,1-fib_02,1-fib_01
)
color1=color.new(input.color(color.rgb(175, 76, 76, 0),"Fill-Color 0-1",group="Fiblevels 01",inline="1a"),transp)
color2=color.new(input.color(color.rgb(175, 172, 76, 0),"Fill-Color 2-3",group="Fiblevels 23",inline="1b"),transp)
color3=color.new(input.color(color.rgb(175, 172, 76, 0),"Fill-Color 5-6",group="Fiblevels 56",inline="1c"),transp)
color4=color.new(input.color(color.rgb(76, 175, 79, 0),"Fill-Color 7-8",group="Fiblevels 78",inline="1d"),transp)
bool ChartisLog = input.bool(false,'Logarithmic',group='Global',inline='11a')
if tracking and time > Starttime
Top := Top < high ? high:Top
Bottom := Bottom > low ? low:Bottom
linearray = array.new_line(0,na)
shifting(_value) =>
var string output = ""
output := ""
for i = 0 to _value by 3
output := output + " "
float LOGICAL_OFFSET = 4
float COORD_OFFSET = 0.0001
f_round(_val, decimals) =>
// Rounds _val to _decimals places.
_p = math.pow(10, decimals)
math.round(math.abs(_val) * _p) / _p * math.sign(_val)
fromLog(series float value) =>
float exponent = math.abs(value)
float product = math.pow(10, exponent - LOGICAL_OFFSET) - COORD_OFFSET
float result = exponent < 1e-8 ? 0 : value < 0 ? - product : product
toLog(series float value) =>
float exponent = math.abs(value)
float product = math.log10(exponent + COORD_OFFSET) + LOGICAL_OFFSET
float result = exponent < 1e-8 ? 0 : value < 0 ? - product : product
f_fibcalc(Top, Bottom, channels, ChartisLog) =>
output = array.new<float>()
Diff = Top-Bottom
for i = 0 to array.size(channels) -1
if ChartisLog
array.push(output, fromLog( toLog(Bottom) + (toLog(Top)-toLog(Bottom)) * array.get(channels,i) ))
else
array.push(output, (Bottom) + (Diff) * (array.get(channels,i)))
output
output = f_fibcalc(Top,Bottom, channels,ChartisLog)
cleareverything() =>
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
a_allLabel = label.all
if array.size(a_allLabel) > 0
for i = 0 to array.size(a_allLabel) - 1
label.delete(array.get(a_allLabel, i))
a_allFills = linefill.all
if array.size(a_allFills) > 0
for i = 0 to array.size(a_allFills) - 1
linefill.delete(array.get(a_allFills, i))
drawout() =>
for i = 0 to array.size(channels)-1
line line1 = na
linefill fill1 = na
label label1 = na
label label2 = na
line1 := line.new(x1= Starttime, y1= array.get(output,i),x2 = time, y2 = array.get(output,i), xloc=xloc.bar_time, style=line.style_solid, extend=extend.right,color=Linecolor_Global)
array.insert(linearray,i,line1)
if i == 1
fill1 := linefill.new(array.get(linearray,0),array.get(linearray,1),color1)
if i == 3
fill1 := linefill.new(array.get(linearray,2),array.get(linearray,3),color2)
if i == 6
fill1 := linefill.new(array.get(linearray,5),array.get(linearray,6),color3)
if i == 8
fill1 := linefill.new(array.get(linearray,7),array.get(linearray,8),color4)
label1 := label.new(x=time <= chart.right_visible_bar_time?time:chart.right_visible_bar_time, y= array.get(output,i),
text = time <= chart.right_visible_bar_time?
" " + str.tostring(fibreverse?(1-array.get(channels,i)):array.get(channels,i)) + ' (' + str.tostring(f_round(array.get(output,i),decimals_price)) + ') ' + str.tostring(f_round(array.get(output,i)/close*100-100,decimals_percent)) + '% = ' + str.tostring(f_round(array.get(output,i)-close,decimals_price)) :
"" + str.tostring(fibreverse?(1-array.get(channels,i)):array.get(channels,i)) + ' (' + str.tostring(f_round(array.get(output,i),decimals_price)) + ') ',
xloc=xloc.bar_time,
yloc=yloc.price,
color=color.white,
style=label.style_none,
textcolor=textcolor1,
size=size1,
textalign=text.align_left)
if i == 8
label2 := label.new(x=time <= chart.right_visible_bar_time?time:chart.right_visible_bar_time, y= array.get(output,i),
text = time <= chart.right_visible_bar_time?
" Range-Up = " + str.tostring(f_round(array.get(output,0)/array.get(output,8)*100-100,decimals_percent)) + '% / ' + str.tostring(f_round(array.get(output,0)-array.get(output,8),decimals_price)) + '\n Range-Down = ' + str.tostring(f_round(array.get(output,8)/array.get(output,0)*100-100,decimals_percent)) + '%\n':
"",
xloc=xloc.bar_time,
yloc=yloc.price,
color=color.white,
style=label.style_none,
textcolor=textcolor1,
size=size1,
textalign=text.align_left)
cleareverything()
drawout() |
10y3mYieldInversion | https://www.tradingview.com/script/DyeUoVGB-10y3mYieldInversion/ | faizmaricar | https://www.tradingview.com/u/faizmaricar/ | 4 | 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/
// © faizmaricar
//@version=5
indicator("10y3mYieldInversion", overlay = true)
tenYearYield = request.security('US10Y', '', close)
threeMonthYield = request.security('US03MY', '', close)
inversion = if threeMonthYield[1] < tenYearYield[1] and threeMonthYield[0] > tenYearYield[0]
line.new(bar_index , close, bar_index, close * 1.01, extend = extend.both, color = color.green, style = line.style_solid, width = 1) |
Breadth - Advance Decline Thrust | https://www.tradingview.com/script/OgCeAUsw-Breadth-Advance-Decline-Thrust/ | andr3w321 | https://www.tradingview.com/u/andr3w321/ | 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/
// © andr3w321
//@version=5
indicator('Breadth - Advance Decline Thrust')
// cumulative net up volume will show lower values than advance decline thrust on days where there were large buy/sell imbalances, but the total day's volume was low
// advance decline thrust will show values between 0 to 1
display_as_cum_net_up_volume = input.bool(title="Display as cumulative net up volume", defval=false)
lookbackInput = input.int(title="Cumulative lookback days including today", defval=1, minval = 1, maxval = 4999)
include_ny = input.bool(title="Include NYSE Up Volume?", defval=true)
include_nq = input.bool(title="Include NQ Up Volume?", defval=true)
include_us = input.bool(title="Include US Up Volume?", defval=true)
upper_band_value = input.float(title="Upper band value", defval=0.80)
middle_band_value = input.float(title="Middle band value", defval=0.50)
lower_band_value = input.float(title="Lower band value", defval=0.20)
ny_uvol = request.security('UPVOL.NY', "D", close)
nq_uvol = request.security('UPVOL.NQ', "D", close)
us_uvol = request.security('UPVOL.US', "D", close)
ny_dvol = request.security('DNVOL.NY', "D", close)
nq_dvol = request.security('DNVOL.NQ', "D", close)
us_dvol = request.security('DNVOL.US', "D", close)
cumulative_net_uvol = 0.0
cumulative_dvol = 0.0
cumulative_uvol = 0.0
for i = 0 to lookbackInput - 1
ny_net_uvol = ny_uvol[i] - ny_dvol[i]
nq_net_uvol = nq_uvol[i] - nq_dvol[i]
us_net_uvol = us_uvol[i] - us_dvol[i]
if include_ny
cumulative_net_uvol += ny_net_uvol
cumulative_uvol += ny_uvol[i]
cumulative_dvol += ny_dvol[i]
if include_nq
cumulative_net_uvol += nq_net_uvol
cumulative_uvol += nq_uvol[i]
cumulative_dvol += nq_dvol[i]
if include_us
cumulative_net_uvol += us_net_uvol
cumulative_uvol += us_uvol[i]
cumulative_dvol += us_dvol[i]
cumulative_net_uvol := cumulative_net_uvol / 10000000 // make y axis more readable
advance_decline_thrust = cumulative_uvol / (cumulative_uvol + cumulative_dvol)
plot(display_as_cum_net_up_volume ? na : advance_decline_thrust, title="Advance Decline Thrust", color=color.blue)
plot(display_as_cum_net_up_volume ? cumulative_net_uvol : na, title="Cumulative Net Up Volume", color=color.purple)
upper_band = hline(upper_band_value, "Upper Band", color=#787B86)
hline(middle_band_value, "Middle Band", color=color.new(#787B86, 50))
lower_band = hline(lower_band_value, "Lower Band", color=#787B86)
fill(upper_band, lower_band, color=color.rgb(126, 87, 194, 90), title="Background Fill") |
Global & local RSI / quantifytools | https://www.tradingview.com/script/sPxBNfGd-Global-local-RSI-quantifytools/ | quantifytools | https://www.tradingview.com/u/quantifytools/ | 475 | 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/
// © quantifytools
//@version=5
indicator("Global & local RSI w/ adaptive bands", max_labels_count=500)
// Inputs
//RSI inputs
groupRsi= "RSI settings"
i_plotType = input.string("Candle", "Plot type", options=["Line", "Candle", "Bar"], group=groupRsi)
i_rsiLength = input.int(14, "Global and local RSI length", group=groupRsi, minval=1, maxval=100)
groupSmoothing = "Smoothing settings"
i_adaptiveOn = input.bool(false, "Enable adaptive bands", group=groupSmoothing, tooltip="Unlikely to have meaningful difference if smoothing is off (set to 1) and/or RSI length is set to default length (14). Will increase script loading time.")
i_Smoothing = input.int(1, "Smoothing factor", minval=1, maxval=100, group=groupSmoothing)
i_smoothingType = input.string("SMA", "Smoothing type", options=["SMA", "EMA", "HMA", "RMA", "WMA"], group=groupSmoothing)
//Stochastic RSI inputs
groupLocal = "Local RSI colors"
localExtremeUpCol1 = input.color(color.new(color.yellow, 60), "1 ▲", group=groupLocal, inline="up")
localExtremeUpCol2 = input.color(color.new(color.orange, 40), "2 ▲", group=groupLocal, inline="up")
localExtremeUpCol3 = input.color(color.new(color.fuchsia, 20), "3 ▲", group=groupLocal, inline="up")
localExtremeDownCol1 = input.color(color.new(color.yellow, 60), "1 ▼", group=groupLocal, inline="down")
localExtremeDownCol2 = input.color(color.new(color.orange, 40), "2 ▼", group=groupLocal, inline="down")
localExtremeDownCol3 = input.color(color.new(color.fuchsia, 20), "3 ▼", group=groupLocal, inline="down")
//Color inputs
groupGlobal = "Global RSI colors"
globalUpCol = input.color(color.white, "▲", group=groupGlobal, inline="global")
globalDownCol = input.color(color.rgb(85, 85, 85), "▼", group=groupGlobal, inline="global")
globalBandCol = input.color(color.rgb(255, 255, 255, 84), "☰", group=groupGlobal, inline="global")
groupDots = "Panel colors"
panelCol = input.color(color.rgb(255, 255, 255), "● & T", group=groupDots, inline="global")
// RSI calculations
//RSI length, stochastic RSI length and default smoothing for stochastic RSI
lengthRSI = i_rsiLength
lengthStoch = i_rsiLength
smoothK = 3
//Separated RSI OHLC values for bars/candles
rsiOpen = ta.rsi(open, lengthRSI)
rsiHigh = ta.rsi(high, lengthRSI)
rsiLow = ta.rsi(low, lengthRSI)
rsiClose = ta.rsi(close, lengthRSI)
//Function to smooth RSI values with chosen method
smoothedValue(source, length) =>
i_smoothingType == "SMA" ? ta.sma(source, length) :
i_smoothingType == "EMA" ? ta.ema(source, length) :
i_smoothingType == "HMA" ? ta.hma(source, length) :
i_smoothingType == "RMA" ? ta.rma(source, length) : ta.wma(source, length)
//If smoothing is at or above 2, apply smoothing, else regular value. Same for stochastic RSI, but using smoothing length of 3 as a baseline.
rsiOpenSmooth = i_Smoothing >= 2 ? smoothedValue(rsiOpen, i_Smoothing) : rsiOpen
rsiHighSmooth = i_Smoothing >= 2 ? smoothedValue(rsiHigh, i_Smoothing) : rsiHigh
rsiLowSmooth = i_Smoothing >= 2 ? smoothedValue(rsiLow, i_Smoothing) : rsiLow
rsiCloseSmooth = i_Smoothing >= 2 ? smoothedValue(rsiClose, i_Smoothing) : rsiClose
//If smoothing at or above 2, use smoothedValue function for smoothing stochastic RSI, else use smooth factor of 3.
rsiStochNoSmooth = ta.stoch(rsiClose, rsiClose, rsiClose, lengthStoch)
rsiStochLightSmooth = ta.sma(rsiStochNoSmooth, smoothK)
k = i_Smoothing >= 2 ? smoothedValue(rsiStochNoSmooth, 3 + i_Smoothing) : rsiStochLightSmooth
// Adaptive bands
//When RSI > 55 or < 45, fetch pivot point. Same for stochastic RSI.
rsiPivotHigh = rsiCloseSmooth > 55 ? ta.pivothigh(rsiCloseSmooth, 5, 5) : na
rsiPivotLow = rsiCloseSmooth < 45 ? ta.pivotlow(rsiCloseSmooth, 5, 5) : na
stochPivotHigh = k > 55 ? ta.pivothigh(k, 5, 5) : na
stochPivotLow = k < 45 ? ta.pivotlow(k, 5, 5) : na
//Arrays for pivots
var pivotHighs = array.new_float(0, 0)
var pivotLows = array.new_float(0, 0)
var pivotHighsStoch = array.new_float(0, 0)
var pivotLowsStoch = array.new_float(0, 0)
//Populate RSI pivot arrays if adaptive bands are on
if i_adaptiveOn == true
array.push(pivotHighs, rsiPivotHigh)
array.push(pivotLows, rsiPivotLow)
//Populate stochastic RSI pivot arrays if adaptive bands are on
if i_adaptiveOn == true
array.push(pivotHighsStoch, stochPivotHigh)
array.push(pivotLowsStoch, stochPivotLow)
//Keep array size fixed
sizeLimit = 3000
if array.size(pivotHighs) > sizeLimit
array.remove(pivotHighs, 0)
if array.size(pivotLows) > sizeLimit
array.remove(pivotLows, 0)
if array.size(pivotHighsStoch) > sizeLimit
array.remove(pivotHighsStoch, 0)
if array.size(pivotLowsStoch) > sizeLimit
array.remove(pivotLowsStoch, 0)
//Median pivots for RSI and stochastic RSI to form adaptive bands. If adaptive is off, use traditional values.
medianPivotHigh = i_adaptiveOn == true ? array.median(pivotHighs) : 70
medianPivotLow = i_adaptiveOn == true ? array.median(pivotLows) : 30
medianPivotHighStoch = i_adaptiveOn == true ? array.median(pivotHighsStoch) : 100
medianPivotLowStoch = i_adaptiveOn == true ? array.median(pivotLowsStoch) : 1
//Forming middle point for RSI and stochastic RSI based on median pivots
medianMiddle = (medianPivotHigh + medianPivotLow) / 2
stochMid = (medianPivotHighStoch + medianPivotLowStoch) / 2
//Forming extreme zones for stochastic RSI based on median pivots (1/4, 1.5/4, 3/4, 3.5/4 of median pivots)
stochdDownExtreme1 = (stochMid + medianPivotLowStoch) / 2
stochUpExtreme1 = (stochMid + medianPivotHighStoch) / 2
stochdDownExtreme2 = (stochdDownExtreme1 + medianPivotLowStoch) / 2
stochUpExtreme2 = (stochUpExtreme1 + medianPivotHighStoch) / 2
stochUpExtreme3 = medianPivotHighStoch
stochdDownExtreme3 = medianPivotLowStoch
//RSI median band lower/upper part of bands. If adaptive is off, use traditional values, else extend 10 %.
medianPivotHighX = i_adaptiveOn == true ? medianPivotHigh * 1.10 : 80
medianPivotLowX = i_adaptiveOn == true ? medianPivotLow - (medianPivotHighX - medianPivotHigh) : 20
// Plot related calculations
//Pick user defined stochastic RSI colors
localExtremeUp = k >= stochUpExtreme1 ? localExtremeUpCol1 : na
localExtremeDown = k <= stochdDownExtreme1 ? localExtremeDownCol1: na
localExtremeUp2 = k >= stochUpExtreme2 ? localExtremeUpCol2 : na
localExtremeDown2 = k <= stochdDownExtreme2 ? localExtremeDownCol2 : na
localExtremeUp3 = k >= stochUpExtreme3 ? localExtremeUpCol3: na
localExtremeDown3 = k <= stochdDownExtreme3 ? localExtremeDownCol3: na
//Pick user defined visualization
//Bar
plotBarOpen = i_plotType == "Bar" ? rsiOpenSmooth : na
plotBarClose = i_plotType == "Bar" ? rsiCloseSmooth : na
plotBarHigh = i_plotType == "Bar" ? rsiHighSmooth : na
plotBarLow = i_plotType == "Bar" ? rsiLowSmooth : na
//Candle
plotCandleOpen = i_plotType == "Candle" ? rsiOpenSmooth : na
plotCandleClose = i_plotType == "Candle" ? rsiCloseSmooth : na
plotCandleHigh = i_plotType == "Candle" ? rsiHighSmooth : na
plotCandleLow = i_plotType == "Candle" ? rsiLowSmooth : na
//Line
plotLine = i_plotType == "Line" ? rsiCloseSmooth : na
//Up and down color for global RSI
globalCol = rsiCloseSmooth > rsiCloseSmooth[1] ? globalUpCol : globalDownCol
// Plots
//Plots for bands
p2x = plot(medianPivotHighX, "Upper RSI band 2", color=color.new(color.white, 1), linewidth=1)
p2 = plot(medianPivotHigh, "Upper RSI band 1", color=color.white, linewidth=1)
p3 = plot(medianMiddle, "Middle point", color=globalBandCol, linewidth=1)
p1 = plot(medianPivotLow, "Lower RSI band 1", color=color.white, linewidth=1)
p1x = plot(medianPivotLowX, "Lower RSI band 2", color=color.new(color.white, 1), linewidth=1)
//Fills for bands
fill(p1, p1x, color=globalBandCol)
fill(p2, p2x, color=globalBandCol)
fill(p1, p1x, color=localExtremeDown)
fill(p2, p2x, color=localExtremeUp)
fill(p1, p1x, color=localExtremeDown2)
fill(p2, p2x, color=localExtremeUp2)
fill(p1, p1x, color=localExtremeDown3)
fill(p2, p2x, color=localExtremeUp3)
//Plots for bars, candles and line
plotbar(plotBarOpen, plotBarHigh, plotBarLow, plotBarClose, title="RSI bars", color=globalCol)
plotcandle(plotCandleOpen, plotCandleHigh, plotCandleLow, plotCandleClose, title="RSI candles", color=globalCol, wickcolor=globalCol, bordercolor=globalCol)
plot(plotLine, title="RSI line", color=globalCol)
// Table
//Rounding RSI and stochastic RSI values for table
roundedGlobal = math.round(rsiCloseSmooth, 0)
roundedLocal = math.round(k, 0)
//Colors for dot on table, the more blue the closer to 0, the more red the closer to 100.
globalDotUpCol = color.from_gradient(rsiCloseSmooth, medianMiddle, medianPivotHigh, panelCol, color.red)
globalDotDownCol = color.from_gradient(rsiCloseSmooth, medianPivotLow, medianMiddle, color.blue, panelCol)
localDotUpCol = color.from_gradient(k, stochMid, medianPivotHighStoch, panelCol, color.red)
localDotDownCol = color.from_gradient(k, medianPivotLowStoch, stochMid, color.blue, panelCol)
globalDotCol = rsiCloseSmooth >= 50 ? globalDotUpCol : globalDotDownCol
localDotCol = k >= 50 ? localDotUpCol : localDotDownCol
//Initializing table
var rsiTable = table.new(position = position.top_right, columns = 50, rows = 50, bgcolor = color.new(color.black, 100), border_width = 0, border_color=color.gray)
//Populating table
table.cell(table_id = rsiTable, column = 0, row = 0, text = "Global RSI: " + str.tostring(roundedGlobal), text_color=panelCol)
table.cell(table_id = rsiTable, column = 1, row = 0, text = "●", text_color=globalDotCol)
table.cell(table_id = rsiTable, column = 2, row = 0, text = "Local RSI: " + str.tostring(roundedLocal), text_color=panelCol)
table.cell(table_id = rsiTable, column = 3, row = 0, text = "●", text_color=localDotCol)
// Alerts
//Defining alert condition for global RSI extremes
globalRsiExtremeUp = ta.crossover(rsiCloseSmooth, medianPivotHigh)
globalRsiExtremeDown = ta.crossunder(rsiCloseSmooth, medianPivotLow)
//Defining alert condition for local RSI extremes
localRsiExtremeUp = ta.crossover(k, medianPivotHighStoch)
localRsiExtremeDown = ta.crossunder(k, medianPivotLowStoch)
//Alerts
alertcondition(globalRsiExtremeUp, "Global RSI > upper band", "Global RSI overbought condition detected.")
alertcondition(globalRsiExtremeDown, "Global RSI < lower band", "Global RSI oversold condition detected.")
alertcondition(localRsiExtremeUp, "Local RSI > upper band", "Local RSI extreme up condition detected.")
alertcondition(localRsiExtremeDown, "Local RSI < lower band", "Local RSI extreme down condition detected.") |
Open Close Trend | https://www.tradingview.com/script/L4WLqM65-Open-Close-Trend/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 23 | 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/
// © peacefulLizard50262
//@version=5
indicator("Open Close Trend", overlay = false)
ema(src, len) => //{
alpha = 2 / (len + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
//}
//Tripple EMA
tma(src, int len) => //{
//src is an input.source
//len is an input.int
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
tma = 3 * (ema1 - ema2) + ema3
normalize(src, float len = 200, bool ena = false) =>
float a = 0
float b = 1
min = ta.lowest(src, int(len))
max = ta.highest(src, int(len))
float x = ((a + (src - min) * (b - a) / (max - min))- 0.5) * 2
ena ? x : src * len
norm(src, min, max, bool pass = true) =>
num = src - min
den = max - min
norm = num / den
out = pass == true ? (norm - 0.5) * 2 : src
ma_type = input.string("EMA", "MA Select", ["SMA","EMA","TMA","WMA"])
select = input.string("Gradient", "Feature Select", ["Gradient","Histogram","BG Color"])
type = input.string("Normalize", "Style", ["Normalize","Moving Average"])
length = input.int(20, "Length", 1)
signal_smoothing = input.int(1, "Signal Smoothing", 1)
colour_smoothing = input.int(2, "Divergence Convergence Smoothing", 1)
lookback = input.float(50, "DC Normalization Lookback / Scale", 1, inline = "Back", tooltip = "When enabled the hist will be normalized. When dissabled this will double as a scaler for the hist.")
enable = input.bool(true, "", inline = "Back")
moving_average = input.int(200, "Moving Average Length")
grad_col_dwn = input.color(color.new(color.red, 90), "Gradient Color", inline = "grad")
grad_col_up = input.color(color.new(color.blue, 90), "", inline = "grad")
col_grow_below = input.color(color.new(#FFCDD2, 50), "Hist Low Color", inline = "low")
col_fall_below = input.color(color.new(#FF5252, 50), "", inline = "low")
col_fall_above = input.color(color.new(#B2DFDB, 50), "Hist High Color", inline = "high")
col_grow_above = input.color(color.new(#26A69A, 50), "", inline = "high")
bg_colour = input.color(color.new(color.blue, 90), "Background Color")
ma(src, length)=>
switch ma_type
"SMA" => ta.sma(src, length)
"EMA" => ema(src, length)
"TMA" => tma(src, length)
"WMA" => ta.wma(src, length)
High = ta.sma(ma(high, length) - (type == "Normalize" ? 0 : ta.sma(close, moving_average)), signal_smoothing)
Low = ta.sma(ma(low, length) - (type == "Normalize" ? 0 : ta.sma(close, moving_average)), signal_smoothing)
Close = ta.sma(ma(close, length) - (type == "Normalize" ? 0 : ta.sma(close, moving_average)), signal_smoothing)
Open = ta.sma(ma(open, length) - (type == "Normalize" ? 0 : ta.sma(close, moving_average)), signal_smoothing)
hist =
select == "BG Color" ? na :
select == "Gradient" ? ta.sma(normalize(Close - Open, lookback, true), colour_smoothing) :
type == "Normalize" ? ta.sma(normalize(Close - Open, lookback, enable), colour_smoothing) :
ta.sma(Close - Open, colour_smoothing)
colour = color.from_gradient(hist, -1, 1, grad_col_dwn, grad_col_up)
hist_col = hist >= 0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)
h = plot(norm(High, Low, High, type == "Normalize" ? true : false), color = color.gray)
l = plot(norm(Low, Low, High, type == "Normalize" ? true : false), color = color.gray)
plot(select == "Histogram" ? hist : na, "Open Close Hist", hist_col, style = plot.style_columns)
fill(h, l, color = select == "Gradient" ? colour : color.new(color.blue, 90))
//bgcolor(type == "Normalize" ? na : select == "Gradient" ? colour : na)
c = plot(norm(Close, Low, High, type == "Normalize" ? true : false), color = color.green)
o = plot(norm(Open, Low, High, type == "Normalize" ? true : false), color = color.red)
plotshape(ta.crossover(Close, Open), "Green", color = color.green, location = location.top)
plotshape(ta.crossunder(Close, Open), "Red", color = color.red, location = location.bottom)
plot(0, color = color.gray) |
AM's SRT | https://www.tradingview.com/script/QukDTBeJ-AM-s-SRT/ | maity420 | https://www.tradingview.com/u/maity420/ | 3 | 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/
// © maity420
//@version=5
// Thanks to Nitish Sir for teaching the concept of SRT for Investments
indicator("AM'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,"#.##")) |
MA Cross Screener | https://www.tradingview.com/script/3JxwMNfy-MA-Cross-Screener/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 111 | 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/
// © peacefulLizard50262
//@version=5
indicator("MA Cross Screener", overlay = false, precision = 0)
ma(src, len, type)=>
switch type
"SMA" => ta.sma(src, len)
"EMA" => ta.ema(src, len)
"WMA" => ta.wma(src, len)
select = input.string("MA Cross", "Strategy Select", ["MA Cross", "RSI", "MACD", "Stochastic", "200 MA"], group = "Settings")
custom = input.bool(false, "Custom Time Frame", inline = "Time", tooltip = "When using custom time frame use the minimum time on your chart.", group = "Settings")
ctime = input.timeframe("D", "", inline = "Time", group = "Settings")
txt_col = input.color(color.new(color.black, 0), "Title Color", inline = "bull", group = "Settings")
box_col = input.color(color.new(color.white, 0), "", inline = "bull", group = "Settings")
sig_col2 = input.color(color.new(color.red, 0), "Signal Color", inline = "bull", group = "Settings")
sig_col1 = input.color(color.new(color.green, 0), "", inline = "bull", group = "Settings")
fast = input.int(9, "Fast Length", 1, group = "MA Cross")
slow = input.int(21, "Slow Length", 1, group = "MA Cross")
type = input.string("EMA", "MA Type Fast", ["SMA","EMA","WMA"], group = "MA Cross")
type2 = input.string("EMA", "MA Type Slow", ["SMA","EMA","WMA"], group = "MA Cross")
rsi_length = input.int(14, "RSI Length", 1, group = "RSI")
rsi_high = input.int(70 , "RSI High Threshold", group = "RSI")
rsi_low = input.int(30 , "RSI Low Threshold", group = "RSI")
macd_fast = input.int(12 , "MACD", 1, group = "MACD")
macd_slow = input.int(26 , "MACD", 1, group = "MACD")
macd_siglen = input.int(9 , "MACD", 1, group = "MACD")
stoch_len = input.int(14, group = "Stochastic")
stoch_smo = input.int(1, group = "Stochastic")
stoch_hi = input.int(80 , "Stochastic High Threshold", group = "Stochastic")
stoch_lo = input.int(20 , "Stochastic Low Threshold", group = "Stochastic")
ma_length = input.int(200, "MA '200' Length", 1, group = "MA 200")
timep = custom ? ctime : timeframe.period
main(src, n) =>
exn = str.tostring(src)
var color col = na
var label lab = na
label.delete(lab)
lab := label.new(bar_index + 5, n, exn, textcolor = txt_col, color = box_col)
sig_p = false
sig_q = false
ex = request.security(src , timep, close)
exh = ta.highest(ex, 1)
exl = ta.lowest(ex, 1)
fast_n = ma(ex, fast, type)
slow_n = ma(ex, slow, type2)
rsi = ta.rsi(ex, rsi_length)
[macd1, macd2, hist] = ta.macd(ex, macd_fast, macd_slow, macd_siglen)
stoch = ta.sma(ta.stoch(ex, exh, exl, stoch_len), stoch_smo)
ma200 = ta.sma(ex, ma_length)
logic_up = switch select
"MA Cross" => ta.crossover(fast_n, slow_n)
"RSI" => ta.crossover(rsi, rsi_high)
"MACD" => ta.crossover(macd1, macd2)
"Stochastic" => ta.crossover(stoch, rsi_low)
"200 MA" => ta.crossover(ex, ma200)
logic_down = switch select
"MA Cross" => ta.crossunder(fast_n, slow_n)
"RSI" => ta.crossover(rsi, stoch_hi)
"MACD" => ta.crossunder(macd1, macd2)
"Stochastic" => ta.crossover(stoch, stoch_lo)
"200 MA" => ta.crossunder(ex, ma200)
if logic_up
alert("Symbol " + exn + " crossed up")
col := sig_col1
sig_p := true
sig_q := true
if logic_down
alert("Symbol " + exn + " crossed down")
col := sig_col2
sig_p := true
sig_q := true
[sig_p, sig_q, col]
ext1 = input.symbol('BTCUSD', 'Symbol 1', group = "Symbols")
ext2 = input.symbol('ETHUSD', 'Symbol 2', group = "Symbols")
ext3 = input.symbol('BNBUSD', 'Symbol 3', group = "Symbols")
ext4 = input.symbol('XRPUSD', 'Symbol 4', group = "Symbols")
ext5 = input.symbol('DOGEUSD', 'Symbol 5', group = "Symbols")
ext6 = input.symbol('ETCUSD', 'Symbol 6', group = "Symbols")
ext7 = input.symbol('LTCUSD', 'Symbol 7', group = "Symbols")
ext8 = input.symbol('XLMUSD', 'Symbol 8', group = "Symbols")
ext9 = input.symbol('XMRUSD', 'Symbol 9', group = "Symbols")
ext10 = input.symbol('TRXUSD', 'Symbol 10', group = "Symbols")
ext11 = input.symbol('AAPL', 'Symbol 11', group = "Symbols")
ext12 = input.symbol('MSFT', 'Symbol 12', group = "Symbols")
ext13 = input.symbol('GOOG', 'Symbol 13', group = "Symbols")
ext14 = input.symbol('AMZN', 'Symbol 14', group = "Symbols")
ext15 = input.symbol('TSLA', 'Symbol 15', group = "Symbols")
ext16 = input.symbol('UNH', 'Symbol 16', group = "Symbols")
ext17 = input.symbol('META', 'Symbol 17', group = "Symbols")
ext18 = input.symbol('NVDA', 'Symbol 18', group = "Symbols")
ext19 = input.symbol('V', 'Symbol 19', group = "Symbols")
ext20 = input.symbol('MA', 'Symbol 20', group = "Symbols")
[sig, sig20, col1] = main(ext1, 1)
[sig1, sig21, col2] = main(ext2, 2)
[sig2, sig22, col3] = main(ext3, 3)
[sig3, sig23, col4] = main(ext4, 4)
[sig4, sig24, col5] = main(ext5, 5)
[sig5, sig25, col6] = main(ext6, 6)
[sig6, sig26, col7] = main(ext7, 7)
[sig7, sig27, col8] = main(ext8, 8)
[sig8, sig28, col9] = main(ext9, 9)
[sig9, sig29, col10] = main(ext10, 10)
[sig10, sig30, col11] = main(ext11, 11)
[sig11, sig31, col12] = main(ext12, 12)
[sig12, sig32, col13] = main(ext13, 13)
[sig13, sig33, col14] = main(ext14, 14)
[sig14, sig34, col15] = main(ext15, 15)
[sig15, sig35, col16] = main(ext16, 16)
[sig16, sig36, col17] = main(ext17, 17)
[sig17, sig37, col18] = main(ext18, 18)
[sig18, sig38, col19] = main(ext19, 19)
[sig19, sig39, col20] = main(ext20, 20)
plotshape(sig or sig20 ? 1 : na, location = location.absolute, color = col1, style = shape.circle)
plotshape(sig1 or sig21 ? 2 : na, location = location.absolute, color = col2, style = shape.circle)
plotshape(sig2 or sig22 ? 3 : na, location = location.absolute, color = col3, style = shape.circle)
plotshape(sig3 or sig23 ? 4 : na, location = location.absolute, color = col4, style = shape.circle)
plotshape(sig4 or sig24 ? 5 : na, location = location.absolute, color = col5, style = shape.circle)
plotshape(sig5 or sig25 ? 6 : na, location = location.absolute, color = col6, style = shape.circle)
plotshape(sig6 or sig26 ? 7 : na, location = location.absolute, color = col7, style = shape.circle)
plotshape(sig7 or sig27 ? 8 : na, location = location.absolute, color = col8, style = shape.circle)
plotshape(sig8 or sig28 ? 9 : na, location = location.absolute, color = col9, style = shape.circle)
plotshape(sig9 or sig29 ? 10 : na, location = location.absolute, color = col10, style = shape.circle)
plotshape(sig10 or sig30 ? 11 : na, location = location.absolute, color = col11, style = shape.circle)
plotshape(sig11 or sig31 ? 12 : na, location = location.absolute, color = col12, style = shape.circle)
plotshape(sig12 or sig32 ? 13 : na, location = location.absolute, color = col13, style = shape.circle)
plotshape(sig13 or sig33 ? 14 : na, location = location.absolute, color = col14, style = shape.circle)
plotshape(sig14 or sig34 ? 15 : na, location = location.absolute, color = col15, style = shape.circle)
plotshape(sig15 or sig35 ? 16 : na, location = location.absolute, color = col16, style = shape.circle)
plotshape(sig16 or sig36 ? 17 : na, location = location.absolute, color = col17, style = shape.circle)
plotshape(sig17 or sig37 ? 18 : na, location = location.absolute, color = col18, style = shape.circle)
plotshape(sig18 or sig38 ? 19 : na, location = location.absolute, color = col19, style = shape.circle)
plotshape(sig19 or sig39 ? 20 : na, location = location.absolute, color = col20, style = shape.circle)
hline(1, color = color.new(color.gray, 90))
hline(2, color = color.new(color.gray, 90))
hline(3, color = color.new(color.gray, 90))
hline(4, color = color.new(color.gray, 90))
hline(5, color = color.new(color.gray, 90))
hline(6, color = color.new(color.gray, 90))
hline(7, color = color.new(color.gray, 90))
hline(8, color = color.new(color.gray, 90))
hline(9, color = color.new(color.gray, 90))
hline(10, color = color.new(color.gray, 90))
hline(11, color = color.new(color.gray, 90))
hline(12, color = color.new(color.gray, 90))
hline(13, color = color.new(color.gray, 90))
hline(14, color = color.new(color.gray, 90))
hline(15, color = color.new(color.gray, 90))
hline(16, color = color.new(color.gray, 90))
hline(17, color = color.new(color.gray, 90))
hline(18, color = color.new(color.gray, 90))
hline(19, color = color.new(color.gray, 90))
hline(20, color = color.new(color.gray, 90)) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.