Previous Week High & Low with middle lineDescription:
The Previous Week High & Low Indicator is a powerful tool designed to provide traders with key reference levels from the previous trading week. It dynamically calculates and plots the previous week's high, low, and midpoint levels directly on your chart, helping you identify critical support and resistance zones.
Features:
1. **Previous Week High and Low Lines**:
- The indicator displays the high and low prices of the previous trading week, allowing you to analyze price action relative to these levels.
- These lines are plotted as step lines, visible only during the active trading days (Monday to Friday), ensuring clean and uncluttered charts.
2. Midpoint Line:
- The midpoint between the previous week's high and low is calculated and displayed as a reference level.
- This white line can act as a psychological pivot point for market participants.
3. Customizable Display:
- You can toggle the visibility of the high and low lines using input options, tailoring the indicator to your preferences.
4. Precision and Aesthetics:
- The lines are plotted with precision and styled for clarity, using subtle transparency for an unobtrusive yet informative appearance.
Use Case:
- This indicator is ideal for traders who rely on historical price levels for planning entries, exits, or stop-loss placements.
- It works seamlessly with any timeframe and asset, making it versatile for various trading strategies.
How It Works:
- The indicator fetches the previous week's high and low prices using the weekly timeframe and "lookahead" mode to ensure these levels remain static after the week's close.
- The lines are plotted only on weekdays (Monday to Friday) to exclude weekend data, ensuring accuracy for markets that operate 24/5.
This tool simplifies your chart analysis and empowers you to make informed trading decisions based on historical price dynamics.
النطاقات والقنوات
JP'S LEVELThe Indictor shown level of yesterday data and today open when market moves up to green line you make long position same market moves down cross the red line you go for short position its work in intraday .
Demo GPT - Bull Market Support BandAI generated pinescript 6 strategy of buying and selling based on Bull Market Support Band. Buy when EMAs cross upward while sell when EMAs cross downward.
EMA 20 Band + EMA 200Beste traders,
Deze indicator tekent een EMA-band bestaande uit drie lijnen: een High EMA, een Mid EMA, en een Low EMA, evenals een afzonderlijke EMA 200.
De band geeft de dynamische ondersteunings- en weerstandsniveaus weer, gebaseerd op de high-, low- en close-prijzen van candles. De ruimte tussen de High en Low EMA wordt visueel ingevuld, wat helpt om trends en prijsschommelingen beter te identificeren.
De EMA 200 dient als een lange-termijn trendindicator: als de prijs erboven ligt, is er vaak sprake van een opwaartse trend, en eronder van een neerwaartse trend. Traders gebruiken deze indicator om in sterke trends in te stappen, of om mogelijke omkeringen te herkennen wanneer de prijs buiten de band beweegt.
Het kan ook nuttig zijn om overbought- of oversold-condities te spotten als de prijs ver buiten de band komt.
Deze indicator is geschikt voor zowel daytrading als swing trading en werkt op alle tijdframes.
ICCMSThis TradingView Pine Script implements the Cloud indicator, which consists of several components to analyze market trends. It calculates the Tenkan-sen (conversion line) and Kijun-sen (base line) using Donchian channel averages over specified periods. Additionally, it computes two leading spans to create a cloud (Kumo) that visually represents support and resistance levels. The script plots these lines on the chart, including a lagging span that follows the price. The cloud's fill color changes based on the relationship between the leading spans, indicating bullish or bearish conditions.
Turtle Soup - SR BREAKS AND RETEST | Dante123456PS
Kindly read the desciption through;
ICT TURTLE SOUP AND SUPPORT AND RESISTANCE BREAK & RESEST INDICATOR
First and foremost i would like to credit the following : @fluxchart for the open souce script on ICT TURTLE SOUP indicator as well as @ChartPrime for the open source Support and Resistance breaks and retest indicator.This indicator combines the 2 and also adds the Bollinger Bands for added entries refinement.
Here is how to use them:
ICT TURTLE SOUP
The ICT Turtle Soup strategy is a trading approach that capitalizes on false breakouts near key liquidity levels, aiming to identify potential market reversals. It provides traders with visual cues and signals to facilitate its application.
Understanding the ICT Turtle Soup Strategy
The strategy focuses on liquidity areas—zones with a high concentration of buy or sell orders, typically found at recent highs and lows. A false breakout, or liquidity sweep, occurs when the price briefly moves beyond these levels, triggering stop-loss orders, before reversing direction. Identifying such movements can signal potential entry points for trades.
Features of ICT Turtle Soup Indicator
This indicator offers several functionalities to assist traders:
Liquidity Zone Identification: Automatically marks higher timeframe liquidity zones, highlighting areas where false breakouts are likely to occur.
Market Structure Analysis: Assesses the current market structure to determine trends and potential reversal points.
Entry and Exit Signals: Provides buy and sell signals based on detected liquidity grabs and market structure shifts.
Take-Profit (TP) and Stop-Loss (SL) Levels: Calculates TP and SL levels using the Average True Range (ATR), allowing for dynamic risk management.
Backtesting Dashboard: Includes a dashboard to evaluate the performance of the strategy over historical data.
Alerts: Offers customizable alerts for buy, sell, TP, and SL signals to keep traders informed in real-time.
USAGE:
Identify Liquidity Zones: The indicator will highlight potential liquidity zones on the chart, based on higher timeframe analysis.
Monitor for Signals: Watch for buy or sell signals generated when the price performs a liquidity grab and a market structure shift is detected.
Execute Trades: Upon receiving a signal, consider entering a trade in the indicated direction. Use the suggested TP and SL levels for risk management.
Backtesting: Utilize the backtesting dashboard to assess the strategy's performance with your chosen settings, enabling data-driven adjustments.
Considerations
Timeframes: For optimal results, it's recommended to use the indicator on timeframes such as 15-minute, 30-minute, or 1-hour charts, with higher timeframe liquidity zones identified on 1-hour or 4-hour charts.
Market Conditions: The strategy is particularly effective in markets prone to false breakouts. However, it's essential to be cautious in highly volatile or illiquid markets where false signals may occur
SR BREAKS AND RETEST {HIG VOL BOXES}
The Support and Resistance (High Volume Boxes) is a tool designed to help traders identify key support and resistance levels by analyzing pivot points and volume data. It visually represents these levels using dynamically colored boxes, providing insights into potential price reversals and key zones for trading opportunities.
Key Features:
Dynamic Support and Resistance Boxes: The indicator plots boxes based on pivot points and volume thresholds. The color intensity of these boxes varies with volume, reflecting the strength of the support or resistance. Green boxes indicate support levels with positive volume, while red boxes denote resistance levels with negative volume.
Hold Signals: Green diamonds (◆) appear when support holds, signaling potential buy opportunities. Red diamonds (◆) appear when resistance holds, indicating potential sell opportunities.
Breakout Labels: Labels such as "Break Sup" and "Break Res" are displayed when support or resistance levels are broken, highlighting significant market movements.
Using the Indicator:
Configure Settings: Adjust the following parameters to suit your trading preferences:
Lookback Period: Determines the number of bars to consider for pivot points.
Delta Volume Filter Length: Sets the length of the volume filter for accurate analysis; higher values filter out low-volume boxes.
Adjust Box Width: Modifies the width of the support and resistance boxes; higher values result in thinner boxes.
Incorporating the Indicator into Your Trading Strategy:
Identify Key Levels: Use the colored boxes to spot strong support and resistance zones, which can serve as entry or exit points.
Monitor Hold Signals: Pay attention to the diamond symbols indicating when support or resistance holds, as they suggest potential buying or selling opportunities.
Watch for Breakouts: Observe breakout labels to identify significant market movements and adjust your trading strategy accordingly.
By integrating this indicator into your trading routine, you can enhance your ability to recognize critical market levels and make more informed decisions. It's essential to combine this tool with other analyses and risk management practices to optimize your trading performance.
PS
Use both the indicators as well as the Bollinger Band to execute better trades, i have just twerked the script a little bit,
Swing Trading with Mean Reversion - Stonk_BUDThe Swing Trading Analyzer is built for traders looking to catch medium-term swing trading opportunities. It combines trend-following techniques with mean reversion strategies, making it a versatile tool for analyzing daily and weekly charts.
---
#### **Key Features**
- **Moving Average Crossovers**
Tracks 10-day and 50-day moving averages to identify trend shifts. You'll see clear signals for bullish (BUY) and bearish (SELL) momentum.
- **Mean Reversion Analysis**
Uses Bollinger Bands and Z-score calculations to pinpoint overbought and oversold conditions. These tools help confirm when the price is stretched and likely to reverse back toward the mean.
- **Swing Trading Focus**
Designed specifically for daily and weekly timeframes, this indicator avoids the noise of intraday trading and helps you focus on bigger moves.
- **Visual and Alert System**
Plots clear BUY and SELL signals directly on your chart, with optional background highlights for overbought (red) and oversold (green) zones. Plus, you can set custom alerts to get notified when signals trigger.
---
#### **How It Works**
- **Buy Signals**: Triggered when the 10-day moving average crosses above the 50-day moving average, and the price shows oversold conditions (Z-score < -2 and price below the lower Bollinger Band).
- **Sell Signals**: Generated when the 10-day moving average crosses below the 50-day moving average, with overbought confirmation (Z-score > 2 and price above the upper Bollinger Band).
---
Who It's For
- Swing traders looking for reliable signals to ride medium-term market trends.
- Anyone who wants a blend of trend-following and mean reversion strategies.
---
**Pro Tip**: Pair this indicator with solid risk management and additional tools like volume analysis for even better results.
---
Smart Money FlowThis script detects where "smart money" might be flowing by analyzing:
Volume Spikes: Highlights significant increases in trading volume.
Price Imbalances: Identifies sharp upward or downward moves indicating potential institutional activity.
Smart Money Zones: Marks zones where buying or selling from institutional traders is likely.
Features:
Buy and Sell Labels: Visual indicators on the chart for smart money activity.
Zone Highlighting: Background color changes for visual emphasis on potential zones.
Alerts: Configurable alerts for buy and sell zone detection.
You can further fine-tune the thresholds to match your trading style or asset-specific behaviors. Let me know if you need further adjustments or additional features!
My script
//@version=5
indicator("USD/IRR Custom Data", overlay=true)
// دادههای شما
var float data = array.from(42400, 42500, 42600, 42700) // نرخ دلار
var int dates = array.from(20240101, 20240102, 20240103, 20240104) // تاریخ (YYYYMMDD)
// رسم نمودار
var lineColor = color.new(color.blue, 0)
for i = 0 to array.size(data) - 1
label.new(bar_index + i, array.get(data, i), tostring(array.get(dates, i)), color=lineColor)
My script
Ebrahim Shojaee
1:20 PM (0 minutes ago)
to me
//@version=5
indicator("USD/IRR Custom Data", overlay=true)
// دادههای شما
var float data = array.from(42400, 42500, 42600, 42700) // نرخ دلار
var int dates = array.from(20240101, 20240102, 20240103, 20240104) // تاریخ (YYYYMMDD)
// رسم نمودار
var lineColor = color.new(color.blue, 0)
for i = 0 to array.size(data) - 1
label.new(bar_index + i, array.get(data, i), tostring(array.get(dates, i)), color=lineColor)
HH||LL||KCThis script is written in Pine Script version 5, designed for TradingView. It defines a custom trading indicator named **HH||LL||KC**. Here's a breakdown of its components and functionality:
---
### **Indicator Overview**
- **Purpose**: Combines multiple technical analysis tools to generate trading signals, including Keltner Channels, RSI-based stochastic oscillator, and conditions for buy and sell alerts.
- **Overlay**: The indicator plots directly on the price chart (overlay = `true`).
- **Precision**: Values are displayed with 2 decimal points.
---
### **Key Components**
1. **Keltner Channels**:
- Defined by `ma`, `upper`, and `lower` bands.
- Uses an exponential moving average (EMA) as the basis (`ma`).
- The upper and lower bands are derived from the range of highs and lows over the specified `length` (default is 100), multiplied by a factor (`mult`, default is 0.5).
2. **RSI Stochastic Oscillator**:
- Combines RSI and Stochastic calculations to create `%K` and `%D` lines:
- RSI is calculated over `lengthRSI` (default 14) using the specified source (`close` by default).
- Stochastic uses `lengthStoch` (default 14) smoothed by `smoothK` and `smoothD`.
- `%K` and `%D` are used for overbought/oversold signals and crossovers.
3. **Highs, Lows, and Alerts**:
- Identifies:
- **Highs (HH)** when `%K > 80`.
- **Lows (LL)** when `%K < 20`.
- Generates `red` and `green` points based on crossovers of `%K` with overbought/oversold levels.
- A 36-period EMA is plotted as an additional trend indicator.
4. **Additional Plots**:
- `ta.linreg(close, 21, 0)`: Short-term linear regression line.
- `ta.linreg(close, 375, 0)`: Long-term linear regression line.
- Plots for `red` and `green` points for potential reversal levels.
- Buy and Sell signal markers:
- **Buy**: Appears below the bar when `condi1` is true.
- **Sell**: Appears above the bar when `condi2` is true.
5. **Alerts**:
- Triggered when:
- `%K` crosses `%D` with specific conditions (e.g., close above `green` or below `red`).
- Defined via `alertcondition`.
---
### **Trading Logic**
1. **Buy Signal (condi1)**:
- EMA is above the upper Keltner Channel.
- Red marker (`red`) is above the EMA, and:
- Current or past candles open and close above the marker.
- `%K` is below 20, and `%K` crosses `%D`.
2. **Sell Signal (condi2)**:
- EMA is below the lower Keltner Channel.
- Green marker (`green`) is below the EMA, and:
- Current or past candles open below the marker.
- `%K` is above 80, and `%K` crosses under `%D`.
---
### **Visualization**
- **Keltner Channel**: Blue bands for upper and lower limits, with a gray center line.
- **Trend Lines**:
- Orange for short-term linear regression.
- White for long-term linear regression and EMA.
- **Markers**:
- Green for buy signals.
- Red for sell signals.
- **Cross Points**:
- Green dots (`green`) for potential buy reversals.
- Red dots (`red`) for potential sell reversals.
---
### **Use Case**
Traders can use this indicator for:
- Identifying overbought/oversold conditions.
- Spotting trend reversals and continuation patterns.
- Generating buy/sell alerts based on multi-condition logic.
It is versatile and integrates several technical analysis concepts into a single script.
Enhanced Multi-Indicator StrategyEnhance your strategy by incorporating a combination of indicators to improve accuracy. We'll use the Relative Strength Index (RSI) and the Moving Average Convergence Divergence (MACD) along with your moving averages to provide a more robust signal.
EMA36ssasdasdsaasddsasaddasdassaddsadasasddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
Optimal Grid Levels with Trend, RSI, MACD, and FibonacciOptimal Grid Levels with Trend, RSI, MACD, and Fibonacci
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!
Raj Daily, Weekly & Monthly OHLC Lines - Bold & ExtendedRAj daily weekly monthly high lo kfsadhsdufho8wejfjwjcoidwjcoijfwicn;dnc;qdihcd8hvhfqwihcqdnqcudhvcwhfqrohf;owihf;owihfowqhf;owefhowhfoqewfohwfh
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
Bollinger Bands Strategy Low InvestHere is a basic trading strategy for ZEREBRO/USDT in Pine Script based on Bollinger Bands. This strategy sets buy and sell signals and can be automatically linked to Bybit via TradingView.
Bollinger Strategy
This strategy uses Bollinger Bands to generate buy and sell signals.
Started with 86 USDT and 52 Zerebro.
RSI + MACD + EMA + Bollinger + Volume indicatorThe combined conditions for entry (RSI, MACD, EMA, Bollinger Bands, Volume) may be too restrictive, causing no trades to meet the criteria.
You may want to test each condition individually first to ensure that each is producing signals that are in line with market action.