RSI with Reverse RSIThe RSI with Reverse RSI indicator is a powerful tool designed for traders who want an enhanced view of market momentum using two complementary RSI calculations:
1. Standard RSI: The classic Relative Strength Index (RSI) to measure overbought and oversold conditions.
2. Reverse RSI: A flipped version of RSI, offering an inverted perspective to provide additional context for decision-making.
Features:
• Dynamic Colors:
• Green indicates the RSI is above the upper threshold.
• Red indicates the RSI is below the lower threshold.
• Customizable Levels: Set your preferred overbought/oversold levels for both RSI calculations.
• Alerts: Optional real-time alerts notify you when the RSI crosses the 50-level midpoint.
• Visual Simplicity: Both RSIs are plotted as lines with changing colors, making it easier to interpret.
Use Cases:
• Spot potential reversals with overbought/oversold levels.
• Monitor momentum shifts when crossing the 50-level midpoint.
• Combine insights from standard and reversed RSIs for better entry/exit strategies.
Customization Options:
• Periods for both RSIs.
• Levels for determining overbought/oversold conditions.
• Enable/disable alerts for RSI midpoint crossings.
Whether you’re a beginner or an experienced trader, this indicator simplifies the RSI analysis by combining the standard and flipped RSI in one chart.
Indicators and strategies
AbhiramReddy_5, 13, 26, 50, 100, 200 EMAshis will plot the 5, 13, 26, 50, 100, and 200 EMAs directly on the price chart.
The EMAs will help you visually track the short-term and long-term trends in the market.
How to Use:
Add the Script to TradingView:
Open TradingView.
Go to the Pine Editor.
Paste the above code.
Click Add to Chart.
AbhiramReddy_RSI, Stochastic, and MACD Combinedyou will get these indicators combine in one indicator
EMA36ssasdasdsaasddsasaddasdassaddsadasasddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
Optimal Grid Levels with Trend, RSI, MACD, and FibonacciOptimal Grid Levels with Trend, RSI, MACD, and Fibonacci
Enhanced Market Opportunity StrategyThe Enhanced Market Opportunity Strategy is a versatile Pine Script designed for trading various asset classes (forex, crypto, indices, etc.) and timeframes. It combines technical indicators like MACD, RSI, and EMA with dynamic risk management tools such as ATR-based stop-loss and take-profit levels. The script highlights buy/sell signals and includes features like partial profit targets, trailing stops, and performance tracking (wins/losses). It also provides customizable alerts and labels for price movements (+100 points) for effective trade execution
RAJ larg Daily, Weekly & Monthly OHLC Lines - Extra Longhjdgasdgkajfkudhf.sdndsc.jdwnfiljewinD.CN/lwiv/wklf /mwmecW
RSI Status v1Simple RSI status indicator that displays GREEN for RSI cross-up of its EMA, and RED for RSI cross-down of its EMA. RSI value is also displayed.
RSI Status v1Simple RSI status indicator that displays GREEN for RSI cross-up of its EMA, and RED for RSI cross-down of its EMA. RSI value is also displayed.
Asia Sessions AutoPlotting**Asia Sessions AutoPlotting**
This script is designed to automatically detect and plot the Asia session high and low levels directly on your chart, providing key session data for trading analysis. It is highly customizable, making it an essential tool for traders who rely on session data for decision-making.
### Key Features:
- **Asia Session Detection**: Automatically identifies the Asia session based on user-defined time settings (default: 0000-0845 UTC).
- **High/Low Line Plotting**: Displays high and low price levels for the session with customizable colors and line styles.
- **Line Extensions**: Option to extend session high/low lines for future price action reference.
- **Session Background Fill**: Adds an optional colored background to highlight the Asia session period.
- **Day Labels**: Includes labels for the session high/low levels with the corresponding day of the week.
- **Dynamic Session History**: Limits the display to a user-specified number of past sessions (default: 7) to keep the chart clean and focused.
- **Customizable Colors**: Highlights Mondays with unique colors for easy identification, while other weekdays use a different scheme.
### Use Cases:
- Identify key session levels for trading strategies.
- Monitor Asia session dynamics and their impact on subsequent sessions.
- Spot significant price reactions around session highs/lows.
### Inputs:
- **Session Time**: Adjust the session time to match your preferred Asia trading hours.
- **Toggle High/Low Lines**: Enable or disable the plotting of session highs and lows.
- **Line Extensions**: Extend the session high/low lines into future bars for better visualization.
- **Background Highlight**: Toggle a colored background for the Asia session.
- **Maximum Sessions**: Define how many past sessions to display for clarity.
This script is perfect for intraday traders, scalpers, and swing traders looking to gain insight into the Asia session and its influence on global markets. Fully adjustable and easy to use, it enhances your chart with critical information at a glance.
Simply add it to your TradingView chart, configure your settings, and let it do the work for you!
EMA RSI Strategy harih1 zone based 5min entry 10 ema cross 20 ema for h1 timeframe bullish bios anr 5min rsi signal entry
EMA with Bar CountThis indicator, **"EMA with Bar Count"**, is a comprehensive tool for traders that combines multiple technical analysis techniques to enhance decision-making. Here's a summary of its features:
### Features:
1. **Multiple Timeframe EMA (Exponential Moving Average):**
- Allows traders to visualize EMAs from multiple timeframes, such as 1-minute, 5-minute, 60-minute, daily, and custom intervals.
- EMAs are displayed in different colors for easy differentiation, aiding in identifying key trend directions and support/resistance levels.
2. **Bar Count Tracker:**
- Tracks and labels bars at specific intervals (e.g., every 3 bars) with customizable label size and color.
- Useful for monitoring bar progression and aligning with time-based strategies.
3. **Inside and Outside Bars:**
- Highlights inside bars (bars completely within the range of the previous bar) and outside bars (bars exceeding the range of the previous bar).
- Provides visual markers for potential consolidation (inside bars) or volatility (outside bars) setups.
4. **Trend Candle Analysis:**
- Detects sequences of three consecutive bullish or bearish candles.
- Marks these trends on the chart for potential continuation or reversal strategies.
5. **Micro Gaps:**
- Detects and marks gaps between the current bar's open and the previous bar's close, highlighting potential price inefficiencies.
- Differentiates between bullish (gap up) and bearish (gap down) gaps with unique symbols.
6. **50% Line Visualization:**
- Calculates and optionally displays a midline for each bar, representing 50% of its range.
- Helps traders identify equilibrium levels within individual bars.
7. **Overlap and TR Detector:**
- Measures the overlap between consecutive bars as a proportion of their range.
- Marks TR (Trading Range) bars with significant overlaps, highlighting potential areas of consolidation.
8. **Pattern Alerts:**
- Identifies advanced patterns like IOI (Inside-Outside-Inside), OII (Outside-Inside-Inside), and IOO (Inside-Outside-Outside).
- Includes customizable alerts for these patterns and specific bar counts to improve reaction times.
9. **Customizable Background Highlighting:**
- Option to color the chart background based on specific conditions, like time (e.g., 7:30 AM) or relative position to the 1-hour EMA.
10. **Gap Detector for Fair Value Gaps (FVG):**
- Highlights gaps between bars using shaded boxes.
- Useful for identifying untested price areas that may attract future price action.
11. **Wedge and Flag Patterns:**
- Analyzes pivot points to identify wedges and flag patterns.
- Provides visual guides to aid in breakout or continuation trade setups.
12. **Alerts for Key Events:**
- Customizable alerts for a wide range of trading events, including long wicks, range breakouts, and key bar patterns.
This indicator is designed for traders who want an all-in-one tool that provides actionable insights from multiple technical perspectives, enabling them to spot trends, reversals, breakouts, and consolidation zones effectively.
EMA with Bar CountThis indicator, **"EMA with Bar Count"**, is a comprehensive tool for traders that combines multiple technical analysis techniques to enhance decision-making. Here's a summary of its features:
### Features:
1. **Multiple Timeframe EMA (Exponential Moving Average):**
- Allows traders to visualize EMAs from multiple timeframes, such as 1-minute, 5-minute, 60-minute, daily, and custom intervals.
- EMAs are displayed in different colors for easy differentiation, aiding in identifying key trend directions and support/resistance levels.
2. **Bar Count Tracker:**
- Tracks and labels bars at specific intervals (e.g., every 3 bars) with customizable label size and color.
- Useful for monitoring bar progression and aligning with time-based strategies.
3. **Inside and Outside Bars:**
- Highlights inside bars (bars completely within the range of the previous bar) and outside bars (bars exceeding the range of the previous bar).
- Provides visual markers for potential consolidation (inside bars) or volatility (outside bars) setups.
4. **Trend Candle Analysis:**
- Detects sequences of three consecutive bullish or bearish candles.
- Marks these trends on the chart for potential continuation or reversal strategies.
5. **Micro Gaps:**
- Detects and marks gaps between the current bar's open and the previous bar's close, highlighting potential price inefficiencies.
- Differentiates between bullish (gap up) and bearish (gap down) gaps with unique symbols.
6. **50% Line Visualization:**
- Calculates and optionally displays a midline for each bar, representing 50% of its range.
- Helps traders identify equilibrium levels within individual bars.
7. **Overlap and TR Detector:**
- Measures the overlap between consecutive bars as a proportion of their range.
- Marks TR (Trading Range) bars with significant overlaps, highlighting potential areas of consolidation.
8. **Pattern Alerts:**
- Identifies advanced patterns like IOI (Inside-Outside-Inside), OII (Outside-Inside-Inside), and IOO (Inside-Outside-Outside).
- Includes customizable alerts for these patterns and specific bar counts to improve reaction times.
9. **Customizable Background Highlighting:**
- Option to color the chart background based on specific conditions, like time (e.g., 7:30 AM) or relative position to the 1-hour EMA.
10. **Gap Detector for Fair Value Gaps (FVG):**
- Highlights gaps between bars using shaded boxes.
- Useful for identifying untested price areas that may attract future price action.
11. **Wedge and Flag Patterns:**
- Analyzes pivot points to identify wedges and flag patterns.
- Provides visual guides to aid in breakout or continuation trade setups.
12. **Alerts for Key Events:**
- Customizable alerts for a wide range of trading events, including long wicks, range breakouts, and key bar patterns.
This indicator is designed for traders who want an all-in-one tool that provides actionable insights from multiple technical perspectives, enabling them to spot trends, reversals, breakouts, and consolidation zones effectively.
Turtle Soup ICT Strategy [TradingFinder] FVG + CHoCH/CSD🔵 Introduction
The ICT Turtle Soup trading setup, designed in the ICT style, operates by hunting or sweeping liquidity zones to exploit false breakouts and failed breakouts in key liquidity Zones, such as recent highs, lows, or major support and resistance levels.
This setup identifies moments when the price breaches these liquidity zones, triggering stop orders placed (Stop Hunt) by other traders, and then quickly reverses direction. These movements are often associated with liquidity sweeps that create temporary market imbalances.
The reversal is typically confirmed by one of three structural shifts : a Market Structure Shift (MSS), a Change of Character (CHoCH), or a break of the Change in State of Delivery (CISD). Each of these structural shifts provides a reliable signal to interpret market intent and align trading decisions with the expected price movement. After the structural shift, the price frequently pullback to a Fair Value Gap (FVG), offering a precise entry point for trades.
By integrating key concepts such as liquidity, liquidity sweeps, stop order activation, structural shifts (MSS, CHoCH, CISD), and price imbalances, the ICT Turtle Soup setup enables traders to identify reversal points and key entry zones with high accuracy.
This strategy is highly versatile, making it applicable across markets such as forex, stocks, cryptocurrencies, and futures. It offers traders a robust and systematic approach to understanding price movements and optimizing their trading strategies
🟣 Bullish and Bearish Setups
Bullish Setup : The price first sweeps below a Sell-Side Liquidity (SSL) zone, then reverses upward after forming an MSS or CHoCH, and finally pulls back to an FVG, creating a buying opportunity.
Bearish Setup : The price first sweeps above a Buy-Side Liquidity (BSL) zone, then reverses downward after forming an MSS or CHoCH, and finally pulls back to an FVG, creating a selling opportunity.
🔵 How to Use
To effectively utilize the ICT Turtle Soup trading setup, begin by identifying key liquidity zones, such as recent highs, lows, or support and resistance levels, in higher timeframes.
Then, monitor lower timeframes for a Liquidity Sweep and confirmation of a Market Structure Shift (MSS) or Change of Character (CHoCH).
After the structural shift, the price typically pulls back to an FVG, offering an optimal trade entry point. Below, the bullish and bearish setups are explained in detail.
🟣 Bullish Turtle Soup Setup
Identify Sell-Side Liquidity (SSL) : In a higher timeframe (e.g., 1-hour or 4-hour), identify recent price lows or support levels that serve as SSL zones, typically the location of stop-loss orders for traders.
Observe a Liquidity Sweep : On a lower timeframe (e.g., 15-minute or 30-minute), the price must move below one of these liquidity zones and then reverse. This movement indicates a liquidity sweep.
Confirm Market Structure Shift : After the price reversal, look for a structural shift (MSS or CHoCH) indicated by the formation of a Higher Low (HL) and Higher High (HH).
Enter the Trade : Once the structural shift is confirmed, the price typically pulls back to an FVG. Enter a buy trade in this zone, set a stop-loss slightly below the recent low, and target Buy-Side Liquidity (BSL) in the higher timeframe for profit.
🟣 Bearish Turtle Soup Setup
Identify Buy-Side Liquidity (BSL) : In a higher timeframe, identify recent price highs or resistance levels that serve as BSL zones, typically the location of stop-loss orders for traders.
Observe a Liquidity Sweep : On a lower timeframe, the price must move above one of these liquidity zones and then reverse. This movement indicates a liquidity sweep.
Confirm Market Structure Shift : After the price reversal, look for a structural shift (MSS or CHoCH) indicated by the formation of a Lower High (LH) and Lower Low (LL).
Enter the Trade : Once the structural shift is confirmed, the price typically pulls back to an FVG. Enter a sell trade in this zone, set a stop-loss slightly above the recent high, and target Sell-Side Liquidity (SSL) in the higher timeframe for profit.
🔵 Settings
Higher TimeFrame Levels : This setting allows you to specify the higher timeframe (e.g., 1-hour, 4-hour, or daily) for identifying key liquidity zones.
Swing period : You can set the swing detection period.
Max Swing Back Method : It is in two modes "All" and "Custom". If it is in "All" mode, it will check all swings, and if it is in "Custom" mode, it will check the swings to the extent you determine.
Max Swing Back : You can set the number of swings that will go back for checking.
FVG Length : Default is 120 Bar.
MSS Length : Default is 80 Bar.
FVG Filter : This refines the number of identified FVG areas based on a specified algorithm to focus on higher quality signals and reduce noise.
Types of FVG filter s:
Very Aggressive Filter: Adds a condition where, for an upward FVG, the last candle's highest price must exceed the middle candle's highest price, and for a downward FVG, the last candle's lowest price must be lower than the middle candle's lowest price. This minimally filters out FVGs.
Aggressive Filter: Builds on the Very Aggressive mode by ensuring the middle candle is not too small, filtering out more FVGs.
Defensive Filter: Adds criteria regarding the size and structure of the middle candle, requiring it to have a substantial body and specific polarity conditions, filtering out a significant number of FVGs.
Very Defensive Filter: Further refines filtering by ensuring the first and third candles are not small-bodied doji candles, retaining only the highest quality signals.
In the indicator settings, you can customize the visibility of various elements, including MSS, FVG, and HTF Levels. Additionally, the color of each element can be adjusted to match your preferences. This feature allows traders to tailor the chart display to their specific needs, enhancing focus on the key data relevant to their strategy.
🔵 Conclusion
The ICT Turtle Soup trading setup is a powerful tool in the ICT style, enabling traders to exploit false breakouts in key liquidity zones. By combining concepts of liquidity, liquidity sweeps, market structure shifts (MSS and CHoCH), and pullbacks to FVG, this setup helps traders identify precise reversal points and execute trades with reduced risk and increased accuracy.
With applications across various markets, including forex, stocks, crypto, and futures, and its customizable indicator settings, the ICT Turtle Soup setup is ideal for both beginner and advanced traders. By accurately identifying liquidity zones in higher timeframes and confirming structure shifts in lower timeframes, this setup provides a reliable strategy for navigating volatile market conditions.
Ultimately, success with this setup requires consistent practice, precise market analysis, and proper risk management, empowering traders to make smarter decisions and achieve their trading goals.
Raj Daily, Weekly & Monthly OHLC Lines - Bold & ExtendedRAj daily weekly monthly high lo kfsadhsdufho8wejfjwjcoidwjcoijfwicn;dnc;qdihcd8hvhfqwihcqdnqcudhvcwhfqrohf;owihf;owihfowqhf;owefhowhfoqewfohwfh
Pink PantherThis strategy embodies elegance, speed, and intelligence.
🦄 Main Advantage: Combines key indicators (EMA, RSI, MACD, and Bollinger Bands) to gracefully adapt to any market changes, just like a panther.
💗 Feature: Like the iconic Pink Panther, this strategy skillfully identifies entry and exit points, even in chaotic market conditions.
Quote for inspiration:
“Patience and timing are the greatest allies of success.” — (Pink Panther, probably)
Leonardo Pereira - Dynamic Levels"Leonardo Pereira - Dynamic Levels" é uma ferramenta desenvolvida por Leonardo Dias Pereira para traders que buscam análises precisas e objetivas no mercado financeiro. Este indicador identifica automaticamente níveis essenciais, como suporte, resistência, alvo e stop-loss, com base em cálculos dinâmicos e parâmetros personalizáveis, como risco percentual e alavancagem.
Com detecção automática de tendência (alta, baixa ou configurável manualmente), o script desenha linhas no gráfico para auxiliar na tomada de decisões estratégicas, fornecendo uma visão clara dos níveis críticos de preço. É ideal tanto para iniciantes quanto para traders experientes que desejam aprimorar suas operações com maior confiança e eficiência.
Recursos Principais:
Identificação automática de suporte, resistência, alvo e stop-loss.
Configuração de tendência (automática ou manual).
Personalização de risco percentual e alavancagem.
Atualização dinâmica das linhas no gráfico.
Indicação visual da tendência detectada.
Maximize seus resultados e simplifique sua análise com esta poderosa ferramenta de suporte à decisão!
MarketMagnet Algo//@version=5
indicator(" MarketMagnet Algo ", overlay = true, max_bars_back = 5000, max_labels_count = 500, max_lines_count = 500)
const bool DEBUG = false
const float epsilon = 0.02 / 100.0
const int showLastXPivots = 50
todayEnabled = input.bool(true, "Today ", group = "General Configuration", inline = "Today")
todayLineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "Today", display = display.none)
todayHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "Today", display = display.none)
todayLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "Today", display = display.none)
todayOpenLineColor = input.color(color.blue, "Open", group = "General Configuration", inline = "Today", display = display.none)
yesterdayEnabled = input.bool(true, "Yesterday ", group = "General Configuration", inline = "Yesterday")
yesterdayLineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "Yesterday", display = display.none)
yesterdayHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "Yesterday", display = display.none)
yesterdayLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "Yesterday", display = display.none)
yesterdayCloseLineColor = input.color(color.fuchsia, "Close", group = "General Configuration", inline = "Yesterday", display = display.none)
day3 = input.bool(false, "3rd Day ", group = "General Configuration", inline = "day3")
day3LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day3", display = display.none)
day3HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day3", display = display.none)
day3LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day3", display = display.none)
day4 = input.bool(false, "4th Day ", group = "General Configuration", inline = "day4")
day4LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day4", display = display.none)
day4HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day4", display = display.none)
day4LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day4", display = display.none)
day5 = input.bool(false, "5th Day ", group = "General Configuration", inline = "day5")
day5LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day5", display = display.none)
day5HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day5", display = display.none)
day5LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day5", display = display.none)
day6 = input.bool(false, "6th Day ", group = "General Configuration", inline = "day6")
day6LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day6", display = display.none)
day6HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day6", display = display.none)
day6LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day6", display = display.none)
day7 = input.bool(false, "7th Day ", group = "General Configuration", inline = "day7")
day7LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day7", display = display.none)
day7HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day7", display = display.none)
day7LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day7", display = display.none)
day8 = input.bool(false, "8th Day ", group = "General Configuration", inline = "day8")
day8LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day8", display = display.none)
day8HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day8", display = display.none)
day8LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day8", display = display.none)
day9 = input.bool(false, "9th Day ", group = "General Configuration", inline = "day9")
day9LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day9", display = display.none)
day9HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day9", display = display.none)
day9LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day9", display = display.none)
day10 = input.bool(false, "10th Day ", group = "General Configuration", inline = "day10")
day10LineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "day10", display = display.none)
day10HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day10", display = display.none)
day10LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day10", display = display.none)
preMarketEnabled = input.bool(false, "Pre-Market ", group = "General Configuration", inline = "premarket")
preMarketLineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "premarket", display = display.none)
preMarketHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "premarket", display = display.none)
preMarketLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "premarket", display = display.none)
previousMonthEnabled = input.bool(false, "Previous Month ", group = "General Configuration", inline = "month")
monthLineStyle = input.string("____", " ", options = , group = "General Configuration", inline = "month", display = display.none)
monthHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "month", display = display.none)
monthLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "month", display = display.none)
pivotsEnabled = input.bool(false, "Enabled", group = "High & Low Pivots")
pivotRange = input.int(14, "Pivot Range", options = , group = "High & Low Pivots")
pivotHighColor = input.color(color.green, "High", group = "High & Low Pivots", inline = "style", display = display.none)
pivotLowColor = input.color(color.red, "Low", group = "High & Low Pivots", inline = "style", display = display.none)
textSizePivotIn = input.string("Normal", "Size", , group = "High & Low Pivots", inline = "style", display = display.none)
barOffset = input.int(20, "Text Offset", group = "Style Settings", display = display.none)
lineThickness = input.int(2, "Thickness", group = "Style Settings", options = , display = display.none)
extendLines = input.bool(true, "Extend Lines", group = "Style Settings", tooltip = "Enabled -> Extend lines infinitely. Disabled -> Clamp lines in their timestamps.", display = display.none)
showLineValues = input.bool(true, "Show Line Values", group = "Style Settings", display = display.none)
labelsAlign = input.string("Right", "Align Labels", options = , group = "Style Settings", display = display.none)
textColor = input.color(color.white, "Text Color", group = "Style Settings", inline = "text", display = display.none)
textSizeIn = input.string("Normal", "Size", , group = "Style Settings", inline = "text", display = display.none)
textSize = (textSizeIn == "Normal" ? size.normal : (textSizeIn == "Small" ? size.small : size.large))
textSizePivot = (textSizePivotIn == "Normal" ? size.normal : (textSizePivotIn == "Small" ? size.small : size.large))
type bInfo
float h = high
float l = low
float o = open
float c = close
int t = time
curBInfo = bInfo.new()
doValuesTouch (float value1, float value2) =>
if math.abs(value1 - value2) / ((value1 + value2) / 2.0) <= epsilon
true
else
false
f_newLine(_color, _lineStyle) => line.new(na, na, na, na, xloc.bar_time, width = lineThickness ,extend = extendLines ? extend.both : extend.none, color = _color, style = _lineStyle == "____" ? line.style_solid : _lineStyle == "----" ? line.style_dashed : line.style_dotted)
f_moveLine(_line, _x, _y, _x2) =>
line.set_xy1(_line, _x, _y)
line.set_xy2(_line, _x2, _y)
f_getInfo (timeframe) =>
request.security(syminfo.tickerid, timeframe, [curBInfo, curBInfo , curBInfo , curBInfo , curBInfo , curBInfo , curBInfo , curBInfo , curBInfo , curBInfo ], calc_bars_count = 30)
f_calculatePreMarketHighLow () =>
curIndex = 0
float preMarketHighF = 0
float preMarketLowF = -1
bool foundPreMarket = false
while (session.isfirstbar == false)
if session.ispremarket
foundPreMarket := true
preMarketHighF := math.max(preMarketHighF, high )
preMarketLowF := preMarketLowF == -1 ? low : math.min(preMarketLowF, low )
if not session.ispremarket and foundPreMarket
break
curIndex += 1
if curIndex > 4000
break
type lineInfo
string timeNames
string infos
float price
int startTime
int endTime
color col
string lStyle
line zone
label lbl
bool disabled = false
type pivot
bool isHigh = false
int index
float price
float atr
label textLabel
safeDeletePivot (pivot p) =>
label.delete(p.textLabel)
createLineInfo (string timeName, string info, float p, int t, int tend, color col, string sty) =>
newLI = lineInfo.new(array.new(0), array.new(0), p, t, tend, col, sty)
if not na(timeName)
newLI.timeNames.unshift(timeName)
if not na (info)
newLI.infos.unshift(info)
newLI
safeDeleteLineInfo (lineInfoF) =>
line.delete(lineInfoF.zone)
label.delete(lineInfoF.lbl)
var allLineInfos = array.new(0)
var allPivots = array.new(0)
extendedTicker = ticker.modify(syminfo.tickerid, session = session.extended)
= request.security(extendedTicker, "1", f_calculatePreMarketHighLow())
= f_getInfo("D")
= f_getInfo("M")
calculateLineInfos () =>
if allLineInfos.size() > 0
for i = 0 to allLineInfos.size() - 1
safeDeleteLineInfo(allLineInfos.get(i))
allLineInfos.clear()
if todayEnabled and not na(bInfo1)
allLineInfos.unshift(createLineInfo("Today", "High", bInfo1.h, bInfo1.t, time, todayHighLineColor, todayLineStyle))
allLineInfos.unshift(createLineInfo("Today", "Low", bInfo1.l, bInfo1.t, time, todayLowLineColor, todayLineStyle))
allLineInfos.unshift(createLineInfo("Today", "Open", bInfo1.o, bInfo1.t, time, todayOpenLineColor, todayLineStyle))
if yesterdayEnabled and not na(bInfo2)
allLineInfos.unshift(createLineInfo("Yesterday", "High", bInfo2.h, bInfo2.t, bInfo1.t, yesterdayHighLineColor, yesterdayLineStyle))
allLineInfos.unshift(createLineInfo("Yesterday", "Low", bInfo2.l, bInfo2.t, bInfo1.t, yesterdayLowLineColor, yesterdayLineStyle))
allLineInfos.unshift(createLineInfo("Yesterday", "Close", bInfo2.c, bInfo2.t, bInfo1.t, yesterdayCloseLineColor, yesterdayLineStyle))
if day3 and not na(bInfo3)
allLineInfos.unshift(createLineInfo("3rd Day", "High", bInfo3.h, bInfo3.t, bInfo2.t, day3HighLineColor, day3LineStyle))
allLineInfos.unshift(createLineInfo("3rd Day", "Low", bInfo3.l, bInfo3.t, bInfo2.t, day3LowLineColor, day3LineStyle))
if day4 and not na(bInfo4)
allLineInfos.unshift(createLineInfo("4th Day", "High", bInfo4.h, bInfo4.t, bInfo3.t, day4HighLineColor, day4LineStyle))
allLineInfos.unshift(createLineInfo("4th Day", "Low", bInfo4.l, bInfo4.t, bInfo3.t, day4LowLineColor, day4LineStyle))
if day5 and not na(bInfo5)
allLineInfos.unshift(createLineInfo("5th Day", "High", bInfo5.h, bInfo5.t, bInfo4.t, day5HighLineColor, day5LineStyle))
allLineInfos.unshift(createLineInfo("5th Day", "Low", bInfo5.l, bInfo5.t, bInfo4.t, day5LowLineColor, day5LineStyle))
if day6 and not na(bInfo6)
allLineInfos.unshift(createLineInfo("6th Day", "High", bInfo6.h, bInfo6.t, bInfo5.t, day6HighLineColor, day6LineStyle))
allLineInfos.unshift(createLineInfo("6th Day", "Low", bInfo6.l, bInfo6.t, bInfo5.t, day6LowLineColor, day6LineStyle))
if day7 and not na(bInfo7)
allLineInfos.unshift(createLineInfo("7th Day", "High", bInfo7.h, bInfo7.t, bInfo6.t, day7HighLineColor, day7LineStyle))
allLineInfos.unshift(createLineInfo("7th Day", "Low", bInfo7.l, bInfo7.t, bInfo6.t, day7LowLineColor, day7LineStyle))
if day8 and not na(bInfo8)
allLineInfos.unshift(createLineInfo("8th Day", "High", bInfo8.h, bInfo8.t, bInfo7.t, day8HighLineColor, day8LineStyle))
allLineInfos.unshift(createLineInfo("8th Day", "Low", bInfo8.l, bInfo8.t, bInfo7.t, day8LowLineColor, day8LineStyle))
if day9 and not na(bInfo9)
allLineInfos.unshift(createLineInfo("9th Day", "High", bInfo9.h, bInfo9.t, bInfo8.t, day9HighLineColor, day9LineStyle))
allLineInfos.unshift(createLineInfo("9th Day", "Low", bInfo9.l, bInfo9.t, bInfo8.t, day9LowLineColor, day9LineStyle))
if day10 and not na(bInfo10)
allLineInfos.unshift(createLineInfo("10th Day", "High", bInfo10.h, bInfo10.t, bInfo9.t, day10HighLineColor, day10LineStyle))
allLineInfos.unshift(createLineInfo("10th Day", "Low", bInfo10.l, bInfo10.t, bInfo9.t, day10LowLineColor, day10LineStyle))
if preMarketEnabled and not na(preMarketHigh) and not na(bInfo1)
allLineInfos.unshift(createLineInfo("Pre-Market", "High", preMarketHigh, bInfo1.t, time, preMarketHighLineColor, preMarketLineStyle))
allLineInfos.unshift(createLineInfo("Pre-Market", "Low", preMarketLow, bInfo1.t, time, preMarketLowLineColor, preMarketLineStyle))
if previousMonthEnabled and not na(mInfo2)
allLineInfos.unshift(createLineInfo("Previous Month", "High", mInfo2.h, mInfo2.t, mInfo1.t, monthLowLineColor, monthLineStyle))
allLineInfos.unshift(createLineInfo("Previous Month", "Low", mInfo2.l, mInfo2.t, mInfo1.t, monthHighLineColor, monthLineStyle))
calculateLineInfos()
combineLineInfos () =>
if allLineInfos.size() > 0
lastCombinations = 999
while lastCombinations > 0
lastCombinations := 0
for i = 0 to allLineInfos.size() - 1
curLI1 = allLineInfos.get(i)
for j = 0 to allLineInfos.size() - 1
curLI2 = allLineInfos.get(j)
if i == j
continue
if curLI1.disabled or curLI2.disabled
continue
if doValuesTouch(curLI1.price, curLI2.price) and extendLines
curLI1.disabled := true
curLI2.disabled := true
newLI = createLineInfo(na, na, curLI1.price, na, na, na, na)
if curLI1.timeNames.size() > 0
for a = 0 to curLI1.timeNames.size() - 1
newLI.timeNames.unshift(curLI1.timeNames.get(a))
for a = 0 to curLI1.infos.size() - 1
newLI.infos.unshift(curLI1.infos.get(a))
if curLI2.timeNames.size() > 0
for a = 0 to curLI2.timeNames.size() - 1
newLI.timeNames.unshift(curLI2.timeNames.get(a))
for a = 0 to curLI2.infos.size() - 1
newLI.infos.unshift(curLI2.infos.get(a))
newLI.startTime := math.min(curLI1.startTime, curLI2.startTime)
newLI.endTime := math.max(curLI1.endTime, curLI2.endTime)
newLI.col := curLI1.col
newLI.lStyle := curLI1.lStyle
allLineInfos.unshift(newLI)
lastCombinations += 1
renderPivot (pivot pivotF) =>
pivotF.textLabel := label.new(pivotF.index, pivotF.price + (pivotF.atr * 1 * (pivotF.isHigh ? 1 : -1)), str.tostring(pivotF.price, format.mintick), style = label.style_none, size = textSizePivot, textcolor = (pivotF.isHigh ? pivotHighColor : pivotLowColor))
renderLineInfo (lineInfoF) =>
safeDeleteLineInfo(lineInfoF)
if not lineInfoF.disabled
lineInfoF.zone := f_newLine(lineInfoF.col, lineInfoF.lStyle)
if lineInfoF.startTime == lineInfoF.endTime
lineInfoF.endTime += 1
f_moveLine(lineInfoF.zone, lineInfoF.startTime, lineInfoF.price, lineInfoF.endTime)
lblText = ""
if lineInfoF.timeNames.size() > 0
for i = 0 to lineInfoF.timeNames.size() - 1
lblText += lineInfoF.timeNames.get(i) + " "
lblText += lineInfoF.infos.get(i)
if i != lineInfoF.timeNames.size() - 1
lblText += " & "
if showLineValues
lblText += " (" + str.tostring(lineInfoF.price, format.mintick) + ")"
if extendLines
lineInfoF.lbl := label.new(labelsAlign == "Center" ? ((chart.right_visible_bar_time + chart.left_visible_bar_time) / 2) : (last_bar_index + barOffset), lineInfoF.price, textcolor = textColor, text = lblText, style = label.style_none, xloc = labelsAlign == "Center" ? xloc.bar_time : xloc.bar_index, size = textSize)
else
lineInfoF.lbl := label.new(labelsAlign == "Center" ? (lineInfoF.startTime + lineInfoF.endTime) / 2 : lineInfoF.endTime, lineInfoF.price, xloc = xloc.bar_time, textcolor = textColor, text = lblText, style = label.style_none, size = textSize)
renderLineInfos () =>
if allLineInfos.size() > 0
for i = 0 to allLineInfos.size() - 1
curLineInfo = allLineInfos.get(i)
renderLineInfo(curLineInfo)
renderPivots () =>
if allPivots.size() > 0
for i = 0 to allPivots.size() - 1
curPivot = allPivots.get(i)
safeDeletePivot(curPivot)
renderPivot(curPivot)
combineLineInfos()
renderLineInfos()
pivotHigh = ta.pivothigh(pivotRange, pivotRange)
pivotLow = ta.pivotlow(pivotRange, pivotRange)
curAtr = ta.atr(5)
if not na(pivotHigh)
allPivots.unshift(pivot.new(true, bar_index - pivotRange, pivotHigh, curAtr))
if not na(pivotLow)
allPivots.unshift(pivot.new(false, bar_index - pivotRange, pivotLow, curAtr))
if allPivots.size() > showLastXPivots
allPivots.remove(allPivots.size() - 1)
if barstate.islast
if pivotsEnabled
renderPivots()
// Get user input
sensitivity = input.float(2.8, " Sensitivity (0.5 - 10)", 0.5, 10, step=0.1)
emaEnergy = input.bool(true, "EMA Energy")
keltner_length = input(10, "Keltner Channel Length")
atrPeriod = input(10, "ATR Length")
factor = input.float(3.5, "Factor", step = 0.01)
// Keltner Channel function
keltner_channel(src, length) =>
ma = ta.sma(src, length)
rangec = high - low
upper = ma + rangec
lower = ma - rangec
// Modified Supertrend function using Keltner Channel
supertrend(_src, factor, atrLen, kel_length) =>
= keltner_channel(_src, kel_length)
rangec = upperKeltner - lowerKeltner
upperBand = _src + factor * rangec
lowerBand = _src - factor * rangec
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or close < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend
if na(rangec )
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
// Get Components
ema1 = ta.ema(high, 9)
ema2 = ta.ema(high, 12)
ema3 = ta.ema(high, 15)
ema4 = ta.ema(high, 18)
ema5 = ta.ema(high, 21)
ema6 = ta.ema(high, 24)
ema7 = ta.ema(high, 27)
ema8 = ta.ema(high, 30)
ema9 = ta.ema(high, 33)
ema10 = ta.ema(high, 36)
ema11 = ta.ema(high, 39)
ema12 = ta.ema(high, 42)
ema13 = ta.ema(high, 45)
ema14 = ta.ema(high, 48)
ema15 = ta.ema(high, 51)
// Colors
green = #2BBC4D, red = #C51D0B
emaEnergyColor(ma) => emaEnergy ? (close >= ma ? green : red) : na
// Plots
plot(ema1, "", emaEnergyColor(ema1), editable=false)
plot(ema2, "", emaEnergyColor(ema2), editable=false)
plot(ema3, "", emaEnergyColor(ema3), editable=false)
plot(ema4, "", emaEnergyColor(ema4), editable=false)
plot(ema5, "", emaEnergyColor(ema5), editable=false)
plot(ema6, "", emaEnergyColor(ema6), editable=false)
plot(ema7, "", emaEnergyColor(ema7), editable=false)
plot(ema8, "", emaEnergyColor(ema8), editable=false)
plot(ema9, "", emaEnergyColor(ema9), editable=false)
plot(ema10, "", emaEnergyColor(ema10), editable=false)
plot(ema11, "", emaEnergyColor(ema11), editable=false)
plot(ema12, "", emaEnergyColor(ema12), editable=false)
plot(ema13, "", emaEnergyColor(ema13), editable=false)
plot(ema14, "", emaEnergyColor(ema14), editable=false)
plot(ema15, "", emaEnergyColor(ema15), editable=false)
= supertrend(close, sensitivity, 11, keltner_length)
bull = ta.crossover(close, supertrend)
bear = ta.crossunder(close, supertrend)
y1 = low - (ta.atr(30) * 2)
y2 = high + (ta.atr(30) * 2)
buy = bull ? label.new(bar_index, y1, "BUY CE", xloc.bar_index, yloc.price, green, label.style_label_up, color.white, size.normal) : na
sell = bear ? label.new(bar_index, y2, "BUY PE", xloc.bar_index, yloc.price, red, label.style_label_down, color.white, size.normal) : na
= ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
// Trend Catcher Indicator (Example)
ema100 = ta.ema(close, 10)
ema200 = ta.ema(close, 20)
trendCatcher = ta.crossover(ema100, ema200) ? 1 : ta.crossunder(ema100, ema200) ? -1 : 0
trendColor = trendCatcher == 1 ? color.rgb(90, 23, 102) : na
barcolor(trendColor)
// Colored candles
barcolor(color = close > supertrends ? color.rgb(102, 255, 0) : color.rgb(255, 0, 0))
// 添加警報條件
alertcondition(bull, title="Buy CE", message="Buy CE!")
alertcondition(bear, title="Buy PE", message="Buy PE!")
// Plot EMAs
plot(ema1, color=color.blue, title="EMA 9")
plot(ema2, color=color.orange, title="EMA 21")
plot(ema3, color=color.purple, title="EMA 61")
// Input settings
ccimomCross = input.string('CCI', 'Entry Signal Source', options= , tooltip='CCI or Momentum will be the final source of the Entry signal if selected.')
ccimomLength = input.int(10, minval=1, title='CCI/Momentum Length')
useDivergence = input.bool(true, title='Find Regular Bullish/Bearish Divergence', tooltip='If checked, it will only consider an overbought or oversold condition that has a regular bullish or bearish divergence formed inside that level.')
rsiOverbought = input.int(65, minval=1, title='RSI Overbought Level', tooltip='Adjusting the level to extremely high may filter out some signals especially when the option to find divergence is checked.')
rsiOversold = input.int(35, minval=1, title='RSI Oversold Level', tooltip='Adjusting this level extremely low may filter out some signals especially when the option to find divergence is checked.')
rsiLength = input.int(14, minval=1, title='RSI Length')
plotMeanReversion = input.bool(false, 'Plot Mean Reversion Bands on the chart', tooltip='This function doesn\'t affect the entry of signal but it suggests buying when the price is at the lower band, and then sell it on the next bounce at the higher bands.')
emaPeriod = input(200, title='Lookback Period (EMA)')
bandMultiplier = input.float(1.8, title='Outer Bands Multiplier', tooltip='Multiplier for both upper and lower bands')
// CCI and Momentum calculation
momLength = ccimomCross == 'Momentum' ? ccimomLength : 10
mom = close - close
cci = ta.cci(close, ccimomLength)
ccimomCrossUp = ccimomCross == 'Momentum' ? ta.cross(mom, 0) : ta.cross(cci, 0)
ccimomCrossDown = ccimomCross == 'Momentum' ? ta.cross(0, mom) : ta.cross(0, cci)
// RSI calculation
src = close
up = ta.rma(math.max(ta.change(src), 0), rsiLength)
down = ta.rma(-math.min(ta.change(src), 0), rsiLength)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
oversoldAgo = rsi <= rsiOversold or rsi <= rsiOversold or rsi <= rsiOversold or rsi <= rsiOversold
overboughtAgo = rsi >= rsiOverbought or rsi >= rsiOverbought or rsi >= rsiOverbought or rsi >= rsiOverbought
// Regular Divergence Conditions
bullishDivergenceCondition = rsi > rsi and rsi < rsi
bearishDivergenceCondition = rsi < rsi and rsi > rsi
// Entry Conditions
longEntryCondition = ccimomCrossUp and oversoldAgo and (not useDivergence or bullishDivergenceCondition)
shortEntryCondition = ccimomCrossDown and overboughtAgo and (not useDivergence or bearishDivergenceCondition)
// Mean Reversion Indicator
meanReversion = plotMeanReversion ? ta.ema(close, emaPeriod) : na
stdDev = plotMeanReversion ? ta.stdev(close, emaPeriod) : na
upperBand = plotMeanReversion ? meanReversion + stdDev * bandMultiplier : na
lowerBand = plotMeanReversion ? meanReversion - stdDev * bandMultiplier : na
// Plotting
plotshape(longEntryCondition, title='BUY', style=shape.triangleup, text='B', location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(shortEntryCondition, title='SELL', style=shape.triangledown, text='S', location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plot(upperBand, title='Upper Band', color=color.new(color.fuchsia, 0), linewidth=1)
plot(meanReversion, title='Mean', color=color.new(color.gray, 0), linewidth=1)
plot(lowerBand, title='Lower Band', color=color.new(color.blue, 0), linewidth=1)
// Entry signal alerts
alertcondition(longEntryCondition, title='BUY Signal', message='Buy Entry Signal')
alertcondition(shortEntryCondition, title='SELL Signal', message='Sell Entry Signal')
alertcondition(longEntryCondition or shortEntryCondition, title='BUY or SELL Signal', message='Entry Signal')
// User Input To Enable / Disable, Either / Both Side Levels
bullishbreakout = input(true, title="Bullish Target & SL")
bearishbreakout = input(true, title="Bearish Target & SL")
// Identify High & Low for Selected Scripts
prevClose = request.security(syminfo.tickerid, "D", close )
is_newbar(res) => ta.change(time(res)) != 0
adopt(r, s) => request.security(syminfo.tickerid, r, s)
open_range_high = ta.valuewhen(is_newbar('D'),high,0)
open_range_low = ta.valuewhen(is_newbar('D'),low,0)
// Function to check if a candle is the 1:15 PM candle
is_115_candle() =>
hour == 13 and minute == 15
// Check if the current candle is the 1:15 PM candle
is_115_candle_current = is_115_candle()
// Plotting the candle highlight
bgcolor(is_115_candle_current ? color.new(color.blue, 80) : na)
// Marking high and low of the 1:15 PM candle
var float high_115_candle = na
var float low_115_candle = na
if is_115_candle_current and not is_115_candle_current
high_115_candle := high
low_115_candle := low
// Plotting high and low of the 1:15 PM candle
plot(high_115_candle, color=color.red, style=plot.style_circles, linewidth=2)
plot(low_115_candle, color=color.green, style=plot.style_circles, linewidth=2)
//rsi
mrsi = ta.rsi(close,14)
colorRsi = mrsi>55?color.green: mrsi<45?color.red:color.gray
//ADX
len = input.int(14, minval=1, title="DI Length")
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
= ta.dmi(len, lensig)
colorADX = adx>25?color.rgb(33, 208, 243):color.gray
//creating the table
var testTable = table.new(position = position.top_right, columns = 4, rows = 2, border_width = 1, border_color = color.black, frame_width = 1, frame_color = color.black)
//column Headings
table.cell(table_id = testTable, column = 0, row = 0, text = " RSI ", bgcolor=color.aqua, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 0, text = " DI+ ", bgcolor=color.green, text_color = color.white)
table.cell(table_id = testTable, column = 2, row = 0, text = " DI- ", bgcolor=color.red, text_color = color.white)
table.cell(table_id = testTable, column = 3, row = 0, text = " ADX ", bgcolor=color.aqua, text_color = color.white)
//column values
table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(math.round(mrsi,0)) , bgcolor= color.aqua, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 1, text = str.tostring(math.round(diplus,0)) , bgcolor= color.green, text_color = color.white)// "RSI")//, bgcolor=color.red)
table.cell(table_id = testTable, column = 2, row = 1, text = str.tostring(math.round(diminus,0)) , bgcolor= color.red, text_color = color.white)// "DI+")//, bgcolor=color.red)
table.cell(table_id = testTable, column = 3, row = 1, text = str.tostring(math.round(adx,0)) , bgcolor= color.aqua, text_color = color.white)//"DI-")//, bgcolor=color.red)
// SmartMoneyConcept
string visual = "➞ Visuals Settings🔸"
string core = "➞ Main Core Settings 🔸"
int atrLen = 30
float mult = 0.3
float per = 10.0
float perc = close * (per/100)
float srdatr = ta.atr (atrLen) * mult
float band = math.min (srdatr, perc) /2
int sync = bar_index
var BINDEX = 0
var line Lines = array.new_line()
var label Labels = array.new_label()
float TotalVolume = array.new_float()
float Greenvolume = array.new_float()
float redvolume = array.new_float()
var ph = float(na)
var phL = int(na)
var pl = float(na)
float lowestValue = low
float HighValue = high
float Midhigh = high
float Midindex = bar_index
int lowestIndex = bar_index
int HighIndex = bar_index
float HH = low
int prd = input.int(30,"period",group = core)
int levs = input.int(24,"Volume Levels",tooltip = "Number of the Volume levels to check", group = core)
bool ShowVolume = input.bool(true,"Show Volume ❓ ",inline = "01",group = visual)
bool randomcolor = input.bool(false,"Random Coloring ❓ ",inline = "01",group = visual)
color Bull = input.color(color.new(#42f07f, 35),"1st",inline = "01",group = visual)
color Bear = input.color(color.new(#f37451, 70),"2nd",inline = "01",group = visual)
bool Showlines = input.bool(true,"Show Zigzag ❓ ",inline = "02",group = visual)
bool randomcolor1 = input.bool(false,"Random Coloring ❓ ",inline = "02",group = visual)
color LineZ = input.color(color.yellow,"",inline = "02",group = visual)
//~~~~~~~~~}
// ~~ Pivots {
pvtHi = ta.pivothigh(high,prd,prd)
pvtLo = ta.pivotlow(low,prd,prd)
if pvtHi
ph := high
phL:= sync
if pvtLo
pl:=low
Points = array.new_float(2,0)
Counter(lev,sup = true)=>
if sup
for i = 0 to 2000
max_bars_back(low,2000)
if low < lev and lev < close
array.set(Points,0,array.get(Points,0)+1)
Points.get(0)
else
for i = 0 to 2000
max_bars_back(high,2000)
if high > lev and lev > close
array.set(Points,1,array.get(Points,1)+1)
Points.get(1)
if barstate.islast
Count = (bar_index - phL)
// levs= math.floor(Count/3)
// levs= math.floor(24)
float VPlevels = array.new_float(levs+1)
var box VPboxes = array.new_box(levs+3)
var box VPboxes2 = array.new_box(levs+3)
int ticks = array.new_int(levs,0)
float Volumes = array.new_float(levs,0.0)
float SCR = array.new_float()
for i = 0 to Count
SCR.push(close )
for i = 1 to Count
if low <= lowestValue
lowestValue := low
lowestIndex := bar_index
if high >= HighValue
HighValue := high
HighIndex := bar_index
//
// M = bar_index + 135
// CC = int( (M - lowestIndex) / 2) s
Value = Counter(pl)
Value2 = Counter(HighValue,false)
max_bars_back(Value,2000)
max_bars_back(Value2,2000)
for i = 1 to 20
if high >= Midhigh
Midhigh := high
Midindex := bar_index
step = ( HighValue-lowestValue ) / levs
for i=0 to levs by 1
array.set(VPlevels,i, lowestValue + step * i)
Col=color.rgb(math.random(10,200),math.random(10,160),math.random(10,180))
Gcolo = color.rgb(math.random(25,32),math.random(40,200),math.random(15,100))
//color.rgb(9, 155, 99, 90)
var box BOX1 = na , box.delete(BOX1)
var box BOX2 = na , box.delete(BOX2)
LA = sync - HighIndex
labelplace = (170 + LA ) / 2
BOX1:=box.new(lowestIndex,lowestValue+ (band* 2),bar_index+170,lowestValue,bgcolor = color.rgb(9, 155, 99, 90),border_color = color.rgb(9, 155, 99, 50))
BOX2:=box.new(HighIndex,HighValue + (band* 2),bar_index+170,HighValue,bgcolor = color.rgb(255, 4, 4, 90) ,border_color = color.rgb(255, 4, 4, 50))
Labels.push(label.new(lowestIndex ,lowestValue - (band * 13),str.tostring(Value),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
Labels.push(label.new(bar_index+135 ,lowestValue - (band * 13),str.tostring(Value + 1),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
Labels.push(label.new(HighIndex + labelplace ,HighValue + (band * 10),str.tostring(Value2),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
if Showlines
// 2
Lines.push(line.new(HighIndex,HighValue,lowestIndex + 50,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(HighIndex + 2 ,HighValue,lowestIndex + 52,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
// 3
Lines.push(line.new(lowestIndex + 50,lowestValue+ (band* 2),HighIndex + (labelplace-2) ,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(lowestIndex + 52,lowestValue+ (band* 2),HighIndex + labelplace,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
// 4
Lines.push(line.new(HighIndex + (labelplace-2),HighValue,bar_index+133,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(HighIndex + labelplace,HighValue,bar_index+135,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(bar_index+135,lowestValue+ (band* 2),bar_index+170,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(bar_index+133,lowestValue+ (band* 2),bar_index+168,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
if array.size(Lines) > 8
for i = 0 to 7
line.delete(Lines.shift())
if array.size(Labels) > 3
for i = 0 to 2
label.delete(Labels.shift())
for i=0 to array.size(SCR) -1
for x=0 to array.size(VPlevels) - 2 by 1
if low < array.get(VPlevels,x+1) and array.get(VPlevels,x) < close
array.set(ticks,x,array.get(ticks,x)+1)
array.set(Volumes,x,array.get(Volumes,x)+Counter(close ))
break
// label.new(bar_index+20 , low , str.tostring(ticks.size()))
if ShowVolume
for i = 0 to array.size(ticks) -2
box.delete(array.get(VPboxes,i))
array.set(VPboxes,i,
box.new(sync + 170+array.get(ticks,i),
array.get(VPlevels,i+1)+(band* 2),
sync + 170,
array.get(VPlevels,i)+(band* 2),
border_color = color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Col : Bull , 70),
color.new(randomcolor ? Col : Bull , 35)),
bgcolor=color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Col : Bull , 70),
color.new(randomcolor ? Col : Bull , 35)),
text=array.get(Volumes,i) > 0 ? str.tostring(array.get(Volumes,i),format.volume): "",
text_color=color.white))
for i = 0 to array.size(ticks) -2
box.delete(array.get(VPboxes2,i))
array.set(VPboxes2,i,
box.new(sync + 170-array.get(ticks,i),
array.get(VPlevels,i+1)+(band* 2),
sync + 170,
array.get(VPlevels,i)+(band* 2),
border_color = color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Gcolo : Bear , 70),
color.new(randomcolor ? Gcolo : Bear , 35)),
bgcolor=color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Gcolo : Bear , 70),
color.new(randomcolor ? Gcolo : Bear , 35)),
text=str.tostring(array.get(ticks,i)),
text_color=color.white))
// )
// AutoFibExtension
depthTooltip = "The minimum number of bars that will be taken into account when calculating the indicator."
depth = input.int(title="Depth", defval=10, minval=2, inline = "Pivots", tooltip=depthTooltip)
reverse = input(false, "Reverse", display = display.data_window)
var extendLeft = input(false, "Extend Left | Extend Right", inline = "Extend Lines", display = display.data_window)
var extendRight = input(true, "", inline = "Extend Lines", display = display.data_window)
var extending = extend.none
if extendLeft and extendRight
extending := extend.both
if extendLeft and not extendRight
extending := extend.left
if not extendLeft and extendRight
extending := extend.right
prices = input(true, "Show Prices", display = display.data_window)
levels = input(true, "Show Levels", inline = "Levels", display = display.data_window)
levelsFormat = input.string("Values", "", options = , inline = "Levels", display = display.data_window)
labelsPosition = input.string("Left", "Labels Position", options = , display = display.data_window)
backgroundTransparency = input.int(85, "Background Transparency", minval = 0, maxval = 100, display = display.data_window)
upperThreshold = 0.236
lowerThreshold = 1.0
import TradingView/ZigZag/7 as zigzag
pivots(src, length, isHigh) =>
if bar_index >= length
price = nz(src )
found = true
for i = 0 to length * 2
if (isHigh and src > price) or (not isHigh and src < price)
found := false
break
if found
chart.point.from_time(time , price)
update()=>
var line lineLastHL = na
var line lineLastLH = na
var line lineLast = na
var chart.point pivotsH = array.new()
var chart.point lastH = na
var chart.point pivotsL = array.new()
var chart.point lastL = na
var isHighLast = false
var float startPrice = na
var float endPrice = na
H = pivots(high, depth / 2, true)
L = pivots(low, depth / 2, false)
countPivotsH = array.size(pivotsH)
countPivotsL = array.size(pivotsL)
if countPivotsH > 0 and countPivotsL > 0
lastH := array.get(pivotsH, countPivotsH-1)
lastL := array.get(pivotsL, countPivotsL-1)
isHighLast := lastH.time > lastL.time
if isHighLast
if not na(H)
if H.price > lastH.price
array.set(pivotsH, countPivotsH-1, H)
H := na
else
if not na(L)
if L.price < lastL.price
array.set(pivotsL, countPivotsL-1, L)
L := na
if not na(H)
array.push(pivotsH, H)
if not na(L)
array.push(pivotsL, L)
if barstate.islast and array.size(pivotsH) > 0 and array.size(pivotsL) > 0
pivotsHCopy = array.copy(pivotsH)
pivotsLCopy = array.copy(pivotsL)
while array.size(pivotsHCopy) > 0 and array.size(pivotsLCopy) > 0
lastH := array.pop(pivotsHCopy)
lastL := array.pop(pivotsLCopy)
isHighLast := lastH.time > lastL.time
pivots = isHighLast ? pivotsHCopy : pivotsLCopy
for i = array.size(pivots)-1 to 0
if i < 0
break
p = array.get(pivots, i)
if p.time < lastL.time
break
betterPrice = isHighLast ? p.price > lastH.price : p.price < lastL.price
if p.price > lastH.price
lastH := array.pop(pivots)
else
array.remove(pivots, i)
if array.size(pivotsHCopy) == 0 or array.size(pivotsLCopy) == 0
break
isHighLast := lastH.time > lastL.time
pivots := isHighLast ? pivotsHCopy : pivotsLCopy
prevPivot = array.get(pivots, array.size(pivots)-1)
startPrice := prevPivot.price
if isHighLast
endPrice := lastL.price
diff = math.abs(startPrice - endPrice)
if lastH.price > endPrice + diff * lowerThreshold or lastH.price < endPrice + diff * upperThreshold
array.push(pivotsLCopy, lastL)
continue
line.delete(lineLastHL)
line.delete(lineLastLH)
lineLastHL := line.new(prevPivot, lastL, color=color.red, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLastLH := line.new(lastL, lastH, color=color.green, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLast := lineLastLH
else
endPrice := lastH.price
diff = math.abs(startPrice - endPrice)
if lastL.price < endPrice - diff * lowerThreshold or lastL.price > endPrice - diff * upperThreshold
array.push(pivotsHCopy, lastH)
continue
line.delete(lineLastHL)
line.delete(lineLastLH)
lineLastLH := line.new(prevPivot, lastH, color=color.red, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLastHL := line.new(lastH, lastL, color=color.green, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLast := lineLastHL
break
diff = (isHighLast ? -1 : 1) * math.abs(startPrice - endPrice)
offset = isHighLast ? line.get_y1(lineLastLH) - line.get_y2(lineLastLH) : line.get_y1(lineLastHL) - line.get_y2(lineLastHL)
offset := (isHighLast ? -1 : 1) * math.abs(offset)
= update()
_draw_line(price, col) =>
var id = line.new(time, price, time, price, color=col, width=1, extend=extending, xloc = xloc.bar_time)
if not na(lineLast)
line.set_xy1(id, line.get_x1(lineLast), price)
line.set_xy2(id, line.get_x2(lineLast), price)
id
_draw_label(price, txt, txtColor) =>
if not na(price)
x = labelsPosition == "Left" ? line.get_x1(lineLast) : not extendRight ? line.get_x2(lineLast) : time
labelStyle = labelsPosition == "Left" ? label.style_label_right : label.style_label_left
align = labelsPosition == "Left" ? text.align_right : text.align_left
labelsAlignStrLeft = txt + ' '
labelsAlignStrRight = ' ' + txt + ' '
labelsAlignStr = labelsPosition == "Left" ? labelsAlignStrLeft : labelsAlignStrRight
var id = label.new(x=x, y=price, text=labelsAlignStr, textcolor=txtColor, style=labelStyle, textalign=align, color=#00000000, xloc = xloc.bar_time)
label.set_xy(id, x, price)
label.set_text(id, labelsAlignStr)
label.set_textcolor(id, txtColor)
_wrap(txt) =>
"(" + str.tostring(txt, format.mintick) + ")"
_label_txt(level, price) =>
if not na(price)
l = levelsFormat == "Values" ? str.tostring(level) : str.tostring(level * 100) + "%"
(levels ? l : "") + (prices ? _wrap(price) : "")
_crossing_level(sr, r) =>
(r > sr and r < sr ) or (r < sr and r > sr )
processLevel(show, value, colorL, lineIdOther) =>
float m = value
r = endPrice + ((reverse ? -1 : 1) * diff * m)
if show
lineId = _draw_line(r, colorL)
_draw_label(r, _label_txt(m, r), colorL)
if _crossing_level(close, r)
alert("Autofib: " + syminfo.ticker + " crossing level " + str.tostring(value))
if not na(lineIdOther)
linefill.new(lineId, lineIdOther, color = color.new(colorL, backgroundTransparency))
lineId
else
lineIdOther
show_0 = input(true, "", inline = "Level0", display = display.data_window)
value_0 = input(0, "", inline = "Level0", display = display.data_window)
color_0 = input(#787b86, "", inline = "Level0", display = display.data_window)
show_0_236 = input(true, "", inline = "Level0", display = display.data_window)
value_0_236 = input(0.236, "", inline = "Level0", display = display.data_window)
color_0_236 = input(#f44336, "", inline = "Level0", display = display.data_window)
show_0_382 = input(true, "", inline = "Level1", display = display.data_window)
value_0_382 = input(0.382, "", inline = "Level1", display = display.data_window)
color_0_382 = input(#81c784, "", inline = "Level1", display = display.data_window)
show_0_5 = input(true, "", inline = "Level1", display = display.data_window)
value_0_5 = input(0.5, "", inline = "Level1", display = display.data_window)
color_0_5 = input(#4caf50, "", inline = "Level1", display = display.data_window)
show_0_618 = input(true, "", inline = "Level2", display = display.data_window)
value_0_618 = input(0.618, "", inline = "Level2", display = display.data_window)
color_0_618 = input(#009688, "", inline = "Level2", display = display.data_window)
show_0_65 = input(false, "", inline = "Level2", display = display.data_window)
value_0_65 = input(0.65, "", inline = "Level2", display = display.data_window)
color_0_65 = input(#009688, "", inline = "Level2", display = display.data_window)
show_0_786 = input(true, "", inline = "Level3", display = display.data_window)
value_0_786 = input(0.786, "", inline = "Level3", display = display.data_window)
color_0_786 = input(#64b5f6, "", inline = "Level3", display = display.data_window)
show_1 = input(true, "", inline = "Level3", display = display.data_window)
value_1 = input(1, "", inline = "Level3", display = display.data_window)
color_1 = input(#787b86, "", inline = "Level3", display = display.data_window)
show_1_272 = input(false, "", inline = "Level4", display = display.data_window)
value_1_272 = input(1.272, "", inline = "Level4", display = display.data_window)
color_1_272 = input(#81c784, "", inline = "Level4", display = display.data_window)
show_1_414 = input(false, "", inline = "Level4", display = display.data_window)
value_1_414 = input(1.414, "", inline = "Level4", display = display.data_window)
color_1_414 = input(#f44336, "", inline = "Level4", display = display.data_window)
show_1_618 = input(true, "", inline = "Level5", display = display.data_window)
value_1_618 = input(1.618, "", inline = "Level5", display = display.data_window)
color_1_618 = input(#2962ff, "", inline = "Level5", display = display.data_window)
show_1_65 = input(false, "", inline = "Level5", display = display.data_window)
value_1_65 = input(1.65, "", inline = "Level5", display = display.data_window)
color_1_65 = input(#2962ff, "", inline = "Level5", display = display.data_window)
show_2_618 = input(true, "", inline = "Level6", display = display.data_window)
value_2_618 = input(2.618, "", inline = "Level6", display = display.data_window)
color_2_618 = input(#f44336, "", inline = "Level6", display = display.data_window)
show_2_65 = input(false, "", inline = "Level6", display = display.data_window)
value_2_65 = input(2.65, "", inline = "Level6", display = display.data_window)
color_2_65 = input(#f44336, "", inline = "Level6", display = display.data_window)
show_3_618 = input(true, "", inline = "Level7", display = display.data_window)
value_3_618 = input(3.618, "", inline = "Level7", display = display.data_window)
color_3_618 = input(#9c27b0, "", inline = "Level7", display = display.data_window)
show_3_65 = input(false, "", inline = "Level7", display = display.data_window)
value_3_65 = input(3.65, "", inline = "Level7", display = display.data_window)
color_3_65 = input(#9c27b0, "", inline = "Level7", display = display.data_window)
show_4_236 = input(true, "", inline = "Level8", display = display.data_window)
value_4_236 = input(4.236, "", inline = "Level8", display = display.data_window)
color_4_236 = input(#e91e63, "", inline = "Level8", display = display.data_window)
show_4_618 = input(false, "", inline = "Level8", display = display.data_window)
value_4_618 = input(4.618, "", inline = "Level8", display = display.data_window)
color_4_618 = input(#81c784, "", inline = "Level8", display = display.data_window)
show_neg_0_236 = input(false, "", inline = "Level9", display = display.data_window)
value_neg_0_236 = input(-0.236, "", inline = "Level9", display = display.data_window)
color_neg_0_236 = input(#f44336, "", inline = "Level9", display = display.data_window)
show_neg_0_382 = input(false, "", inline = "Level9", display = display.data_window)
value_neg_0_382 = input(-0.382, "", inline = "Level9", display = display.data_window)
color_neg_0_382 = input(#81c784, "", inline = "Level9", display = display.data_window)
show_neg_0_618 = input(false, "", inline = "Level10", display = display.data_window)
value_neg_0_618 = input(-0.618, "", inline = "Level10", display = display.data_window)
color_neg_0_618 = input(#009688, "", inline = "Level10", display = display.data_window)
show_neg_0_65 = input(false, "", inline = "Level10", display = display.data_window)
value_neg_0_65 = input(-0.65, "", inline = "Level10", display = display.data_window)
color_neg_0_65 = input(#009688, "", inline = "Level10", display = display.data_window)
lineId0 = processLevel(show_neg_0_65, value_neg_0_65, color_neg_0_65, line(na))
lineId1 = processLevel(show_neg_0_618, value_neg_0_618, color_neg_0_618, lineId0)
lineId2 = processLevel(show_neg_0_382, value_neg_0_382, color_neg_0_382, lineId1)
lineId3 = processLevel(show_neg_0_236, value_neg_0_236, color_neg_0_236, lineId2)
lineId4 = processLevel(show_0, value_0, color_0, lineId3)
lineId5 = processLevel(show_0_236, value_0_236, color_0_236, lineId4)
lineId6 = processLevel(show_0_382, value_0_382, color_0_382, lineId5)
lineId7 = processLevel(show_0_5, value_0_5, color_0_5, lineId6)
lineId8 = processLevel(show_0_618, value_0_618, color_0_618, lineId7)
lineId9 = processLevel(show_0_65, value_0_65, color_0_65, lineId8)
lineId10 = processLevel(show_0_786, value_0_786, color_0_786, lineId9)
lineId11 = processLevel(show_1, value_1, color_1, lineId10)
lineId12 = processLevel(show_1_272, value_1_272, color_1_272, lineId11)
lineId13 = processLevel(show_1_414, value_1_414, color_1_414, lineId12)
lineId14 = processLevel(show_1_618, value_1_618, color_1_618, lineId13)
lineId15 = processLevel(show_1_65, value_1_65, color_1_65, lineId14)
lineId16 = processLevel(show_2_618, value_2_618, color_2_618, lineId15)
lineId17 = processLevel(show_2_65, value_2_65, color_2_65, lineId16)
lineId18 = processLevel(show_3_618, value_3_618, color_3_618, lineId17)
lineId19 = processLevel(show_3_65, value_3_65, color_3_65, lineId18)
lineId20 = processLevel(show_4_236, value_4_236, color_4_236, lineId19)
lineId21 = processLevel(show_4_618, value_4_618, color_4_618, lineId20)
//=====Inputs
//____Source Inputs allowing for non-price inputs such as an oscillator
hi_ = input.source(high,"High variable input",inline="source",group="Source")
lo_ = input.source(low,"Low variable input",inline="source",group="Source")
track_var = input.source(hlc3,title="Value to use to locate levels",group="Source")
//____Presentation related inputs
bool use_vis = input.bool(false,"Use Visible range",tooltip="Limit lines drawn to the pane visible range",group="Pivots",inline="p0")
bool use_fibs = input.bool(false,"Use Fibs vs Divide by 2",tooltip="Fibs Used: 0.236, 0.382, 0.5, 0.618, 0.786",group="Pivots",inline="p0")
int layer_to_show = input.int(2,"Layers",minval=0,maxval=10,group="Pivots",tooltip="Increasing will further subdivid the range")-1
int offset_lastbar = input.int(defval=5,minval=0,maxval=300,title="Offset to last bar",group="Pivots",inline="p1")
int l_len = input.int(50,"Root layer length",group="Pivots",inline="p1",tooltip="Higher level lengths will be a multiple>1 of this length")
bool show_labels = input.bool(false,title="Show Labels",group="Labels",inline="lbl1")
bool label_info = input.bool(false,"Show value vs ratio",group="Labels",inline="lbl1")
int label_layer_lim = input.int(2,title="Layer limit",group="Labels",inline="lbl2")
bool show_only_50 = input.bool(false,"Show mid_points for layers above limit ",group="Labels",inline="lbl2")
string label_location = input.string("Center",title="Location",options= ,group="Labels",inline="lbl3")
string label_string = input.string("Center",title="Orientation",options= ,group="Labels",inline="lbl3")
string label_txt_size = input.string('Normal',"Text Size",options= ,group="Labels",inline="lbl3")
//==== UDTs and Methods
//___ Detailed layer UDT - a wrapper for a map
type level
map level_data
//____ Pivot UDT
type cPivot
bool recalc = false
bool show_labels = false
bool label_info = false
bool new_variable_location = false
int line_length = 0
int label_offset = 0
int label_limit = 0
float layer_mult = 0
float current_top
float current_bot
string label_txt_size = size.auto
string label_style
string label_loc
map level_groups
map level_color
map level_label
array lines_
array labels_
// @function Finds levels by drilling down and iterating to desired layer
// @param this (cPivot) UDT for the pivots
// @param hi (float) high value variable
// @param lo (float) low value variable
// @param tracking_x (float) value to be used to find levels in proximity
// @param layer (int) drill down layer
// @returns (void) all maps stored in UDT
method get_levels(cPivot this,float hi,float lo,float tracking_x_, int layer)=>
var Max_H=0.
var Min_L=10E10
=request.security(syminfo.tickerid,"W", ,lookahead=barmerge.lookahead_off)
Max_H := math.max(Max_H,nz(htf_max,hi_),hi_)
Min_L := math.min(Min_L,nz(htf_min,lo_),lo_)
change_high = nz(ta.change(Max_H))!=0
change_low = nz(ta.change(Min_L))!=0
this.recalc := change_low or change_high or bar_index==120
top_line =0.
bot_line =0.
//__If the bar_index==120 to avoid potential issues with a range of 0 at bar_index==0
//__or if there is a change in the ATH or ATL
if this.recalc
this.level_groups.clear()
one_before_levels=map.new()
for i=0 to layer
new_levels = map.new()
if i==0
top_line := Max_H
bot_line := Min_L
else
levels_array = one_before_levels.values()
for in levels_array
if tracking_x_>= level_
bot_line := level_
if idx>0
top_line := levels_array.get(idx-1)
else
top_line := levels_array.get(idx)
break
range_ = top_line - bot_line
key_array = this.level_color.keys()
for fib_ratio in key_array
level_calc = math.round_to_mintick(bot_line+fib_ratio*(range_))
new_levels.put(fib_ratio,level_calc)
this.level_groups.put(i,level.new(new_levels))
one_before_levels := new_levels.copy()
this.current_top := top_line
this.current_bot := bot_line
this.new_variable_location := true
// end recalc
//Check if the tracking_x location changed to a different map and if it did then redo the lower layer maps
this.new_variable_location := (tracking_x_> this.current_top or tracking_x_< this.current_bot)
// only refresh levels if the variable location change requires it
if not(this.recalc) and this.new_variable_location and bar_index>120
one_before_levels = this.level_groups.get(0).level_data.copy()
this.level_groups.clear()
this.level_groups.put(0,level.new(one_before_levels))
for i=1 to layer
new_levels = map.new()
levels_array= one_before_levels.values()
for in levels_array
if tracking_x_>= level_
bot_line := level_
if idx>0
top_line := levels_array.get(idx-1)
else
top_line := levels_array.get(idx)
break
range_ = top_line - bot_line
key_array = this.level_color.keys()
for fib_ratio in key_array
level_calc = math.round_to_mintick(bot_line+fib_ratio*(range_))
new_levels.put(fib_ratio,level_calc)
this.level_groups.put(i,level.new(new_levels))
if i
//Refresh lines and labels if either ATH/ATL changed or teh variable location moved to a new zone
if bar_index>120 and (this.recalc or this.new_variable_location)
label_map=map.new()
label_map.clear()
for element in this.lines_
line.delete(element)
for element in this.labels_
label.delete(element)
this.lines_.clear()
this.labels_.clear()
for i=0 to layer
j= layer - i
layer_adj = (1+ i* this.layer_mult)
x1_offset = math.round(this.line_length*layer_adj)
x1_coord = math.max(0,bar_index- x1_offset)
lab_layer = (1+ j* this.layer_mult)
x1_lab_offset= math.round(this.line_length*lab_layer)
x1_lab_coord = math.max(0,bar_index-x1_lab_offset)
x2_coord = bar_index+this.label_offset
ln_width = layer-j
x2_lab_coord = switch this.label_loc
"Right" => x2_coord+ math.round(this.label_offset*lab_layer)
"Left" => x1_lab_coord
"Center" => x1_lab_coord+ int(x1_lab_offset/2)
lvl_str = "L"+str.tostring(i+1)+": "
// Label drawing
if this.show_labels
for key_ in this.level_groups.get(i).level_data.keys()
element = this.level_groups.get(i).level_data.get(key_)
text_ = this.label_info? str.tostring(math.round_to_mintick(element)): this.level_label.get(key_)
conditions_ = (i+1<= this.label_limit or (i+1> this.label_limit and show_only_50 and key_==0.5)) and (element>= 0.98*vis_lo and element<=1.02*vis_hi or vis_range_off)
if na(label_map.get(element)) and conditions_
this.labels_.push(label.new(x2_lab_coord,element,text=lvl_str+text_,color=this.level_color.get(key_), textcolor=color.black,style=this.label_style,size=this.label_txt_size))
label_map.put(element,1)
// Line drawing
for key_ in this.level_groups.get(j).level_data.keys()
element = this.level_groups.get(j).level_data.get(key_)
if (element>= 0.98*vis_lo and element<=1.02*vis_hi) or vis_range_off
this.lines_.push(line.new(x1_coord,element,x2_coord,element,color=this.level_color.get(key_),width=ln_width))
//Only update the x coordinate if the levels have not changed or the variabel did not force a change
if bar_index>120 and not(this.recalc) and not(this.new_variable_location)
if this.show_labels
for label_ in this.labels_
label_.set_x(label_.get_x()+1)
// Line drawing
for line_ in this.lines_
line_.set_x1(line_.get_x1()+1)
line_.set_x2(line_.get_x2()+1)
//==== Execution
var clone_pivot = cPivot.new(label_limit=label_layer_lim,label_loc=label_location,label_info=label_info, show_labels=show_labels, level_color=map.new(), level_label=map.new(), level_groups =map.new(),lines_=array.new(),labels_=array.new(), layer_mult=1.25,label_offset=offset_lastbar, line_length=l_len)
//___One time bar index at 0 execution and setup.
if bar_index==0
clone_pivot.label_txt_size := switch label_txt_size
"Tiny" => size.tiny
"Small" => size.small
"Normal"=> size.normal
"Large" => size.large
=> size.auto
clone_pivot.label_style := switch label_location
"Right"=>
switch label_string
"Center" => label.style_label_left
"Above" => label.style_label_lower_left
"Below" => label.style_label_upper_left
"Center"=>
switch label_string
"Center" => label.style_label_center
"Above" => label.style_label_down
"Below" => label.style_label_up
"Left"=>
switch label_string
"Center" => label.style_label_right
"Above" => label.style_label_lower_right
"Below" => label.style_label_upper_right
//maps are not ordered but we will put (or push in array terms) the ratios in
//descending order since in the method it will be needed in that order
if use_fibs
clone_pivot.level_color.put(1.0,color.white)
clone_pivot.level_color.put(0.7864,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0.618,color.silver)
clone_pivot.level_color.put(0.5,color.yellow)
clone_pivot.level_color.put(0.382,color.silver)
clone_pivot.level_color.put(0.236,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0,color.white)
clone_pivot.level_label.put(1.0,'top')
clone_pivot.level_label.put(0.7864,'0.786')
clone_pivot.level_label.put(0.618,'0.618')
clone_pivot.level_label.put(0.5,'0.5')
clone_pivot.level_label.put(0.382,'0.386')
clone_pivot.level_label.put(0.236,'0.236')
clone_pivot.level_label.put(0,'bot')
else
clone_pivot.level_color.put(1.0,color.white)
clone_pivot.level_color.put(0.75,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0.5,color.yellow)
clone_pivot.level_color.put(0.25,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0,color.white)
clone_pivot.level_label.put(1.0,'top')
clone_pivot.level_label.put(0.75,'0.75')
clone_pivot.level_label.put(0.5,'0.5')
clone_pivot.level_label.put(0.25,'0.25')
clone_pivot.level_label.put(0.,'bot')
//=== Get visible chart information to limit what is drawn
visible_bars = (chart.right_visible_bar_time - chart.left_visible_bar_time)/(1000*timeframe.in_seconds())
if bar_index==0
visible_bars:= 3000
max_hi = nz(ta.highest(visible_bars,3000),hi_)
min_lo = nz(ta.lowest(visible_bars,3000),lo_)
visible_hi = nz(ta.highest(hi_, visible_bars),max_hi)
visible_lo = nz(ta.lowest(lo_, visible_bars),min_lo)
//___ Method calls on each bar
clone_pivot.get_levels(hi_,lo_,track_var,layer_to_show)
clone_pivot.draw_pivots(layer_to_show,visible_hi,visible_lo,not(use_vis))
// While it seemed like a nice idea at the time, having separately-configurable upper and lower bands just doesn't really seem that useful as 90% of the time the settings for both are the same.
// Therefore, We're going to simplify the config to make these settings unified for both bands, as it would otherwise just add even more confusion with the addition of take-profit bands as well...
//
// atrMultiplierUpper = input.float(title='ATR Upper Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Upper Band Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
// "This will usually be between 1 and 3.")
// srcUpper = input.source(title='ATR Upper Offset Source', defval=close, group="ATR Upper Band Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "For this band, 'high' and 'close' (default) are generally the most appropriate values.")
//
atrMultiplier = input.float(title='ATR Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Bands Standard Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
"This will usually be between 1 and 3. Default: 2.5")
// On second thought, I'm going to nix this setting and force it to be the "close" source. Having the ability to offset based on the wicks was a nice idea, but doesn't really seem to have any notable practical application.
atrSourceRef = "close"
//atrSourceRef = input.string(title='ATR Upper Offset Source', defval="close", options= , group="ATR Bands Standard Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "The default value 'close' should be your go-to, but 'wicks' might provide a bit more breathing room in securities that tend to have large wicks.")
//
// See above - these are deprecated and no longer used...
//
// atrMultiplierLower = input.float(title='ATR Lower Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Lower Band Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
// "This will usually be between 1 and 3.")
// srcLower = input.source(title='ATR Lower Offset Source', defval=close, group="ATR Lower Band Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "For this band, 'low' and 'close' (default) are generally the most appropriate values.")
//
//
// Take-Profit band settings
showTPBands = input.bool(title="Show opposite bands for take-profit zones", defval=false, tooltip="If enalbled, the existing ATR bands will be treated as 'stop-loss' bands, and 'take-profit' bands will be plotted " +
"to depict potential take-profit targets that are scaled based on the 'stop-loss' band and an additional reward/risk scaling factor (see below). Default: Unchecked", group="Take-Profit Settings")
tpScaleFactor = input.float(title="Take-Profit Scale Factor", defval=1.5, minval=1, step=0.1, tooltip="This is a secondary scaling factor used based on the 'stop-loss' ATR bands to calculate and plot a potential take-profit target. " +
"The easiest way to think of this is as a desired reward/risk ratio, where the primary ATR Bands
Magical LineUsage:
1. Import into your trading platform
2. Magic line = (Previous High + Previous Low + Previous Close) / 3
3. Buy signal when price crosses above magic line
4. Sell signal when price crosses below magic line
JCM_MadridThis indicator provides dynamic bar coloring and buy/sell signals based on EMA relationships and price momentum. It allows traders to visually identify trend changes and potential trade opportunities directly on the chart.
Indicator Basics:
Name: The script is titled "JCM_Madrid".
Overlay: It overlays its calculations and outputs directly on the price chart.
User Inputs:
-Range: Defines the length of the EMA (Exponential Moving Average).
-Ref-1 and Ref-2: Set reference lengths for secondary EMAs used in the calculations.
-Source: The price data source for EMA calculations (e.g., close, open, high, low).
-Enable Buy/Sell: Boolean toggles to activate or deactivate buy and sell signals.
Calculations:
EMA Value: Computes the main EMA based on the source and Range.
CloseMA: The difference between the close price and the EMA.
SqzMA: The difference between a secondary EMA (Ref-1) and the main EMA.
RefMA: The difference between another secondary EMA (Ref-2) and the main EMA.
Bar Coloring:
Bars are colored based on the relationship between SqzMA and CloseMA:
Purple: When SqzMA > CloseMA.
Blue: When SqzMA < CloseMA.
Buy/Sell Signals:
A Buy Signal is generated when:
CloseMA crosses from below to above 0.
The close price is higher than the previous close.
Buy signals are enabled.
A Sell Signal is generated when:
CloseMA crosses from above to below 0.
The close price is lower than the previous close.
Sell signals are enabled.
Signals are displayed as labels on the chart:
"Buy": Green label below the candle.
"Sell": Yellow label below the candle