30-10-3 MAX,min dinamici Supported timeframes: The script works only on timeframes of 1 minute or lower (including second-based timeframes).
Displayed levels: The highs and lows of the last closed candle are plotted for the 30-minute, 10-minute, and 3-minute timeframes.
Updates: The levels update only when a candle closes in the respective timeframe (e.g., every 30 minutes for the 30m levels).
Visualization: Dashed lines for highs and lows (blue for 30m, green for 10m, red for 3m).
Labels indicating "Max 30m", "Min 30m", etc., positioned above the highs and below the lows.
Indicadores e estratégias
Elliott Wave Auto + Fib Targets + Scalper Strategy (Fixed)// Elliott Wave Auto + Fib Targets + Scalper Strategy
//
// Fixed by expert trader:
// - Replaced table with label-based visualization to avoid 'Column 2 is out of table bounds' error.
// - Uses label.new to display buy/sell signal counts in top-right corner, mimicking table layout.
// - Fixed array.sum() error: Replaced invalid range-based array.sum() with custom sum_array_range() function.
// - Removed barstate usage to fix 'Undeclared identifier barstate' error.
// - Replaced barstate.isconfirmed with true (process every bar).
// - Replaced barstate.isfirstconfirmed with bar_index == 0 (first bar).
// - Replaced strategy.alert with label.new for long/short entry signals (buy/sell markers).
// - Fixed array index out-of-bounds: Protected array.get() calls with size checks.
// - Fixed pyramiding: Set constant pyramiding=4 (max 5 entries); use allow_pyramiding to limit entries.
// - Fixed default_qty_value: Set constant default_qty_value=100.0; use entry_size_pct to scale qty.
// - Replaced alertcondition with labels for Elliott Wave patterns.
// - Fixed partial exits: 50% at TP1 with fixed SL, 50% at TP2 with fixed SL or trailing.
// - Fixed Elliott Wave pivot indexing for alternating H/L check.
// - Ensured proper position sizing and exit logic.
Peak Support/Resistance Lines v1//@version=6
indicator("Peak Support/Resistance Lines", shorttitle="Peak S/R", overlay=true, max_lines_count=500)
// Input parameters
lookback = input.int(5, title="Lookback Period", minval=1, maxval=50)
show_resistance = input.bool(true, title="Show Resistance Lines")
show_support = input.bool(true, title="Show Support Lines")
resistance_color = input.color(color.red, title="Resistance Color")
support_color = input.color(color.green, title="Support Color")
// Function to check if current bar is a peak
is_peak() =>
ta.pivothigh(high, lookback, lookback)
// Function to check if current bar is a valley
is_valley() =>
ta.pivotlow(low, lookback, lookback)
// Main logic
if barstate.isconfirmed
// Check for resistance peaks
if show_resistance
peak_price = is_peak()
if not na(peak_price)
line.new(x1=bar_index - lookback, y1=peak_price, x2=bar_index + 50, y2=peak_price, color=resistance_color, width=1)
// Check for support valleys
if show_support
valley_price = is_valley()
if not na(valley_price)
line.new(x1=bar_index - lookback, y1=valley_price, x2=bar_index + 50, y2=valley_price, color=support_color, width=1)
By Gadirov Reliable 3M Binary Signals for binary codeBy Gadirov Reliable 3M Binary Signals for binary code
2nd 1H: Midpoints (white=2nd mid, blue=2-candle range mid)2nd 1H: Midpoints (white=2nd mid, blue=2-candle range mid)
Multi-Timeframe MACD Score(Customized)this is a momentum based indicator to know the direction of the market
RSI: alternative derivationMost traders accept the Relative Strength Index (RSI) as a standard tool for measuring momentum. But what if RSI is actually a position indicator?
This script introduces an alternative derivation of RSI, offering a fresh perspective on its true nature. Instead of relying on the traditional calculation of average gains and losses, this approach directly considers the price's position relative to its equilibrium (moving average), adjusted for volatility.
While the final value remains identical to the standard RSI, this alternative derivation offers a completely new understanding of the indicator.
Key components:
Price (Close)
Utilizes the closing price, consistent with the original RSI formula.
normalization factor
Transforms raw calculations into a fixed range between -1 and +1.
normalization_factor = 1 / (Length - 1)
EMA of Price
Applies Wilder’s Exponential Moving Average (EMA) to the price, serving as the anchor point for measuring price position, similar to the traditional RSI formula.
myEMA = ta.rma(close,Length)
EMA of close-to-close absolute changes (unit of volatility)
Adjusts for market differences by applying a Wilder’s EMA to absolute price changes (volatility), ensuring consistency across various assets.
CC_vol = ta.rma(math.abs(close - close ),Length)
Calculation Breakdown
DISTANCE:
Calculate the difference between the closing price and its Wilder's EMA. A positive value indicates the price is above the EMA; a negative value indicates it is below.
distance = close - myEMA
STANDARDIZED DISTANCE
Divide the distance by the unit of volatility to standardize the measurement across different markets.
S_distance = distance / CC_vol
NORMALIZED DISTANCE
Normalize the standardized distance using the normalization factor (n-1) to adjust for the lookback period.
N_distance = S_distance * normalization_factor
RSI
Finally, scale the normalized distance to fit within the standard RSI range of 0 to 100.
myRSI = 50 * (1 + N_distance)
The final equation:
RSI = 50 ×
What This Means for RSI
Same RSI Values, Different Interpretation
The standard RSI formula may obscure its true measurement, whereas this approach offers clarity.
RSI primarily indicates the price's position relative to its equilibrium, rather than directly measuring momentum.
RSI can still be used to analyze momentum, but in a more intuitive and well-informed way.
Double Moving Average█ OVERVIEW
The Double Moving Average (DMA) smooths one moving average with a second moving average.
Includes moving average type, higher timeframe, offset, alerts, and style settings for all of the indicator's visual components. This indicator includes an optional line and label to indicate the latest value of the DMA that repaints.
█ CONCEPTS
Shorter term moving averages, especially in choppy markets, can rapidly increase and decrease their slope. Which could lead some traders into assuming that the series trend may continue at that steeper slope. By smoothing a moving average with another one, the magnitude of rapid choppy movements is mitigated.
█ FEATURES
DMA Customization
Most inputs have a tooltip that can be read by interacting with the information icon to guide users.
For both moving averages in the DMA, users can set the lookback length and moving average type independently. Available moving average types include:
Simple Moving Average
Exponential Moving Average
Hull Moving Average
Weighted Moving Average
Volume Weighted Moving Average
A bar offset setting is included for shifting the indicator's placement. Using different lookback combinations for both averages alongside an offset can create equivalent values of other types of moving averages not included in this indicator. For example, if the default lookback settings are offset by 1 bar, this duplicates a 4 period centered moving average.
Colors for the DMA's plot can toggle between a single "base" color, or using increasing and decreasing colors. Changing the plot's style, line style, and width is also supported.
Latest Value Line and Label
The latest value of the DMA plot is replaced by default with a feature called the Latest Value Line and Label: a stylized line and label to help indicate the part of the indicator that can repaint from the parts that don't repaint. Data used to draw this feature is calculated separately from the indicator's confirmed historical calculations.
A label is included to display the latest value of the DMA which includes complete style settings. The style of both the line and label are completely customizable; every style feature that can be included has a corresponding input you can set.
Toggling off the Latest Value Line and Label feature will cause all the respective style inputs to deactivate so that they're no longer in focus or editable until the feature is toggled on again.
Higher Timeframes
Users can plot the DMA from higher timeframes on their chart.
As new bars print, the non-repainting DMA historical plot uses the last confirmed higher timeframe value. The repainting Latest Value Line and Label will update with the most recent higher timeframe value only for the latest bar. If the Latest Value Line feature is toggled off, the last confirmed higher timeframe DMA value is plotted up to the latest bar.
The built-in Moving Average Simple (SMA) indicator includes several of the features in this indicator, like an option for using higher timeframe. However, by default, it plots no values except on bars with higher timeframe close updates. Disabling "Wait for timeframe closes" to get values between updates causes repainting in both replay mode and realtime bars.
Since the calculations that repaint are separate and optional in the DMA indicator, historical plotted values will not repaint in replay mode or on realtime bars while using higher timeframes.
Alerts
There are two DMA value options when creating an alert:
DMA Latest Value: Use the latest updating DMA Value. The same value as the Latest Value Line.
DMA Last Confirmed Value: Use the last historical closed DMA value.
The default alert option is DMA Latest because most users expect alerts when the price crosses the latest updating DMA value. The Last Confirmed Value alert option uses the DMA value from the latest confirmed historical bar.
When creating an alert you should see a "Caution!" warning saying, "This is due to calculations being based on an indicator or strategy that can get repainted." This warning is intentional because the DMA indicator's Latest Value Line and Label feature is supposed to repaint in order to display the latest value.
█ FOR Pine Script™ CODERS
StyleLibrary is used to create user-friendly plot, line, and label style enum type inputs. The library's functions then take those user inputs and convert them into the appropriate values/built-in constants to customize styles for plot, line, and label functions.
Titles for #region blocks are included after #endregion statements for clarity when multiple #endregion statements occur.
This indicator utilizes the new active parameter for style inputs of togglable features.
Gold Lagging (N days)This indicator overlays the price of gold (XAUUSD) on any chart with a customizable lag in days. You can choose the price source (open, high, low, close, hlc3, ohlc4), shift the series by a set number of daily bars, and optionally normalize the values so that the first visible bar equals 100. The original gold line can also be displayed alongside the lagged series for direct comparison.
It is especially useful for analyzing delayed correlations between gold and other assets, observing shifts in safe-haven demand, or testing hypotheses about lagging market reactions. Since the lag is calculated on daily data, it remains consistent even if applied on intraday charts, while the indicator itself can be plotted on a separate price scale for clarity.
이 지표는 금(XAUUSD) 가격을 원하는 차트 위에 N일 지연된 형태로 표시합니다. 가격 소스(시가, 고가, 저가, 종가, hlc3, ohlc4)를 선택할 수 있으며, 지정한 일 수만큼 시리즈를 뒤로 이동시킬 수 있습니다. 또한 첫 값 기준으로 100에 맞춰 정규화하거나, 원래 금 가격선을 함께 표시해 비교할 수도 있습니다.
금과 다른 자산 간의 지연 상관관계를 분석하거나 안전자산 수요 변화를 관찰할 때 유용하며, 시장 반응의 시차 효과를 검증하는 데에도 활용할 수 있습니다. 지연은 일봉 데이터 기준으로 계산되므로 단기 차트에 적용해도 일 단위 기준이 유지되며, 별도의 가격 스케일에 표시되어 가독성을 높일 수 있습니다.
Strong Body Close Candle (90%)This indicator highlights Strong Body Close Candles, which are single bars where the real body makes up the vast majority of the total range and the close is positioned very close to the candle’s extreme. By default, the script looks for candles where the body is at least 90% of the full high-low range, and the close falls within the top 10% (for bullish) or bottom 10% (for bearish). These settings ensure that only very strong, conviction-driven candles are marked. The script plots labels above or below qualifying bars, colors the candle accordingly, and provides alert conditions so you can be notified in real time when such a candle forms.
Both percentages are fully adjustable so you can fine-tune the strictness of the definition. For example, if you change the body threshold to 85% and the close-to-extreme threshold to 15%, the script will highlight candles where the body makes up at least 85% of the total range and the close is within 15% of the high or low. This adjustment allows for a slightly looser definition, catching more frequent signals while still maintaining strength criteria. Built-in alerts let you choose between bullish and bearish signals separately (or both), ensuring you won’t miss setups even when you’re away from the chart.
This tool is flexible across timeframes and instruments. On lower timeframes, signals may appear more frequently, highlighting intraday momentum bursts, while on higher timeframes such as daily or weekly charts, these signals often represent periods of strong directional conviction. Traders can combine this indicator with additional filters such as trend direction, volume confirmation, VWAP, or moving averages to improve reliability and fit it into their broader strategy. Because the body and close thresholds are user-defined, you have control over whether the indicator is tuned to rare but powerful candles (stricter settings) or more frequent signals (looser settings).
The indicator is designed to be non-repainting since it only evaluates candles after they close. It can be used purely visually with chart labels and bar coloring or as part of an automated workflow with TradingView alerts. Alerts are triggered on bar close whenever a bullish or bearish strong body close candle is detected, allowing you to integrate them into your trading process via pop-ups, emails, mobile notifications, or webhooks. Whether you’re looking for sharp reversals, momentum continuation signals, or simply want to filter out weaker candles, this tool provides a clear and adjustable framework for identifying high-conviction bars.
Adjustable Day MarkersPlaces vertical dashed lines for each new day at midnight in light grey, so you have a visual reference on the chart rather than having to look at the time at the bottom.
To adjust it to your time zone: go to settings , then give a - or + value for " Timezone Offset ".
I'm at GMT+2, so I set it to 2 .
If you rather have the line appear at the beginning of your trading day, then that's also possible. Say I start every day at 8 AM, I would have to set it to +10 (since I'm currently GMT +2).
AI Trading Alerts v6 — SL/TP + Confidence + Panel (Fixed)Overview
This Pine Script is designed to identify high-probability trading opportunities in Forex, commodities, and crypto markets. It combines EMA trend filters, RSI, and Stochastic RSI, with automatic stop-loss (SL) & take-profit (TP) suggestions, and provides a confidence panel to quickly assess the trade setup strength.
It also includes TradingView alert conditions so you can set up notifications for Long/Short setups and EMA crosses.
⚙️ Features
EMA Trend Filter
Uses EMA 50, 100, 200 for trend confirmation.
Bull trend = EMA50 > EMA100 > EMA200
Bear trend = EMA50 < EMA100 < EMA200
RSI Filter
Bullish trades require RSI > 50
Bearish trades require RSI < 50
Stochastic RSI Filter
Prevents entries during overbought/oversold extremes.
Bullish entry only if %K and %D < 80
Bearish entry only if %K and %D > 20
EMA Proximity Check
Price must be near EMA50 (within ATR × adjustable multiplier).
Signals
Continuation Signals:
Long if all bullish conditions align.
Short if all bearish conditions align.
Cross Events:
Long Cross when price crosses above EMA50 in bull trend.
Short Cross when price crosses below EMA50 in bear trend.
Automatic SL/TP Suggestions
SL size adjusts depending on asset:
Gold/Silver (XAU/XAG): 5 pts
Bitcoin/Ethereum: 100 pts
FX pairs (default): 20 pts
TP = SL × Risk:Reward ratio (default 1:2).
Confidence Score (0–4)
Based on conditions met (trend, RSI, Stoch, EMA proximity).
Labels:
Strongest (4/4)
Strong (3/4)
Medium (2/4)
Low (1/4)
Visual Panel on Chart
Shows ✅/❌ for each condition (trend, RSI, Stoch, EMA proximity, signal now).
Confidence row with color-coded strength.
Alerts
Long Setup
Short Setup
Long Cross
Short Cross
🖥️ How to Use
1. Add the Script
Open TradingView → Pine Editor.
Paste the full script.
Click Add to chart.
Save as "AI Trading Alerts v6 — SL/TP + Confidence + Panel".
2. Configure Inputs
EMA Lengths: Default 50/100/200 (works well for swing trading).
RSI Length: 14 (standard).
Stochastic Length/K/D: Default 14/3/3.
Risk:Reward Ratio: Default 2.0 (can change to 1.5, 3.0, etc.).
EMA Proximity Threshold: Default 0.20 × ATR (adjust to be stricter/looser).
3. Read the Panel
Top-right of chart, you’ll see ✅ or ❌ for:
Trend → Are EMAs aligned?
RSI → Above 50 (bull) or below 50 (bear)?
Stoch OK → Not extreme?
Near EMA50 → Close enough to EMA50?
Above/Below OK → Price position vs. EMA50 matches trend?
Signal Now → Entry triggered?
Confidence row:
🟢 Green = Strongest
🟩 Light green = Strong
🟧 Orange = Medium
🟨 Yellow = Low
⬜ Gray = None
4. Alerts Setup
Go to TradingView Alerts (⏰ icon).
Choose the script under “Condition”.
Select alert type:
Long Setup
Short Setup
Long Cross
Short Cross
Set notification method (popup, sound, email, mobile).
Click Create.
Now TradingView will notify you automatically when signals appear.
5. Example Workflow
Wait for Confidence = Strong/Strongest.
Check if market session supports volatility (e.g., XAU in London/NY).
Review SL/TP suggestions:
Long → Entry: current price, SL: close - risk_pts, TP: close + risk_pts × RR.
Short → Entry: current price, SL: close + risk_pts, TP: close - risk_pts × RR.
Adjust based on your own price action analysis.
📊 Best Practices
Use on H1 + D1 combo → align higher timeframe bias with intraday entries.
Risk only 1–2% of account per trade (position sizing required).
Filter with market sessions (Asia, Europe, US).
Strongest signals work best with trending pairs (e.g., XAUUSD, USDJPY, BTCUSD).
Capitulation DayThe idea is that when US indexes are >10% below their 50,100,200sma it is a capitulation day.
Multi-Asset Arbitrage CalculatorMulti-Asset Arbitrage Calculator
📊 Overview
A comprehensive Pine Script indicator designed to identify and monitor arbitrage opportunities across multiple trading pairs in real-time. This tool calculates potential profit percentages from various transaction paths while accounting for trading fees and market inefficiencies.
🎯 Purpose
- Arbitrage Detection : Automatically identifies price discrepancies between related trading pairs
- Multi-Path Analysis : Supports up to 10 simultaneous arbitrage loops with different transaction sequences
- Fee Integration : Incorporates comprehensive fee structures for realistic profit calculations
- Real-Time Monitoring : Provides continuous monitoring with customizable alert thresholds
🚀 Key Features
Flexible Transaction Paths
- Triangular Arbitrage : A→B→C→A patterns for three-asset opportunities
- Direct Pairs : Simple A→B conversions
- Reverse Paths : Inverse transaction sequences
- Custom Routing : Multiple path options for diverse market scenarios
Comprehensive Fee Structure
- Start/End transaction fees
- Deposit/Withdrawal fees
- Inter-asset conversion fees
- Configurable percentage-based calculations
Professional Tools
- Moving Average Smoothing: Reduces noise with configurable MA periods
- Alert System : Individual and combined alert conditions
- Weekend Detection : Visual highlighting for market hours
- Clean Interface : Organized input groups for easy configuration
📋 Supported Transaction Types
1. `A→B→C→A` - Standard triangular arbitrage
2. `B→A→C→A` - Reverse entry triangular
3. `A→B→A→C` - Split conversion path
4. `A→C→B→A` - Alternative triangular route
5. `A→C→A→B` - Modified split path
6. `A→B` - Direct pair conversion
7. `A→B (Inverse)` - Inverse direct conversion
8. `B→A (Inverse)` - Reverse inverse conversion
🛠️ Configuration Options
General Settings
- Alert threshold percentage
- Moving average period
- Enable/disable individual loops
Per Loop Settings
- Transaction path selection
- Three symbol inputs (A, B, C)
- Six fee parameters (Start, Deposit, Step1, Step2, End, Withdraw)
- Individual on/off controls
📈 Use Cases
- Cross-Exchange Arbitrage : Identify price differences between exchanges
- Currency Triangulation : Find inefficiencies in forex/crypto triangular paths
- Fee Analysis : Understand the impact of trading costs on profitability
- Market Research : Study price relationships and correlations
⚙️ Technical Specifications
- Pine Script Version : v6
- Chart Type : Oscillator (overlay=false)
- Data Source : Real-time price feeds via TradingView
- Calculations : Percentage-based profit/loss with fee adjustments
- Alerts : TradingView alert system integration
📊 Visual Elements
- Clean Charts : Plots hidden by default for uncluttered interface
- Weekend Highlighting : Yellow background during market closures
- Color Coding : Distinct colors for each arbitrage loop
- MA Overlay : Optional moving average display
🔧 Installation & Setup
1. Add indicator to TradingView chart
2. Configure desired number of arbitrage loops
3. Set symbol pairs for each active loop
4. Adjust fee parameters based on your broker/exchange
5. Set alert threshold percentage
6. Enable alerts for desired loops
⚠️ Important Notes
- Real-time Data : Requires live market data for accurate calculations
- Fee Accuracy : Ensure fee parameters match your actual trading costs
- Market Hours : Consider exchange operating hours and liquidity
- Risk Management : This is an analysis tool, not investment advice
OPEN = LOW + VWAP + Volume SurgeTradingView Pine Script that scans for OPEN = LOW, confirms VWAP support, and checks for volume surge — tailored for your intraday breakout strategy
MajorTop DeltaVol ma5-52wThe idea is to identify major tops on the weekly when both are above 0 at the same time; to look just for mkt tops.
Major tops use to drag on for a little with increasing volatility before crashing.
green is 5-52sma
fuchsia 3-9sma
Sma are on the candle's range ratio on the close.
Liquidity+FVG+OB Strategy (v6)How the strategy works (summary)
Entry Long when a Bullish FVG is detected (optionally requires a recent Bullish OB).
Entry Short when a Bearish FVG is detected (optionally requires a recent Bearish OB).
Stop Loss and Take Profit are placed using ATR multiples (configurable).
Position sizing is fixed contract/lot size (configurable).
You can require OB confirmation (within ob_confirm_window bars).
Alerts still exist and visuals are preserved.
Morning Peak FadeMorning Peak Fade is an intraday analysis tool that identifies and measures the probability of early session rallies turning into sharp pullbacks.
📊 Core Idea
• Many stocks surge after the open, reaching an intraday peak before fading lower.
• This script anchors at the first significant morning high and tracks the drawdowns that follow within a customizable time window.
• It provides:
• Probability of a fade after the peak
• Average and maximum drawdown statistics
• Event-day hit rate (how often such setups occur)
🎯 Use Cases
• Spot potential “fade setups” where early enthusiasm exhausts quickly.
• Quantify how often chasing the morning high turns into a losing trade.
• Backtest opening range failure or fade strategies with hard data.
⚙️ Features
• Customizable thresholds for the initial surge (relative to prior close).
• Marks the peak (max) and subsequent low (min) used in calculations.
• Draws a reference line at the surge threshold to visualize when the fade triggers.
• Outputs summary stats directly on the chart.
Double Top/Bottom Screener - Today Only v2 //@version=6
indicator("Double Top/Bottom Screener - Today Only", overlay=true, max_lines_count=500)
// Inputs
leftBars = input.int(5, "Left Bars")
rightBars = input.int(5, "Right Bars")
tolerance = input.float(0.02, "Max Difference (e.g., 0.02 for 2 cents)", step=0.01)
atrLength = input.int(14, "ATR Length for Normalized Distance", minval=1)
requiredPeaks = input.int(3, "Required Identical Peaks", minval=2, maxval=5)
// Declarations of persistent variables and arrays
var array resistanceLevels = array.new(0)
var array resistanceCounts = array.new(0)
var array supportLevels = array.new(0)
var array supportCounts = array.new(0)
var array resLines = array.new(0)
var array supLines = array.new(0)
var bool hasDoubleTop = false
var bool hasDoubleBottom = false
var float doubleTopLevel = na
var float doubleBottomLevel = na
var int todayStart = na
// Step 1: Identify Swing Highs/Lows
swingHigh = ta.pivothigh(high, leftBars, rightBars)
swingLow = ta.pivotlow(low, leftBars, rightBars)
// Today's premarket start (04:00 AM ET)
todayStart := timestamp(syminfo.timezone, year, month, dayofmonth, 4, 0, 0)
// Clear arrays and delete lines on the first bar or new day
if barstate.isfirst or (dayofmonth != dayofmonth and time >= todayStart)
// Delete all existing lines only if arrays are not empty
if array.size(resLines) > 0
for i = array.size(resLines) - 1 to 0
line.delete(array.get(resLines, i))
if array.size(supLines) > 0
for i = array.size(supLines) - 1 to 0
line.delete(array.get(supLines, i))
// Clear arrays
array.clear(resistanceLevels)
array.clear(supportLevels)
array.clear(resistanceCounts)
array.clear(supportCounts)
array.clear(resLines)
array.clear(supLines)
// Reset flags
hasDoubleTop := false
hasDoubleBottom := false
doubleTopLevel := na
doubleBottomLevel := na
// Add new swings only if today and after premarket
if not na(swingHigh) and time >= todayStart and dayofmonth == dayofmonth
bool isEqualHigh = false
int peakIndex = -1
float prevLevel = na
if array.size(resistanceLevels) > 0
for i = 0 to array.size(resistanceLevels) - 1
prevLevel := array.get(resistanceLevels, i)
if math.abs(swingHigh - prevLevel) <= tolerance
isEqualHigh := true
peakIndex := i
break
if isEqualHigh and peakIndex >= 0
array.set(resistanceCounts, peakIndex, array.get(resistanceCounts, peakIndex) + 1)
if array.get(resistanceCounts, peakIndex) == requiredPeaks
hasDoubleTop := true
doubleTopLevel := prevLevel
else
array.push(resistanceLevels, swingHigh)
array.push(resistanceCounts, 1)
line newResLine = line.new(bar_index - rightBars, swingHigh, bar_index, swingHigh, color=color.red, width=2, extend=extend.none)
array.push(resLines, newResLine)
if not na(swingLow) and time >= todayStart and dayofmonth == dayofmonth
bool isEqualLow = false
int peakIndex = -1
float prevLevel = na
if array.size(supportLevels) > 0
for i = 0 to array.size(supportLevels) - 1
prevLevel := array.get(supportLevels, i)
if math.abs(swingLow - prevLevel) <= tolerance
isEqualLow := true
peakIndex := i
break
if isEqualLow and peakIndex >= 0
array.set(supportCounts, peakIndex, array.get(supportCounts, peakIndex) + 1)
if array.get(supportCounts, peakIndex) == requiredPeaks
hasDoubleBottom := true
doubleBottomLevel := prevLevel
else
array.push(supportLevels, swingLow)
array.push(supportCounts, 1)
line newSupLine = line.new(bar_index - rightBars, swingLow, bar_index, swingLow, color=color.green, width=2, extend=extend.none)
array.push(supLines, newSupLine)
// Monitor and remove broken levels/lines; reset pattern if the equal level breaks
if array.size(resistanceLevels) > 0
for i = array.size(resistanceLevels) - 1 to 0
float level = array.get(resistanceLevels, i)
if close > level
line.delete(array.get(resLines, i))
array.remove(resLines, i)
array.remove(resistanceLevels, i)
array.remove(resistanceCounts, i)
if level == doubleTopLevel
hasDoubleTop := false
doubleTopLevel := na
if array.size(supportLevels) > 0
for i = array.size(supportLevels) - 1 to 0
float level = array.get(supportLevels, i)
if close < level
line.delete(array.get(supLines, i))
array.remove(supLines, i)
array.remove(supportLevels, i)
array.remove(supportCounts, i)
if level == doubleBottomLevel
hasDoubleBottom := false
doubleBottomLevel := na
// Limit arrays (after removals)
if array.size(resistanceLevels) > 10
line oldLine = array.shift(resLines)
line.delete(oldLine)
array.shift(resistanceLevels)
array.shift(resistanceCounts)
if array.size(supportLevels) > 10
line oldLine = array.shift(supLines)
line.delete(oldLine)
array.shift(supportLevels)
array.shift(supportCounts)
// Pattern Signal: 1 only if the exact required number of peaks is met
patternSignal = (hasDoubleTop or hasDoubleBottom) ? 1 : 0
// New: Nearest Double Level Price
var float nearestDoubleLevel = na
if hasDoubleTop and not na(doubleTopLevel)
nearestDoubleLevel := doubleTopLevel
if hasDoubleBottom and not na(doubleBottomLevel)
nearestDoubleLevel := na(nearestDoubleLevel) ? doubleBottomLevel : (math.abs(close - doubleBottomLevel) < math.abs(close - nearestDoubleLevel) ? doubleBottomLevel : nearestDoubleLevel)
// New: Distance to Nearest Level (using ATR for normalization)
var float atr = ta.atr(atrLength)
var float distanceNormalizedATR = na
if not na(nearestDoubleLevel) and not na(atr) and atr > 0
distanceNormalizedATR := math.abs(close - nearestDoubleLevel) / atr
// Optional Bounce Signal (for reference)
bounceSignal = 0
if array.size(resistanceLevels) > 0
for i = 0 to array.size(resistanceLevels) - 1
float level = array.get(resistanceLevels, i)
if low <= level and high >= level and close < level
bounceSignal := 1
if array.size(supportLevels) > 0
for i = 0 to array.size(supportLevels) - 1
float level = array.get(supportLevels, i)
if high >= level and low <= level and close > level
bounceSignal := 1
// Outputs
plot(patternSignal, title="Pattern Signal", color=patternSignal == 1 ? color.purple : na, style=plot.style_circles)
plot(bounceSignal, title="Bounce Signal", color=bounceSignal == 1 ? color.yellow : na, style=plot.style_circles)
plot(nearestDoubleLevel, title="Nearest Double Level Price", color=color.orange)
plot(distanceNormalizedATR, title="Normalized Distance (ATR)", color=color.green)
bgcolor(patternSignal == 1 ? color.new(color.purple, 80) : na)
if patternSignal == 1 and barstate.isconfirmed
alert("Double Pattern detected on " + syminfo.ticker + " at " + str.tostring(close), alert.freq_once_per_bar_close)
if barstate.islast
var table infoTable = table.new(position.top_right, 1, 4, bgcolor=color.new(color.black, 50))
table.cell(infoTable, 0, 0, "Pattern: " + str.tostring(patternSignal), bgcolor=patternSignal == 1 ? color.purple : color.gray)
table.cell(infoTable, 0, 1, "Bounce: " + str.tostring(bounceSignal), bgcolor=bounceSignal == 1 ? color.yellow : color.gray)
table.cell(infoTable, 0, 2, "Level: " + str.tostring(nearestDoubleLevel, "#.##"), bgcolor=color.orange)
table.cell(infoTable, 0, 3, "ATR Dist: " + str.tostring(distanceNormalizedATR, "#.##"), bgcolor=color.green)
Multi-Timeframe MACD Score(Customizable)this is a momentum based indicator to know the direction of the market
MA Divergence中文介绍:
均线背离指标是一款用于分析价格与均线(如EMA或SMA)之间的背离情况的技术分析工具。该指标结合了标准差、波动性分析和背离信号的检测,旨在帮助交易者识别市场中的潜在反转信号。
主要功能:
背离检测: 该指标根据价格与指定均线(EMA或SMA)之间的乖离(百分比差异),绘制背离柱状图,便于快速识别背离信号。
标准差与阈值: 根据过去一段时间内的历史数据,自动计算标准差并设置动态阈值,用以判断价格背离的异常程度。当背离信号超出设定的阈值时,柱状图将标记为蓝色,突出显示潜在的反转信号。
警报功能: 为用户提供警报设置,当背离信号突破上阈值或下阈值时,能够及时提醒交易者,帮助做出决策。
适用对象:
短期交易者: 用于快速捕捉反转信号,帮助制定更具针对性的交易策略。
中长期交易者: 通过背离与均线的结合,帮助识别趋势的潜在转折点。
技术分析爱好者: 提供了一种新的背离分析视角,帮助用户理解市场行为。
英文介绍:
The Moving Average Divergence (MA Divergence) Indicator is a technical analysis tool designed to analyze the divergence between price and a moving average (such as EMA or SMA). The indicator combines standard deviation, volatility analysis, and divergence signal detection to help traders identify potential reversal signals in the market.
Key Features:
Divergence Detection: The indicator plots divergence histograms based on the percentage difference between price and the selected moving average (EMA or SMA), making it easy to spot divergence signals at a glance.
Standard Deviation & Thresholds: The indicator automatically calculates the standard deviation based on historical data over a specified period and sets dynamic thresholds to assess the abnormality of price divergence. When the divergence signal exceeds the set thresholds, the histogram is highlighted in blue, emphasizing potential reversal signals.
Alert Functionality: The indicator includes alert conditions, allowing users to receive notifications when the divergence breaks above or below a defined threshold, helping traders take timely actions.
Target Audience:
Short-term traders: Designed for quick identification of reversal signals to formulate more targeted trading strategies.
Mid-to-long-term traders: Helps to identify potential trend reversal points by combining divergence with moving averages.
Technical analysis enthusiasts: Provides a new perspective on divergence analysis, helping users better understand market behavior.
总结:
无论是短期的交易决策,还是长期的市场趋势判断,“均线背离”指标都能为交易者提供强大的支持。通过标准差、波动性分析、警报提醒等功能,帮助用户实时捕捉市场中的背离信号,并快速做出反应。
Double Top/Bottom Screener with ATR otential Issues in the Latest Script
Based on the code and your previous feedback, here are possible mistakes:
Syntax or Compilation Error:
The script might have a typo or incomplete logic, especially with the new nearestDoubleLevel and distanceNormalizedATR additions.
Check: The table definition in the if barstate.islast block has 4 columns defined but tries to access a 5th with table.cell(infoTable, 0, 4, ...), which causes an "index out of bounds" error. This is a clear mistake.
Distance or Level Calculation:
If "Dist: NaN%" or "Level: NaN" appears, it might indicate that doubleTopLevel or doubleBottomLevel isn’t being set correctly, possibly due to the tolerance or array logic.
Check: The ATR-normalized distance (distanceNormalizedATR) might fail if atr is na due to insufficient bars.
Screener Column Issue:
The new columns ("Nearest Double Level Price" and "Normalized Distance (ATR)") might not display or sort correctly in the Pine Screener due to plotting or naming conflicts.