Relative VolatilityRelative Volatility is a technical indicator designed to assess changes in market volatility by comparing fast and slow Average True Range (ATR) values. It operates by subtracting a slower ATR (e.g., 50-period ATR) from a faster ATR (e.g., 20-period ATR) and visualizing the result as a histogram. This enables traders to determine whether volatility is increasing or decreasing over time.
This indicator can help traders recognize volatility trends, which can inform decisions related to trade entries, exits, and risk management.
Interpreting Volatility Changes
Increasing Volatility: When the histogram is above zero, it indicates that the fast ATR is greater than the slow ATR, signifying an increase in short-term volatility compared to the long-term average. This may suggest heightened market activity and potential trading opportunities.
Decreasing Volatility: When the histogram is below zero, it shows that the fast ATR is less than the slow ATR, indicating a decrease in short-term volatility relative to the long-term average. This may suggest consolidating markets or reduced trading activity.
Relative Volatility assists traders in monitoring and analyzing changes in market volatility, providing insights that can enhance trading strategies and decision-making processes.
Chỉ báo và chiến lược
Savitzky-Golay Z-Score [BackQuant]Savitzky-Golay Z-Score
The Savitzky-Golay Z-Score is a powerful trading indicator that combines the precision of the Savitzky-Golay filter with the statistical strength of the Z-Score. This advanced indicator is designed to detect trend shifts, identify overbought or oversold conditions, and highlight potential divergences in the market, providing traders with a unique edge in detecting momentum changes and trend reversals.
Core Concept: Savitzky-Golay Filter
The Savitzky-Golay filter is a widely-used smoothing technique that preserves important signal features such as peak detection while filtering out noise. In this indicator, the filter is applied to price data (default set to HLC3) to smooth out volatility and produce a cleaner trend line. By specifying the window size and polynomial degree, traders can fine-tune the degree of smoothing to match their preferred trading style or market conditions.
Z-Score: Measuring Deviation
The Z-Score is a statistical measure that indicates how far the current price is from its mean in terms of standard deviations. In trading, the Z-Score can be used to identify extreme price moves that are likely to revert or continue trending. A positive Z-Score means the price is above the mean, while a negative Z-Score indicates the price is below the mean.
This script calculates the Z-Score based on the Savitzky-Golay filtered price, enabling traders to detect moments when the price is diverging from its typical range and may present an opportunity for a trade.
Long and Short Conditions
The Savitzky-Golay Z-Score generates clear long and short signals based on the Z-Score value:
Long Signals : When the Z-Score is positive, indicating the price is above its smoothed mean, a long signal is generated. The color of the bars turns green, signaling upward momentum.
Short Signals : When the Z-Score is negative, indicating the price is below its smoothed mean, a short signal is generated. The bars turn red, signaling downward momentum.
These signals allow traders to follow the prevailing trend with confidence, using statistical backing to avoid false signals from short-term volatility.
Standard Deviation Levels and Extreme Levels
This indicator includes several features to help visualize overbought and oversold conditions:
Standard Deviation Levels: The script plots horizontal lines at +1, +2, -1, and -2 standard deviations. These levels provide a reference for how far the current price is from the mean, allowing traders to quickly identify when the price is moving into extreme territory.
Extreme Levels: Additional extreme levels at +3 and +4 (and their negative counterparts) are plotted to highlight areas where the price is highly likely to revert. These extreme levels provide important insight into market conditions that are far outside the norm, signaling caution or potential reversal zones.
The indicator also adapts the color shading of these extreme zones based on the Z-Score’s strength. For example, the area between +3 and +4 is shaded with a stronger color when the Z-Score approaches these values, giving a visual representation of market pressure.
Divergences: Detecting Hidden and Regular Signals
A key feature of the Savitzky-Golay Z-Score is its ability to detect bullish and bearish divergences, both regular and hidden:
Regular Bullish Divergence: This occurs when the price makes a lower low while the Z-Score forms a higher low. It signals that bearish momentum is weakening, and a bullish reversal could be near.
Hidden Bullish Divergence: This divergence occurs when the price makes a higher low while the Z-Score forms a lower low. It signals that bullish momentum may continue after a temporary pullback.
Regular Bearish Divergence: This occurs when the price makes a higher high while the Z-Score forms a lower high, signaling that bullish momentum is weakening and a bearish reversal may be near.
Hidden Bearish Divergence: This divergence occurs when the price makes a lower high while the Z-Score forms a higher high, indicating that bearish momentum may continue after a temporary rally.
These divergences are plotted directly on the chart, making it easier for traders to spot when the price and momentum are out of sync and when a potential reversal may occur.
Customization and Visualization
The Savitzky-Golay Z-Score offers a range of customization options to fit different trading styles:
Window Size and Polynomial Degree: Adjust the window size and polynomial degree of the Savitzky-Golay filter to control how much smoothing is applied to the price data.
Z-Score Lookback Period: Set the lookback period for calculating the Z-Score, allowing traders to fine-tune the sensitivity to short-term or long-term price movements.
Display Options: Choose whether to display standard deviation levels, extreme levels, and divergence labels on the chart.
Bar Color: Color the price bars based on trend direction, with green for bullish trends and red for bearish trends, allowing traders to easily visualize the current momentum.
Divergences: Enable or disable divergence detection, and adjust the lookback periods for pivots used to detect regular and hidden divergences.
Alerts and Automation
To ensure you never miss an important signal, the indicator includes built-in alert conditions for the following events:
Positive Z-Score (Long Signal): Triggers an alert when the Z-Score crosses above zero, indicating a potential buying opportunity.
Negative Z-Score (Short Signal): Triggers an alert when the Z-Score crosses below zero, signaling a potential short opportunity.
Shifting Momentum: Alerts when the Z-Score is shifting up or down, providing early warning of changing market conditions.
These alerts can be configured to notify you via email, SMS, or app notification, allowing you to stay on top of the market without having to constantly monitor the chart.
Trading Applications
The Savitzky-Golay Z-Score is a versatile tool that can be applied across multiple trading strategies:
Trend Following: By smoothing the price and calculating the Z-Score, this indicator helps traders follow the prevailing trend while avoiding false signals from short-term volatility.
Mean Reversion: The Z-Score highlights moments when the price is far from its mean, helping traders identify overbought or oversold conditions and capitalize on potential reversals.
Divergence Trading: Regular and hidden divergences between the Z-Score and price provide early warning of trend reversals, allowing traders to enter trades at opportune moments.
Final Thoughts
The Savitzky-Golay Z-Score is an advanced statistical tool designed to provide a clearer view of market trends and momentum. By applying the Savitzky-Golay filter and Z-Score analysis, this indicator reduces noise and highlights key areas where the market may reverse or accelerate, giving traders a significant edge in understanding price behavior.
Whether you’re a trend follower or a reversal trader, this indicator offers the flexibility and insights you need to navigate complex markets with confidence.
Freak VolumeFreak Volume is a technical indicator designed to identify bars with exceptionally high trading volume. It operates by calculating the mean volume over a specified period and determines high volume thresholds using both multiples of the mean and standard deviations from this mean.
High Volume Identification:
Standard Deviation Threshold: Bars with volume exceeding a specified number of standard deviations above the mean are highlighted within the indicator and on the corresponding candlesticks on the chart.
Mean Multiple Threshold: Bars with volume exceeding a multiple of the average volume are also highlighted. This highlighting is secondary to the standard deviation threshold, meaning standard deviation-based highlights take precedence.
Price Range Plotting: The indicator offers an option to display the price range of high volume candles, which may serve as potential supply and demand zones or support and resistance levels.
Freak Volume assists traders in visually identifying significant volume spikes that could indicate important market activity or potential turning points by providing multiple methods of high volume detection.
Trading IQ - ICT LibraryLibrary "ICTlibrary"
Used to calculate various ICT related price levels and strategies. An ongoing project.
Hello Coders!
This library is meant for sourcing ICT related concepts. While some functions might generate more output than you require, you can specify "Lite Mode" as "true" in applicable functions to slim down necessary inputs.
isLastBar(userTF)
Identifies the last bar on the chart before a timeframe change
Parameters:
userTF (simple int) : the timeframe you wish to calculate the last bar for, must be converted to integer using 'timeframe.in_seconds()'
Returns: bool true if bar on chart is last bar of higher TF, dalse if bar on chart is not last bar of higher TF
necessaryData(atrTF)
returns necessaryData UDT for historical data access
Parameters:
atrTF (float) : user-selected timeframe ATR value.
Returns: logZ. log return Z score, used for calculating order blocks.
method gradBoxes(gradientBoxes, idColor, timeStart, bottom, top, rightCoordinate)
creates neon like effect for box drawings
Namespace types: array
Parameters:
gradientBoxes (array) : an array.new() to store the gradient boxes
idColor (color)
timeStart (int) : left point of box
bottom (float) : bottom of box price point
top (float) : top of box price point
rightCoordinate (int) : right point of box
Returns: void
checkIfTraded(tradeName)
checks if recent trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent trade id matches target name, false otherwise
checkIfClosed(tradeName)
checks if recent closed trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent closed trade id matches target name, false otherwise
IQZZ(atrMult, finalTF)
custom ZZ to quickly determine market direction.
Parameters:
atrMult (float) : an atr multiplier used to determine the required price move for a ZZ direction change
finalTF (string) : the timeframe used for the atr calcuation
Returns: dir market direction. Up => 1, down => -1
method drawBos(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showBOS, isUp)
calculates and draws Break Of Structure
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the BoS line / label
showBOS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether BoS happened during price increase or price decrease.
Returns: void
method drawMSS(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showMSS, isUp, upRejections, dnRejections, highArr, lowArr, timeArr, closeArr, openArr, atrTFarr, upRejectionsPrices, dnRejectionsPrices)
calculates and draws Market Structure Shift. This data is also used to calculate Rejection Blocks.
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the MSS line / label
showMSS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether MSS happened during price increase or price decrease.
upRejections (array)
dnRejections (array)
highArr (array) : array containing historical highs, should be taken from the UDT "necessaryData" defined above
lowArr (array) : array containing historical lows, should be taken from the UDT "necessaryData" defined above
timeArr (array) : array containing historical times, should be taken from the UDT "necessaryData" defined above
closeArr (array) : array containing historical closes, should be taken from the UDT "necessaryData" defined above
openArr (array) : array containing historical opens, should be taken from the UDT "necessaryData" defined above
atrTFarr (array) : array containing historical atr values (of user-selected TF), should be taken from the UDT "necessaryData" defined above
upRejectionsPrices (array) : array containing up rejections prices. Is sorted and used to determine selective looping for invalidations.
dnRejectionsPrices (array) : array containing down rejections prices. Is sorted and used to determine selective looping for invalidations.
Returns: void
method getTime(id, compare, timeArr)
gets time of inputted price (compare) in an array of data
this is useful when the user-selected timeframe for ICT concepts is greater than the chart's timeframe
Namespace types: array
Parameters:
id (array) : the array of data to search through, to find which index has the same value as "compare"
compare (float) : the target data point to find in the array
timeArr (array) : array of historical times
Returns: the time that the data point in the array was recorded
method OB(id, highArr, signArr, lowArr, timeArr, sign)
store bullish orderblock data
Namespace types: array
Parameters:
id (array)
highArr (array) : array of historical highs
signArr (array) : array of historical price direction "math.sign(close - open)"
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
sign (int) : orderblock direction, -1 => bullish, 1 => bearish
Returns: void
OTEstrat(OTEstart, future, closeArr, highArr, lowArr, timeArr, longOTEPT, longOTESL, longOTElevel, shortOTEPT, shortOTESL, shortOTElevel, structureDirection, oteLongs, atrTF, oteShorts)
executes the OTE strategy
Parameters:
OTEstart (chart.point)
future (int) : future time point for drawings
closeArr (array) : array of historical closes
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
longOTEPT (string) : user-selected long OTE profit target, please create an input.string() for this using the example below
longOTESL (int) : user-selected long OTE stop loss, please create an input.string() for this using the example below
longOTElevel (float) : long entry price of selected retracement ratio for OTE
shortOTEPT (string) : user-selected short OTE profit target, please create an input.string() for this using the example below
shortOTESL (int) : user-selected short OTE stop loss, please create an input.string() for this using the example below
shortOTElevel (float) : short entry price of selected retracement ratio for OTE
structureDirection (string) : current market structure direction, this should be "Up" or "Down". This is used to cancel pending orders if market structure changes
oteLongs (bool) : input.bool() for whether OTE longs can be executed
atrTF (float) : atr of the user-seleceted TF
oteShorts (bool) : input.bool() for whether OTE shorts can be executed
@exampleInputs
oteLongs = input.bool(defval = false, title = "OTE Longs", group = "Optimal Trade Entry")
longOTElevel = input.float(defval = 0.79, title = "Long Entry Retracement Level", options = , group = "Optimal Trade Entry")
longOTEPT = input.string(defval = "-0.5", title = "Long TP", options = , group = "Optimal Trade Entry")
longOTESL = input.int(defval = 0, title = "How Many Ticks Below Swing Low For Stop Loss", group = "Optimal Trade Entry")
oteShorts = input.bool(defval = false, title = "OTE Shorts", group = "Optimal Trade Entry")
shortOTElevel = input.float(defval = 0.79, title = "Short Entry Retracement Level", options = , group = "Optimal Trade Entry")
shortOTEPT = input.string(defval = "-0.5", title = "Short TP", options = , group = "Optimal Trade Entry")
shortOTESL = input.int(defval = 0, title = "How Many Ticks Above Swing Low For Stop Loss", group = "Optimal Trade Entry")
Returns: void (0)
displacement(logZ, atrTFreg, highArr, timeArr, lowArr, upDispShow, dnDispShow, masterCoords, labelLevels, dispUpcol, rightCoordinate, dispDncol, noBorders)
calculates and draws dispacements
Parameters:
logZ (float) : log return of current price, used to determine a "significant price move" for a displacement
atrTFreg (float) : atr of user-seleceted timeframe
highArr (array) : array of historical highs
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
upDispShow (int) : amount of historical upside displacements to show
dnDispShow (int) : amount of historical downside displacements to show
masterCoords (map) : a map to push the most recent displacement prices into, useful for having key levels in one data structure
labelLevels (string) : used to determine label placement for the displacement, can be inside box, outside box, or none, example below
dispUpcol (color) : upside displacement color
rightCoordinate (int) : future time for displacement drawing, best is "last_bar_time"
dispDncol (color) : downside displacement color
noBorders (bool) : input.bool() to remove box borders, example below
@exampleInputs
labelLevels = input.string(defval = "Inside" , title = "Box Label Placement", options = )
noBorders = input.bool(defval = false, title = "No Borders On Levels")
Returns: void
method getStrongLow(id, startIndex, timeArr, lowArr, strongLowPoints)
unshift strong low data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the low before an upside BoS
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
strongLowPoints (array) : array of strong low prices. Used to retrieve highest strong low price and see if need for
removal of invalidated strong lows
Returns: void
method getStrongHigh(id, startIndex, timeArr, highArr, strongHighPoints)
unshift strong high data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the high before a downside BoS
timeArr (array) : array of historical times
highArr (array) : array of historical highs
strongHighPoints (array)
Returns: void
equalLevels(highArr, lowArr, timeArr, rightCoordinate, equalHighsCol, equalLowsCol, liteMode)
used to calculate recent equal highs or equal lows
Parameters:
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
rightCoordinate (int) : a future time (right for boxes, x2 for lines)
equalHighsCol (color) : user-selected color for equal highs drawings
equalLowsCol (color) : user-selected color for equal lows drawings
liteMode (bool) : optional for a lite mode version of an ICT strategy. For more control over drawings leave as "True", "False" will apply neon effects
Returns: void
quickTime(timeString)
used to quickly determine if a user-inputted time range is currently active in NYT time
Parameters:
timeString (string) : a time range
Returns: true if session is active, false if session is inactive
macros(showMacros, noBorders)
used to calculate and draw session macros
Parameters:
showMacros (bool) : an input.bool() or simple bool to determine whether to activate the function
noBorders (bool) : an input.bool() to determine whether the box anchored to the session should have borders
Returns: void
po3(tf, left, right, show)
use to calculate HTF po3 candle
@tip only call this function on "barstate.islast"
Parameters:
tf (simple string)
left (int) : the left point of the candle, calculated as bar_index + left,
right (int) : :the right point of the candle, calculated as bar_index + right,
show (bool) : input.bool() whether to show the po3 candle or not
Returns: void
silverBullet(silverBulletStratLong, silverBulletStratShort, future, userTF, H, L, H2, L2, noBorders, silverBulletLongTP, historicalPoints, historicalData, silverBulletLongSL, silverBulletShortTP, silverBulletShortSL)
used to execute the Silver Bullet Strategy
Parameters:
silverBulletStratLong (simple bool)
silverBulletStratShort (simple bool)
future (int) : a future time, used for drawings, example "last_bar_time"
userTF (simple int)
H (float) : the high price of the user-selected TF
L (float) : the low price of the user-selected TF
H2 (float) : the high price of the user-selected TF
L2 (float) : the low price of the user-selected TF
noBorders (bool) : an input.bool() used to remove the borders from box drawings
silverBulletLongTP (series silverBulletLevels)
historicalPoints (array)
historicalData (necessaryData)
silverBulletLongSL (series silverBulletLevels)
silverBulletShortTP (series silverBulletLevels)
silverBulletShortSL (series silverBulletLevels)
Returns: void
method invalidFVGcheck(FVGarr, upFVGpricesSorted, dnFVGpricesSorted)
check if existing FVGs are still valid
Namespace types: array
Parameters:
FVGarr (array)
upFVGpricesSorted (array) : an array of bullish FVG prices, used to selective search through FVG array to remove invalidated levels
dnFVGpricesSorted (array) : an array of bearish FVG prices, used to selective search through FVG array to remove invalidated levels
Returns: void (0)
method drawFVG(counter, FVGshow, FVGname, FVGcol, data, masterCoords, labelLevels, borderTransp, liteMode, rightCoordinate)
draws FVGs on last bar
Namespace types: map
Parameters:
counter (map) : a counter, as map, keeping count of the number of FVGs drawn, makes sure that there aren't more FVGs drawn
than int FVGshow
FVGshow (int) : the number of FVGs to show. There should be a bullish FVG show and bearish FVG show. This function "drawFVG" is used separately
for bearish FVG and bullish FVG.
FVGname (string) : the name of the FVG, "FVG Up" or "FVG Down"
FVGcol (color) : desired FVG color
data (FVG)
masterCoords (map) : a map containing the names and price points of key levels. Used to define price ranges.
labelLevels (string) : an input.string with options "Inside", "Outside", "Remove". Determines whether FVG labels should be inside box, outside,
or na.
borderTransp (int)
liteMode (bool)
rightCoordinate (int) : the right coordinate of any drawings. Must be a time point.
Returns: void
invalidBlockCheck(bullishOBbox, bearishOBbox, userTF)
check if existing order blocks are still valid
Parameters:
bullishOBbox (array) : an array declared using the UDT orderBlock that contains bullish order block related data
bearishOBbox (array) : an array declared using the UDT orderBlock that contains bearish order block related data
userTF (simple int)
Returns: void (0)
method lastBarRejections(id, rejectionColor, idShow, rejectionString, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws rejectionBlocks on last bar
Namespace types: array
Parameters:
id (array) : the array, an array of rejection block data declared using the UDT rejection block
rejectionColor (color) : the desired color of the rejection box
idShow (int)
rejectionString (string) : the desired name of the rejection blocks
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
method OBdraw(id, OBshow, BBshow, OBcol, BBcol, bullishString, bearishString, isBullish, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws orderblocks and breaker blocks for data stored in UDT array()
Namespace types: array
Parameters:
id (array) : the array, an array of order block data declared using the UDT orderblock
OBshow (int) : the number of order blocks to show
BBshow (int) : the number of breaker blocks to show
OBcol (color) : color of order blocks
BBcol (color) : color of breaker blocks
bullishString (string) : the title of bullish blocks, which is a regular bullish orderblock or a bearish orderblock that's converted to breakerblock
bearishString (string) : the title of bearish blocks, which is a regular bearish orderblock or a bullish orderblock that's converted to breakerblock
isBullish (bool) : whether the array contains bullish orderblocks or bearish orderblocks. If bullish orderblocks,
the array will naturally contain bearish BB, and if bearish OB, the array will naturally contain bullish BB
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
FVG
UDT for FVG calcualtions
Fields:
H (series float) : high price of user-selected timeframe
L (series float) : low price of user-selected timeframe
direction (series string) : FVG direction => "Up" or "Down"
T (series int) : => time of bar on user-selected timeframe where FVG was created
fvgLabel (series label) : optional label for FVG
fvgLineTop (series line) : optional line for top of FVG
fvgLineBot (series line) : optional line for bottom of FVG
fvgBox (series box) : optional box for FVG
labelLine
quickly pair a line and label together as UDT
Fields:
lin (series line) : Line you wish to pair with label
lab (series label) : Label you wish to pair with line
orderBlock
UDT for order block calculations
Fields:
orderBlockData (array) : array containing order block x and y points
orderBlockBox (series box) : optional order block box
vioCount (series int) : = 0 violation count of the order block. 0 = Order Block, 1 = Breaker Block
traded (series bool)
status (series string) : = "OB" status == "OB" => Level is order block. status == "BB" => Level is breaker block.
orderBlockLab (series label) : options label for the order block / breaker block.
strongPoints
UDT for strong highs and strong lows
Fields:
price (series float) : price of the strong high or strong low
timeAtprice (series int) : time of the strong high or strong low
strongPointLabel (series label) : optional label for strong point
strongPointLine (series line) : optional line for strong point
overlayLine (series line) : optional lines for strong point to enhance visibility
overlayLine2 (series line) : optional lines for strong point to enhance visibility
displacement
UDT for dispacements
Fields:
highPrice (series float) : high price of displacement
lowPrice (series float) : low price of displacement
timeAtPrice (series int) : time of bar where displacement occurred
displacementBox (series box) : optional box to draw displacement
displacementLab (series label) : optional label for displacement
po3data
UDT for po3 calculations
Fields:
dHigh (series float) : higher timeframe high price
dLow (series float) : higher timeframe low price
dOpen (series float) : higher timeframe open price
dClose (series float) : higher timeframe close price
po3box (series box) : box to draw po3 candle body
po3line (array) : line array to draw po3 wicks
po3Labels (array) : label array to label price points of po3 candle
macros
UDT for session macros
Fields:
sessions (array) : Array of sessions, you can populate this array using the "quickTime" function located above "export macros".
prices (matrix) : Matrix of session data -> open, high, low, close, time
sessionTimes (array) : Array of session names. Pairs with array sessions.
sessionLines (matrix) : Optional array for sesion drawings.
OTEtimes
UDT for data storage and drawings associated with OTE strategy
Fields:
upTimes (array) : time of highest point before trade is taken
dnTimes (array) : time of lowest point before trade is taken
tpLineLong (series line) : line to mark tp level long
tpLabelLong (series label) : label to mark tp level long
slLineLong (series line) : line to mark sl level long
slLabelLong (series label) : label to mark sl level long
tpLineShort (series line) : line to mark tp level short
tpLabelShort (series label) : label to mark tp level short
slLineShort (series line) : line to mark sl level short
slLabelShort (series label) : label to mark sl level short
sweeps
UDT for data storage and drawings associated with liquidity sweeps
Fields:
upSweeps (matrix) : matrix containing liquidity sweep price points and time points for up sweeps
dnSweeps (matrix) : matrix containing liquidity sweep price points and time points for down sweeps
upSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
dnSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
raidExitDrawings
UDT for drawings associated with the Liquidity Raid Strategy
Fields:
tpLine (series line) : tp line for the liquidity raid entry
tpLabel (series label) : tp label for the liquidity raid entry
slLine (series line) : sl line for the liquidity raid entry
slLabel (series label) : sl label for the liquidity raid entry
m2022
UDT for data storage and drawings associated with the Model 2022 Strategy
Fields:
mTime (series int) : time of the FVG where entry limit order is placed
mIndex (series int) : array index of FVG where entry limit order is placed. This requires an array of FVG data, which is defined above.
mEntryDistance (series float) : the distance of the FVG to the 50% range. M2022 looks for the fvg closest to 50% mark of range.
mEntry (series float) : the entry price for the most eligible fvg
fvgHigh (series float) : the high point of the eligible fvg
fvgLow (series float) : the low point of the eligible fvg
longFVGentryBox (series box) : long FVG box, used to draw the eligible FVG
shortFVGentryBox (series box) : short FVG box, used to draw the eligible FVG
line50P (series line) : line used to mark 50% of the range
line100P (series line) : line used to mark 100% (top) of the range
line0P (series line) : line used to mark 0% (bottom) of the range
label50P (series label) : label used to mark 50% of the range
label100P (series label) : label used to mark 100% (top) of the range
label0P (series label) : label used to mark 0% (bottom) of the range
sweepData (array)
silverBullet
UDT for data storage and drawings associated with the Silver Bullet Strategy
Fields:
session (series bool)
sessionStr (series string) : name of the session for silver bullet
sessionBias (series string)
sessionHigh (series float) : = high high of session // use math.max(silverBullet.sessionHigh, high)
sessionLow (series float) : = low low of session // use math.min(silverBullet.sessionLow, low)
sessionFVG (series float) : if applicable, the FVG created during the session
sessionFVGdraw (series box) : if applicable, draw the FVG created during the session
traded (series bool)
tp (series float) : tp of trade entered at the session FVG
sl (series float) : sl of trade entered at the session FVG
sessionDraw (series box) : optional draw session with box
sessionDrawLabel (series label) : optional label session with label
silverBulletDrawings
UDT for trade exit drawings associated with the Silver Bullet Strategy
Fields:
tpLine (series line) : tp line drawing for strategy
tpLabel (series label) : tp label drawing for strategy
slLine (series line) : sl line drawing for strategy
slLabel (series label) : sl label drawing for strategy
unicornModel
UDT for data storage and drawings associated with the Unicorn Model Strategy
Fields:
hPoint (chart.point)
hPoint2 (chart.point)
hPoint3 (chart.point)
breakerBlock (series box) : used to draw the breaker block required for the Unicorn Model
FVG (series box) : used to draw the FVG required for the Unicorn model
topBlock (series float) : price of top of breaker block, can be used to detail trade entry
botBlock (series float) : price of bottom of breaker block, can be used to detail trade entry
startBlock (series int) : start time of the breaker block, used to set the "left = " param for the box
includes (array) : used to store the time of the breaker block, or FVG, or the chart point sequence that setup the Unicorn Model.
entry (series float) : // eligible entry price, for longs"math.max(topBlock, FVG.get_top())",
tpLine (series line) : optional line to mark PT
tpLabel (series label) : optional label to mark PT
slLine (series line) : optional line to mark SL
slLabel (series label) : optional label to mark SL
rejectionBlocks
UDT for data storage and drawings associated with rejection blocks
Fields:
rejectionPoint (chart.point)
bodyPrice (series float) : candle body price closest to the rejection point, for "Up" rejections => math.max(open, close),
rejectionBox (series box) : optional box drawing of the rejection block
rejectionLabel (series label) : optional label for the rejection block
equalLevelsDraw
UDT for data storage and drawings associated with equal highs / equal lows
Fields:
connector (series line) : single line placed at the first high or low, y = avgerage of distinguished equal highs/lows
connectorLab (series label) : optional label to be placed at the highs or lows
levels (array) : array containing the equal highs or lows prices
times (array) : array containing the equal highs or lows individual times
startTime (series int) : the time of the first high or low that forms a sequence of equal highs or lows
radiate (array) : options label to "radiate" the label in connector lab. Can be used for anything
necessaryData
UDT for data storage of historical price points.
Fields:
highArr (array) : array containing historical high points
lowArr (array) : array containing historical low points
timeArr (array) : array containing historical time points
logArr (array) : array containing historical log returns
signArr (array) : array containing historical price directions
closeArr (array) : array containing historical close points
binaryTimeArr (array) : array containing historical time points, uses "push" instead of "unshift" to allow for binary search
binaryCloseArr (array) : array containing historical close points, uses "push" instead of "unshift" to allow the correct
binaryOpenArr (array) : array containing historical optn points, uses "push" instead of "unshift" to allow the correct
atrTFarr (array) : array containing historical user-selected TF atr points
openArr (array) : array containing historical open points
Supply and demandHi all!
This is my take on supply/demand. The gist is that it creates a zone if there is a big enough reaction. This is configurable in settings as "Minimum range (ATR factor)" (the Average True Length of length 14) that is the distance that the price must travel and "Reaction bars" that is the maximum number of bars that price must travel this distance. The zones that are shown are the ones that have a retest, break and retest or is unmitigated (untouched). If a zone is mitigated (entered) or broken it is temporarily hidden. For a zone to be created it needs to have this reaction and the previous bar does not.
So this script will show you zones that are fresh (unmitigated), retested or broken and retested. This means that the zones that are shown have "proven" that they are good zones through this. Basically it means that the script creates a bunch of zones and then picks the good once. This makes the script have some latency, but will hopefully give you good zones. A zone is completely removed if it's broken twice (it's okay if it's broken once and can still have a retest after it has flipped from previous supply (or resistance) into demand (or support)).
Here is a zone (the one that has the lowest opacity) that is broken and retested that could have resulted in a good long trade (the settings are default but has a stop in the beginning of 2024):
You have a setting to remove zones that are pierced (broken by price wicks). The following zone is pierced by price (in the beginning of May) that will not be shown after the start of May if you have "Pierced" checked (the indicator has default settings but a stop in the middle of April):
You have a trend section. Zones that create a reaction upwards can only be created if the trend is considered to be up, and vice versa. The options here are "SMA50" (the current price needs to be over the Simple Moving Average of length 50) and "SMA50, SMA200" (price needs to be over the Simple Moving Average of length 50 and the Simple Moving Average of length 50 needs to be over the Simple Moving Average of length 200). If these conditions are met the trend is considered to be up, otherwise it's down. You can disable this by choosing "No detection".
The zones that are shown also need to be within a limit (of the current price). This limit is 10 (factor of the Average True Range if length 14) by default. Set this to 0 to deactivate. This is useful for not showing zones that are far away from current price and therefore unlikely to be interacted with.
You can stop the calculation of zones (through the "Stop" value in the settings). This is useful to see if previous zones were any good. I used it in my testing of the script but left it because it can be nice to have.
The zones created by the script have different transparency based upon the zone's interaction. The clearest zones are the ones that are unmitigated, the second clearest ones are the ones having a retest and lastly the zones which are most unclear are the ones having a break and then a retest.
You can see the concept of this script to be a mix of supply/demand and support/resistance, having zones being unmitigated (untouched) as the most important but also show the zones having an interaction (in the form of a retest or a break and retest).
This is from a previous supply (or resistance) zone that has flipped into demand (or support) and has shown to be a good zone through a retest followed by a rally (default settings):
This zone has multiple retest and then rallies that could have given a good long trades (it has the default settings but a "Stop" time at 2022-01-14):
TODO:
- Create zones based on pivots
- Handle overlapping zones
- Incorporate volume in the creation and/or interaction with zones
- Add alerts
- Add ability to set maximum zone width
- Add ability to set the maximum number of retest bars
- ...?
The example for this publication has the default settings bit a "Stop" and a tighter "Limit" of 4.
I hope this explanation makes sense, let me know otherwise. Also let me know if you have any suggestions on improvements.
Best of trading luck!
Earnings Surprise Indicator (Post-Earnings Announcement Drift)What It Does:
- Displays a company's actual earnings vs. analysts' estimates over time
- Shows "earnings surprises" - when actual results beat or miss expectations
- Helps identify trends in a company's financial performance
How It Works:
- Green bars: Positive surprise (earnings beat estimates)
- Red bars: Negative surprise (earnings missed estimates)
- Yellow line: Analysts' earnings estimates
Correlation with Post Earnings Announcement Drift (PEAD): PEAD is the tendency for a stock's price to drift in the direction of an earnings surprise for several weeks or months after the announcement.
Why It Matters:
- Positive surprises often lead to upward price drift
- Negative surprises often lead to downward price drift
- This drift can create trading opportunities
How to Use It:
1. Spot Trends:
- Consistent beats may indicate strong company performance
- Consistent misses may signal underlying issues
2. Gauge Market Expectations:
- Large surprises may lead to significant price movements
3. Timing Decisions:
- Consider long positions after positive surprises
- Consider short positions or exits after negative surprises
4. Risk Management:
- Be cautious of reversal if the drift seems excessive
- Use in conjunction with other technical and fundamental analysis
Key Takeaways:
- Earnings surprises can be fundamental-leading indicators of future stock performance, especially when correlated with analyst projections
- PEAD suggests that markets often underreact to earnings news initially
- This indicator helps visualize the magnitude and direction of surprises
- It can be a valuable tool for timing entry and exit points in trades
Savitzky Golay Median Filtered RSI [BackQuant]Savitzky Golay Median Filtered RSI
Introducing BackQuant's Savitzky Golay Median Filtered RSI, a cutting-edge indicator that enhances the classic Relative Strength Index (RSI) by applying both a Savitzky-Golay filter and a median filter to provide smoother and more reliable signals. This advanced approach helps reduce noise and captures true momentum trends with greater precision. Let’s break down how the indicator works, the features it offers, and how it can improve your trading strategy.
Core Concept: Relative Strength Index (RSI)
The Relative Strength Index (RSI) is a widely used momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100, with levels above 70 typically indicating overbought conditions and levels below 30 indicating oversold conditions. However, the standard RSI can sometimes generate noisy signals, especially in volatile markets, making it challenging to identify reliable entry and exit points.
To improve upon the traditional RSI, this indicator introduces two powerful filters: the Savitzky-Golay filter and a median filter.
Savitzky-Golay Filter: Smoothing with Precision
The Savitzky-Golay filter is a digital filtering technique used to smooth data while preserving important features, such as peaks and trends. Unlike simple moving averages that can distort important price data, the Savitzky-Golay filter uses polynomial regression to fit the data, providing a more accurate and less lagging result.
In this script, the Savitzky-Golay filter is applied to the RSI values to smooth out short-term fluctuations and provide a more reliable signal. By using a window size of 5 and a polynomial degree of 2, the filter effectively reduces noise without compromising the integrity of the underlying price movements.
Median Filter: Reducing Outliers
After applying the Savitzky-Golay filter, the median filter is applied to the smoothed RSI values. The median filter is particularly effective at removing short-lived outliers, further enhancing the accuracy of the RSI by reducing the impact of sudden and temporary price spikes or drops. This combination of filters creates an ultra-smooth RSI that is better suited for detecting true market trends.
Long and Short Signals
The Savitzky Golay Median Filtered RSI generates long and short signals based on user-defined threshold levels:
Long Signals: A long signal is triggered when the filtered RSI exceeds the Long Threshold (default set at 176). This indicates that momentum is shifting upward, and it may present a good buying opportunity.
Short Signals: A short signal is generated when the filtered RSI falls below the Short Threshold (default set at 162). This suggests that momentum is weakening, potentially signaling a selling opportunity or exit from a long position.
These threshold levels can be adjusted to suit different market conditions and timeframes, allowing traders to fine-tune the sensitivity of the indicator.
Customization and Visualization Options
The Savitzky Golay Median Filtered RSI comes with several customization options, enabling traders to tailor the indicator to their specific needs:
Calculation Source: Select the price source for the RSI calculation (default is OHLC4, but it can be changed to close, open, high, or low prices).
RSI Period: Adjust the lookback period for the RSI calculation (default is 14).
Median Filter Length: Control the length of the median filter applied to the smoothed RSI, affecting how much noise is removed from the signal.
Threshold Levels: Customize the long and short thresholds to define the sensitivity for generating buy and sell signals.
UI Settings: Choose whether to display the RSI and thresholds on the chart, color the bars according to trend direction, and adjust the line width and colors used for long and short signals.
Visual Feedback: Color-Coded Signals and Thresholds
To make the signals easier to interpret, the indicator offers visual feedback by coloring the price bars and the RSI plot according to the current market trend:
Green Bars indicate long signals when momentum is bullish.
Red Bars indicate short signals when momentum is bearish.
Gray Bars indicate neutral or undecided conditions when no clear signal is present.
In addition, the Long and Short Thresholds can be plotted directly on the chart to provide a clear reference for when signals are triggered, allowing traders to visually gauge the strength of the RSI relative to its thresholds.
Alerts for Automation
For traders who prefer automated notifications, the Savitzky Golay Median Filtered RSI includes built-in alert conditions for long and short signals. You can configure these alerts to notify you when a buy or sell condition is met, ensuring you never miss a trading opportunity.
Trading Applications
This indicator is versatile and can be used in a variety of trading strategies:
Trend Following: The combination of Savitzky-Golay and median filtering makes this RSI particularly useful for identifying strong trends without being misled by short-term noise. Traders can use the long and short signals to enter trades in the direction of the prevailing trend.
Reversal Trading: By adjusting the threshold levels, traders can use this indicator to spot potential reversals. When the RSI moves from overbought to oversold levels (or vice versa), it may signal a shift in market direction.
Swing Trading: The smoothed RSI provides a clear signal for short to medium-term price movements, making it an excellent tool for swing traders looking to capitalize on momentum shifts.
Risk Management: The filtered RSI can be used as part of a broader risk management strategy, helping traders avoid false signals and stay in trades only when the momentum is strong.
Final Thoughts
The Savitzky Golay Median Filtered RSI takes the classic RSI to the next level by applying advanced smoothing techniques that reduce noise and improve signal reliability. Whether you’re a trend follower, swing trader, or reversal trader, this indicator provides a more refined approach to momentum analysis, helping you make better-informed trading decisions.
As with all indicators, it is important to backtest thoroughly and incorporate sound risk management strategies when using the Savitzky Golay Median Filtered RSI in your trading system.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Big Volume Highlighter ADVANCEDBIG VOLUME HIGHLIGHTER INDICATOR ADVANCED
The BIG VOLUME INDICATOR ADVANCED is an essential tool for traders who want to gain a deeper understanding of market dynamics through volume analysis. This advanced indicator highlights significant volume spikes, enabling traders to make more informed decisions based on market activity and price movements.
Key Features:
Customizable Lookback Period: Define the number of candles over which the highest volume is calculated, allowing you to adjust the analysis to fit your specific trading strategy and timeframe.
Approximate Volume Matching: Activate the approximate volume matching feature to identify candles that fall within a specified range of a target volume. This feature is particularly valuable for capturing notable volume spikes that may not match your exact input but are within an acceptable tolerance.
Flexible Volume Units: Input volumes in various units (Hundreds, Thousands, Millions, or Billions) to cater to your trading preferences. This flexibility ensures that you can analyze volume data in a way that aligns with your trading style.
Dynamic Tolerance Calculation: Set a percentage-based tolerance for volume matching, allowing for greater flexibility. For instance, if you input a volume of 600 million with a tolerance of 1.5%, the indicator will highlight candles with volumes ranging from 591 million to 609 million.
Visual Alerts: Highlighted candles are marked with clear, color-coded labels positioned above the bars. Green labels represent bullish candles, while red labels denote bearish candles, providing immediate visual feedback on market sentiment.
Mobile and Desktop Compatibility: Designed for seamless integration with TradingView, this indicator is accessible on both desktop and mobile devices, ensuring that you can monitor the market wherever you are.
How to Use:
Set the Lookback Period: Adjust the lookback period to analyze a specific number of candles for volume spikes.
Enable Approximate Volume Matching: If desired, toggle the approximate volume matching feature and enter your target volume, selecting the appropriate unit.
Adjust Tolerance: Define the tolerance percentage to specify how close the volume must be to your input for it to be considered significant.
Analyze the Chart: Observe the highlighted candles on your chart, which indicate significant volume activity based on your criteria.
Make Informed Decisions: Leverage the insights provided by the indicator to guide your trading decisions, identifying potential entry or exit points based on volume analysis.
****
Kalman For Loop [BackQuant]Kalman For Loop
Introducing BackQuant's Kalman For Loop (Kalman FL) — a highly adaptive trading indicator that uses a Kalman filter to smooth price data and generate actionable long and short signals. This advanced indicator is designed to help traders identify trends, filter out market noise, and optimize their entry and exit points with precision. Let’s explore how this indicator works, its key features, and how it can enhance your trading strategies.
Core Concept: Kalman Filter
The Kalman Filter is a mathematical algorithm used to estimate the state of a system by filtering noisy data. It is widely used in areas such as control systems, signal processing, and time-series analysis. In the context of trading, a Kalman filter can be applied to price data to smooth out short-term fluctuations, providing a clearer view of the underlying trend.
Unlike moving averages, which use fixed weights to smooth data, the Kalman Filter adjusts its estimate dynamically based on the relationship between the process noise and the measurement noise. This makes the filter more adaptive to changing market conditions, providing more accurate trend detection without the lag associated with traditional smoothing techniques.
Please see the original Kalman Price Filter
In this script, the Kalman For Loop applies the Kalman filter to the price source (default set to the closing price) to generate a smoothed price series, which is then used to calculate signals.
Adaptive Smoothing with Process and Measurement Noise
Two key parameters govern the behavior of the Kalman filter:
Process Noise: This controls the extent to which the model allows for uncertainty in price changes. A lower process noise value will make the filter smoother but slower to react to price changes, while a higher value makes it more sensitive to recent price fluctuations.
Measurement Noise: This represents the uncertainty or "noise" in the observed price data. A higher measurement noise value gives the filter more leeway to ignore short-term fluctuations, focusing on the broader trend. Lowering the measurement noise makes the filter more responsive to minor changes in price.
These settings allow traders to fine-tune the Kalman filter’s sensitivity, adjusting it to match their preferred trading style or market conditions.
For-Loop Scoring Mechanism
The Kalman FL further enhances the effectiveness of the Kalman filter by using a for-loop scoring system. This mechanism evaluates the smoothed price over a range of periods (defined by the Calculation Start and Calculation End inputs), assigning a score based on whether the current filtered price is higher or lower than previous values.
Long Signals: A long signal is generated when the for-loop score surpasses the Long Threshold (default set at 20), indicating a strong upward trend. This helps traders identify potential buying opportunities.
Short Signals: A short signal is triggered when the score crosses below the Short Threshold (default set at -10), signaling a potential downtrend or selling opportunity.
These signals are plotted on the chart, giving traders a clear visual indication of when to enter long or short positions.
Customization and Visualization Options
The Kalman For Loop comes with a range of customization options to give traders full control over how the indicator operates and is displayed on the chart:
Kalman Price Source: Choose the price data used for the Kalman filter (default is the closing price), allowing you to apply the filter to other price points like open, high, or low.
Filter Order: Set the order of the Kalman filter (default is 5), controlling how far back the filter looks in its calculations.
Process and Measurement Noise: Fine-tune the sensitivity of the Kalman filter by adjusting these noise parameters.
Signal Line Width and Colors: Customize the appearance of the signal line and the colors used to indicate long and short conditions.
Threshold Lines: Toggle the display of the long and short threshold lines on the chart for better visual clarity.
The indicator also includes the option to color the candlesticks based on the current trend direction, allowing traders to quickly identify changes in market sentiment. In addition, a background color feature further highlights the overall trend by shading the background in green for long signals and red for short signals.
Trading Applications
The Kalman For Loop is a versatile tool that can be adapted to a variety of trading strategies and markets. Some of the primary use cases include:
Trend Following: The adaptive nature of the Kalman filter helps traders identify the start of new trends with greater precision. The for-loop scoring system quantifies the strength of the trend, making it easier to stay in trades for longer when the trend remains strong.
Mean Reversion: For traders looking to capitalize on short-term reversals, the Kalman filter's ability to smooth price data makes it easier to spot when price has deviated too far from its expected path, potentially signaling a reversal.
Noise Reduction: The Kalman filter excels at filtering out short-term price noise, allowing traders to focus on the broader market movements without being distracted by minor fluctuations.
Risk Management: By providing clear long and short signals based on filtered price data, the Kalman FL helps traders manage risk by entering positions only when the trend is well-defined, reducing the chances of false signals.
Alerts and Automation
To further assist traders, the Kalman For Loop includes built-in alert conditions that notify you when a long or short signal is generated. These alerts can be configured to trigger notifications, helping you stay on top of market movements without constantly monitoring the chart.
Final Thoughts
The Kalman For Loop is a powerful and adaptive trading indicator that combines the precision of the Kalman filter with a for-loop scoring mechanism to generate reliable long and short signals. Whether you’re a trend follower or a reversal trader, this indicator offers the flexibility and accuracy needed to navigate complex markets with confidence.
As always, it’s important to backtest the indicator and adjust the settings to fit your trading style and market conditions. No indicator is perfect, and the Kalman FL should be used alongside other tools and sound risk management practices for the best results.
Enhanced Kelly Criterion with Risk ManagementThis script is a trading tool for risk management and position size calculations based on the Kelly criteria. The objective is to calculate the optimal position size for each trade based on win/loss ratio and win/loss ratio to manage your money.
Overview
Initial Funding: Starting with an initial capital of $10,000, the balance (amount of funds) of both “bullish” and “bearish” positions will increase or decrease depending on the outcome of the trade.
Risk Management: Users can set their risk tolerance from 1-100%. In addition, the maximum position size per trade is also limited at 50%, for example. This setting allows the user to limit risk.
Record of trade results: For each trade, a positive (bullish) or negative (bearish) line is determined, and wins and losses are recorded accordingly. Win/loss ratios and win/loss ratios are also calculated in real time from this data.
Win rate: Calculates the percentage of winning trades in a trade.
Win/Loss Ratio: Calculates the ratio of profit/loss between positive and negative trades.
Position sizing using the Kelly Criterion: Based on the win/loss ratio, the optimal position size to take on the next trade is calculated using the Kelly Criterion. However, this Kelly Criterion is treated with caution because of the potential for increased risk.
Controlling Risk and Position Size
Volatility adjustment using ATR (Average True Range): The script considers market volatility (range of price fluctuation) using a measure called ATR. This allows for smaller position sizes when price volatility is high, thereby reducing risk.
Position Size Limit: The maximum position size is limited so that the calculated position size does not exceed a certain range. This reduces the risk of large losses.
Display of Results
The script visually plots the final position size and amount of funds so that traders can see the changes in balance. To highlight points of change, position size expansions and contractions are shown, allowing traders to catch signs of sudden fluctuations or changes in volatility.
Suggested Improvements and Considerations
Kelly Criteria Overexposure Risk: Calculations based on the Kelly Criteria are theoretically correct, but they tend to take large positions. This can be very damaging in the event of losses. Therefore, while this script limits risk by setting a maximum position size, it is recommended that you adjust to an even more modest position size.
Data Reliability: The calculation of win/loss ratios and win/loss ratios relies on historical trade data, which can be unreliable until sufficient trade data is gathered. When trade data is scarce, calculations based on the Kelly Criteria may be overly optimistic.
Volatility considerations: Volatility adjustment using ATR is effective, but ATR alone may not be sufficient when markets fluctuate rapidly; if ATR adjustment is insufficient, additional risk mitigation techniques should be used in conjunction.
Overall, this script emphasizes risk management and optimizes position size using the Kelly criteria, but real market conditions require careful risk management with attention to overexposure.
ATR Trailing Stop by tactical trade 22 Oct 2024Description:
The ATR Dual Trailing Stop indicator is a versatile and powerful tool designed to help traders visualize dynamic support and resistance levels based on the Average True Range (ATR). This indicator plots two separate ATR-based trailing stops with customizable settings, providing a comprehensive view of potential market reversals and trend strength.
Key features:
Two ATR Trailing Stops: The first stop uses customizable ATR settings (default: 10-period ATR with a 3x multiplier), while the second stop uses an alternate configuration (default: 21-period ATR with a 7x multiplier).
Multi-Timeframe ATR Calculation: Regardless of the chart's time frame, the ATR is calculated based on a user-selected time frame (e.g., daily), allowing for consistent stop-loss levels even in lower time frames like 5-minute or 15-minute charts.
Visual Cues: The indicator clearly plots two trailing stop lines in different colors, making it easy to track the market’s volatility-based support and resistance areas.
No Buy/Sell Signals: This is purely a trailing stop indicator with no embedded buy/sell signals, giving traders the flexibility to use it with their preferred entry/exit strategies.
This indicator is especially useful in highly volatile markets where precise trailing stop levels are essential for managing risk and maximizing profit potential. The dual ATR configuration helps traders adapt to changing market conditions by providing two levels of stop placement: a shorter-term and a longer-term trailing stop.
SMI Ergodic Indicator/Oscillator▮ Introduction
The Stochastic Momentum Index Ergodic Indicator (SMII) is a technical analysis tool designed to predict trend reversals in the price of an asset.
It functions as a momentum oscillator, measuring the ratio of the smoothed price change to the smoothed absolute price change over a given number of previous periods.
The Ergodic SMI is based on the True Strength Index (TSI) and integrates a signal line, which is an exponential moving average (EMA) of the SMI indicator itself.
It provides a clearer picture of market trends than the traditional stochastic oscillator by incorporating the concept of "ergodicity", which helps remove market noise.
On ther other hand, the Stochastic Momentum Index Ergodic Oscillator (SMIO) is a histogram that measures the difference between TSI and it's signal line.
By default, in TradingView both SMII and SMIO are provided independently.
Here in this script these two indicators are combined, providing a more comprehensive view of price direction and market strength.
▮ Motivation: why another indicator?
The intrinsic value of this indicator lies in the fact that it allows fine adjustments in both calculation parameters, data source and visualization, features that are not present in the standard indicators or similar.
Also, trend lines breakouts and divergences detector were added.
▮ What to look for
When using the indicator, there are a few things to look out for.
First, look at the SMI signal line.
When the line crosses above -40, it is considered a buy signal, while the crossing below +40 is considered a sell signal.
Also, pay attention to divergences between the SMI and the price.
If price is rising but the SMI is showing negative divergence, it could indicate that momentum is waning and a reversal could be in the offing.
Likewise, if price is falling but the SMI is showing positive divergence, this could indicate that momentum is building and a reversal could also be in the offing.
Divergences can be considered in both indicator and/or histogram.
Examples:
▮ Notes
The indicator presented here offers both the "SMII" and the "SMIO", that is, the "Stochastic Momentum Index Ergodic Indicator" together with the "Stochastic Momentum Index Ergodic Oscillator" (histogram), as per the documentation described in reference links.
So it is important to highlight the differences in relation to my other indicator, Stochastic Momentum Index (SMI) Refurbished .
This last one is purely based on the **SMI**, which is implemented using smoothed ratio between the relative range and the high/low range.
Although they may seem the same in some situations, the calculation is actually different. The TSI tends to be more responsive at the expense of being noisier, while the SMI tends to be smoother. Which of these two indicators is best depends on the situation, the context, and the analyst's personal preference.
Please refer to reference links to more info.
▮ References
SMI documentation
SMII documentation
SMIO documentation
Profitable Mondays & Losing FridaysHere's a Pine Script that marks profitable Mondays and losing Fridays for a given stock:
Explanation
Input Parameter: The script allows you to input the stock symbol, defaulting to SPX.
Daily Returns: It calculates the daily return based on the closing price.
Day Identification: It checks if the current day is Monday or Friday.
Conditions:
Profitable Mondays: Marks with a green background if Monday's return is positive.
Losing Fridays: Marks with a red background if Friday's return is negative.
Visualization: Uses bgcolor to highlight the respective days on the chart.
You can adjust the stockSymbol input to analyze different stocks.
Price Action All In OneThis indicator represents the most advanced level of price action indicators, incorporating six useful features: traditional gaps, shadow gaps, bar counting, moving averages, previous values, and IO pattern matching .
When I refer to price action, I mean the teachings of Dr. Al Brooks.
While you can find these features in other indicators, mine is more advanced. The default settings are designed to work on a 5-minute timeframe, but you can also use this indicator on other time periods if you prefer.
Gaps
Traditional Gaps: Occurs when the lowest price of a bar is higher than the highest price of the previous bar, or the highest price of a bar is lower than the lowest price of the previous bar.
Shadow/Tail Gaps: Occurs when the lowest price of a bar is higher than the highest price of the second last bar, or the highest price of a bar is lower than the lowest price of the second last bar.
Gaps indicate strength, and consecutive gaps in one direction are characteristic of a strong trend. They offer a perspective on the strength of a trend, signifying that limit orders on one side are at a loss with no opportunity to exit at breakeven. Can bulls or bears create gaps? Are the gaps they create filled, or do they remain open?
Traditional Gaps & Shadow/Tail Gaps
Bar Counting
The ability to use different timeframes (e.g., to determine the minute within an hour or the hour within a week).
Consistent display of 1; in other indicators, if you set intervals to 2, you see 2, 4, 6, etc., or 1, 2, 4, 6. In my indicator, you will see 1, 3, 5, etc.
In intraday trading, certain specific times are more important than others. For example, a form of reversal is more likely to occur at the midpoint of the trading day (if there are 80 candles in a day, the midpoint is at the 40th candle).
This doesn't mean you should make reversal trades at the 40th candle. The bar count feature simply reminds you of the current time, helping you gauge how long until the trading day ends. For instance, if there are 80 candles in a day and you're an intraday trader, you probably shouldn't make a swing trade at the 70th candle because there are only 10 candles left until the close—likely not enough time for a swing to develop.
Additionally, if you trade on a 5-minute timeframe, seeing candles numbered 3, 6, 9, etc. indicates the close of a 15-minute candle. This means that in addition to 5-minute timeframe traders, 15-minute timeframe traders will also pay attention to these candles, making them more significant. For the same reason, the 12th candle is crucial, as its close also marks the close of an hourly candle.
Day Time Frame & Week Time Frame
Moving Averages
Provides three EMAs. You can set different timeframes and choose between continuous or discrete modes.
Moving averages are excellent tools for determining trends. The 20 EMA is particularly popular, which increases its significance. Traders using different timeframes, such as 5-minute, 15-minute, and 1-hour, all utilize the 20 EMA. This indicator allows you to see what traders on 15-minute and 1-hour timeframes are observing, even when you're on a 5-minute timeframe.
Once again, the default settings of this indicator assume that the user is trading intraday on a 5-minute timeframe. However, if that's not the case, you can easily adjust the moving average periods. For instance, if you trade on a 1-hour timeframe and want to display the 4-hour and daily moving averages on your chart, this can be done effortlessly.
5m 20, 15m 20 & 1h 20
Previous Values
Features three previous value displays. You can set their sources and timeframes independently and define the range for all previous values.
For intraday trading, marking the previous day's high, low, and close prices can be crucial. While some other indicators provide this feature, mine does it better. You can set different timeframes and choose various sources. For example, you might want to display the average of (O+H+L+C)/4 for the last week.
In addition to setting the timeframe and source, you can also configure the display range:
All: This will show the data in all positions. For example, you can see the high price from two days ago on yesterday's chart.
Today: This will only display the previous day's high price on the current day's chart.
Timeframe: This will display the data based on the specified timeframe you set.
Last Week High, Last Day Close & Low(Timeframe Display)
IO Pattern Matching
More advanced than other IO pattern matching indicators. For adjacent IIs, it merges to display as III, IIII, and so on. The same applies to OO patterns. Additionally, it automatically merges adjacent IOI and II into IOII, and adjacent OO and IOI into IIOI.
II Pattern: This refers to two consecutive inside bar candles. On a lower timeframe, the II pattern forms a converging triangle, which is a breakout pattern. The II pattern could also potentially become a final flag, which is the last flag in a trend.
OO Pattern: This refers to two consecutive outside bar candles. On a lower timeframe, the OO pattern forms an expanding triangle. You can use the OO pattern similarly to how you would use an expanding triangle.
IOI Pattern: This pattern occurs when the first candle is contained within the second candle, and the third candle is also contained within the second candle. This is a breakout pattern and could similarly represent a terminal flag in a trend.
The appearance of II, OO, or IOI patterns does not necessarily mean you should make a reversal trade. These patterns are meant to mark potential moves in a lower timeframe within the current cycle, providing a new perspective on the market and reminding you to stay vigilant.
You shouldn't look for IO patterns in a tight trading range. There are many IO patterns in a tight trading range, but they don't hold much significance.
II, OO & IOI
RSI Ignoring Gaps Between DaysThe RSI Ignoring Gaps Between Days indicator is an advanced modification of the traditional Relative Strength Index (RSI) designed to exclude price gaps that occur between the last bar of one trading day and the first bar of the next. This ensures that the RSI calculations remain focused on the actual price action during the trading session, avoiding distortions caused by overnight price gaps.
Key Features:
Gap Ignoring Mechanism: The indicator detects when a new day begins and skips the price change between the last bar of the previous day and the first bar of the current day. This ensures that only the intra-day price changes are included in the RSI calculation.
Intra-day Price Movement: The RSI calculations are based on real price changes within each trading day, providing a clearer reflection of momentum without interference from overnight events.
Dynamic RSI Calculation: The traditional RSI formula is preserved, but gains and losses are recalculated based on price changes from bar to bar within the same day.
Overbought/Oversold Levels: The indicator retains standard RSI overbought (70) and oversold (30) levels, allowing traders to easily identify potential reversal zones.
Alerts for Crossovers: Built-in alert conditions trigger when the RSI crosses key levels (30 or 70), signaling potential buying or selling opportunities.
This indicator is particularly useful for traders looking to focus on intra-day price action and avoid the influence of gaps caused by overnight market activity. It is suitable for intraday trading strategies where consistency in price movement measurement is crucial.
Stochastic RSI OHLC StrategyThe script titled "Stochastic RSI High Low Close Bars" is a versatile trading strategy implemented in Pine Script, designed for TradingView. Here's an overview of its features:
Description
This strategy leverages the Stochastic RSI to determine entry and exit signals in the market, focusing on high, low, and close values of the indicator. It incorporates various trading styles, stop-loss mechanisms, and multi-timeframe analysis to adapt to different market conditions.
Key Features
Stochastic RSI Analysis:
Uses the Stochastic RSI to identify potential entry points for long and short positions.
Tracks high, low, and close values for more granular analysis.
Multiple Trading Styles:
Supports diverse trading styles like Volume Color Swing, RSI Divergence, RSI Pullback, and more.
Allows switching between these styles to suit market dynamics.
Session-Based Trading:
Offers session control, limiting trades to specific hours (e.g., NY sessions).
Can close all positions at the end of the trading day.
Stop-Loss and Take-Profit Mechanisms:
Includes both static and dynamic stop-losses, with options for time-based stops, trailing stops, and momentum-based exits.
Customizable take-profit levels ensure efficient trade management.
Volume Analysis:
Integrates volume indicators to add a bias for trade entries and exits, enhancing signal reliability.
Multi-Timeframe Integration:
Employs multi-timeframe RSI analysis, allowing the strategy to capture broader trends and optimize entries.
This script is designed to provide flexibility and adaptability, making it useful for different trading strategies and market conditions. It is suitable for traders looking to refine their entries and exits with a focus on the Stochastic RSI.
AndreundCristianIndicator Overview:
The "Trade Signals with Volume" indicator is a custom script that generates buy and sell signals based on the crossover of two moving averages (a fast one and a slow one) and adds a volume filter to validate these signals. It plots these signals directly on the chart, using arrows or labels to indicate where buy and sell signals occur.
Key Features:
Moving Averages (MA):
The indicator uses two Simple Moving Averages (SMA): a fast SMA and a slow SMA.
A buy signal is triggered when the fast MA crosses above the slow MA, signaling potential bullish momentum.
A sell signal is triggered when the fast MA crosses below the slow MA, indicating potential bearish momentum.
Volume Filter:
To ensure that signals are more reliable, the indicator only triggers a buy or sell signal if the volume is above a certain threshold. This threshold can be adjusted by the user in the input settings.
For example, if the volume exceeds 100,000 (or any set value), and a crossover occurs, the signal is validated.
Visual Representation:
Buy signals are represented with green labels or arrows below the price bars.
Sell signals are represented with red labels or arrows above the price bars.
The MAs are also plotted on the chart for visual reference.
Input Parameters:
Fast Moving Average Length: The number of periods for the fast SMA (default is 9 periods).
Slow Moving Average Length: The number of periods for the slow SMA (default is 21 periods).
Volume Threshold: The minimum volume required to validate a buy or sell signal (default is 100,000).
NYSE, Euronext, and Shanghai Stock Exchange Hours IndicatorNYSE, Euronext, and Shanghai Stock Exchange Hours Indicator
This script is designed to enhance your trading experience by visually marking the opening and closing hours of major global stock exchanges: the New York Stock Exchange (NYSE), Euronext, and Shanghai Stock Exchange. By adding vertical lines and background fills during trading sessions, it helps traders quickly identify these critical periods, potentially informing better trading decisions.
Features of This Indicator:
NYSE, Euronext, and Shanghai Stock Exchange Hours: Displays vertical lines at market open and close times for these three exchanges. You can easily switch between showing or hiding the different exchanges to customize the indicator for your needs.
Background Fill: Highlights the trading hours of these exchanges using faint background colors, making it easy to spot when markets are in session. This feature is crucial for timing trades around overlapping trading hours and volume peaks.
Customizable Visuals: Adjust the color, line style (solid, dotted, dashed), and line width to match your preferences, making the indicator both functional and visually aligned with your chart's aesthetics.
How to Use the Indicator:
Add the Indicator to Your Chart: Add the script to your chart from the TradingView script library. Once added, the indicator will automatically plot vertical lines at the opening and closing times of the NYSE, Euronext, and Shanghai Stock Exchange.
Customize Display Settings: Choose which exchanges to display by enabling or disabling the NYSE, Euronext, or Shanghai sessions in the indicator settings. This allows you to focus only on the exchanges that are relevant to your trading strategy.
Adjust Visual Properties: Customize the appearance of the vertical lines and background fill through the settings. Modify the color of each exchange, adjust the line style (solid, dotted, dashed), and control the line thickness to suit your chart preferences. The background fill can also be customized to clearly highlight active trading sessions.
Identify Key Market Hours: Use the vertical lines and background fills to identify the market open and close times. This is particularly useful for understanding how price action changes during specific trading hours or for finding high liquidity periods when multiple markets are open simultaneously.
Adapt Trading Strategies: By knowing when major stock exchanges are open, you can adapt your trading strategy to take advantage of potential price movements, increased volatility, or volume. This can help you avoid low-liquidity times and capitalize on more active trading periods.
This indicator is especially valuable for traders focusing on cross-market dynamics or those interested in understanding how different sessions influence market liquidity and price action. With this tool, you can gain insight into market conditions and adapt your trading strategies accordingly. The clean visual separation of session times helps you maintain context, whether you're trading Forex, stocks, or cryptocurrencies.
Disclaimer: This script is intended for informational and educational purposes only. It does not constitute financial advice or a recommendation to buy or sell any financial instrument. Always conduct your own research and consult with a licensed financial advisor before making any trading decisions. Trading involves risk, and past performance is not indicative of future results.
Portfolio SnapShot v0.3Here is a Tradingview Pinescript that I call "Portfolio Snapshot". It is based on two other separate scripts that I combined, modified and simplified - shoutout to RedKTrader (Portfolio Tracker - Table Version) and FriendOfTheTrend (Portfolio Tracker For Stocks & Crypto) for their inspiration and code. I was using both of these scripts, and decided to combine the two and increase the number of stocks to 20. I was looking for an easy way to track my entire portfolio (scattered across 5 accounts) PnL on a total and stock basis. PnL - that's it, very simple by design. The features are:
1) Track PnL across multiple accounts, from inception and current day.
2) PnL is reported in two tables, at the portfolio level and individual stock level
3) Both tables can be turned on/off and placed anywhere on the chart.
4) Input up to 20 assets (stocks, crypto, ETFs)
The user has to manually calculate total shares and average basis for stocks in multiple accounts, and then inputs this in the user input dialog. I update mine as each trade is made, or you can just update once a week or so.
I've pre-loaded it with the major indices and sector ETFs, plus URA, GLD, SLV. 100 shares of each, and prices are based on the close Jan 2 2024. So if you don't want to track your portfolio, you can use it to track other things you find interesting, such as annual performance of each sector.
OBV based on Heikin-AshiDescription
This indicator calculates the On-Balance Volume (OBV) based on Heikin-Ashi candles rather than regular candlesticks.
OBV based on Heikin-Ashi: The OBV is calculated based on Heikin-Ashi candle trends. Volume is added when the Heikin-Ashi close is above the open (bullish) and subtracted when the close is below the open (bearish).
Volume Analysis: This approach helps traders identify significant volume shifts in a smoother trend environment, reducing market noise that often accompanies traditional candlestick charts.
説明
このインジケーターは、通常のローソク足ではなく、平均足(Heikin-Ashi)を基にオンバランス・ボリューム(OBV)を計算します。
平均足に基づくOBV: OBVは、平均足のトレンドに基づいて計算されます。平均足の終値が始値を上回った場合(陽線)は出来高が加算され、終値が始値を下回った場合(陰線)は出来高が減算されます。
出来高分析: この手法により、通常のローソク足チャートで発生するノイズを軽減し、滑らかなトレンド環境で重要な出来高の変化を把握できます。
Prometheus Fractal-Based TrendThe Fractal-Based Trend indicator is a tool that uses fractals to try and detect which direction an underlying will continue to go.
Calculation:
A bullish fractal occurs when the current bar's high is lower than the previous bar high, and the previous bar's high is higher than both the high from two bars ago and the high from three bars ago.
A bearish fractal happens when the current bar's low is higher than the previous bar's low, and the previous bar's low is lower than both the low from two bars ago and the low from three bars ago.
When a bullish or bearish fractal forms, the corresponding value stored is the previous bar high for a bearish fractal or the previous bar's low for a bullish fractal.
The trade scenarios are when these fractals occur, a green or red label being plotted on the chart for whatever direction it predicts.
Trade examples:
We see on this daily chart of AMEX:SPY that the fractals represent the potential for a directional trade that can last a few days. The more volatile a chart is the more of these fractals we can see.
We see on this 5 minute chart for NASDAQ:TSLA there is way more activity, there are more sporadic candles on a lower time frame, so we can see more anomalies in the price action.
We see this to be true for BITSTAMP:BTCUSD even on a daily time frame, since it is very volatile. There are a lot of these labels plotted.
This is the perspective we aim to provide. We encourage traders to not follow indicators blindly. No indicator is 100% accurate. This one can give you a different perspective of price strength with volatility. We encourage any comments about desired updates or criticism!
Memecoin TrackerMemecoin Z-Score Tracker with Buy/Sell Table - Technical Explanation
How it Works:
This indicator calculates the Z-scores of various memecoins based on their price movements, using historical funding rates across multiple exchanges. A Z-score measures the deviation of the current price from its moving average, expressed in standard deviations. This provides insight into whether a coin is overbought (positive Z-score) or oversold (negative Z-score) relative to its recent history.
Key Components:
- Z-Score Calculation
- The lookback period is dynamically adjusted based on the chart’s timeframe to ensure consistency across different time intervals:
- For lower timeframes (e.g., minutes), the base lookback period is scaled to match approximately 240 minutes.
- For daily and higher timeframes, the base lookback period is fixed (e.g., 14 bars).
Memecoin Selection:
The indicator tracks several popular memecoins, including DOGE, SHIB, PEPE, FLOKI, and others.
Funding rates are fetched from exchanges like Binance, Bybit, and MEXC using the request.security() function, ensuring accurate real-time price data.
Thresholds for Buy/Sell Signals:
Users can set custom Z-score thresholds for buy (oversold) and sell (overbought) signals:
Default upper threshold: 2.5 (indicates overbought condition).
Default lower threshold: -2.5 (indicates oversold condition).
When a memecoin’s Z-score crosses above or below these thresholds, it signals potential buy or sell conditions.
Buy/Sell Table:
A table with two columns (BUY and SELL) is dynamically populated with memecoins that are currently oversold (buy signal) or overbought (sell signal).
Each column can hold up to 20 entries, providing a clear overview of current market opportunities.
Visual Feedback:
The Z-scores of each memecoin are plotted as a line on the chart, with color-coded feedback:
Red for overbought (Z-score > upper threshold),
Green for oversold (Z-score < lower threshold),
Other colors indicate neutral conditions.
Horizontal lines representing the upper and lower thresholds are plotted for reference.
How to Use It:
Adjust Thresholds:
You can modify the upper and lower Z-score thresholds in the settings to customize sensitivity. Lower thresholds will increase the likelihood of triggering buy/sell signals for smaller price deviations, while higher thresholds will focus on more extreme conditions.
View Real-Time Signals:
The table shows which memecoins are currently oversold (buy column) or overbought (sell column), updating dynamically as price data changes. Traders can monitor this table to identify trading opportunities quickly.
Use with Different Timeframes:
The Z-score lookback period adjusts automatically based on the chart's timeframe, making this indicator suitable for intraday and long-term traders.
Use shorter timeframes (e.g., 1-minute, 5-minute charts) for faster signals, while longer timeframes (e.g., daily, weekly) may yield more stable, trend-based signals.
Who It Is For:
Short-Term Traders: Those looking to capitalize on short-term price imbalances (e.g., day traders, scalpers) can use this indicator to identify quick buy/sell opportunities as memecoins oscillate around their moving averages.
Swing Traders: Swing traders can use the Z-score tracker to identify overbought or oversold conditions across multiple memecoins and ride the reversals back toward equilibrium.
Crypto Enthusiasts and Memecoin Investors: Anyone involved in the volatile memecoin market can use this tool to better time entries and exits based on market extremes.
This indicator is for traders seeking quantitative analysis of price extremes in memecoins. By tracking the Z-scores across multiple coins and dynamically updating buy/sell opportunities in a table, it provides a systematic approach to identifying trade setups.
Fetch Z-scoreThis script is enspired by the creator of the Z-score probability indicator made by www.tradingview.com
I took his calculation for the z-score and created my own strategy based on that z-score.
What is z-score? The Z-score represents how far the current price deviates from the moving average, measured in terms of standard deviations
What does this script do with the Z-score?
The script offers several customizable options, including displaying buy and sell signals based on Z-score thresholds and overlaying these signals directly on the chart or below/above the bars.
The idea is that when the Z-score exceeds a certain treshold, a count will start. The count will lead to a signal. For example: Say the Z-score dipped below -1. From there, the script will by default count whether the current Z-score is higher than the Z-score of the past 10 datapoints. If so, a buy signal will be printed on the chart. The idea is that the Z-score will creep up after a low, making sure you buy earyly in the new uptrend, making this a trend followiung system, with early trend detection.
You can choose whether you want the buy and sell signals on the seperate pane, or on the chart by toggeling a simple setting.
What are my favorite settings?
- Timeframe: weekly
- SMA Length: 75
- Z score buy treshold: -1.5
- Z score sell treshold: 3
- Lookback buy period: 20
- Lookback sell period: 20