ZigZaglibraryLibrary "ZigZaglibrary"
method lastPivot(this)
Returns the last `Pivot` object from a `ZigZag` instance if it contains at
least one `Pivot`, and `na` otherwise.
Can be used as a function or method.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) A `ZigZag` object.
Returns: (Pivot) The last `Pivot` object in the `ZigZag`.
method update(this)
Updates a `ZigZag` objects with new pivots, volume, lines, and labels.
NOTE: This function must be called on every bar for accurate calculations.
Can be used as a function or method.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) A `ZigZag` object.
Returns: (bool) `true` when a new pivot point is registered and the `ZigZag` is updated,
`false` otherwise.
newInstance(settings)
Instantiates a new `ZigZag` object with optional `settings`.
If no `settings` are provided, creates a `ZigZag` object with default settings.
Parameters:
settings (Settings) : (series Settings) A `Settings` object.
Returns: (ZigZag) A new `ZigZag` instance.
Settings
Provides calculation and display properties to `ZigZag` objects.
Fields:
devThreshold (series float) : The minimum percentage deviation from a point before the `ZigZag` changes direction.
depth (series int) : The number of bars required for pivot detection.
lineColor (series color) : The color of each line drawn by the `ZigZag`.
extendLast (series bool) : A condition allowing a line to connect the most recent pivot with the current close.
displayReversalPrice (series bool) : A condition to display the pivot price in the pivot label.
displayCumulativeVolume (series bool) : A condition to display the cumulative volume for the pivot segment in the pivot label.
displayReversalPriceChange (series bool) : A condition to display the change in price or percent from the previous pivot in each pivot label.
differencePriceMode (series string) : The reversal change display mode. Options are "Absolute" or "Percent".
draw (series bool) : A condition to determine whether the `ZigZag` displays lines and labels.
allowZigZagOnOneBar (series bool) : A condition to allow double pivots i.e., when a large bar makes both a pivot high and a pivot low.
Pivot
Represents a significant level that indicates directional movement or potential support and resistance.
Fields:
ln (series line) : A `line` object connecting the `start` and `end` chart points.
lb (series label) : A `label` object to display pivot values.
isHigh (series bool) : A condition to determine whether the pivot is a pivot high.
vol (series float) : The cumulative volume for the pivot segment.
start (chart.point) : A `chart.point` object representing the coordinates of the previous point.
end (chart.point) : A `chart.point` object representing the coordinate of the current point.
ZigZag
An object to maintain a Zig Zag's settings, pivots, and cumulative volume.
Fields:
settings (Settings) : A `Settings` object to provide calculation and display properties.
pivots (array) : An array of `Pivot` objects.
sumVol (series float) : The volume sum for the current `Pivot` object's line segment.
extend (Pivot) : A `Pivot` object used to project a line from the last pivot point to the current bar.
Indicators and strategies
Fast WMAThe Fast WMA is a reactive trend-following tool designed to provide rapid signals on the ETHBTC ratio. It uses advanced smoothing techniques and normalized thresholds to detect trends effectively. Let’s break it down further:
Source Smoothing with Standard Deviations
The source price data is smoothed by calculating its standard deviation, which measures how far prices typically move from the average. This creates upper and lower deviation levels:
The upper deviation represents a high boundary where prices might be overextended.
The lower deviation represents a low boundary where prices might be oversold.
These deviations are combined with the Weighted Moving Average (WMA) to filter out noise and focus on significant price movements.
Weighting the WMA for Further Smoothing
The Weighted Moving Average (WMA) itself is refined by applying adjustable weights:
An upper weight expands the WMA, forming an Upper Band.
A lower weight compresses the WMA, forming a Lower Band.
This dual-weighted approach allows the tool to adapt dynamically to price action, highlighting areas of potential trend reversals or continuations.
Normalized WMA (NWMA) with Adjustable Thresholds
The Normalized WMA (NWMA) adds an extra layer of analysis:
It compares the source price to its smoothed average, expressing the result as a percentage change.
This helps identify whether the market is overbought (positive NWMA) or oversold (negative NWMA).
Two adjustable thresholds—a long threshold (for buy signals) and a short threshold (for sell signals)—allow users to fine-tune the sensitivity of these signals based on their trading style or the market's volatility.
Entry/Exit Conditions
The Fast WMA generates signals based on two conditions:
Buy (Long) Signal:
Occurs when the price stays above the lower deviation level, and the NWMA crosses above the long threshold.
Indicates bullish momentum and suggests an upward trend.
Sell (Short) Signal:
Occurs when the price falls below the upper deviation level, and the NWMA drops below the short threshold.
Indicates bearish momentum and suggests a downward trend.
Important Note
This indicator is not designed to work alone. It’s a powerful tool for identifying trends but should be combined with other analyses, such as volume, higher time-frame trends, or fundamental analysis, for better decision-making.
Plotting Features
The Fast WMA includes intuitive visual cues to enhance usability:
Color-Coded Signals:
Colors change dynamically to indicate trend direction.
Options are available to customize the color scheme (e.g., for specific trading pairs like ETHBTC or SOLBTC).
Threshold Lines:
Dashed horizontal lines mark the long and short thresholds, helping users visualize signal levels.
Bands and Fill Areas:
The Upper Band and Lower Band are plotted around the WMA, with shaded regions indicating the deviation zones.
Signal Arrows:
Triangles appear below or above candles to highlight potential buy (upward arrow) or sell (downward arrow) points.
Bar Coloring:
Candlesticks are colored according to trend direction, making it easier to identify trends at a glance.
The Fast WMA combines mathematical precision with user-friendly visualization, offering traders a versatile tool to analyze trends and make informed decisions. However, like any indicator, it’s most effective when used as part of a broader trading strategy.
Quantuan Research - AlphaFree alpha for you folks. This is my Hanukkah/Christmas gift for you folks.
Enjoy, best regards;
- Quantuan Research
Squeeze Momentum Indicator [CHE] Squeeze Momentum Indicator
The Squeeze Momentum Indicator is an improved and simplified version of the classic Squeeze Momentum Indicator by LazyBear. It focuses on precise detection of squeeze phases without relying on Keltner Channels (KC) or complex momentum calculations. Instead, it emphasizes the dynamic analysis of Bollinger Band widths and their distance changes to provide clear and intuitive signals.
What is the Squeeze Momentum Indicator ?
This indicator helps you identify periods of low volatility (squeeze phases) when the market is often poised for significant moves. With its clear visualization and innovative methods, it enables traders to spot breakout opportunities early and trade strategically.
Differences from the Original LazyBear Indicator
1. Use of Bollinger Bands (BB):
- LazyBear Indicator combines Bollinger Bands with Keltner Channels. A squeeze is detected when the Bollinger Bands fall inside the Keltner Channels.
- CHE Indicator relies solely on Bollinger Bands and an additional analysis of their width (distance between the upper and lower bands). This makes the calculation more straightforward and reduces dependency on multiple indicator families.
2. Squeeze Detection:
- LazyBear: A squeeze is defined based on the relationship between Bollinger Bands and Keltner Channels. It has three states: “Squeeze On,” “Squeeze Off,” and “No Squeeze.”
- CHE: A squeeze is detected when the width of the Bollinger Bands falls below the lower "Distance Bollinger Bands." It only has two states: Squeeze Active and No Squeeze.
3. Momentum Calculation:
- LazyBear: Uses linear regression (LinReg) to calculate momentum and displays it as color-coded histograms.
- CHE: Does not include momentum calculations. The focus is entirely on volatility visualization and squeeze detection.
4. Visualization:
- LazyBear: Displays momentum histograms and horizontal lines to signal different states.
- CHE: Visualizes the width of the Bollinger Bands and their Distance Bollinger Bands as lines on the chart. The chart background turns green when a squeeze is detected, simplifying interpretation.
What Is Plotted?
1. Bollinger Band Width:
- A line representing the distance between the upper and lower Bollinger Bands, measuring market volatility.
2. Distance Bollinger Bands:
- Two additional lines (upper and lower Distance Bollinger Bands) based on the Bollinger Band width, defining thresholds for squeeze conditions.
3. Session-Specific Box:
- A dynamic box is drawn on the chart during a squeeze phase. The box marks the high and low of the market for the squeeze duration. It visually frames the range, helping traders monitor breakouts beyond these levels.
4. Max/Min Markers:
- The indicator dynamically updates and marks the maximum and minimum price levels during a squeeze. These levels can serve as breakout thresholds or critical reference points for price action.
5. Background Color:
- The chart background turns green when a squeeze is active (Bollinger Band width falls below the lower Distance Bollinger Bands). This highlights potential breakout conditions.
How to Use the CHE Indicator
1. Add the Indicator:
- Add the indicator to your chart and customize settings such as Bollinger Band length (`sqz_length`) and multiplier (`sqz_multiplier`) to fit your strategy.
2. Identify Squeeze Conditions:
- Watch for the green background, which signals a squeeze—indicating a period of low volatility where significant market moves often follow.
3. Monitor the Box and Max/Min Levels:
- During a squeeze, the box outlines the trading range, and the maximum and minimum levels are updated in real time. Use these as breakout triggers or support/resistance zones.
4. Session-Specific Analysis:
- The indicator can highlight squeezes during specific trading sessions (e.g., market open), allowing you to focus on key time frames.
5. Additional Confirmation:
- Combine the CHE Indicator with price action analysis or momentum tools to determine the direction of potential breakouts.
Why Use the Squeeze Momentum Indicator ?
- Simplicity: Clear visualization and reduced complexity by eliminating Keltner Channels and momentum calculations.
- Flexibility: Suitable for all markets—stocks, forex, crypto, and more.
- Enhanced Visualization: The box and max/min markers provide real-time visual cues for range-bound trading and breakout strategies.
- Efficiency: Focuses on what matters most—identifying volatility and squeeze phases.
With the Squeeze Momentum Indicator , you can take your trading strategy to the next level. Thanks to its clear design, dynamic range visualization, and innovative methods, you’ll recognize breakout opportunities earlier and trade with greater precision. Try it out and experience its user-friendliness and effectiveness for yourself!
Volume & Range Spike DiamondVolume & Range Spike Diamond
Detect significant volume and price range breakouts directly on your chart with this intuitive indicator.
This TradingView indicator highlights bullish and bearish breakout opportunities by analyzing both volume and price range spikes. Perfect for identifying strong market movements in real-time.
Key Features:
Volume Increase Threshold (%): Customize the percentage increase in volume required to trigger a spike.
Price Range Increase Threshold (%): Define the percentage increase in the price range for additional precision.
Volume Lookback Period: Set the number of bars to calculate the average volume for comparison.
Bullish and Bearish Signals: Highlights bullish spikes below bars and bearish spikes above bars using colored diamonds.
Detailed Labels: Optionally display labels with percentage increases for volume and range.
Alerts Integration: Receive notifications for bullish and bearish breakout conditions.
How It Works:
The indicator compares the current bar's volume to the average volume of previous bars over the specified lookback period.
It also evaluates the price range (high - low) of the current bar against the previous bar.
If both volume and price range exceed their respective thresholds, a breakout condition is flagged.
Bullish spikes are displayed with upward-pointing diamonds below the bars, while bearish spikes use downward-pointing diamonds above the bars.
Optional labels show detailed percentage increases for both metrics.
Customization Options:
// Inputs
volumeIncreaseThreshold = input.float(50, "Volume Increase Threshold (%)", minval=0, step=5)
rangeIncreaseThreshold = input.float(200, "Price Range Increase Threshold (%)", minval=0, step=5)
lookbackPeriod = input.int(5, "Volume Lookback Period", minval=1, maxval=50)
showLastLabel = input.bool(false, "Show Only Last Label")
Alerts Configuration:
Bullish Volume Breakout: Triggered when a bullish spike is detected.
Bearish Volume Breakout: Triggered when a bearish spike is detected.
Enhance your trading strategy by detecting high-probability breakout opportunities with this reliable indicator!
[Sapphire] RSI Divergence Indicator + AlertsRSI Divergence Indicator
I added time filters so you can have up to 3 time windows you can filter signals with so you can utilize the signal at your discretion.
Each type of signal has an alert coded into it so you can get alerts when each signal occurs.
Trading Style:
Use the Bull as your entry and exit when a Bear signal occurs or when RSI reaches 80 (default).
Supertrend with Targets by Mr. Debabrata Sahathis is a SUPERTREND indicator with some added features.
this indicator normally gives buy and sell as other SUPERTREND does, but it also provides 1 to 8 targets and also provides entry price and stop-loss.
Also it has one extra higher time frame SUPERTREND indicator, which probably show higher time frame trend
fvg+support and ristence + ema Indicator Description: EMA with OB, FVG, Alerts, and Support/Resistance
This script combines multiple technical analysis tools into a single indicator to provide traders with enhanced market insights. Here's what it offers:
Features:
Exponential Moving Averages (EMAs):
Supports dynamic input lengths for EMA 20, EMA 50, EMA 100, and EMA 200.
Plots EMAs on the chart with distinct colors for quick visualization of trends.
Order Block (OB) Identification:
Automatically detects bullish and bearish order blocks based on user-defined parameters, including periods and threshold percentage.
Provides visual markers (triangle shapes) to highlight significant order blocks on the chart.
Offers flexibility to use candle bodies or wicks for OB calculations.
Fair Value Gap (FVG) Detection:
Identifies "UP" and "DOWN" fair value gaps with customizable lookback periods.
Plots boxes and lines to highlight gaps, with optional midpoint (CE) lines for added precision.
Configurable colors, styles, and behavior for filled gap management.
Support and Resistance:
Automatically detects pivot highs and lows to plot dynamic support and resistance levels.
Highlights potential reversal zones for better decision-making.
Alerts:
The indicator is equipped with built-in alerts to notify users of significant events, such as order block formations or FVG appearances.
Use Cases:
Trend Analysis: Use EMAs to identify the current market trend and potential crossover opportunities.
Order Flow Insights: Recognize critical order blocks where institutional traders may enter or exit.
Gap Trading: Spot fair value gaps to understand price inefficiencies and potential filling zones.
Reversal Zones: Leverage support and resistance levels to anticipate market turning points.
Arrow-Trade vol1.2-FinalSkrypt ten jest przydatnym narzędziem dla traderów, którzy chcą szybko zidentyfikować istotne sygnały rynkowe oraz formacje świecowe w czasie rzeczywistym, a także dostosować wygląd wskaźników do swoich potrzeb.
Jest on prosty w obsłudze, wystarczy zaobserwować ruch ceny na wykresie. Dostosować się do wytycznych takie jak strzałki.
All Market Indicator (Scalping & Swing Trading)Hey,
This indicator works fine in both scalping and swing trading and avoiding sideways market by highlighting in blue colour.
for scalping, use timeframe of 1 min and 3 min and for swing use 15 min, 30 min and 1 hr.
Yu can use 1D timeframe if you wish to carry your trade for more than 1 day.
Liquidity Swings & Sweeps-KawzRelevance:
Liquidity levels & sweeps are crucial for many SMC/ICT setups and can indicate a point at which the price changes direction or may re-trace in an opposite direction to provide additional liquidity for continued move in the original direction. Additionally, liquidity levels may provide targets for setups, as price action will often seek to take out those levels as they main contain many buy/sell stops.
How It Works:
The indicator tracks all swing points, as identified using user-defined strength of the swing. Once a swing is formed that meets the criteria, it is represented by a horizontal line starting at the price of the current swing until the last bar on the chart. While the swing is valid, this line will continue to be extended until the swing is invalid or a new swing is formed. Upon identifying a new swing, the indicator then scans the earlier swings in the same direction looking for a point of greatest liquidity that was taken by the current swing. This level is then denoted by dashed horizontal line, connecting earlier swing point to the current. At the same time any liquidity zones between the two swings are automatically removed from the chart if they had previously been rendered on the chart. If the setting to enable scan for maximum liquidity is enabled, then while looking back, the indicator will look for lowest low or highest high that was taken by the current swing point, which may not be a swing itself, however, is a lowest/highest price point taken (mitigated) by the current swing, which in many cases will be better price then then the one represented by previous swing. If the option to render sweep label is enabled, the sweep line will also be completed by a label, that will score the sweep and a tooltip showing the details of the level swept and the time it took to sweep it. The score explained further in configurability section ranks the strength of the sweep based on time and is complemented by price (difference in price between the two liquidity levels).
Configurability:
A user may configure the strength of the swing using both left/right strength (number of bars) as well as optionally instruct the indicator to seek the lowest/highest price point which may not be previous swing that was taken out by newly formed swing.
From appearance perspective liquidity level colors & line width presenting the liquidity/swing can be configured. There is also an option to render the liquidity sweep label that will generate an icon-based rating of the liquidity sweep and a tooltip that provides details on the scope of the swing, which includes liquidity level swept and when it was formed along with the time it took to sweep the liquidity.
Rating is of sweeps is primarily based on time with a secondary reference to price
💥- Best rating, very strong sweep with an hourly or better liquidity sweep
🔥- Second rating, strong sweep with 15 – 59 minute liquidity sweep, or 5+ minute sweep of 10+ points
✅- Third rating, ok sweep with 5 - 15 minute liquidity sweep, or lower-time-frame sweep of 10+ points
❄️ - Weakest sweep, with liquidity of 5 or less minutes swept
What makes this indicator different:
Designed with high performance in mind, to reduce impact on chart render time.
Only keeps valid liquidity levels & sweeps on the chart
Automatically removes previously taken liquidity levels
Ranks liquidity sweeps to indicate strength of the sweep
Open High MarkingThis TradingView script marks stocks or candles where the Opening Price equals the Highest Price during the specified time frame (e.g., daily, hourly). It is commonly used by traders to identify bearish signals since such patterns may indicate selling pressure or resistance at the opening level.
Features:
Highlight Open=High Condition:
Marks candles with a specific color or label where the opening price equals the high price.
Customizable Time Frames:
Allows the selection of intraday or daily time frames for monitoring the condition.
Visual Alerts:
Displays arrows, dots, or shapes above candles meeting the condition.
Alerts Notifications:
Sends alerts via pop-ups, SMS, email, or push notifications when the condition is triggered.
Multi-Time Frame Analysis (Optional):
Allows the user to select different time frames for confirming trends.
Filters for Noise Reduction:
Option to ignore small price deviations (tolerance level) to reduce false signals.
Triple Supertrend by Mr. Debabrata SahaThis is a triple supertrend indicator, in which :- 01 current time frame and 02 multi timeframe supertrend are used
A. Supertrend of Current time frame
B. Supertrend of higher time frame 1
c. Supertrend of higher time frame 2
* it also has background colour, by seeing background colour it smoothen understanding of current trend.
PIP Algorithm
# **Script Overview (For Non-Coders)**
1. **Purpose**
- The script tries to capture the essential “shape” of price movement by selecting a limited number of “key points” (anchors) from the latest bars.
- After selecting these anchors, it draws straight lines between them, effectively simplifying the price chart into a smaller set of points without losing major swings.
2. **How It Works, Step by Step**
1. We look back a certain number of bars (e.g., 50).
2. We start by drawing a straight line from the **oldest** bar in that range to the **newest** bar—just two points.
3. Next, we find the bar whose price is *farthest away* from that straight line. That becomes a new anchor point.
4. We “snap” (pin) the line to go exactly through that new anchor. Then we re-draw (re-interpolate) the entire line from the first anchor to the last, in segments.
5. We repeat the process (adding more anchors) until we reach the desired number of points. Each time, we choose the biggest gap between our line and the actual price, then re-draw the entire shape.
6. Finally, we connect these anchors on the chart with red lines, visually simplifying the price curve.
3. **Why It’s Useful**
- It highlights the most *important* bends or swings in the price over the chosen window.
- Instead of plotting every single bar, it condenses the information down to the “key turning points.”
4. **Key Takeaway**
- You’ll see a small number of red line segments connecting the **most significant** points in the price data.
- This is especially helpful if you want a simplified view of recent price action without minor fluctuations.
## **Detailed Logic Explanation**
# **Script Breakdown (For Coders)**
//@version=5
indicator(title="PIP Algorithm", overlay=true)
// 1. Inputs
length = input.int(50, title="Lookback Length")
num_points = input.int(5, title="Number of PIP Points (≥ 3)")
// 2. Helper Functions
// ---------------------------------------------------------------------
// reInterpSubrange(...):
// Given two “anchor” indices in `linesArr`, linearly interpolate
// the array values in between so that the subrange forms a straight line
// from linesArr to linesArr .
reInterpSubrange(linesArr, segmentLeft, segmentRight) =>
float leftVal = array.get(linesArr, segmentLeft)
float rightVal = array.get(linesArr, segmentRight)
int segmentLen = segmentRight - segmentLeft
if segmentLen > 1
for i = segmentLeft + 1 to segmentRight - 1
float ratio = (i - segmentLeft) / segmentLen
float interpVal = leftVal + (rightVal - leftVal) * ratio
array.set(linesArr, i, interpVal)
// reInterpolateAllSegments(...):
// For the entire “linesArr,” re-interpolate each subrange between
// consecutive breakpoints in `lineBreaksArr`.
// This ensures the line is globally correct after each new anchor insertion.
reInterpolateAllSegments(linesArr, lineBreaksArr) =>
array.sort(lineBreaksArr, order.asc)
for i = 0 to array.size(lineBreaksArr) - 2
int leftEdge = array.get(lineBreaksArr, i)
int rightEdge = array.get(lineBreaksArr, i + 1)
reInterpSubrange(linesArr, leftEdge, rightEdge)
// getMaxDistanceIndex(...):
// Return the index (bar) that is farthest from the current “linesArr.”
// We skip any indices already in `lineBreaksArr`.
getMaxDistanceIndex(linesArr, closeArr, lineBreaksArr) =>
float maxDist = -1.0
int maxIdx = -1
int sizeData = array.size(linesArr)
for i = 1 to sizeData - 2
bool isBreak = false
for b = 0 to array.size(lineBreaksArr) - 1
if i == array.get(lineBreaksArr, b)
isBreak := true
break
if not isBreak
float dist = math.abs(array.get(linesArr, i) - array.get(closeArr, i))
if dist > maxDist
maxDist := dist
maxIdx := i
maxIdx
// snapAndReinterpolate(...):
// "Snap" a chosen index to its actual close price, then re-interpolate the entire line again.
snapAndReinterpolate(linesArr, closeArr, lineBreaksArr, idxToSnap) =>
if idxToSnap >= 0
float snapVal = array.get(closeArr, idxToSnap)
array.set(linesArr, idxToSnap, snapVal)
reInterpolateAllSegments(linesArr, lineBreaksArr)
// 3. Global Arrays and Flags
// ---------------------------------------------------------------------
// We store final data globally, then use them outside the barstate.islast scope to draw lines.
var float finalCloseData = array.new_float()
var float finalLines = array.new_float()
var int finalLineBreaks = array.new_int()
var bool didCompute = false
var line pipLines = array.new_line()
// 4. Main Logic (Runs Once at the End of the Current Bar)
// ---------------------------------------------------------------------
if barstate.islast
// A) Prepare closeData in forward order (index 0 = oldest bar, index length-1 = newest)
float closeData = array.new_float()
for i = 0 to length - 1
array.push(closeData, close )
// B) Initialize linesArr with a simple linear interpolation from the first to the last point
float linesArr = array.new_float()
float firstClose = array.get(closeData, 0)
float lastClose = array.get(closeData, length - 1)
for i = 0 to length - 1
float ratio = (length > 1) ? (i / float(length - 1)) : 0.0
float val = firstClose + (lastClose - firstClose) * ratio
array.push(linesArr, val)
// C) Initialize lineBreaks with two anchors: 0 (oldest) and length-1 (newest)
int lineBreaks = array.new_int()
array.push(lineBreaks, 0)
array.push(lineBreaks, length - 1)
// D) Iteratively insert new breakpoints, always re-interpolating globally
int iterationsNeeded = math.max(num_points - 2, 0)
for _iteration = 1 to iterationsNeeded
// 1) Re-interpolate entire shape, so it's globally up to date
reInterpolateAllSegments(linesArr, lineBreaks)
// 2) Find the bar with the largest vertical distance to this line
int maxDistIdx = getMaxDistanceIndex(linesArr, closeData, lineBreaks)
if maxDistIdx == -1
break
// 3) Insert that bar index into lineBreaks and snap it
array.push(lineBreaks, maxDistIdx)
array.sort(lineBreaks, order.asc)
snapAndReinterpolate(linesArr, closeData, lineBreaks, maxDistIdx)
// E) Save results into global arrays for line drawing outside barstate.islast
array.clear(finalCloseData)
array.clear(finalLines)
array.clear(finalLineBreaks)
for i = 0 to array.size(closeData) - 1
array.push(finalCloseData, array.get(closeData, i))
array.push(finalLines, array.get(linesArr, i))
for b = 0 to array.size(lineBreaks) - 1
array.push(finalLineBreaks, array.get(lineBreaks, b))
didCompute := true
// 5. Drawing the Lines in Global Scope
// ---------------------------------------------------------------------
// We cannot create lines inside barstate.islast, so we do it outside.
array.clear(pipLines)
if didCompute
// Connect each pair of anchors with red lines
if array.size(finalLineBreaks) > 1
for i = 0 to array.size(finalLineBreaks) - 2
int idxLeft = array.get(finalLineBreaks, i)
int idxRight = array.get(finalLineBreaks, i + 1)
float x1 = bar_index - (length - 1) + idxLeft
float x2 = bar_index - (length - 1) + idxRight
float y1 = array.get(finalCloseData, idxLeft)
float y2 = array.get(finalCloseData, idxRight)
line ln = line.new(x1, y1, x2, y2, extend=extend.none)
line.set_color(ln, color.red)
line.set_width(ln, 2)
array.push(pipLines, ln)
1. **Data Collection**
- We collect the **most recent** `length` bars in `closeData`. Index 0 is the oldest bar in that window, index `length-1` is the newest bar.
2. **Initial Straight Line**
- We create an array called `linesArr` that starts as a simple linear interpolation from `closeData ` (the oldest bar’s close) to `closeData ` (the newest bar’s close).
3. **Line Breaks**
- We store “anchor points” in `lineBreaks`, initially ` `. These are the start and end of our segment.
4. **Global Re-Interpolation**
- Each time we want to add a new anchor, we **re-draw** (linear interpolation) for *every* subrange ` [lineBreaks , lineBreaks ]`, ensuring we have a globally consistent line.
- This avoids the “local subrange only” approach, which can cause clustering near existing anchors.
5. **Finding the Largest Distance**
- After re-drawing, we compute the vertical distance for each bar `i` that isn’t already a line break. The bar with the biggest distance from the line is chosen as the next anchor (`maxDistIdx`).
6. **Snapping and Re-Interpolate**
- We “snap” that bar’s line value to the actual close, i.e. `linesArr = closeData `. Then we globally re-draw all segments again.
7. **Repeat**
- We repeat these insertions until we have the desired number of points (`num_points`).
8. **Drawing**
- Finally, we connect each consecutive pair of anchor points (`lineBreaks`) with a `line.new(...)` call, coloring them red.
- We offset the line’s `x` coordinate so that the anchor at index 0 lines up with `bar_index - (length - 1)`, and the anchor at index `length-1` lines up with `bar_index` (the current bar).
**Result**:
You get a simplified representation of the price with a small set of line segments capturing the largest “jumps” or swings. By re-drawing the entire line after each insertion, the anchors tend to distribute more *evenly* across the data, mitigating the issue where anchors bunch up near each other.
Enjoy experimenting with different `length` and `num_points` to see how the simplified lines change!
[Sapphire] Fibonacci Bollinger Bands Strategy (FiboBands)The FiboBands Strategy is a combination of the Fibonacci Sequence and Bollinger Band.
It uses the Fibonacci Sequence in place for the Bollinger Band values.
The user can choose which band level they want to use as their long and short signals accordingly.
The strategy has built in trade management settings so if you would like to have a predefined take profit and stop loss level as a percentage, you can use that.
It also has a trading window you can filter to what time of day you want to see signals and backtest for, with the option to close the trade at the end of that session.
My Bitcoin Futures Settings:
Fibonacci Buy - Fibo 1
Fibonacci Sell - Fibo 2
Rest is Default
CandelaCharts - Opening Gap (OG) 📝 Overview
The ICT (Inner Circle Trader) Opening Gap represents the price difference between the previous trading session's closing price and the current session's opening price. This gap serves as a key indicator of market sentiment and can offer valuable clues about the market's potential direction throughout the trading day.
A bullish Opening Gap forms when the market opens higher than the previous session's close, signaling strong buying interest or positive sentiment heading into the new session
A bearish Opening Gap occurs when the market opens lower than the previous session's close, reflecting heightened selling pressure or negative sentiment among market participants
The Opening Gap is significant as it often establishes the market's tone for the trading session. Accurately interpreting this gap enables traders to make informed decisions about when to enter or exit positions. Serving as a gauge of market strength or weakness, the gap provides a clear signal of whether the market is likely to trend upward or downward during the day.
📦 Features
MTF
Mitigation
Consequent Encroachment
Threshold
Hide Overlap
Advanced Styling
⚙️ Settings
Show: Controls whether OGs are displayed on the chart.
Show Last: Sets the number of OGs you want to display.
Length: Determines the length of each OG.
Mitigation: Highlights when an OG has been touched, using a different color without marking it as invalid.
Timeframe: Specifies the timeframe used to detect OGs.
Threshold: Sets the minimum gap size required for OG detection on the chart.
Show Mid-Line: Configures the midpoint line's width and style within the OG. (Consequent Encroachment - CE)
Show Border: Defines the border width and line style of the OG.
Hide Overlap: Removes overlapping OGs from view.
Extend: Extends the OG length to the current candle.
Elongate: Fully extends the OG length to the right side of the chart.
⚡️ Showcase
Simple
Mitigated
Bordered
Consequent Encroachment
Extended
🚨 Alerts
This script provides alert options for all signals.
Bearish Signal
A bearish signal is triggered when the price opens lower than the previous session's close.
Bullish Signal
A bullish signal is triggered when the price opens higher than the previous session's close.
⚠️ Disclaimer
Trading involves significant risk, and many participants may incur losses. The content on this site is not intended as financial advice and should not be interpreted as such. Decisions to buy, sell, hold, or trade securities, commodities, or other financial instruments carry inherent risks and are best made with guidance from qualified financial professionals. Past performance is not indicative of future results.
Order Blocks - VK TradingOrder Blocks - VK Trading
This script in Pine Script identifies and highlights Order Blocks, key tools in institutional trading. Designed for traders of all levels, it provides clear and customizable visualization, helping you anticipate market movements with greater accuracy.
Key Features:
Order Block Visualization: Highlights relevant bullish and bearish zones directly on the chart.
Customizable Settings: Adjust sensitivity, colors, and other parameters to suit your analysis needs.
Dual Block Detection: Uses two independent settings to cover different market perspectives.
Visual Alerts: Automatic line drawing for key levels.
Automatic Clearing: Dynamic clearing of already invalidated blocks.
User Benefits:
Clear Visual Analysis: Identifies key supply and demand points used by institutions.
Improved Trading Decisions: Anticipate entry and exit zones more accurately.
Time Saver: Automates level plotting, allowing you to focus on strategy and execution.
Strategy Adaptability: Compatible with Smart Money, Wyckoff, and Price Action approaches.
Disclaimer:
This script is an educational and analytical tool. It does not guarantee specific results or eliminate trading risk. Trading in the financial markets involves significant risks; use this script at your own risk.
First AI generator IndicatorI generated this on getpinescript.com. It's just a roughly generated code. I will further study and refine it.
Momentum and Mean Reversion Strategy[Kopottaja]Momentum and Mean Reversion Strategy
Description:
The Momentum and Mean Reversion Strategy is a versatile trading strategy that combines two popular approaches: momentum trading and mean reversion. Designed for cryptocurrency markets on the 5-minute timeframe, this strategy identifies profitable opportunities by detecting trend-following signals using Exponential Moving Averages (EMA) and reversal signals based on Bollinger Bands (BB). Its dual-layered logic makes it suitable for a wide range of market conditions, from trending to ranging markets.
Key Features:
Momentum Trading with EMA Crossover:
Tracks short- and long-term price trends using Exponential Moving Averages (EMAs).
A buy signal is generated when the short EMA crosses above the long EMA, indicating bullish momentum.
A sell signal is generated when the short EMA crosses below the long EMA, signaling bearish momentum.
Customizable EMA periods to suit different assets and timeframes.
Mean Reversion with Bollinger Bands:
Utilizes Bollinger Bands to identify potential price reversals.
A buy signal is triggered when the price crosses above the lower Bollinger Band, indicating a potential oversold condition.
A sell signal is triggered when the price crosses below the upper Bollinger Band, indicating a potential overbought condition.
Adjustable Bollinger Band parameters for length and standard deviation.
Dual Strategy Toggle:
Enables traders to toggle between momentum-based trading, mean reversion, or use both strategies simultaneously.
Allows flexibility to adapt to trending or ranging market conditions.
Optimized for Crypto Markets:
This strategy has been designed to work effectively with cryptocurrency markets on the 5-minute timeframe. Its responsiveness to short-term price movements makes it ideal for scalping and intraday trading.
How It Works:
Momentum Strategy:
Monitors the relationship between a short-term EMA and a long-term EMA.
Buy signals occur when the short EMA crosses above the long EMA, suggesting upward momentum.
Sell signals occur when the short EMA crosses below the long EMA, signaling downward momentum.
Mean Reversion Strategy:
Leverages Bollinger Bands to detect when price deviates significantly from its average.
Buy signals occur when the price moves back above the lower Bollinger Band.
Sell signals occur when the price moves back below the upper Bollinger Band.
Trade Execution:
Depending on the selected strategy (momentum, mean reversion, or both), the script will enter and exit trades based on the conditions met.
Compatible with all major cryptocurrency pairs and scalable to other timeframes.
CYP STRUCTURE AND RANGEThis open-source indicator combines market structure analysis based on the Lux Algo methodology with range detection techniques inspired by Lazy Bear’s range identifier. It’s designed to help traders identify key market structures and potential ranges in price action, enabling more informed trading decisions.
Features:
Market Structure Analysis: Uses the Lux Algo market structure concept to detect trending and reversal zones.
Range Detection: Implements Lazy Bear’s range identification logic to highlight significant price ranges.
Customizable: Fully customizable inputs to adjust sensitivity and timeframes based on user preferences.
Open Source: This code is freely available for modification, redistribution, and educational use.
Credits:
Lux Algo for the market structure concept.
Lazy Bear for the range detection logic.
This indicator is open-source, and I encourage traders and developers to contribute, suggest improvements, and modify the code for their needs.
Sanjay RS&RSI Strategy V3 for nifty 15min, SL-1.3one of the best swing strategy of nifty futures, fix SL of 1.1%.
Support And Resistance | EcoX TradingPurpose
This indicator identifies key support and resistance levels and visualizes them alongside Bollinger Bands. It is designed specifically for the 1-minute timeframe, targeting liquidity zones through higher timeframe levels. The indicator assists traders in spotting potential reversal zones and overbought/oversold conditions. While it highlights important price levels, it is not intended for precise entry or exit signals and works best when combined with other tools like RSI, SMI, AI Trend or indicator of your choice.
Calculation Overview
Support and Resistance Levels:
Derived from ta.lowest() and ta.highest() functions for specific intervals:
15 minutes, 1 hour, 2 hours, 4 hours, 12 hours, and 1 day.
These intervals are carefully selected to capture liquidity zones respected by price action.
Bollinger Bands:
Uses a 200-period volume-weighted moving average (VWMA) as the basis.
The bands are calculated with a 3x standard deviation, marking extreme price levels.
Usage / Example Scenario
1. Long Positions
Identify a Strong Support Level:
Locate a support level (e.g., 2-hour support in green) that the price consistently bounces off without breaking lower.
Confirm Liquidity:
Check the order book and market depth chart to confirm the presence of substantial limit buy orders just below the support.
Strong liquidity reinforces the potential for a reversal at the support level.
Entry Strategy:
Open a long position when the price approaches the support level and shows signs of reversal (e.g., respecting the support without further downward momentum).
Exit Strategy:
Exit the position near a resistance level (e.g., 4-hour resistance in yellow) where the price has historically struggled to break higher.
2. Short Positions
Identify a Strong Resistance Level:
Find a resistance level (e.g., 1-hour resistance in orange) where the price frequently gets rejected.
Confirm Liquidity:
Use the order book and market depth chart to verify significant limit sell orders above the resistance.
Strong sell-side liquidity indicates a high probability of a reversal at this level.
Entry Strategy:
Open a short position when the price approaches the resistance level and shows signs of reversal (e.g., failing to move higher and respecting the resistance zone).
Exit Strategy:
Close the position near a support level (e.g., 2-hour support in green) where buying pressure is likely to occur.
Disclaimer
This indicator is a technical tool for identifying price zones of interest. It does not guarantee accurate entry or exit points. Always use it as part of a broader trading strategy.
Support & Resistance with Hammer/Hanging Man (Day, Week, Month)//@version=5
indicator("Support & Resistance with Hammer/Hanging Man (Day, Week, Month)", overlay=true)
// Swing High and Low Length
swingLength = 3 // Number of bars to the left and right for confirmation
// Hammer Candle Logic (Swing High / Resistance)
isHammer = (close > open) and ((high - math.max(open, close)) <= (0.4 * (high - low))) and ((math.min(open, close) - low) >= (0.5 * (high - low)))
// Hanging Man Logic (Swing Low / Support)
isHangingMan = (open > close) and ((math.min(open, close) - low) <= (0.4 * (high - low))) and ((high - math.max(open, close)) >= (0.5 * (high - low)))
// Swing High and Swing Low Logic
isSwingHigh = high == ta.highest(high, swingLength)
isSwingLow = low == ta.lowest(low, swingLength)
// Plot Support and Resistance Levels for Current Timeframe
var line resistanceLine = na // Variable for storing resistance line
var line supportLine = na // Variable for storing support line
// Draw Resistance Line (Current Timeframe)
if isSwingHigh and isHammer
if not na(resistanceLine)
line.delete(resistanceLine) // Delete previous line
resistanceLine := line.new(bar_index, high, bar_index + 10, high, color=color.red, width=1, extend=extend.right)
// Draw Support Line (Current Timeframe)
if isSwingLow and isHangingMan
if not na(supportLine)
line.delete(supportLine) // Delete previous line
supportLine := line.new(bar_index, low, bar_index + 10, low, color=color.green, width=1, extend=extend.right)
// Resistance and Support for Daily Timeframe
daily_high = request.security(syminfo.tickerid, "D", high)
daily_low = request.security(syminfo.tickerid, "D", low)
// Resistance and Support for Weekly Timeframe
weekly_high = request.security(syminfo.tickerid, "W", high)
weekly_low = request.security(syminfo.tickerid, "W", low)
// Resistance and Support for Monthly Timeframe
monthly_high = request.security(syminfo.tickerid, "M", high)
monthly_low = request.security(syminfo.tickerid, "M", low)
// Plot Resistance and Support for Daily, Weekly, and Monthly Timeframes
plot(daily_high, color=color.red, linewidth=1, title="Daily Resistance", style=plot.style_line)
plot(daily_low, color=color.green, linewidth=1, title="Daily Support", style=plot.style_line)
plot(weekly_high, color=color.red, linewidth=2, title="Weekly Resistance", style=plot.style_line)
plot(weekly_low, color=color.green, linewidth=2, title="Weekly Support", style=plot.style_line)
plot(monthly_high, color=color.red, linewidth=3, title="Monthly Resistance", style=plot.style_line)
plot(monthly_low, color=color.green, linewidth=3, title="Monthly Support", style=plot.style_line)
// Plot Markers for Swing High and Low (Current Timeframe)
plotshape(isSwingHigh and isHammer, style=shape.triangleup, location=location.abovebar, color=color.red, size=size.small, title="Resistance - Hammer")
plotshape(isSwingLow and isHangingMan, style=shape.triangledown, location=location.belowbar, color=color.green, size=size.small, title="Support - Hanging Man")