Index & Stock Options Reference Tool-(ISORT) [Arjo]The Index & Stock Options Reference Tool-(ISORT) is an indicator that helps users observe price trend direction together with commonly used option strike levels for selected indices and stocks in Indian market .
The indicator integrates a smoothed trend framework with structured option-related data to help users observe how price direction aligns with commonly referenced option strike levels .
It does not generate trading signals, does not provide buy or sell recommendations, and does not evaluate profitability .
Key Features
1. Trend Context Engine
Uses a Super-Smoother filter combined with EMA smoothing
Highlights directional context through color-based trend states
Designed to reduce short-term noise
2. Dynamic ATM & Strike Reference
Automatically computes ATM strike and offset strike levels to select OTM strike
Strike intervals adapt to the selected index or stock
Supports both NSE and BSE instruments, including SENSEX
3. Expiry Awareness
User-selectable expiry date inputs
Displays a visual warning if the selected expiry has already passed
Helps avoid referencing outdated option contracts
4. Option Price Reference Panel
Displays last observed CALL and PUT prices (when available)
Allows optional manual entry values for analytical comparison
All price values are shown strictly as references
5. Informational Table Overlay
Customizable on-chart table layout
Displays strike, timestamp, price reference, and arithmetic P&L values
Table values are informational only, not predictive or advisory
How to Use
1. Select the Underlying Instrument
Choose whether to reference the current chart symbol or a custom index/stock from the input settings
Supported instruments include major NSE indices, selected stocks, and SENSEX
2. Configure Expiry Parameters
Enter the option expiry date using the Day, Month, and Year inputs
If an expired date is selected, the indicator will display a visual warning
This helps ensure option references remain time-relevant
3. Observe Trend Context
The smoothed trend line provides directional context only
Color changes reflect shifts in price structure, not trade instructions
This trend is intended for contextual analysis, not timing entries
4. Review Strike References
The indicator automatically calculates ATM and offset strike levels
Strike spacing adjusts based on the selected index or stock
These values serve as reference levels commonly observed in options markets
5. Interpret the Information Table
The on-chart table displays:
Strike level
Timestamp of the most recent context change
Last observed option price (when available)
Arithmetic price difference values
All values are informational references only and do not represent performance or outcomes
6. Optional Manual Inputs
Manual price fields can be used to compare external reference values
These inputs do not trigger signals or automated calculations
Important Notes
This indicator is not a trading system
It does not generate buy or sell signals
It does not provide financial or trading advice
It is intended for learning, observation, and market study
Disclaimer
This script is provided for educational and analytical purposes only. It does not constitute investment advice, trading advice. The author assumes no responsibility for decisions made using this indicator.
Happy Trading (Arjo)
Cerca negli script per "entry"
ATR Trailing StopATR Trailing Stop (Dynamic Volatility Regimes)
==============================================
This indicator implements an adaptive ATR-based trailing stop for long positions. The stop automatically adjusts based on stock volatility, tightening during fast movements and widening during calm periods. It is designed as a trade management tool to help protect profits while staying aligned with strong trends.
How It Works
------------
* Tracks the highest high over a configurable lookback window and ensures this “top” never moves downward.
* Computes the trailing stop as:**Top – ATR × Dynamic Multiplier**
* The ATR multiplier changes depending on volatility:
* Low volatility → Wide stop (slower trailing)
* Medium volatility → Standard trailing
* High volatility → Tight stop (faster trailing)
* The trailing stop only moves upward; it never decreases.
* If price falls significantly below the stop (default: 5%), the system resets and begins trailing from a new top.
* An optional price-scale label displays:
* Current stop value
* Volatility regime (LOW / MID / HIGH)
* ATR percentage and active multiplier
Alerts
------
Two alert conditions are included:
### Trailing Stop – Near
Triggers when price moves within a user-defined percentage above the stop.
### Trailing Stop – Hit
Triggers when price touches or closes below the stop.
How to Use
----------
1. Add the indicator to any chart (daily timeframe recommended).
2. Configure:
* ATR length
* Lookback bars
* Volatility thresholds
* ATR multipliers
3. Set alerts for early warnings or stop-hit events.
4. Use the stop line as a dynamic risk-management tool to guide exit decisions and protect profits.
Notes
-----
* Designed for long-only trailing logic.
* This indicator does not generate entry signals; it is intended for stop management.
Zee's A+ MOMO BreakThis just shows an indicator when you have a 5 minute momentum candle that breaks PMH under specific parameters, i.e candle size, wick size, relative volume, time of day, etc. It will plot the PMH with a gold line automatically. Entry would be at the close of the MOMO break. I highly encourage you to back test your results and see how strong this setup is. Any questions feel free to comment or reach out, thanks.
FibLevel Size CalculatorThis skript calculates position sizes and new take profits for sizing into an long or short position with 3 entrys defined at custom fibonacci retracement levels.
TP: -0,272
Entry1: 0.382
Entry2: 0.618
Entry3: 0.83
SL: 1.05
Expected RR per trade is 0.2 with a High Win rate definitly profitable.
Search for an established trend on the higher timeframe, drop to the smaller ones and look for correction waves. Once they break to the trenddirection of the higher timeframe take the fib from lowest to highes point. Draw a fib level on the chart and use the Indicator to define these Levels above. The calculator gives you the Margin to use in each position, and will check that you will not get liquidated an that you have enough margin. It tells you the new TP for Limit2 and Limit3 if they get hit so you can get out of the trade full TP with a small bounce.
Inputs:
Account Balance, Risk Percentage, and Leverage: These inputs are used to calculate the position size and risk.
Entry 1, Entry 2, Entry 3, Take Profit (TP), and Stop Loss (SL): These prices are used for calculating position sizes, risk, and profit for up to three entry points.
Calculations:
Risk Amount: Calculated based on the account balance and risk percentage.
Position Sizes (Qty): For each entry point, the position size is determined. The second and third entries have a multiplier (3x for Entry 2, 5x for Entry 3) compared to the first.
Stop Loss and Profit Calculation: The script calculates the potential profit and adjusts the TP levels based on the average entries for Limit 2 and Limit 3.
Margin Calculation: Margin requirements for each position are calculated based on leverage.
Output:
Table Display: A table shows key values like entry prices, position sizes, TP levels, potential profit, and margin requirements for each limit.
Warnings: It includes a liquidation warning and a check for whether the account is at risk of liquidation based on leverage.
Position Type: It automatically detects if the trade is a long or short based on the relationship between TP and SL.
Visualization:
Lines: It draws horizontal lines on the chart to visually represent the entry, TP, and SL levels.
Overall, this script is designed to help traders manage risk and calculate position sizes for multi-level entries using leverage.
Pls drop feedback in the comments.
BAY_PIVOT S/R(4 Full Lines + ALL Labels)//@version=5
indicator("BAY_PIVOT S/R(4 Full Lines + ALL Labels)", overlay=true, max_labels_count=500, max_lines_count=500)
// ────────────────────── TOGGLES ──────────────────────
showPivot = input.bool(true, "Show Pivot (Full Line + Label)")
showTarget = input.bool(true, "Show Target (Full Line + Label)")
showLast = input.bool(true, "Show Last Close (Full Line + Label)")
showPrevClose = input.bool(true, "Show Previous Close (Full Line + Label)")
useBarchartLast = input.bool(true, "Use Barchart 'Last' (Settlement Price)")
showR1R2R3 = input.bool(true, "Show R1 • R2 • R3")
showS1S2S3 = input.bool(true, "Show S1 • S2 • S3")
showStdDev = input.bool(true, "Show ±1σ ±2σ ±3σ")
showFib4W = input.bool(true, "Show 4-Week Fibs")
showFib13W = input.bool(true, "Show 13-Week Fibs")
showMonthHL = input.bool(true, "Show 1M High / Low")
showEntry1 = input.bool(false, "Show Manual Entry 1")
showEntry2 = input.bool(false, "Show Manual Entry 2")
entry1 = input.float(0.0, "Manual Entry 1", step=0.25)
entry2 = input.float(0.0, "Manual Entry 2", step=0.25)
stdLen = input.int(20, "StdDev Length", minval=1)
fib4wBars = input.int(20, "4W Fib Lookback")
fib13wBars = input.int(65, "13W Fib Lookback")
// ────────────────────── DAILY CALCULATIONS ──────────────────────
high_y = request.security(syminfo.tickerid, "D", high , lookahead=barmerge.lookahead_on)
low_y = request.security(syminfo.tickerid, "D", low , lookahead=barmerge.lookahead_on)
close_y = request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_on)
pivot = (high_y + low_y + close_y) / 3
r1 = pivot + 0.382 * (high_y - low_y)
r2 = pivot + 0.618 * (high_y - low_y)
r3 = pivot + (high_y - low_y)
s1 = pivot - 0.382 * (high_y - low_y)
s2 = pivot - 0.618 * (high_y - low_y)
s3 = pivot - (high_y - low_y)
prevClose = close_y
last = useBarchartLast ? request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_off) : close
target = pivot + (pivot - prevClose)
// StdDev + Fibs + Monthly (unchanged)
basis = ta.sma(close, stdLen)
dev = ta.stdev(close, stdLen)
stdRes1 = basis + dev
stdRes2 = basis + dev*2
stdRes3 = basis + dev*3
stdSup1 = basis - dev
stdSup2 = basis - dev*2
stdSup3 = basis - dev*3
high4w = ta.highest(high, fib4wBars)
low4w = ta.lowest(low, fib4wBars)
fib382_4w = high4w - (high4w - low4w) * 0.382
fib50_4w = high4w - (high4w - low4w) * 0.500
high13w = ta.highest(high, fib13wBars)
low13w = ta.lowest(low, fib13wBars)
fib382_13w_high = high13w - (high13w - low13w) * 0.382
fib50_13w = high13w - (high13w - low13w) * 0.500
fib382_13w_low = low13w + (high13w - low13w) * 0.382
monthHigh = ta.highest(high, 30)
monthLow = ta.lowest(low, 30)
// ────────────────────── COLORS ──────────────────────
colRed = color.rgb(255,0,0)
colLime = color.rgb(0,255,0)
colYellow = color.rgb(255,255,0)
colOrange = color.rgb(255,165,0)
colWhite = color.rgb(255,255,255)
colGray = color.rgb(128,128,128)
colMagenta = color.rgb(255,0,255)
colPink = color.rgb(233,30,99)
colCyan = color.rgb(0,188,212)
colBlue = color.rgb(0,122,255)
colPurple = color.rgb(128,0,128)
colRed50 = color.new(colRed,50)
colGreen50 = color.new(colLime,50)
// ────────────────────── 4 KEY FULL LINES ──────────────────────
plot(showPivot ? pivot : na, title="PIVOT", color=colYellow, linewidth=3, style=plot.style_linebr)
plot(showTarget ? target : na, title="TARGET", color=colOrange, linewidth=2, style=plot.style_linebr)
plot(showLast ? last : na, title="LAST", color=colWhite, linewidth=2, style=plot.style_linebr)
plot(showPrevClose ? prevClose : na, title="PREV CLOSE",color=colGray, linewidth=1, style=plot.style_linebr)
// ────────────────────── LABELS FOR ALL 4 KEY LEVELS (SAME STYLE AS OTHERS) ──────────────────────
f_label(price, txt, bgColor, txtColor) =>
if barstate.islast and not na(price)
label.new(bar_index, price, txt, style=label.style_label_left, color=bgColor, textcolor=txtColor, size=size.small)
if barstate.islast
showPivot ? f_label(pivot, "PIVOT\n" + str.tostring(pivot, "#.##"), colYellow, color.black) : na
showTarget ? f_label(target, "TARGET\n" + str.tostring(target, "#.##"), colOrange, color.white) : na
showLast ? f_label(last, "LAST\n" + str.tostring(last, "#.##"), colWhite, color.black) : na
showPrevClose ? f_label(prevClose, "PREV CLOSE\n"+ str.tostring(prevClose, "#.##"), colGray, color.white) : na
// ────────────────────── OTHER LEVELS – line stops at label ──────────────────────
f_level(p, txt, tc, lc, w=1) =>
if barstate.islast and not na(p)
lbl = label.new(bar_index, p, txt, style=label.style_label_left, color=lc, textcolor=tc, size=size.small)
line.new(bar_index-400, p, label.get_x(lbl), p, extend=extend.none, color=lc, width=w)
if barstate.islast
if showR1R2R3
f_level(r1, "R1\n" + str.tostring(r1, "#.##"), color.white, colRed)
f_level(r2, "R2\n" + str.tostring(r2, "#.##"), color.white, colRed)
f_level(r3, "R3\n" + str.tostring(r3, "#.##"), color.white, colRed, 2)
if showS1S2S3
f_level(s1, "S1\n" + str.tostring(s1, "#.##"), color.black, colLime)
f_level(s2, "S2\n" + str.tostring(s2, "#.##"), color.black, colLime)
f_level(s3, "S3\n" + str.tostring(s3, "#.##"), color.black, colLime, 2)
if showStdDev
f_level(stdRes1, "+1σ\n" + str.tostring(stdRes1, "#.##"), color.white, colPink)
f_level(stdRes2, "+2σ\n" + str.tostring(stdRes2, "#.##"), color.white, colPink)
f_level(stdRes3, "+3σ\n" + str.tostring(stdRes3, "#.##"), color.white, colPink, 2)
f_level(stdSup1, "-1σ\n" + str.tostring(stdSup1, "#.##"), color.white, colCyan)
f_level(stdSup2, "-2σ\n" + str.tostring(stdSup2, "#.##"), color.white, colCyan)
f_level(stdSup3, "-3σ\n" + str.tostring(stdSup3, "#.##"), color.white, colCyan, 2)
if showFib4W
f_level(fib382_4w, "38.2% 4W\n" + str.tostring(fib382_4w, "#.##"), color.white, colMagenta)
f_level(fib50_4w, "50% 4W\n" + str.tostring(fib50_4w, "#.##"), color.white, colMagenta)
if showFib13W
f_level(fib382_13w_high, "38.2% 13W High\n" + str.tostring(fib382_13w_high, "#.##"), color.white, colMagenta)
f_level(fib50_13w, "50% 13W\n" + str.tostring(fib50_13w, "#.##"), color.white, colMagenta)
f_level(fib382_13w_low, "38.2% 13W Low\n" + str.tostring(fib382_13w_low, "#.##"), color.white, colMagenta)
if showMonthHL
f_level(monthHigh, "1M HIGH\n" + str.tostring(monthHigh, "#.##"), color.white, colRed50, 2)
f_level(monthLow, "1M LOW\n" + str.tostring(monthLow, "#.##"), color.white, colGreen50, 2)
// Manual entries
plot(showEntry1 and entry1 > 0 ? entry1 : na, "Entry 1", color=colBlue, linewidth=2, style=plot.style_linebr)
plot(showEntry2 and entry2 > 0 ? entry2 : na, "Entry 2", color=colPurple, linewidth=2, style=plot.style_linebr)
// Background
bgcolor(close > pivot ? color.new(color.blue, 95) : color.new(color.red, 95))
Nef33 Forex & Crypto Trading Signals PRO
1. Understanding the Indicator's Context
The indicator generates signals based on confluence (trend, volume, key zones, etc.), but it does not include predefined SL or TP levels. To establish them, we must:
Use dynamic or static support/resistance levels already present in the script.
Incorporate volatility (such as ATR) to adjust the levels based on market conditions.
Define a risk/reward ratio (e.g., 1:2).
2. Options for Determining SL and TP
Below, I provide several ideas based on the tools available in the script:
Stop Loss (SL)
The SL should protect you from adverse movements. You can base it on:
ATR (Volatility): Use the smoothed ATR (atr_smooth) multiplied by a factor (e.g., 1.5 or 2) to set a dynamic SL.
Buy: SL = Entry Price - (atr_smooth * atr_mult).
Sell: SL = Entry Price + (atr_smooth * atr_mult).
Key Zones: Place the SL below a support (for buys) or above a resistance (for sells), using Order Blocks, Fair Value Gaps, or Liquidity Zones.
Buy: SL below the nearest ob_lows or fvg_lows.
Sell: SL above the nearest ob_highs or fvg_highs.
VWAP: Use the daily VWAP (vwap_day) as a critical level.
Buy: SL below vwap_day.
Sell: SL above vwap_day.
Take Profit (TP)
The TP should maximize profits. You can base it on:
Risk/Reward Ratio: Multiply the SL distance by a factor (e.g., 2 or 3).
Buy: TP = Entry Price + (SL Distance * 2).
Sell: TP = Entry Price - (SL Distance * 2).
Key Zones: Target the next resistance (for buys) or support (for sells).
Buy: TP at the next ob_highs, fvg_highs, or liq_zone_high.
Sell: TP at the next ob_lows, fvg_lows, or liq_zone_low.
Ichimoku: Use the cloud levels (Senkou Span A/B) as targets.
Buy: TP at senkou_span_a or senkou_span_b (whichever is higher).
Sell: TP at senkou_span_a or senkou_span_b (whichever is lower).
3. Practical Implementation
Since the script does not automatically draw SL/TP, you can:
Calculate them manually: Observe the chart and use the levels mentioned.
Modify the code: Add SL/TP as labels (label.new) at the moment of the signal.
Here’s an example of how to modify the code to display SL and TP based on ATR with a 1:2 risk/reward ratio:
Modified Code (Signals Section)
Find the lines where the signals (trade_buy and trade_sell) are generated and add the following:
pinescript
// Calculate SL and TP based on ATR
atr_sl_mult = 1.5 // Multiplier for SL
atr_tp_mult = 3.0 // Multiplier for TP (1:2 ratio)
sl_distance = atr_smooth * atr_sl_mult
tp_distance = atr_smooth * atr_tp_mult
if trade_buy
entry_price = close
sl_price = entry_price - sl_distance
tp_price = entry_price + tp_distance
label.new(bar_index, low, "Buy: " + str.tostring(math.round(bull_conditions, 1)), color=color.green, textcolor=color.white, style=label.style_label_up, size=size.tiny)
label.new(bar_index, sl_price, "SL: " + str.tostring(math.round(sl_price, 2)), color=color.red, textcolor=color.white, style=label.style_label_down, size=size.tiny)
label.new(bar_index, tp_price, "TP: " + str.tostring(math.round(tp_price, 2)), color=color.blue, textcolor=color.white, style=label.style_label_up, size=size.tiny)
if trade_sell
entry_price = close
sl_price = entry_price + sl_distance
tp_price = entry_price - tp_distance
label.new(bar_index, high, "Sell: " + str.tostring(math.round(bear_conditions, 1)), color=color.red, textcolor=color.white, style=label.style_label_down, size=size.tiny)
label.new(bar_index, sl_price, "SL: " + str.tostring(math.round(sl_price, 2)), color=color.red, textcolor=color.white, style=label.style_label_up, size=size.tiny)
label.new(bar_index, tp_price, "TP: " + str.tostring(math.round(tp_price, 2)), color=color.blue, textcolor=color.white, style=label.style_label_down, size=size.tiny)
Code Explanation
SL: Calculated by subtracting/adding sl_distance to the entry price (close) depending on whether it’s a buy or sell.
TP: Calculated with a double distance (tp_distance) for a 1:2 risk/reward ratio.
Visualization: Labels are added to the chart to display SL (red) and TP (blue).
4. Practical Strategy Without Modifying the Code
If you don’t want to modify the script, follow these steps manually:
Entry: Take the trade_buy or trade_sell signal.
SL: Check the smoothed ATR (atr_smooth) on the chart or calculate a fixed level (e.g., 1.5 times the ATR). Also, review nearby key zones (OB, FVG, VWAP).
TP: Define a target based on the next key zone or multiply the SL distance by 2 or 3.
Example:
Buy at 100, ATR = 2.
SL = 100 - (2 * 1.5) = 97.
TP = 100 + (2 * 3) = 106.
5. Recommendations
Test in Demo: Apply this logic in a demo account to adjust the multipliers (atr_sl_mult, atr_tp_mult) based on the market (forex or crypto).
Combine with Zones: If the ATR-based SL is too wide, use the nearest OB or FVG as a reference.
Risk/Reward Ratio: Adjust the TP based on your tolerance (1:1, 1:2, 1:3)
Razzere Cloned! EzAlgo V.8.1showBuySell = input(true, "Show Buy & Sell", group="BUY & SELL SIGNALS")
hassasiyet = input.float(3, "Hassasiyet (1-6)", 0.1, 99999, group="BUY & SELL SIGNALS")
percentStop = input.float(1, "Stop Loss % (0 to Disable)", 0, group="BUY & SELL SIGNALS")
offsetSignal = input.float(5, "Signals Offset", 0, group="BUY & SELL SIGNALS")
showRibbon = input(true, "Show Trend Ribbon", group="TREND RIBBON")
smooth1 = input.int(5, "Smoothing 1", 1, group="TREND RIBBON")
smooth2 = input.int(8, "Smoothing 2", 1, group="TREND RIBBON")
showreversal = input(true, "Show Reversals", group="REVERSAL SIGNALS")
showPdHlc = input(false, "Show P.D H/L/C", group="PREVIOUS DAY HIGH LOW CLOSE")
lineColor = input.color(color.yellow, "Line Colors", group="PREVIOUS DAY HIGH LOW CLOSE")
lineWidth = input.int(1, "Width Lines", group="PREVIOUS DAY HIGH LOW CLOSE")
lineStyle = input.string("Solid", "Line Style", )
labelSize = input.string("normal", "Label Text Size", )
labelColor = input.color(color.yellow, "Label Text Colors")
showEmas = input(false, "Show EMAs", group="EMA")
srcEma1 = input(close, "Source EMA 1")
lenEma1 = input.int(7, "Length EMA 1", 1)
srcEma2 = input(close, "Source EMA 2")
lenEma2 = input.int(21, "Length EMA 2", 1)
srcEma3 = input(close, "Source EMA 3")
lenEma3 = input.int(144, "Length EMA 3", 1)
showSwing = input(false, "Show Swing Points", group="SWING POINTS")
prdSwing = input.int(10, "Swing Point Period", 2, group="SWING POINTS")
colorPos = input(color.new(color.green, 50), "Positive Swing Color")
colorNeg = input(color.new(color.red, 50), "Negative Swing Color")
showDashboard = input(true, "Show Dashboard", group="TREND DASHBOARD")
locationDashboard = input.string("Middle Right", "Table Location", , group="TREND DASHBOARD")
tableTextColor = input(color.white, "Table Text Color", group="TREND DASHBOARD")
tableBgColor = input(#2A2A2A, "Table Background Color", group="TREND DASHBOARD")
sizeDashboard = input.string("Normal", "Table Size", , group="TREND DASHBOARD")
showRevBands = input.bool(true, "Show Reversal Bands", group="REVERSAL BANDS")
lenRevBands = input.int(30, "Length", group="REVERSAL BANDS")
// Fonksiyonlar
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt ) ? x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r : x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
securityNoRep(sym, res, src) => request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on)
swingPoints(prd) =>
pivHi = ta.pivothigh(prd, prd)
pivLo = ta.pivotlow (prd, prd)
last_pivHi = ta.valuewhen(pivHi, pivHi, 1)
last_pivLo = ta.valuewhen(pivLo, pivLo, 1)
hh = pivHi and pivHi > last_pivHi ? pivHi : na
lh = pivHi and pivHi < last_pivHi ? pivHi : na
hl = pivLo and pivLo > last_pivLo ? pivLo : na
ll = pivLo and pivLo < last_pivLo ? pivLo : na
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
f_kc(src, len, hassasiyet) =>
basis = ta.sma(src, len)
span = ta.atr(len)
wavetrend(src, chlLen, avgLen) =>
esa = ta.ema(src, chlLen)
d = ta.ema(math.abs(src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = ta.ema(ci, avgLen)
wt2 = ta.sma(wt1, 3)
f_top_fractal(src) => src < src and src < src and src > src and src > src
f_bot_fractal(src) => src > src and src > src and src < src and src < src
f_fractalize (src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src >= topLimit ? src : na
fractalBot = f_fractalize(src) < 0 and src <= botLimit ? src : na
highPrev = ta.valuewhen(fractalTop, src , 0)
highPrice = ta.valuewhen(fractalTop, high , 0)
lowPrev = ta.valuewhen(fractalBot, src , 0)
lowPrice = ta.valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
// Bileşen...
source = close
smrng1 = smoothrng(source, 27, 1.5)
smrng2 = smoothrng(source, 55, hassasiyet)
smrng = (smrng1 + smrng2) / 2
filt = rngfilt(source, smrng)
up = 0.0, up := filt > filt ? nz(up ) + 1 : filt < filt ? 0 : nz(up )
dn = 0.0, dn := filt < filt ? nz(dn ) + 1 : filt > filt ? 0 : nz(dn )
bullCond = bool(na), bullCond := source > filt and source > source and up > 0 or source > filt and source < source and up > 0
bearCond = bool(na), bearCond := source < filt and source < source and dn > 0 or source < filt and source > source and dn > 0
lastCond = 0, lastCond := bullCond ? 1 : bearCond ? -1 : lastCond
bull = bullCond and lastCond == -1
bear = bearCond and lastCond == 1
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
ribbon1 = ta.sma(close, smooth1)
ribbon2 = ta.sma(close, smooth2)
rsi = ta.rsi(close, 21)
rsiOb = rsi > 70 and rsi > ta.ema(rsi, 10)
rsiOs = rsi < 30 and rsi < ta.ema(rsi, 10)
dHigh = securityNoRep(syminfo.tickerid, "D", high )
dLow = securityNoRep(syminfo.tickerid, "D", low )
dClose = securityNoRep(syminfo.tickerid, "D", close )
ema1 = ta.ema(srcEma1, lenEma1)
ema2 = ta.ema(srcEma2, lenEma2)
ema3 = ta.ema(srcEma3, lenEma3)
= swingPoints(prdSwing)
ema = ta.ema(close, 144)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes() and not timeframe.isseconds
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes() or timeframe.isseconds
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep1(sym, res, src) =>
bool bull_ = na
bull_ := equal_tf(res) ? src : bull_
bull_ := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on) : bull_
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) + (timeframe.isseconds ? "S" : "") : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull_ := array.pop(bull_array)
array.clear(bull_array)
bull_
TF1Bull = securityNoRep1(syminfo.tickerid, "1" , emaBull)
TF3Bull = securityNoRep1(syminfo.tickerid, "3" , emaBull)
TF5Bull = securityNoRep1(syminfo.tickerid, "5" , emaBull)
TF15Bull = securityNoRep1(syminfo.tickerid, "15" , emaBull)
TF30Bull = securityNoRep1(syminfo.tickerid, "30" , emaBull)
TF60Bull = securityNoRep1(syminfo.tickerid, "60" , emaBull)
TF120Bull = securityNoRep1(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep1(syminfo.tickerid, "240" , emaBull)
TF480Bull = securityNoRep1(syminfo.tickerid, "480" , emaBull)
TFDBull = securityNoRep1(syminfo.tickerid, "1440", emaBull)
= f_kc(close, lenRevBands, 3)
= f_kc(close, lenRevBands, 4)
= f_kc(close, lenRevBands, 5)
= f_kc(close, lenRevBands, 6)
= wavetrend(hlc3, 9, 12)
= f_findDivs(wt2, 15, -40)
= f_findDivs(wt2, 45, -65)
wtDivBull = wtDivBull1 or wtDivBull2
wtDivBear = wtDivBear1 or wtDivBear2
// Renkler
cyan = #00DBFF, cyan30 = color.new(cyan, 70)
pink = #E91E63, pink30 = color.new(pink, 70)
red = #FF5252, red30 = color.new(red , 70)
// Plotlar
off = percWidth(300, offsetSignal)
plotshape(showBuySell and bull ? low - off : na, "Buy Label" , shape.labelup , location.absolute, cyan, 0, "Buy" , color.white, size=size.normal)
plotshape(showBuySell and bear ? high + off : na, "Sell Label", shape.labeldown, location.absolute, pink, 0, "Sell", color.white, size=size.normal)
plotshape(ta.crossover(wt1, wt2) and wt2 <= -53, "Mild Buy" , shape.xcross, location.belowbar, cyan, size=size.tiny)
plotshape(ta.crossunder(wt1, wt2) and wt2 >= 53, "Mild Sell", shape.xcross, location.abovebar, pink, size=size.tiny)
plotshape(wtDivBull, "Divergence Buy ", shape.triangleup , location.belowbar, cyan, size=size.tiny)
plotshape(wtDivBear, "Divergence Sell", shape.triangledown, location.abovebar, pink, size=size.tiny)
barcolor(up > dn ? cyan : pink)
plotshape(showreversal and rsiOs, "Reversal Buy" , shape.diamond, location.belowbar, cyan30, size=size.tiny)
plotshape(showreversal and rsiOb, "Reversal Sell", shape.diamond, location.abovebar, pink30, size=size.tiny)
lStyle = lineStyle == "Solid" ? line.style_solid : lineStyle == "Dotted" ? line.style_dotted : line.style_dashed
lSize = labelSize == "small" ? size.small : labelSize == "normal" ? size.normal : size.large
dHighLine = showPdHlc ? line.new(bar_index, dHigh, bar_index + 1, dHigh , xloc.bar_index, extend.both, lineColor, lStyle, lineWidth) : na, line.delete(dHighLine )
dLowLine = showPdHlc ? line.new(bar_index, dLow , bar_index + 1, dLow , xloc.bar_index, extend.both, lineColor, lStyle, lineWidth) : na, line.delete(dLowLine )
dCloseLine = showPdHlc ? line.new(bar_index, dClose, bar_index + 1, dClose, xloc.bar_index, extend.both, lineColor, lStyle, lineWidth) : na, line.delete(dCloseLine )
dHighLabel = showPdHlc ? label.new(bar_index + 100, dHigh , "P.D.H", xloc.bar_index, yloc.price, #000000, label.style_none, labelColor, lSize) : na, label.delete(dHighLabel )
dLowLabel = showPdHlc ? label.new(bar_index + 100, dLow , "P.D.L", xloc.bar_index, yloc.price, #000000, label.style_none, labelColor, lSize) : na, label.delete(dLowLabel )
dCloseLabel = showPdHlc ? label.new(bar_index + 100, dClose, "P.D.C", xloc.bar_index, yloc.price, #000000, label.style_none, labelColor, lSize) : na, label.delete(dCloseLabel )
plot(showEmas ? ema1 : na, "EMA 1", color.green , 2)
plot(showEmas ? ema2 : na, "EMA 2", color.purple, 2)
plot(showEmas ? ema3 : na, "EMA 3", color.yellow, 2)
plotshape(showSwing ? hh : na, "", shape.triangledown, location.abovebar, color.new(color.green, 50), -prdSwing, "HH", colorPos, false)
plotshape(showSwing ? hl : na, "", shape.triangleup , location.belowbar, color.new(color.green, 50), -prdSwing, "HL", colorPos, false)
plotshape(showSwing ? lh : na, "", shape.triangledown, location.abovebar, color.new(color.red , 50), -prdSwing, "LH", colorNeg, false)
plotshape(showSwing ? ll : na, "", shape.triangleup , location.belowbar, color.new(color.red , 50), -prdSwing, "LL", colorNeg, false)
srcStop = close
atrBand = srcStop * (percentStop / 100)
atrStop = trigger ? srcStop - atrBand : srcStop + atrBand
lastTrade(src) => ta.valuewhen(bull or bear, src, 0)
entry_y = lastTrade(srcStop)
stop_y = lastTrade(atrStop)
tp1_y = (entry_y - lastTrade(atrStop)) * 1 + entry_y
tp2_y = (entry_y - lastTrade(atrStop)) * 2 + entry_y
tp3_y = (entry_y - lastTrade(atrStop)) * 3 + entry_y
labelTpSl(y, txt, color) =>
label labelTpSl = percentStop != 0 ? label.new(bar_index + 1, y, txt, xloc.bar_index, yloc.price, color, label.style_label_left, color.white, size.normal) : na
label.delete(labelTpSl )
labelTpSl(entry_y, "Entry: " + str.tostring(math.round_to_mintick(entry_y)), color.gray)
labelTpSl(stop_y , "Stop Loss: " + str.tostring(math.round_to_mintick(stop_y)), color.red)
labelTpSl(tp1_y, "Take Profit 1: " + str.tostring(math.round_to_mintick(tp1_y)), color.green)
labelTpSl(tp2_y, "Take Profit 2: " + str.tostring(math.round_to_mintick(tp2_y)), color.green)
labelTpSl(tp3_y, "Take Profit 3: " + str.tostring(math.round_to_mintick(tp3_y)), color.green)
lineTpSl(y, color) =>
line lineTpSl = percentStop != 0 ? line.new(bar_index - (trigger ? countBull : countBear) + 4, y, bar_index + 1, y, xloc.bar_index, extend.none, color, line.style_solid) : na
line.delete(lineTpSl )
lineTpSl(entry_y, color.gray)
lineTpSl(stop_y, color.red)
lineTpSl(tp1_y, color.green)
lineTpSl(tp2_y, color.green)
lineTpSl(tp3_y, color.green)
var dashboard_loc = locationDashboard == "Top Right" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard = showDashboard ? table.new(dashboard_loc, 2, 15, tableBgColor, #000000, 2, tableBgColor, 1) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column, row, txt, 0, 0, signal ? #000000 : tableTextColor, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column, row, col)
if barstate.islast and showDashboard
dashboard_cell(0, 0 , "EzAlgo")
dashboard_cell(0, 1 , "Current Position")
dashboard_cell(0, 2 , "Current Trend")
dashboard_cell(0, 3 , "Volume")
dashboard_cell(0, 4 , "Timeframe")
dashboard_cell(0, 5 , "1 min:")
dashboard_cell(0, 6 , "3 min:")
dashboard_cell(0, 7 , "5 min:")
dashboard_cell(0, 8 , "15 min:")
dashboard_cell(0, 9 , "30 min:")
dashboard_cell(0, 10, "1 H:")
dashboard_cell(0, 11, "2 H:")
dashboard_cell(0, 12, "4 H:")
dashboard_cell(0, 13, "8 H:")
dashboard_cell(0, 14, "Daily:")
dashboard_cell(1, 0 , "V.8.1")
dashboard_cell(1, 1 , trigger ? "Buy" : "Sell", true), dashboard_cell_bg(1, 1, trigger ? color.green : color.red)
dashboard_cell(1, 2 , emaBull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 2, emaBull ? color.green : color.red)
dashboard_cell(1, 3 , str.tostring(volume))
dashboard_cell(1, 4 , "Trends")
dashboard_cell(1, 5 , TF1Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 5 , TF1Bull ? color.green : color.red)
dashboard_cell(1, 6 , TF3Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 6 , TF3Bull ? color.green : color.red)
dashboard_cell(1, 7 , TF5Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 7 , TF5Bull ? color.green : color.red)
dashboard_cell(1, 8 , TF15Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 8 , TF15Bull ? color.green : color.red)
dashboard_cell(1, 9 , TF30Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 9 , TF30Bull ? color.green : color.red)
dashboard_cell(1, 10, TF60Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 10, TF60Bull ? color.green : color.red)
dashboard_cell(1, 11, TF120Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 11, TF120Bull ? color.green : color.red)
dashboard_cell(1, 12, TF240Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 12, TF240Bull ? color.green : color.red)
dashboard_cell(1, 13, TF480Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 13, TF480Bull ? color.green : color.red)
dashboard_cell(1, 14, TFDBull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 14, TFDBull ? color.green : color.red)
plot(showRevBands ? upperKC1 : na, "Rev.Zone Upper 1", red30)
plot(showRevBands ? upperKC2 : na, "Rev.Zone Upper 2", red30)
plot(showRevBands ? upperKC3 : na, "Rev.Zone Upper 3", red30)
plot(showRevBands ? upperKC4 : na, "Rev.Zone Upper 4", red30)
plot(showRevBands ? lowerKC4 : na, "Rev.Zone Lower 4", cyan30)
plot(showRevBands ? lowerKC3 : na, "Rev.Zone Lower 3", cyan30)
plot(showRevBands ? lowerKC2 : na, "Rev.Zone Lower 2", cyan30)
plot(showRevBands ? lowerKC1 : na, "Rev.Zone Lower 1", cyan30)
fill(plot(showRibbon ? ribbon1 : na, "", na, editable=false), plot(showRibbon ? ribbon2 : na, "", na, editable=false), ribbon1 > ribbon2 ? cyan30 : pink30, "Ribbon Fill Color")
// Alarmlar
alert01 = ta.crossover(ribbon1, ribbon2)
alert02 = bull
alert03 = wtDivBull
alert04 = wtDivBear
alert05 = bull or bear
alert06 = ta.crossover(wt1, wt2) and wt2 <= -53
alert07 = ta.crossunder(wt1, wt2) and wt2 >= 53
alert08 = ta.crossunder(ribbon1, ribbon2)
alert09 = rsiOb or rsiOs
alert10 = bear
alert11 = ta.cross(ribbon1, ribbon2)
alerts(sym) =>
if alert02 or alert03 or alert04 or alert06 or alert07 or alert10
alert_text = alert02 ? "Buy Signal EzAlgo" : alert03 ? "Strong Buy Signal EzAlgo" : alert04 ? "Strong Sell Signal EzAlgo" : alert06 ? "Mild Buy Signal EzAlgo" : alert07 ? "Mild Sell Signal EzAlgo" : "Sell Signal EzAlgo"
alert(alert_text, alert.freq_once_per_bar_close)
alerts(syminfo.tickerid)
alertcondition(alert01, "Blue Trend Ribbon Alert", "Blue Trend Ribbon, TimeFrame={{interval}}")
alertcondition(alert02, "Buy Signal", "Buy Signal EzAlgo")
alertcondition(alert03, "Divergence Buy Alert", "Strong Buy Signal EzAlgo, TimeFrame={{interval}}")
alertcondition(alert04, "Divergence Sell Alert", "Strong Sell Signal EzAlgo, TimeFrame={{interval}}")
alertcondition(alert05, "Either Buy or Sell Signal", "EzAlgo Signal")
alertcondition(alert06, "Mild Buy Alert", "Mild Buy Signal EzAlgo, TimeFrame={{interval}}")
alertcondition(alert07, "Mild Sell Alert", "Mild Sell Signal EzAlgo, TimeFrame={{interval}}")
alertcondition(alert08, "Red Trend Ribbon Alert", "Red Trend Ribbon, TimeFrame={{interval}}")
alertcondition(alert09, "Reversal Signal", "Reversal Signal")
alertcondition(alert10, "Sell Signal", "Sell Signal EzAlgo")
alertcondition(alert11, "Trend Ribbon Color Change Alert", "Trend Ribbon Color Change, TimeFrame={{interval}}")
Risk & Position DashboardRisk & Position Dashboard
Overview
The Risk & Position Dashboard is a comprehensive trading tool designed to help traders calculate optimal position sizes, manage risk, and visualize potential profit/loss scenarios before entering trades. This indicator provides real-time calculations for position sizing based on account size, risk percentage, and stop-loss levels, while displaying multiple take-profit targets with customizable risk-reward ratios.
Key Features
Position Sizing & Risk Management:
Automatic position size calculation based on account size and risk percentage
Support for leveraged trading with maximum leverage limits
Fractional shares support for brokers that allow partial share trading
Real-time fee calculation including entry, stop-loss, and take-profit fees
Break-even price calculation including trading fees
Multi-Target Profit Management:
Support for up to 3 take-profit levels with individual portion allocations
Customizable risk-reward ratios for each take-profit target
Visual profit/loss zones displayed as colored boxes on the chart
Individual profit calculations for each take-profit level
Visual Dashboard:
Clean, customizable table display showing all key metrics
Configurable label positioning and styling options
Real-time tracking of whether stop-loss or take-profit levels have been reached
Color-coded visual zones for easy identification of risk and reward areas
Advanced Configuration:
Comprehensive input validation and error handling
Support for different chart timeframes and symbols
Customizable colors, fonts, and display options
Hide/show individual data fields for personalized dashboard views
How to Use
Set Account Parameters: Configure your account size, maximum risk percentage per trade, and trading fees in the "Account Settings" section.
Define Trade Setup: Use the "Entry" time picker to select your entry point on the chart, then input your entry price and stop-loss level.
Configure Take Profits: Set your desired risk-reward ratios and portion allocations for each take-profit level. The script supports 1-3 take-profit targets.
Analyze Results: The dashboard will automatically calculate and display position size, number of shares, potential profits/losses, fees, and break-even levels.
Visual Confirmation: Colored boxes on the chart show profit zones (green) and loss zones (red), with lines extending to current price levels.
Reset Entry and SL:
You can easily reset the entry and stop-loss by clicking the "Reset points..." button from the script's "More" menu.
This is useful if you want to quickly clear your current trade setup and start fresh without manually adjusting the points on the chart.
Calculations
The script performs sophisticated calculations including:
Position size based on risk amount and price difference between entry and stop-loss
Leverage requirements and position amount calculations
Fee-adjusted risk-reward ratios for realistic profit expectations
Break-even price including all trading costs
Individual profit calculations for partial position closures
Detailed Take-Profit Calculation Formula:
The take-profit prices are calculated using the following mathematical formula:
// Core variables:
// risk_amount = account_size * (risk_percentage / 100)
// total_risk_per_share = |entry_price - sl_price| + (entry_price * fee%) + (sl_price * fee%)
// shares = risk_amount / total_risk_per_share
// direction_factor = 1 for long positions, -1 for short positions
// Take-profit calculation:
net_win = total_risk_per_share * shares * RR_ratio
tp_price = (net_win + (direction_factor * entry_price * shares) + (entry_price * fee% * shares)) / (direction_factor * shares - fee% * shares)
Step-by-step example for a long position (based on screenshot):
Account Size: 2,000 USDT, Risk: 2% = 40 USDT
Entry: 102,062.9 USDT, Stop Loss: 102,178.4 USDT, Fee: 0.06%
Risk per share: |102,062.9 - 102,178.4| + (102,062.9 × 0.0006) + (102,178.4 × 0.0006) = 115.5 + 61.24 + 61.31 = 238.05 USDT
Shares: 40 ÷ 238.05 = 0.168 shares (rounded to 0.17 in display)
Position Size: 0.17 × 102,062.9 = 17,350.69 USDT
Position Amount (with 9x leverage): 17,350.69 ÷ 9 = 1,927.85 USDT
For 2:1 RR: Net win = 238.05 × 0.17 × 2 = 80.94 USDT
TP1 price = (80.94 + (1 × 102,062.9 × 0.17) + (102,062.9 × 0.0006 × 0.17)) ÷ (1 × 0.17 - 0.0006 × 0.17) = 101,464.7 USDT
For 3:1 RR: TP2 price = 101,226.7 USDT (following same formula with RR=3)
This ensures that after accounting for all fees, the actual risk-reward ratio matches the specified target ratio.
Risk Management Features
Maximum Trade Amount: Optional setting to limit position size regardless of account size
Leverage Limits: Built-in maximum leverage protection
Fee Integration: All calculations include realistic trading fees for accurate expectations
Validation: Automatic checking that take-profit portions sum to 100%
Historical Tracking: Visual indication when stop-loss or take-profit levels are reached (within last 5000 bars)
Understanding Max Trade Amount - Multiple Simultaneous Trades:
The "Max Trade Amount" feature is designed for traders who want to open multiple positions simultaneously while maintaining proper risk management. Here's how it works:
Key Concept:
- Risk percentage (2%) always applies to your full Account Size
- Max Trade Amount limits the capital allocated per individual trade
- This allows multiple trades with full risk on each trade
Example from Screenshot:
Account Size: 2,000 USDT
Max Trade Amount: 500 USDT
Risk per Trade: 2% × 2,000 = 40 USDT per trade
Stop Loss Distance: 0.11% from entry
Result: Position Size = 17,350.69 USDT with 35x leverage
Total Risk (including fees): 40.46 USDT
Multiple Trades Strategy:
With this setup, you can open:
Trade 1: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 2: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 3: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 4: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Total Portfolio Exposure:
- 4 simultaneous trades = 4 × 495.73 = 1,982.92 USDT position amount
- Total risk exposure = 4 × 40 = 160 USDT (8% of account)
PivotBoss VWAP Bands (Auto TF) - FixedWhat this indicator shows (high level)
The indicator plots a VWAP line and three bands above (R1, R2, R3) and three bands below (S1, S2, S3).
Band spacing is computed from STD(abs(VWAP − price), N) and multiplied by 1, 2 and 3 to form R1–R3 / S1–S3. The script is timeframe-aware: on 30m/1H charts it uses Weekly VWAP and weekly bands; on Daily charts it uses Monthly VWAP and monthly bands; otherwise it uses the session/chart VWAP.
VWAP = the market’s volume-weighted average price (a measure of fair value). Bands = volatility-scaled zones around that fair value.
Trading idea — concept summary
VWAP = fair value. Price above VWAP implies bullish bias; below VWAP implies bearish bias.
Bands = graded overbought/oversold zones. R1/S1 are near-term limits, R2/S2 are stronger, R3/S3 are extreme.
Use trend alignment + price action + volume to choose higher-probability trades. VWAP bands give location and magnitude; confirmations reduce false signals.
Entry rules (multiple strategies with examples)
A. Momentum breakout (trend-following) — preferred on trending markets
Setup: Price consolidates near or below R1 and then closes above R1 with above-average volume. Chart: 30m/1H (Weekly VWAP) or Daily (Monthly VWAP) depending on your timeframe.
Entry: Enter long at the close of the breakout bar that closes above R1.
Stop-loss: Place initial stop below the higher of (VWAP or recent swing low). Example: if price broke R1 at ₹1,200 and VWAP = ₹1,150, set stop at ₹1,145 (5 rupee buffer below VWAP) or below the last swing low if that is wider.
Target: Partial target at R2, full target at R3. Trail stop to VWAP or to R1 after price reaches R2.
Example numeric: Weekly VWAP = ₹1,150, R1 = ₹1,200, R2 = ₹1,260. Buy at ₹1,205 (close above R1), stop ₹1,145, target1 ₹1,260 (R2), target2 ₹1,320 (R3).
B. Mean-reversion fade near bands — for range-bound markets
Setup: Market is not trending (VWAP flatish). Price rallies up to R2 or R3 and shows rejection (pin bar, bearish engulfing) on increasing or neutral volume.
Entry: Enter short after a confirmed rejection candle that fails to sustain above R2 or R3 (prefer confirmation: close back below R1 or below the rejection candle low).
Stop-loss: Just above the recent high (e.g., 1–2 ATR or a fixed buffer above R2/R3).
Target: First target VWAP, second target S1. Reduce size if taking R3 fade as it’s an extreme.
Example numeric: VWAP = ₹950, R2 = ₹1,020. Price spikes to ₹1,025 and forms a bearish engulfing candle. Enter short at ₹1,015 after the next close below ₹1,020. Stop at ₹1,035, target VWAP ₹950.
C. Pullback entries in trending markets — higher probability
Setup: Price is above VWAP and trending higher (higher highs and higher lows). Price pulls back toward VWAP or S1 with decreasing downside volume and a reversal candle forms.
Entry: Long when price forms a bullish reversal (hammer/inside-bar) with a close back above the pullback candle.
Stop-loss: Below the pullback low (or below S2 if a larger stop is justified).
Target: VWAP then R1; if momentum resumes, trail toward R2/R3.
Example numeric: Price trending above Weekly VWAP at ₹1,400; pullback to S1 at ₹1,360. Enter long at ₹1,370 when a bullish candle closes; stop at ₹1,350; first target VWAP ₹1,400, second target R1 ₹1,450.
Exit rules and money management
Basic exit hierarchy
Hard stop exit — when price hits initial stop-loss. Always use.
Target exit — take partial profits at R1/R2 (for longs) or S1/S2 (for shorts). Use trailing stops for the remainder.
VWAP invalidation — if you entered long above VWAP and price returns and closes significantly below VWAP, consider exiting (condition depends on timeframe and trade size).
Price action exit — reversal patterns (strong opposite candle, bearish/bullish engulfing) near targets or beyond signals to exit.
Trailing rules
After price reaches R2, move stop to breakeven + a small buffer or to VWAP.
After price reaches R3, trail by 1 ATR or lock a defined profit percentage.
Position sizing & risk
Risk per trade: commonly 0.5–2% of account equity.
Determine position size by RiskAmount ÷ (EntryPrice − StopPrice).
If the stop distance is large (e.g., trading R3 fades), reduce position size.
Filters & confirmation (to reduce false signals)
Volume filter: For breakouts, require volume above short-term average (e.g., >20-period average). Breakouts on low volume are suspect.
Trend filter: Only take breakouts in the direction of the higher-timeframe trend (for example, use Daily/Weekly trend when trading 30m/1H).
Candle confirmation: Prefer entries on close of the confirming candle (not intrabar noise).
Multiple confirmations: When R1 break happens but RSI/plotted momentum indicator does not confirm, treat signal as lower probability.
Special considerations for timeframe-aware logic
On 30m/1H the script uses Weekly VWAP/bands. That means band levels change only on weekly candles — they are strong, structural levels. Treat R1/R2/R3 as significant and expect fewer, stronger signals.
On Daily, the script uses Monthly VWAP/bands. These are wider; trades should allow larger stops and smaller position sizes (or be used for swing trades).
On other intraday charts you get session VWAP (useful for intraday scalps).
Example: If you trade 1H and the Weekly R1 is at ₹2,400 while session VWAP is ₹2,350, a close above Weekly R1 represents a weekly-level breakout — prefer that for swing entries rather than scalps.
Example trade walkthrough (step-by-step)
Context: 1H chart, auto-mapped → Weekly VWAP used.
Weekly VWAP = ₹3,000; R1 = ₹3,080; R2 = ₹3,150.
Price consolidates below R1. A large bullish candle closes at ₹3,085 with volume 40% above the 20-bar average.
Entry: Buy at close ₹3,085.
Stop: Place stop at ₹2,995 (just under Weekly VWAP). Risk = ₹90.
Position size: If risking ₹900 per trade → size = 900 ÷ 90 = 10 units.
Targets: Partial take-profit at R2 = ₹3,150; rest trailed with stop moved to breakeven after R2 is hit.
If price reverses and closes below VWAP within two bars, exit immediately to limit drawdown.
When to avoid trading these signals
High-impact news (earnings, macro announcements) that can gap through bands unpredictably.
Thin markets with low volume — VWAP loses significance when volumes are extremely low.
When weekly/monthly bands are flat but intraday price is volatile without clear structure — prefer session VWAP on smaller timeframes.
Alerts & automation suggestions
Alert on close above R1 / below S1 (use the built-in alertcondition the script adds). For higher-confidence alerts, require volume filter in the alert condition.
Automated order rules (if you automate): use limit entry at breakout close plus a small slippage buffer, immediate stop order, and OCO for TP and SL.
AI Strat ATR Dinamico + ADX + Trend Adaptivo (No Repaint)Below is a fully self-contained, English-language description of every input, function, and logical block inside the “AI Strat ATR Dinamico + ADX + Trend Adaptivo (No Repaint)” indicator. You can copy and paste this into TradingView’s “Description” field when you publish, without exposing any Pine code.
---
## Indicator Name and Purpose
**Name (Short Title):**
AI Strat Adaptive v3 (NoRepaint)
**Overview:**
This indicator combines multiple technical tools—RSI, EMA, ATR (with a dynamic multiplier), ADX/DI, and an “AI‐style” scoring mechanism—to generate trend-filtered and reversal signals. It also optionally confirms signals on a higher timeframe, dynamically adjusts its sensitivity based on volatility, and plots intrabar stop‐loss (SL) and take‐profit (TP) levels derived from ATR. Special care has been taken to ensure that no signals “repaint” (i.e., once drawn on a closed bar, they never disappear or shift).
---
## 1. Main Inputs
All of the inputs appear in the Settings dialog for the published indicator. Below is a detailed explanation of each input, grouped by logical category.
### A. RSI & EMA Base Parameters
1. **RSI Length (Base)**
* **Input type:** Integer (default 14)
* **Description:** Number of bars used to calculate the Relative Strength Index (RSI). A shorter RSI reacts more quickly to price changes; a longer RSI is smoother.
2. **RSI Overbought Threshold**
* **Input type:** Integer (default 60)
* **Description:** If the RSI value rises above this level, it contributes a “sell” signal component. You can adjust this (e.g., 70) to make your system more conservative.
3. **RSI Oversold Threshold**
* **Input type:** Integer (default 40)
* **Description:** If the RSI falls below this level, it contributes a “buy” signal component. Raising this threshold (e.g., 50) makes the strategy more aggressive in seeking reversals.
4. **EMA Length (Base)**
* **Input type:** Integer (default 20)
* **Description:** Number of bars for the Exponential Moving Average (EMA). A shorter EMA will produce more frequent crossovers, a longer EMA is smoother.
### B. ATR & Volatility Filter Parameters
5. **ATR Length (Base)**
* **Input type:** Integer (default 14)
* **Description:** Number of bars to calculate Average True Range (ATR). The ATR is used both for measuring volatility and for dynamic SL/TP levels.
6. **ATR SMA Length**
* **Input type:** Integer (default 50)
* **Description:** Number of bars to compute a Simple Moving Average of the ATR itself. This gives a baseline of “normal” volatility. If ATR rises significantly above this SMA, the indicator treats the market as “high volatility.”
7. **ATR Multiplier Base**
* **Input type:** Float (default 1.2, step 0.1)
* **Description:** Base multiplier for ATR when filtering for volatility. The actual threshold is computed as `ATR_SMA × (ATR_Multiplier Base) × sqrt(current_ATR / ATR_SMA)`. In other words, the multiplier becomes larger if volatility is rising, and smaller if volatility is falling.
8. **Disable Volatility Filter**
* **Input type:** Boolean (default false)
* **Description:** If enabled (true), the indicator will ignore any volatility‐based filtering, using signals regardless of ATR behavior. If disabled (false), signals only fire when ATR > (ATR\_SMA × dynamic multiplier).
### C. Price-Change & “AI Score” Parameters
9. **Price Change Period (bars)**
* **Input type:** Integer (default 3)
* **Description:** The number of bars back to measure percentage price change. Used to ensure that a “trend” signal is accompanied by a sufficiently positive (for longs) or negative (for shorts) price movement over this many bars.
10. **Base AI Score Threshold**
* **Input type:** Float (default 0.1)
* **Description:** The indicator computes a composite “AI-style” score by combining the RSI signal (overbought/oversold) and an EMA crossover signal. Only if the absolute value of that composite score exceeds this threshold will a trend signal be eligible. Raising it makes signals rarer but (potentially) higher-conviction.
### D. SMA “ICT” Trend Filter Parameters
11. **ICT SMA Long Length (Base)**
* **Input type:** Integer (default 50)
* **Description:** Number of bars for the “long” Simple Moving Average (SMA) used in the internal trend filter. Typically, price must be above this SMA (and ADX must be strong) to confirm an uptrend, or below it (and ADX strong) to confirm a downtrend.
12. **ICT SMA Short1 Length (Base)**
* **Input type:** Integer (default 10)
* **Description:** Secondary “fast” SMA used both for reversal logic (e.g., price crossing above it can count as a bullish reversal) and part of the internal trend confirmation.
13. **ICT SMA Short2 Length (Base)**
* **Input type:** Integer (default 20)
* **Description:** A second “medium” SMA used for reversal triggers (e.g., crossovers or crossunders alongside RSI conditions).
### E. ADX & DI Parameters
14. **Base ADX Length**
* **Input type:** Integer (default 14)
* **Description:** Number of bars for the ADX (Average Directional Index) moving averages, which measure trend strength. The same length is used for +DI and –DI smoothing.
15. **Base ADX Threshold**
* **Input type:** Float (default 25.0, step 0.5)
* **Description:** If ADX > this threshold and +DI > –DI, we consider an uptrend; if ADX > this threshold and –DI > +DI, we consider a downtrend. Raising this value demands stronger trends to qualify.
### F. Sensitivity & Cooldown
16. **Sensitivity (0–1)**
* **Input type:** Float between 0.0 and 1.0 (default 0.5)
* **Description:** A general “mixture” parameter used internally to weight how aggressively the indicator leans into trend versus reversal. In practice, the code uses it to fine-tune exact thresholds for switching between trend and reversal conditions. You can leave it at 0.5 unless you want to bias more heavily toward either regime.
17. **Base Cooldown Bars Between Signals**
* **Input type:** Integer (default 5, min 0)
* **Description:** Once a long or short signal fires, the indicator will wait at least this many bars before allowing a new signal in the same direction. Prevents “signal flipping” on each bar. A higher number forces fewer, more spaced-out entries.
18. **Trend Confirmation Bars**
* **Input type:** Integer (default 3, min 1)
* **Description:** After the directional filters (+DI/–DI cross, price vs. SMA), the indicator still requires that price remains on the same side of the long SMA for at least this many consecutive bars before confirming “trend up” or “trend down.” Larger values smooth out false breakouts but may lag signals.
### G. Higher Timeframe Confirmation
19. **Use Higher Timeframe Confirmation**
* **Input type:** Boolean (default true)
* **Description:** If true, the indicator will request a block of values (SMA, +DI, –DI, ADX) from a higher timeframe (default 60 minutes) and require that the higher timeframe is also in agreement (strong uptrend or strong downtrend) before confirming your current-timeframe trend. This helps filter out lower-timeframe noise.
20. **Higher Timeframe (TF) for Confirmation**
* **Input type:** Timeframe (default “60”)
* **Description:** The chart timeframe (e.g., 5, 15, 60 minutes) whose trend conditions must also be true. It’s sent through a `request.security(..., lookahead=barmerge.lookahead_off)` call so that it never “paints ahead.”
### H. Dynamic TP/SL Parameters
21. **TP as ATR Multiple**
* **Input type:** Float (default 2.0, step 0.1)
* **Description:** When a trade is open, the “take-profit” price is determined by looking at the highest high (for longs) or lowest low (for shorts) observed since entry, and then plotting a cross (“X”) at that level when the trend finally flips. This is purely for display. However, separate from that, this parameter can be adapted if you want a strictly ATR–based TP. In the “Minimal” version, TP is ≈ (highest high) once trend inverts, but you could rewrite it to use `entry_price + ATR×TP_Multiplier`.
22. **SL as ATR Multiple**
* **Input type:** Float (default 1.0, step 0.1)
* **Description:** While in a trade, a trailing SL line is plotted each bar. Its value is always `entry_price ± (ATR × SL_Multiplier)`. When the trend inverts, the SL no longer updates, and you see it on the chart.
### I. Display and Mode Options
23. **Show Debug Lines**
* **Input type:** Boolean (default true)
* **Description:** When enabled, the indicator will plot all intermediate lines—ATR SMA, ATR Threshold, +DI, –DI, ADX (current and HTF), HTF SMA, etc.—so that you can diagnose exactly what’s happening. Turn this off to hide all debug information and only see entry/exit shapes.
24. **Enable Scalping Mode**
* **Input type:** Boolean (default false)
* **Description:** If true, many of the “base” parameters are halved (e.g., RSI length becomes 7 instead of 14, ATR length becomes 7 instead of 14, ADX length becomes 7, etc.), and the ADX threshold is multiplied by 0.8. This makes all oscillators and moving averages more reactive, suited for very short-term (scalping) setups.
---
## 2. Core Calculation Blocks
Below is a high-level description of each logical block (in code order), translated from Pine into conceptual steps.
### A. Adjust Inputs if “Scalping Mode” Is On
If **Scalping Mode** = true, then:
* `RSI_Length` becomes `max(1, round(Base_RSI_Length / 2))`
* `EMA_Length` becomes `max(1, round(Base_EMA_Length / 2))`
* `ATR_Length` becomes `max(1, round(Base_ATR_Length / 2))`
* `Price_Change_Period` becomes `max(1, round(Base_Price_Change_Period / 2))`
* `SMA_Long_Length`, `SMA_Short1_Length`, and `SMA_Short2_Length` are each halved (minimum 1).
* `ADX_Length` = `max(1, round(Base_ADX_Length / 2))`
* `ADX_Threshold` = `Base_ADX_Threshold × 0.8`
* `Cooldown_Bars` = `max(0, round(Base_Cooldown_Bars / 2))`
Otherwise, all adjusted lengths = their base values.
### B. RSI, EMA & “AI Score” on Current Timeframe
1. **Compute RSI:**
* Uses the (possibly adjusted) `RSI_Length`.
* Denote this as `RSI_Value`.
2. **Compute ATR & Its SMA:**
* `ATR_Value` = `ta.atr(ATR_Length)`.
* `ATR_SMA` = `ta.sma(ATR_Value, ATR_SMA_Length)`.
* Then define `Volatility_Increase` = (`ATR_Value > ATR_SMA`).
* If the volatility has increased, the weighting of RSI vs. EMA changes.
3. **Compute Weights:**
* If `Volatility_Increase == true`, then:
* `RSI_Weight = 0.7`
* `EMA_Weight = 0.3`
* Otherwise:
* `RSI_Weight = 0.3`
* `EMA_Weight = 0.7`
4. **RSI Signal Component (`RSI_Sig`):**
* If `RSI_Value > RSI_Overbought`, then `RSI_Sig = –1`.
* Else if `RSI_Value < RSI_Oversold`, then `RSI_Sig = +1`.
* Otherwise, `RSI_Sig = 0`.
5. **EMA Value & Signal Component (`EMA_Sig`):**
* `EMA_Value` = `ta.ema(close, EMA_Length)`.
* `EMA_Sig = +1` if the current close crosses **above** the EMA; `EMA_Sig = –1` if the current close crosses **below** the EMA; else `0`.
6. **Compute Raw “AI Score”:**
$$
Raw\_AI = (RSI\_Sig \times RSI\_Weight)\;+\;(EMA\_Sig \times EMA\_Weight)
$$
Then,
$$
AI\_Score = \frac{Raw\_AI}{(RSI\_Weight + EMA\_Weight)}
$$
(This normalization ensures the score always ranges between –1 and +1 if both weights sum to 1.)
### C. Dynamic ATR Multiplier & Volatility Filter
1. **Volatility Factor:**
$$
Volatility\_Factor = \frac{ATR\_Value}{ATR\_SMA}
$$
2. **Dynamic ATR Multiplier:**
$$
ATR\_Multiplier = ATR\_Multiplier\_Base \times \sqrt{Volatility\_Factor}
$$
3. **High Volatility Condition (`High_Volatility`):**
* If `Disable_Volatility_Filter == true`, then treat `High_Volatility = true` always.
* Else, `High_Volatility = (ATR_Value > ATR_SMA × ATR_Multiplier)`.
### D. Price Change Percentage
* **Compute Price Change:**
$$
Price\_Change = \frac{(Close - Close )}{Close } \times 100
$$
* This is the percent return from `Price_Change_Period` bars ago to now.
* For a valid long‐trend signal, we require `Price_Change > 0`; for a short trend, `Price_Change < 0`.
### E. Local SMAs for Trend/Reversal Filters
* `SMA_Close_Long` = `ta.sma(close, SMA_Long_Length)`.
* `SMA_Close_Short1` = `ta.sma(close, SMA_Short1_Length)`.
* `SMA_Close_Short2` = `ta.sma(close, SMA_Short2_Length)`.
These three SMAs help define the “local trend” and reversal breakout points:
* **Primary Trend Filter:**
* Price must be above `SMA_Close_Long` for an uptrend filter, or below `SMA_Close_Long` for a downtrend filter.
* **Reversal Filter:**
* A bullish reversal is detected if **(RSI < Oversold AND close crosses above EMA)** OR **(RSI < Oversold AND close crosses above SMA\_Close\_Short1)**.
* A bearish reversal is detected if **(RSI > Overbought AND close crosses below EMA)** OR **(RSI > Overbought AND close crosses below SMA\_Close\_Short1)**.
### F. Manual +DI, –DI & ADX on Current Timeframe
Instead of relying on the built-in `ta.adx`, the script calculates DI and ADX manually. This makes it easier to replicate the exact logic on a higher timeframe via `request.security`. The steps are:
1. **Directional Movement (DM) Components:**
* `Up_Move` = `high – high `
* `Down_Move` = `low – low`
* `Plus_DM` = `Up_Move` if (`Up_Move > Down_Move` AND `Up_Move > 0`), else `0`
* `Minus_DM` = `Down_Move` if (`Down_Move > Up_Move` AND `Down_Move > 0`), else `0`
2. **True Range (TR) Components:**
* `TR1` = `high – low`
* `TR2` = `abs(high – close )`
* `TR3` = `abs(low – close )`
* `True_Range` = `max(TR1, TR2, TR3)`
3. **Smoothed Averages (RMA):**
* `Sm_TR` = `ta.rma(True_Range, ADX_Length)`
* `Sm_Plus` = `ta.rma(Plus_DM, ADX_Length)`
* `Sm_Minus`= `ta.rma(Minus_DM, ADX_Length)`
4. **Compute DI%:**
$$
Plus\_DI = \frac{Sm\_Plus}{Sm\_TR} \times 100,\quad
Minus\_DI = \frac{Sm\_Minus}{Sm\_TR} \times 100
$$
5. **DX and ADX:**
$$
DX = \frac{|Plus\_DI - Minus\_DI|}{Plus\_DI + Minus\_DI} \times 100,\quad
ADX = ta.rma(DX, ADX_Length)
$$
These values are referred to as `(plus_di, minus_di, adx_val)` for the current timeframe.
---
## 3. Higher Timeframe (HTF) Confirmation Function
If **Use Higher Timeframe Confirmation** is enabled, the script calls a single helper (Pine) function `f_htf` with two parameters: the ADX length and the SMA length (both taken from the “base” or “scaled” values). Internally, `f_htf` simply reruns the manual DI/ADX logic (same as above) on the higher timeframe’s bar data, and also includes that timeframe’s closing price and its SMA for trend comparison.
* **Request.Security Call:**
```
= request.security(
syminfo.tickerid,
higher_tf,
f_htf(adx_length, sma_long_len),
lookahead=barmerge.lookahead_off
)
```
* `lookahead=barmerge.lookahead_off` ensures that no HTF value “paints” early; you always see only confirmed HTF bars.
* The returned tuple provides:
1. `ht_close` = HTF closing price
2. `ht_sma` = HTF SMA of length `sma_long_len`
3. `ht_pdi` = HTF +DI percentage
4. `ht_mdi` = HTF –DI percentage
5. `ht_adx` = HTF ADX value
---
## 4. Trend & Reversal Filters (Current & HTF)
### A. Current-Timeframe Trend Filter
1. **Uptrend\_Basic (Current TF)**
$$
(plus\_di > minus\_di)\;\land\;(adx\_val > ADX\_Threshold)\;\land\;(close > SMA\_Close\_Long)
$$
2. **Downtrend\_Basic (Current TF)**
$$
(minus\_di > plus\_di)\;\land\;(adx\_val > ADX\_Threshold)\;\land\;(close < SMA\_Close\_Long)
$$
3. **Trend Confirmation by Bars:**
* `Bars_Since_Below` = number of bars since `close <= SMA_Close_Long`.
* `Bars_Since_Above` = number of bars since `close >= SMA_Close_Long`.
* If `Uptrend_Basic == true` AND `Bars_Since_Below ≥ Trend_Confirmation_Bars` → mark `Uptrend_Confirm = true`.
* If `Downtrend_Basic == true` AND `Bars_Since_Above ≥ Trend_Confirmation_Bars` → mark `Downtrend_Confirm = true`.
### B. Reversal Filters (Current TF)
1. **Bullish Reversal (`Rev_Bullish`):**
* If `(RSI < RSI_Oversold AND close crosses above EMA_Value)` OR
`(RSI < RSI_Oversold AND close crosses above SMA_Close_Short1)`
→ then `Rev_Bullish = true`.
2. **Bearish Reversal (`Rev_Bearish`):**
* If `(RSI > RSI_Overbought AND close crosses below EMA_Value)` OR
`(RSI > RSI_Overbought AND close crosses below SMA_Close_Short1)`
→ then `Rev_Bearish = true`.
### C. Higher-Timeframe Trend Filter (HTF)
1. **HTF Uptrend (`HT_Uptrend`):**
$$
(ht\_pdi > ht\_mdi)\;\land\;(ht\_adx > ADX\_Threshold)\;\land\;(ht\_close > ht\_sma)
$$
2. **HTF Downtrend (`HT_Downtrend`):**
$$
(ht\_mdi > ht\_pdi)\;\land\;(ht\_adx > ADX\_Threshold)\;\land\;(ht\_close < ht\_sma)
$$
3. **Combine Current & HTF:**
* If **Use\_HTF\_Confirmation == true**, then:
* `Uptrend_Confirm := Uptrend_Confirm AND HT_Uptrend`
* `Downtrend_Confirm := Downtrend_Confirm AND HT_Downtrend`
* Otherwise, just use the current timeframe’s `Uptrend_Confirm` and `Downtrend_Confirm`.
4. **Define `CurrentTrend` (Integer):**
* `CurrentTrend = +1` if `Uptrend_Confirm == true`.
* `CurrentTrend = –1` if `Downtrend_Confirm == true`.
* Otherwise, `CurrentTrend = 0`.
5. **Reset “One Trade Per Trend”:**
* There is a persistent variable `LastTradeTrend`.
* Every time `CurrentTrend` flips (i.e., `CurrentTrend != CurrentTrend `), the code sets `LastTradeTrend := 0`.
* That allows one new entry once the detected trend has changed.
---
## 5. One‐Time “Cooldown” Logic
* **`LastSignalBar`**
* A persistent integer (initially undefined).
* After each confirmed long or short entry, `LastSignalBar` is set to the bar index where that signal fired.
* **`Bars_Since_Signal`**
* If `LastSignalBar` is undefined, treat as a very large number (so that initial signals are always allowed).
* Otherwise, `Bars_Since_Signal = bar_index – LastSignalBar`.
* **Cooldown Check:**
* A new long (or short) can only be generated if `(Bars_Since_Signal > Signal_Cooldown)`.
* This prevents multiple signals in rapid succession.
---
## 6. Entry Conditions (No Repaint)
All of the conditions below are calculated “intrabar,” but the script only actually registers a **signal** on **bar close** (`barstate.isconfirmed`) so that signals never repaint.
### A. Trend‐Based “Raw” Conditions
1. **Trend\_Long\_Raw:**
$$
(AI\_Score > AI\_Score\_Threshold)\;\land\;Uptrend\_Confirm\;\land\;High\_Volatility\;\land\;(Price\_Change > 0)
$$
2. **Trend\_Short\_Raw:**
$$
(AI\_Score < -AI\_Score\_Threshold)\;\land\;Downtrend\_Confirm\;\land\;High\_Volatility\;\land\;(Price\_Change < 0)
$$
### B. Reversal “Raw” Conditions
1. **Rev\_Long\_Raw:**
$$
Rev\_Bullish\;\land\;(CurrentTrend \neq +1)
$$
2. **Rev\_Short\_Raw:**
$$
Rev\_Bearish\;\land\;(CurrentTrend \neq -1)
$$
### C. Combine Raw Signals
* `Raw_Long = Trend_Long_Raw OR Rev_Long_Raw`.
* `Raw_Short = Trend_Short_Raw OR Rev_Short_Raw`.
### D. Confirmed Long/Short Signal Flags
On each new bar **close** (`barstate.isconfirmed == true`):
* **Long\_Signal\_Confirmed** can fire if:
1. `Raw_Long == true`
2. `LastTradeTrend != +1` (we haven’t already taken a long in this same trend)
3. `Bars_Since_Signal > Signal_Cooldown`
If all three hold, then on this bar close the code sets:
* `Long_Signal = true`
* `LastTradeTrend := +1`
* `LastSignalBar := bar_index`
Otherwise, `Long_Signal := false` on this bar.
* **Short\_Signal\_Confirmed** works the same way but with `Raw_Short`, `LastTradeTrend != -1`, etc.
If triggered, it sets `Short_Signal = true`, `LastTradeTrend := -1`, and `LastSignalBar := bar_index`. Otherwise `Short_Signal := false`.
* **Important:** If the bar is still forming (`else` branch of `barstate.isconfirmed`), then both `Long_Signal` and `Short_Signal` are forced to `false`. This guarantees that no shape or alert appears until the bar actually closes.
---
## 7. Plotting Entry/Exit Shapes
1. **Trend Long Signal (Triangle Up)**
* Condition: `Long_Signal == true` **AND** `Trend_Long_Raw == true`.
* Appearance: A small, semi-transparent lime green triangle drawn **below** the bar.
2. **Trend Short Signal (Triangle Down)**
* Condition: `Short_Signal == true` **AND** `Trend_Short_Raw == true`.
* Appearance: A small, semi-transparent maroon triangle drawn **above** the bar.
3. **Reversal Long Signal (Circle)**
* Condition: `Long_Signal == true` **AND** `Rev_Long_Raw == true`.
* Appearance: A tiny, more transparent green circle drawn **below** the bar.
4. **Reversal Short Signal (Circle)**
* Condition: `Short_Signal == true` **AND** `Rev_Short_Raw == true`.
* Appearance: A tiny, more transparent red circle drawn **above** the bar.
Since `Long_Signal` and `Short_Signal` only ever become true at bar close, these shapes are never repainted or removed once drawn.
---
## 8. Unified Alert Message
* As soon as a new bar closes with either `Long_Signal` or `Short_Signal == true`, an alert message is sent:
* If `Long_Signal`, then `alert_msg = "action=BUY"`.
* If `Short_Signal`, then `alert_msg = "action=SELL"`.
* If neither, `alert_msg = ""` (no alert).
* The code calls `alert(alert_msg, freq=alert.freq_once_per_bar)` only if `barstate.isconfirmed` and `alert_msg` is non‐empty. This ensures exactly one alert per confirmed bar, no intrabar pops.
---
## 9. Dynamic TP/SL Logic (Minimal Implementation)
Once a long or short position is “open,” the script tracks these variables:
1. **Persistent Flags and Prices** (all persist between bars until reset):
* `InLong` (Boolean)
* `InShort` (Boolean)
* `Long_Max` (Float)
* `Short_Min` (Float)
* `Entry_Price` (Float)
2. **On Bar Close:**
* If `Long_Signal == true` →
* Set `InLong := true`,
* `Entry_Price := close` of that bar,
* `Long_Max := high ` (last bar’s high, so that we’re not using “future” data).
* If `Short_Signal == true` →
* Set `InShort := true`,
* `Entry_Price := close`,
* `Short_Min := low `.
3. **While `InLong == true`:**
* Continuously update `Long_Max = max(Long_Max, current high)` on each bar (intrabar, but finalized each close).
* Compute a dynamic SL:
$$
SL_{Long} = Entry\_Price - (ATR \times SL\_ATR\_Multiplier).
$$
* If **current trend** flips to non-uptrend (`CurrentTrend != +1`), mark `ExitLong = true`.
* Then the routine plots `TP_Long = Long_Max` as a cross (“X”) at that level.
* Set `InLong := false` so that no further changes to `Long_Max` or `Entry_Price` happen on future bars.
4. **While `InShort == true`:**
* Continuously update `Short_Min = min(Short_Min, current low)`.
* Compute a dynamic SL:
$$
SL_{Short} = Entry\_Price + (ATR \times SL\_ATR\_Multiplier).
$$
* If trend flips to non-downtrend (`CurrentTrend != –1`), mark `ExitShort = true`.
* Then the routine plots `TP_Short = Short_Min`.
* Set `InShort := false` to freeze those values.
5. **Plotting TP/SL if “Show Debug” is On:**
* **TP Shapes:**
* When `ExitLong == true`, plot a solid lime “X” at `TP_Long` (highest high).
* When `ExitShort == true`, plot a solid maroon “X” at `TP_Short` (lowest low).
* **SL Lines:**
* If still `InLong`, draw a thin red line at `SL_Long` on each bar.
* If still `InShort`, draw a thin green line at `SL_Short`.
Thus, your charts visually show the highest‐high take-profit cross for longs, the lowest-low take-profit cross for shorts, and a continuously updating trailing SL until the trend flips. Because all of this is triggered on confirmed bars, nothing “jumps around” after the fact.
---
## 10. Debug‐Only Plot Lines (When Enabled)
When **Show Debug Lines** = true, the indicator will also plot:
1. **ATR SMA (Orange):**
* The simple moving average of ATR over `ATR_SMA_Length`.
2. **ATR Threshold (Yellow):**
* `ATR_SMA × ATR_Multiplier` (the dynamically scaled threshold).
3. **+DI & –DI (Current TF):**
* +DI plotted as a green line, –DI plotted as a red line (opacity \~70%).
4. **ADX (Current TF, Blue):**
* A blue line for the present timeframe’s ADX.
5. **ADX Threshold (Gray):**
* A horizontal gray line showing `ADX_Threshold`.
6. **+DI & –DI (HTF, Darker Colors):**
* If HTF confirmation is on, “HTF +DI” is a greener but more transparent line; “HTF –DI” is a redder but more transparent line.
7. **ADX (HTF, Blue but Transparent):**
* HTF ADX plotted in blue (high transparency).
8. **HTF SMA (Orange, Transparent):**
* The higher timeframe’s SMA (same length as `SMA_Long_Length`), drawn in fainter orange.
9. **Volatility Zone Fill (Yellow Tinted Area):**
* Fills the area between `ATR_SMA` and `ATR_SMA × ATR_Multiplier`.
* Indicates “normal” versus “high‐volatility” regimes.
These debug lines are purely visual aids. Disable them if you want a cleaner chart.
---
## 11. Putting It All Together — Step-By-Step Flow
1. **Read Inputs** (RSI lengths, EMA length, ATR settings, etc.).
2. **Optionally Halve All Lengths** if “Scalping Mode” is checked.
3. **Calculate Current TF Indicators:**
* RSI, ATR, ATR\_SMA, EMA, price change, various SMAs, DI/ADX.
4. **Compute “AI Score”** (weighted sum of RSI and EMA signals).
5. **Compute Dynamic ATR Multiplier** and decide if “High Volatility” is true.
6. **Compute Raw Trend/Reversal Conditions** on the current timeframe (without triggering yet).
7. **Fetch HTF Values** in one `request.security` call (SMAs, DI/ADX).
8. **Combine Current & HTF Trend Filters** to confirm `Uptrend_Confirm` or `Downtrend_Confirm`.
9. **Check Reversal Conditions** (price crossing EMA or SMA short, in overbought/oversold zones).
10. **Enforce “One Trade Per Trend”** (clear `LastTradeTrend` whenever `CurrentTrend` flips).
11. **Enforce Cooldown** (must wait at least `Signal_Cooldown` bars since the prior signal).
12. **On Bar Close:**
* If `Raw_Long` AND not already in a long trend AND cooldown met, then fire `Long_Signal`.
* Else if `Raw_Short` AND not already in a short trend AND cooldown met, then fire `Short_Signal`.
* Otherwise, no new signal on this bar.
13. **Plot Long/Short Entry Shapes** according to whether it was a Trend signal or a Reversal signal.
14. **Send Alert** (“action=BUY” or “action=SELL”) exactly once per confirmed bar.
15. **If New Long/Short Signal, Set `InLong`/`InShort`, Record Entry Price, Initialize `Long_Max`/`Short_Min`.**
16. **While `InLong` is true:** Update `Long_Max = max(previous Long_Max, current high)`. Compute `SL_Long`. If the current trend flips (no longer uptrend), set `ExitLong = true`, plot a “TP X,” and close the position logic.
17. **While `InShort` is true:** Similarly update `Short_Min`, compute `SL_Short`, and if trend flips, set `ExitShort = true`, plot a “TP X,” and close the position logic.
18. **Optionally Display Debug Lines** (ATR SMA, ATR threshold, DI/ADX, HTF DI/ADX, etc.).
---
## 12. How to Use in TradingView Community
When you publish this indicator to the TradingView community—choosing “Protected” or “Invite-only” visibility—you can paste the above description into the “Description” field. Users will see exactly what each input does, how signals are generated, and what the various plotted lines represent, **without ever seeing the script source**. In this way, the code itself remains hidden but the logic is fully documented.
1. **Go to “Create New Indicator”** on TradingView.
2. **Paste Your Pine Code** (the full indicator script) in the Pine editor and save it.
3. **Set Visibility = Protected** (or Invite-only).
4. **In the “Description” Text Box, paste the entirety of this document** (steps 1–11).
5. **Click “Publish Script.”**
Users who view your indicator will see its name (“AI Strat Adaptive v3 (NoRepaint)”), a list of all inputs (with default values), and the detailed English description above. They can then load it on any chart, adjust inputs, and see the plotted signals, TP/SL lines, and optional debug overlays—without accessing the underlying Pine code.
---
### Summary of Key Points
* **RSI, EMA, ATR, DI/ADX, and “AI Score”** work together to define “trend vs. reversal.”
* **Dynamic volatility filter** uses ATR and ATR\_SMA to adapt the weighting of RSI vs. EMA and decide whether “volatility is high enough” to permit a trend trade.
* **One trade per detected trend** and a **cooldown period** prevent over‐trading.
* **Higher timeframe confirmation** (optional) further filters out noise.
* **No-repaint logic**:
* All signals only appear at bar close (`barstate.isconfirmed`).
* HTF values are fetched with `lookahead=barmerge.lookahead_off`.
* **Entry shapes** (triangles and circles) clearly mark trend vs. reversal entries.
* **Dynamic TP/SL**: highest‐high (or lowest‐low) since entry is used as TP, ATR×multiplier as SL.
* **Debug mode** (optional) shows every intermediate line for full transparency.
Use this description verbatim (or adapt it slightly for your personal style) when publishing. That way, your community sees exactly how each component works—inputs, functions, filters—while the Pine source code remains private.
P6●智能资金概念交易系统//@version=5
indicator("P6●智能资金概念交易系统", overlay=true, max_boxes_count = 500, max_labels_count = 500)
// === 参数分类标题 ===
// --------------------------
// 1. 基础指标设置
// --------------------------
// 2. 范围过滤器 设置
// --------------------------
// 3. ADX 趋势过滤器 设置
// --------------------------
// 4. 趋势线 设置
// --------------------------
// 5. 支撑与阻力 设置
// --------------------------
// 6. PMA 设置
// --------------------------
// 7. 交易信息表格 设置
// --------------------------
// 8. 顶部规避 设置
// --------------------------
// 9. 底部规避 设置
// --------------------------
// 10. RSI 动量指标 设置
// --------------------------
// 11. 多时间框架 设置
// --------------------------
// === 显示/隐藏选项 ===
showRangeFilter = input.bool(true, title="显示 范围过滤器", group="1. 基础指标设置")
showADXFilter = input.bool(true, title="启用 ADX 趋势过滤器", group="1. 基础指标设置")
showTrendLines = input.bool(false, title="显示 趋势线", group="1. 基础指标设置")
showSupRes = input.bool(true, title="显示 支撑与阻力", group="1. 基础指标设置")
showPMA = input.bool(true, title="显示 多周期移动平均线", group="1. 基础指标设置")
showTable = input.bool(true, title="显示 交易信息表格", group="1. 基础指标设置")
showTopAvoidance = input.bool(false, title="启用 顶部规避系统", group="1. 基础指标设置")
showBottomAvoidance = input.bool(false, title="启用 底部规避系统", group="1. 基础指标设置")
showRSI = input.bool(false, title="启用 RSI 动量指标", group="1. 基础指标设置")
showMTF = input.bool(true, title="启用 多时间框架分析", group="1. 基础指标设置")
// === RSI 动量指标 设置 ===
rsiLength = input.int(14, title="RSI 周期", minval=1, group="10. RSI 动量指标 设置")
rsiOverbought = input.float(70.0, title="超买阈值", minval=50, maxval=90, step=1, group="10. RSI 动量指标 设置")
rsiOversold = input.float(30.0, title="超卖阈值", minval=10, maxval=50, step=1, group="10. RSI 动量指标 设置")
rsiNeutralUpper = input.float(60.0, title="中性区间上沿", minval=50, maxval=70, step=1, group="10. RSI 动量指标 设置")
rsiNeutralLower = input.float(40.0, title="中性区间下沿", minval=30, maxval=50, step=1, group="10. RSI 动量指标 设置")
// === 多时间框架设置 ===
mtfEnable1m = input.bool(true, title="启用 1分钟", group="11. 多时间框架 设置")
mtfEnable5m = input.bool(true, title="启用 5分钟", group="11. 多时间框架 设置")
mtfEnable15m = input.bool(true, title="启用 15分钟", group="11. 多时间框架 设置")
mtfEnable1h = input.bool(true, title="启用 1小时", group="11. 多时间框架 设置")
mtfEnable4h = input.bool(true, title="启用 4小时", group="11. 多时间框架 设置")
// === RSI 计算与状态判断 ===
rsiValue = ta.rsi(close, rsiLength)
rsiPrevious = ta.rsi(close , rsiLength)
// RSI 动量状态判断
getRSIStatus() =>
status = "动量中性"
// 动量回落条件:RSI从高位下降或处于下降趋势
fallCondition1 = rsiValue < rsiPrevious and rsiValue > rsiNeutralUpper
fallCondition2 = rsiValue >= rsiOverbought and rsiValue < rsiPrevious
fallCondition3 = rsiPrevious >= rsiOverbought and rsiValue < rsiOverbought and rsiValue < rsiPrevious
if fallCondition1 or fallCondition2 or fallCondition3
status := "动量回落"
// 动量回升条件:RSI从低位上升或处于上升趋势
riseCondition1 = rsiValue > rsiPrevious and rsiValue < rsiNeutralLower
riseCondition2 = rsiValue <= rsiOversold and rsiValue > rsiPrevious
riseCondition3 = rsiPrevious <= rsiOversold and rsiValue > rsiOversold and rsiValue > rsiPrevious
if riseCondition1 or riseCondition2 or riseCondition3
status := "动量回升"
// 动量中性条件:RSI在中性区间或无明确趋势
if rsiValue >= rsiNeutralLower and rsiValue <= rsiNeutralUpper
status := "动量中性"
status
rsiStatus = getRSIStatus()
// RSI 信号与其他指标结合
rsiSupportsBuy = rsiStatus == "动量回升" or (rsiValue <= rsiOversold and rsiValue > rsiPrevious)
rsiSupportssell = rsiStatus == "动量回落" or (rsiValue >= rsiOverbought and rsiValue < rsiPrevious)
// === 多时间框架数据获取 ===
// 简化的多时间框架趋势计算
calcSimpleTrend(src) =>
ema21 = ta.ema(src, 21)
ema50 = ta.ema(src, 50)
trend = src > ema21 and ema21 > ema50 ? 1 : src < ema21 and ema21 < ema50 ? -1 : 0
trend
// 获取各时间框架的趋势数据
trend1m = showMTF and mtfEnable1m ? request.security(syminfo.tickerid, "1", calcSimpleTrend(close)) : 0
trend5m = showMTF and mtfEnable5m ? request.security(syminfo.tickerid, "5", calcSimpleTrend(close)) : 0
trend15m = showMTF and mtfEnable15m ? request.security(syminfo.tickerid, "15", calcSimpleTrend(close)) : 0
trend1h = showMTF and mtfEnable1h ? request.security(syminfo.tickerid, "60", calcSimpleTrend(close)) : 0
trend4h = showMTF and mtfEnable4h ? request.security(syminfo.tickerid, "240", calcSimpleTrend(close)) : 0
// === 多时间框架趋势判断函数 ===
getTrendDirection(trend) =>
if trend > 0
"多头倾向"
else if trend < 0
"空头倾向"
else
"震荡"
// 获取各时间框架趋势方向
trend1mDir = getTrendDirection(trend1m)
trend5mDir = getTrendDirection(trend5m)
trend15mDir = getTrendDirection(trend15m)
trend1hDir = getTrendDirection(trend1h)
trend4hDir = getTrendDirection(trend4h)
// === 顶部规避系统 ===
ma_period_top = input.int(10, 'MA Period (Length)', group='8. 顶部规避 设置')
topThreshold = input.int(85, 'VAR顶部阈值', minval=70, maxval=95, step=1, group='8. 顶部规避 设置')
// 计算VAR指标 - 顶部(检测上涨动能)
pre_price_top = close
VAR_top = ta.sma(math.max(close-pre_price_top,0), ma_period_top) / ta.sma(math.abs(close-pre_price_top), ma_period_top) * 100
// 顶部信号 - 当上涨动能达到高位时
isTop = VAR_top > topThreshold and VAR_top <= topThreshold
// 图表显示顶部标记
plotshape(series=showTopAvoidance and isTop, title="顶", style=shape.labeldown, location=location.abovebar,
color=color.new(color.purple, 0), textcolor=color.white, size=size.normal, text="顶")
// === 底部规避系统 ===
ma_period_bottom = input.int(14, 'MA Period (Length)', group='9. 底部规避 设置')
bottomThreshold = input.int(15, 'VAR底部阈值', minval=5, maxval=30, step=1, group='9. 底部规避 设置')
// 计算VAR指标 - 底部(检测下跌动能)
pre_price_bottom = close
VAR_bottom = ta.sma(math.max(pre_price_bottom-close,0), ma_period_bottom) / ta.sma(math.abs(close-pre_price_bottom), ma_period_bottom) * 100
// 底部信号 - 当下跌动能达到高位时
isBottom = VAR_bottom > bottomThreshold and VAR_bottom <= bottomThreshold
// 图表显示底部标记
plotshape(series=showBottomAvoidance and isBottom, title="底", style=shape.labelup, location=location.belowbar,
color=color.new(color.orange, 0), textcolor=color.white, size=size.normal, text="底")
// === 范围过滤器 部分 ===
upColor = color.white
midColor = #90bff9
downColor = color.blue
src = input(defval=close, title="数据源", group="2. 范围过滤器 设置")
per = input.int(defval=100, minval=1, title="采样周期", group="2. 范围过滤器 设置")
mult = input.float(defval=3.0, minval=0.1, title="区间倍数", group="2. 范围过滤器 设置")
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult)
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt ) ? x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r :
x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r
rngfilt
filt = rngfilt(src, smrng)
upward = 0.0
upward := filt > filt ? nz(upward ) + 1 : filt < filt ? 0 : nz(upward )
downward = 0.0
downward := filt < filt ? nz(downward ) + 1 : filt > filt ? 0 : nz(downward )
hband = filt + smrng
lband = filt - smrng
filtcolor = upward > 0 ? upColor : downward > 0 ? downColor : midColor
barcolor_ = src > filt and src > src and upward > 0 ? upColor :
src > filt and src < src and upward > 0 ? upColor :
src < filt and src < src and downward > 0 ? downColor :
src < filt and src > src and downward > 0 ? downColor : midColor
longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src and upward > 0 or
src > filt and src < src and upward > 0
shortCond := src < filt and src < src and downward > 0 or
src < filt and src > src and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni
// === ADX 趋势过滤器 部分 ===
adxLength = input.int(defval=14, minval=1, title="ADX 周期", group="3. ADX 趋势过滤器 设置")
adxThreshold = input.float(defval=25.0, minval=0, maxval=100, step=0.5, title="ADX 阈值", tooltip="ADX大于此值才允许交易信号", group="3. ADX 趋势过滤器 设置")
// 简化的ADX计算 - 更准确的方法
calcADX(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), len)
= calcADX(adxLength)
// ADX状态判断
adxStrong = adxValue >= adxThreshold
adxTrendUp = diPlus > diMinus
adxTrendDown = diMinus > diPlus
// 修改信号生成逻辑,加入顶部和底部规避以及RSI确认
longCondition = longCond and CondIni == -1 and (not showADXFilter or adxStrong) and (not showTopAvoidance or not isTop) and (not showRSI or rsiSupportsBuy)
shortCondition = shortCond and CondIni == 1 and (not showADXFilter or adxStrong) and (not showBottomAvoidance or not isBottom) and (not showRSI or rsiSupportssell)
// === 记录买卖信号价格 ===
var float entryPrice = na
var string entryType = na
var float entryTime = na
// 当出现买入信号时记录
if longCondition
entryPrice := close
entryType := "多单"
entryTime := time
// 当出现卖出信号时记录
if shortCondition
entryPrice := close
entryType := "空单"
entryTime := time
// === 趋势颜色逻辑 ===
var trendColor = color.gray
if longCondition
trendColor := color.green
else if shortCondition
trendColor := color.red
// ADX线绘制(可选)- 已隐藏显示
adxColor = adxStrong ? (adxTrendUp ? color.green : color.red) : color.gray
// plot(showADXLine and showADXFilter ? adxValue : na, title="平均方向指数", color=adxColor, linewidth=1)
// hline(showADXLine and showADXFilter ? adxThreshold : na, title="ADX阈值线", color=color.yellow, linestyle=hline.style_dashed)
// 绘图部分 - 已隐藏线条显示,保留功能
// filtplot = plot(showRangeFilter ? filt : na, color=trendColor, linewidth=2, title="区间过滤器")
// hbandplot = plot(showRangeFilter ? hband : na, color=color.new(trendColor, 30), title="上轨线", linewidth=1)
// lbandplot = plot(showRangeFilter ? lband : na, color=color.new(trendColor, 30), title="下轨线", linewidth=1)
// barcolor(na) - 已隐藏K线颜色
plotshape(showRangeFilter and longCondition, title="买入信号", text="买", textcolor=color.white, style=shape.labelup, size=size.small, location=location.belowbar, color=color.new(color.green, 20))
plotshape(showRangeFilter and shortCondition, title="卖出信号", text="卖", textcolor=color.white, style=shape.labeldown, size=size.small, location=location.abovebar, color=color.new(color.red, 20))
// === 趋势线 部分 ===
length_tl = input.int(14, '分型回溯长度', group="4. 趋势线 设置")
mult_tl = input.float(1., '斜率系数', minval = 0, step = .1, group="4. 趋势线 设置")
calcMethod = input.string('平均真实波幅', '斜率计算方法', options = , group="4. 趋势线 设置")
backpaint = input(true, tooltip = '回溯显示:将可视元素向历史偏移,禁用后可查看实时信号。', group="4. 趋势线 设置")
upCss = input.color(color.teal, '上升趋势线颜色', group = "4. 趋势线 设置")
dnCss = input.color(color.red, '下降趋势线颜色', group = "4. 趋势线 设置")
showExt = input(true, '显示延长线', group="4. 趋势线 设置")
var upper_tl = 0.
var lower_tl = 0.
var slope_ph_tl = 0.
var slope_pl_tl = 0.
var offset_tl = backpaint ? length_tl : 0
n = bar_index
src_tl = close
ph = ta.pivothigh(length_tl, length_tl)
pl = ta.pivotlow(length_tl, length_tl)
slope = switch calcMethod
'平均真实波幅' => ta.atr(length_tl) / length_tl * mult_tl
'标准差' => ta.stdev(src_tl, length_tl) / length_tl * mult_tl
'线性回归' => math.abs(ta.sma(src_tl * n, length_tl) - ta.sma(src_tl, length_tl) * ta.sma(n, length_tl)) / ta.variance(n, length_tl) / 2 * mult_tl
slope_ph_tl := ph ? slope : slope_ph_tl
slope_pl_tl := pl ? slope : slope_pl_tl
upper_tl := ph ? ph : upper_tl - slope_ph_tl
lower_tl := pl ? pl : lower_tl + slope_pl_tl
var upos = 0
var dnos = 0
upos := ph ? 0 : close > upper_tl - slope_ph_tl * length_tl ? 1 : upos
dnos := pl ? 0 : close < lower_tl + slope_pl_tl * length_tl ? 1 : dnos
var uptl = line.new(na,na,na,na, color = upCss, style = line.style_dashed, extend = extend.right)
var dntl = line.new(na,na,na,na, color = dnCss, style = line.style_dashed, extend = extend.right)
if ph and showExt and showTrendLines
line.set_xy1(uptl, n-offset_tl, backpaint ? ph : upper_tl - slope_ph_tl * length_tl)
line.set_xy2(uptl, n-offset_tl+1, backpaint ? ph - slope : upper_tl - slope_ph_tl * (length_tl+1))
if pl and showExt and showTrendLines
line.set_xy1(dntl, n-offset_tl, backpaint ? pl : lower_tl + slope_pl_tl * length_tl)
line.set_xy2(dntl, n-offset_tl+1, backpaint ? pl + slope : lower_tl + slope_pl_tl * (length_tl+1))
plot(showTrendLines ? (backpaint ? upper_tl : upper_tl - slope_ph_tl * length_tl) : na, '上升趋势线', color = ph ? na : upCss, offset = -offset_tl)
plot(showTrendLines ? (backpaint ? lower_tl : lower_tl + slope_pl_tl * length_tl) : na, '下降趋势线', color = pl ? na : dnCss, offset = -offset_tl)
// 趋势线突破也需要ADX确认,并加入顶部和底部规避以及RSI确认
trendLineBuySignal = showTrendLines and upos > upos and (not showADXFilter or adxStrong) and (not showTopAvoidance or not isTop) and (not showRSI or rsiSupportsBuy)
trendLineSellSignal = showTrendLines and dnos > dnos and (not showADXFilter or adxStrong) and (not showBottomAvoidance or not isBottom) and (not showRSI or rsiSupportssell)
plotshape(trendLineBuySignal ? low : na, "上轨突破"
, shape.labelup
, location.absolute
, upCss
, text = "突"
, textcolor = color.white
, size = size.tiny)
plotshape(trendLineSellSignal ? high : na, "下轨突破"
, shape.labeldown
, location.absolute
, dnCss
, text = "突"
, textcolor = color.white
, size = size.tiny)
alertcondition(trendLineBuySignal, '上轨突破', '价格向上突破下趋势线')
alertcondition(trendLineSellSignal, '下轨突破', '价格向下突破上趋势线')
// === 支撑与阻力 部分 ===
g_sr = '5. 支撑与阻力'
g_c = '条件'
g_st = '样式'
t_r = 'K线确认:仅在K线收盘时生成警报(延后1根K线)。\n\n高点与低点:默认情况下,突破/回踩系统使用当前收盘价判断,选择高点与低点后将使用高低点判断条件,不再重绘,结果会不同。'
t_rv = '每当检测到潜在回踩时,指标会判断回踩事件即将发生。此输入用于设置在潜在回踩激活时,最大允许检测多少根K线。\n\n例如,出现潜在回踩标签时,该标签允许存在多少根K线以确认回踩?此功能防止回踩警报在10根K线后才触发导致不准确。'
input_lookback = input.int(defval = 20, title = '回溯区间', minval = 1, tooltip = '检测分型事件的K线数量。', group = g_sr)
input_retSince = input.int(defval = 2, title = '突破后K线数', minval = 1, tooltip = '突破后多少根K线内检测回踩。', group = g_sr)
input_retValid = input.int(defval = 2, title = '回踩检测限制', minval = 1, tooltip = t_rv, group = g_sr)
input_breakout = input.bool(defval = true, title = '显示突破', group = g_c)
input_retest = input.bool(defval = true, title = '显示回踩', group = g_c)
input_repType = input.string(defval = '开启', title = '重绘模式', options = , tooltip = t_r, group = g_c)
input_outL = input.string(defval = line.style_dotted, title = '边框样式', group = g_st, options = )
input_extend = input.string(defval = extend.none, title = '延长方向', group = g_st, options = )
input_labelType = input.string(defval = '详细', title = '标签类型', options = , group = g_st)
input_labelSize = input.string(defval = size.small, title = '标签大小', options = , group = g_st)
st_break_lb_co1 = input.color(defval = color.lime , title = '空头突破标签颜色' ,inline = 'st_break_lb_co', group = g_st)
st_break_lb_co2 = input.color(defval = color.new(color.lime,40) , title = '' ,inline = 'st_break_lb_co', group = g_st)
lg_break_lb_co1 = input.color(defval = color.red , title = '多头突破标签颜色' ,inline = 'lg_break_lb_co', group = g_st)
lg_break_lb_co2 = input.color(defval = color.new(color.red,40) , title = '' ,inline = 'lg_break_lb_co', group = g_st)
st_retest_lb_co1 = input.color(defval = color.lime , title = '空头回踩标签颜色' ,inline = 'st_retest_lb_col', group = g_st)
st_retest_lb_co2 = input.color(defval = color.new(color.lime,40) , title = '' ,inline = 'st_retest_lb_col', group = g_st)
lg_retest_lb_co1 = input.color(defval = color.red , title = '多头回踩标签颜色' ,inline = 'lg_retest_lb_co', group = g_st)
lg_retest_lb_co2 = input.color(defval = color.new(color.red,40) , title = '' ,inline = 'lg_retest_lb_co', group = g_st)
input_plColor1 = input.color(defval = color.lime, title = '支撑方框颜色', inline = 'pl_Color', group = g_st)
input_plColor2 = input.color(defval = color.new(color.lime,85), title = '', inline = 'pl_Color', group = g_st)
input_phColor1 = input.color(defval = color.red, title = '阻力方框颜色', inline = 'ph_Color', group = g_st)
input_phColor2 = input.color(defval = color.new(color.red,85), title = '', inline = 'ph_Color', group = g_st)
input_override = input.bool(defval = false, title = '自定义文字颜色', inline = '覆盖', group = g_st)
input_textColor = input.color(defval = color.white, title = '', inline = '覆盖', group = g_st)
bb = input_lookback
// 兼容label与英文选项
rTon = input_repType == '开启'
rTcc = input_repType == '关闭:K线确认'
rThv = input_repType == '关闭:高低点'
breakText = input_labelType == '简洁' ? '突' : '突破'
// 分型
rs_pl = fixnan(ta.pivotlow(low, bb, bb))
rs_ph = fixnan(ta.pivothigh(high, bb, bb))
// Box 高度
s_yLoc = low > low ? low : low
r_yLoc = high > high ? high : high
//-----------------------------------------------------------------------------
// 函数
//-----------------------------------------------------------------------------
drawBox(condition, y1, y2, color,bgcolor) =>
var box drawBox = na
if condition and showSupRes // 仅在显示开关打开时绘制
box.set_right(drawBox, bar_index - bb)
drawBox.set_extend(extend.none)
drawBox := box.new(bar_index - bb, y1, bar_index, y2, color, bgcolor = bgcolor, border_style = input_outL, extend = input_extend)
updateBox(box) =>
if barstate.isconfirmed and showSupRes
box.set_right(box, bar_index + 5)
breakLabel(y, txt_col,lb_col, style, textform) =>
if showSupRes
label.new(bar_index, y, textform, textcolor = input_override ? input_textColor : txt_col, style = style, color = lb_col, size = input_labelSize)
retestCondition(breakout, condition) =>
ta.barssince(na(breakout)) > input_retSince and condition
repaint(c1, c2, c3) => rTon ? c1 : rThv ? c2 : rTcc ? c3 : na
//-----------------------------------------------------------------------------
// 绘制与更新区间
//-----------------------------------------------------------------------------
= drawBox(ta.change(rs_pl), s_yLoc, rs_pl, input_plColor1,input_plColor2)
= drawBox(ta.change(rs_ph), rs_ph, r_yLoc, input_phColor1,input_phColor2)
sTop = box.get_top(sBox), rTop = box.get_top(rBox)
sBot = box.get_bottom(sBox), rBot = box.get_bottom(rBox)
if showSupRes
updateBox(sBox), updateBox(rBox)
//-----------------------------------------------------------------------------
// 突破事件 - 加入顶部和底部规避以及RSI确认
//-----------------------------------------------------------------------------
var bool sBreak = na
var bool rBreak = na
cu = repaint(ta.crossunder(close, box.get_bottom(sBox)), ta.crossunder(low, box.get_bottom(sBox)), ta.crossunder(close, box.get_bottom(sBox)) and barstate.isconfirmed)
co = repaint(ta.crossover(close, box.get_top(rBox)), ta.crossover(high, box.get_top(rBox)), ta.crossover(close, box.get_top(rBox)) and barstate.isconfirmed)
switch
cu and na(sBreak) and showSupRes and (not showADXFilter or adxStrong) and (not showBottomAvoidance or not isBottom) and (not showRSI or rsiSupportssell) =>
sBreak := true
if input_breakout
breakLabel(sBot, st_break_lb_co1,st_break_lb_co2, label.style_label_upper_right, breakText)
co and na(rBreak) and showSupRes and (not showADXFilter or adxStrong) and (not showTopAvoidance or not isTop) and (not showRSI or rsiSupportsBuy) =>
rBreak := true
if input_breakout
breakLabel(rTop, lg_break_lb_co1,lg_break_lb_co2, label.style_label_lower_right, breakText)
if ta.change(rs_pl) and showSupRes
if na(sBreak)
box.delete(sBox )
sBreak := na
if ta.change(rs_ph) and showSupRes
if na(rBreak)
box.delete(rBox )
rBreak := na
//-----------------------------------------------------------------------------
// 回踩事件
//-----------------------------------------------------------------------------
s1 = retestCondition(sBreak, high >= sTop and close <= sBot)
s2 = retestCondition(sBreak, high >= sTop and close >= sBot and close <= sTop)
s3 = retestCondition(sBreak, high >= sBot and high <= sTop)
s4 = retestCondition(sBreak, high >= sBot and high <= sTop and close < sBot)
r1 = retestCondition(rBreak, low <= rBot and close >= rTop)
r2 = retestCondition(rBreak, low <= rBot and close <= rTop and close >= rBot)
r3 = retestCondition(rBreak, low <= rTop and low >= rBot)
r4 = retestCondition(rBreak, low <= rTop and low >= rBot and close > rTop)
retestEvent(c1, c2, c3, c4, y1, y2, txt_col,lb_col, style, pType) =>
if input_retest and showSupRes
var bool retOccurred = na
retActive = c1 or c2 or c3 or c4
retEvent = retActive and not retActive
retValue = ta.valuewhen(retEvent, y1, 0)
if pType == 'ph' ? y2 < ta.valuewhen(retEvent, y2, 0) : y2 > ta.valuewhen(retEvent, y2, 0)
retEvent := retActive
retValue := ta.valuewhen(retEvent, y1, 0)
retSince = ta.barssince(retEvent)
var retLabel = array.new()
if retEvent
retOccurred := na
array.push(retLabel, label.new(bar_index - retSince, y2 , text = input_labelType == '简洁' ? '潜回' : '潜在回踩', color = lb_col, style = style, textcolor = input_override ? input_textColor : txt_col, size = input_labelSize))
if array.size(retLabel) == 2
label.delete(array.first(retLabel))
array.shift(retLabel)
retConditions = pType == 'ph' ? repaint(close >= retValue, high >= retValue, close >= retValue and barstate.isconfirmed) : repaint(close <= retValue, low <= retValue, close <= retValue and barstate.isconfirmed)
retValid = ta.barssince(retEvent) > 0 and ta.barssince(retEvent) <= input_retValid and retConditions and not retOccurred and (not showADXFilter or adxStrong) and (not showRSI or (pType == 'ph' ? rsiSupportsBuy : rsiSupportssell))
if retValid
label.new(bar_index - retSince, y2 , text = input_labelType == '简洁' ? '回' : '回踩', color = lb_col, style = style, textcolor = input_override ? input_textColor : txt_col, size = input_labelSize)
retOccurred := true
if retValid or ta.barssince(retEvent) > input_retValid
label.delete(array.first(retLabel))
if pType == 'ph' and ta.change(rs_ph) and retOccurred
box.set_right(rBox , bar_index - retSince)
retOccurred := na
if pType == 'pl' and ta.change(rs_pl) and retOccurred
box.set_right(sBox , bar_index - retSince)
retOccurred := na
else
= retestEvent(r1, r2, r3, r4, high, low, lg_retest_lb_co1,lg_retest_lb_co2, label.style_label_upper_left, 'ph')
= retestEvent(s1, s2, s3, s4, low, high, st_retest_lb_co1,st_retest_lb_co2, label.style_label_lower_left, 'pl')
//-----------------------------------------------------------------------------
// 警报
//-----------------------------------------------------------------------------
// 买卖信号警报条件
buySignal = showTrendLines and trendLineBuySignal
sellSignal = showTrendLines and trendLineSellSignal
// 添加买卖信号的警报条件
alertcondition(buySignal, title='买入信号', message='范围过滤器买入信号:上轨突破')
alertcondition(sellSignal, title='卖出信号', message='范围过滤器卖出信号:下轨突破')
alertcondition((showSupRes and ta.change(rs_pl)), '新支撑位')
alertcondition((showSupRes and ta.change(rs_ph)), '新阻力位')
alertcondition((showSupRes and ta.barssince(na(sBreak)) == 1), '支撑位突破')
alertcondition((showSupRes and ta.barssince(na(rBreak)) == 1), '阻力位突破')
alertcondition((showSupRes and sRetValid), '支撑位回踩')
alertcondition((showSupRes and sRetEvent), '潜在支撑回踩')
alertcondition((showSupRes and rRetValid), '阻力位回踩')
alertcondition((showSupRes and rRetEvent), '潜在阻力回踩')
AllAlerts(condition, message) =>
if condition and showSupRes
alert(message)
AllAlerts(ta.change(rs_pl), '新支撑位')
AllAlerts(ta.change(rs_ph), '新阻力位')
AllAlerts(ta.barssince(na(sBreak)) == 1, '支撑位突破')
AllAlerts(ta.barssince(na(rBreak)) == 1, '阻力位突破')
AllAlerts(sRetValid, '支撑位回踩')
AllAlerts(sRetEvent, '潜在支撑回踩')
AllAlerts(rRetValid, '阻力位回踩')
AllAlerts(rRetEvent, '潜在阻力回踩')
AllAlerts(buySignal, '买入信号:上轨突破')
AllAlerts(sellSignal, '卖出信号:下轨突破')
// === 多周期移动平均线 部分 ===
// === 公共函数 ===
strRoundValue(num) =>
strv = ''
if num >= 100000
strv := str.tostring(num/1000, '#千')
else if (num < 100000) and (num >= 100)
strv := str.tostring(num, '#')
else if (num < 100) and (num >= 1)
strv := str.tostring(num, '#.##')
else if (num < 1) and (num >= 0.01)
strv := str.tostring(num, '#.####')
else if (num < 0.01) and (num >= 0.0001)
strv := str.tostring(num, '#.######')
else if (num < 0.0001) and (num >= 0.000001)
strv := str.tostring(num, '#.########')
(strv)
defaultFunction(func, src, len, alma_offst, alma_sigma) =>
has_len = false
ma = ta.swma(close)
if func == '自适应移动平均'
ma := ta.alma(src, len, alma_offst, alma_sigma)
has_len := true
else if func == '指数移动平均'
ma := ta.ema(src, len)
has_len := true
else if func == '修正移动平均'
ma := ta.rma(src, len)
has_len := true
else if func == '简单移动平均'
ma := ta.sma(src, len)
has_len := true
else if func == '对称加权移动平均'
ma := ta.swma(src)
has_len := false
else if func == '成交量加权平均价'
ma := ta.vwap(src)
has_len := false
else if func == '成交量加权移动平均'
ma := ta.vwma(src, len)
has_len := true
else if func == '加权移动平均'
ma := ta.wma(src, len)
has_len := true
def_fn = input.string(title='默认移动平均线', defval='指数移动平均', options= , group="6. PMA 设置")
ma1_on = input.bool(inline='均线1', title='启用移动平均线1', defval=false, group="6. PMA 设置")
ma2_on = input.bool(inline='均线2', title='启用移动平均线2', defval=true, group="6. PMA 设置")
ma3_on = input.bool(inline='均线3', title='启用移动平均线3', defval=true, group="6. PMA 设置")
ma4_on = input.bool(inline='均线4', title='启用移动平均线4', defval=true, group="6. PMA 设置")
ma5_on = input.bool(inline='均线5', title='启用移动平均线5', defval=true, group="6. PMA 设置")
ma6_on = input.bool(inline='均线6', title='启用移动平均线6', defval=true, group="6. PMA 设置")
ma7_on = input.bool(inline='均线7', title='启用移动平均线7', defval=true, group="6. PMA 设置")
ma1_fn = input.string(inline='均线1', title='', defval='默认', options= , group="6. PMA 设置")
ma2_fn = input.string(inline='均线2', title='', defval='默认', options= , group="6. PMA 设置")
ma3_fn = input.string(inline='均线3', title='', defval='默认', options= , group="6. PMA 设置")
ma4_fn = input.string(inline='均线4', title='', defval='默认', options= , group="6. PMA 设置")
ma5_fn = input.string(inline='均线5', title='', defval='默认', options= , group="6. PMA 设置")
ma6_fn = input.string(inline='均线6', title='', defval='默认', options= , group="6. PMA 设置")
ma7_fn = input.string(inline='均线7', title='', defval='默认', options= , group="6. PMA 设置")
ma1_len = input.int(inline='均线1', title='', defval=12, minval=1, group="6. PMA 设置")
ma2_len = input.int(inline='均线2', title='', defval=144, minval=1, group="6. PMA 设置")
ma3_len = input.int(inline='均线3', title='', defval=169, minval=1, group="6. PMA 设置")
ma4_len = input.int(inline='均线4', title='', defval=288, minval=1, group="6. PMA 设置")
ma5_len = input.int(inline='均线5', title='', defval=338, minval=1, group="6. PMA 设置")
ma6_len = input.int(inline='均线6', title='', defval=576, minval=1, group="6. PMA 设置")
ma7_len = input.int(inline='均线7', title='', defval=676, minval=1, group="6. PMA 设置")
alma1_offst = input.float(group='均线1其他设置', inline='均线11', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma1_sigma = input.float(group='均线1其他设置', inline='均线11', title=', 西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma1_src = input.source(group='均线1其他设置', inline='均线12', title='数据源', defval=close)
ma1_plt_offst = input.int(group='均线1其他设置', inline='均线12', title=', 绘图偏移', defval=0, minval=-500, maxval=500)
alma2_offst = input.float(group='均线2其他设置', inline='均线21', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma2_sigma = input.float(group='均线2其他设置', inline='均线21', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma2_src = input.source(group='均线2其他设置', inline='均线22', title='数据源', defval=close)
ma2_plt_offst = input.int(group='均线2其他设置', inline='均线22', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma3_offst = input.float(group='均线3其他设置', inline='均线31', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma3_sigma = input.float(group='均线3其他设置', inline='均线31', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma3_src = input.source(group='均线3其他设置', inline='均线32', title='数据源', defval=close)
ma3_plt_offst = input.int(group='均线3其他设置', inline='均线32', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma4_offst = input.float(group='均线4其他设置', inline='均线41', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma4_sigma = input.float(group='均线4其他设置', inline='均线41', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma4_src = input.source(group='均线4其他设置', inline='均线42', title='数据源', defval=close)
ma4_plt_offst = input.int(group='均线4其他设置', inline='均线42', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma5_offst = input.float(group='均线5其他设置', inline='均线51', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma5_sigma = input.float(group='均线5其他设置', inline='均线51', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma5_src = input.source(group='均线5其他设置', inline='均线52', title='数据源', defval=close)
ma5_plt_offst = input.int(group='均线5其他设置', inline='均线52', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma6_offst = input.float(group='均线6其他设置', inline='均线61', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma6_sigma = input.float(group='均线6其他设置', inline='均线61', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma6_src = input.source(group='均线6其他设置', inline='均线62', title='数据源', defval=close)
ma6_plt_offst = input.int(group='均线6其他设置', inline='均线62', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma7_offst = input.float(group='均线7其他设置', inline='均线71', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma7_sigma = input.float(group='均线7其他设置', inline='均线71', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma7_src = input.source(group='均线7其他设置', inline='均线72', title='数据源', defval=close)
ma7_plt_offst = input.int(group='均线7其他设置', inline='均线72', title='绘图偏移', defval=0, minval=-500, maxval=500)
fill_12_on = input.bool(title='启用均线1-2填充', defval=false, group="6. PMA 设置")
fill_23_on = input.bool(title='启用均线2-3填充', defval=true, group="6. PMA 设置")
fill_34_on = input.bool(title='启用均线3-4填充', defval=false, group="6. PMA 设置")
fill_45_on = input.bool(title='启用均线4-5填充', defval=true, group="6. PMA 设置")
fill_56_on = input.bool(title='启用均线5-6填充', defval=false, group="6. PMA 设置")
fill_67_on = input.bool(title='启用均线6-7填充', defval=true, group="6. PMA 设置")
// === 计算移动平均线 ===
= defaultFunction(def_fn, ma1_src, ma1_len, alma1_offst, alma1_sigma)
= defaultFunction(def_fn, ma2_src, ma2_len, alma2_offst, alma2_sigma)
= defaultFunction(def_fn, ma3_src, ma3_len, alma3_offst, alma3_sigma)
= defaultFunction(def_fn, ma4_src, ma4_len, alma4_offst, alma4_sigma)
= defaultFunction(def_fn, ma5_src, ma5_len, alma5_offst, alma5_sigma)
= defaultFunction(def_fn, ma6_src, ma6_len, alma6_offst, alma6_sigma)
= defaultFunction(def_fn, ma7_src, ma7_len, alma7_offst, alma7_sigma)
// === 均线类型切换 ===
if ma1_fn != '默认'
if ma1_fn == '自适应移动平均'
ma1 := ta.alma(ma1_src, ma1_len, alma1_offst, alma1_sigma)
ma1_has_len := true
else if ma1_fn == '指数移动平均'
ma1 := ta.ema(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '修正移动平均'
ma1 := ta.rma(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '简单移动平均'
ma1 := ta.sma(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '对称加权移动平均'
ma1 := ta.swma(ma1_src)
ma1_has_len := false
else if ma1_fn == '成交量加权平均价'
ma1 := ta.vwap(ma1_src)
ma1_has_len := false
else if ma1_fn == '成交量加权移动平均'
ma1 := ta.vwma(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '加权移动平均'
ma1 := ta.wma(ma1_src, ma1_len)
ma1_has_len := true
if ma2_fn != '默认'
if ma2_fn == '自适应移动平均'
ma2 := ta.alma(ma2_src, ma2_len, alma2_offst, alma2_sigma)
ma2_has_len := true
else if ma2_fn == '指数移动平均'
ma2 := ta.ema(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '修正移动平均'
ma2 := ta.rma(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '简单移动平均'
ma2 := ta.sma(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '对称加权移动平均'
ma2 := ta.swma(ma2_src)
ma2_has_len := false
else if ma2_fn == '成交量加权平均价'
ma2 := ta.vwap(ma2_src)
ma2_has_len := false
else if ma2_fn == '成交量加权移动平均'
ma2 := ta.vwma(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '加权移动平均'
ma2 := ta.wma(ma2_src, ma2_len)
ma2_has_len := true
if ma3_fn != '默认'
if ma3_fn == '自适应移动平均'
ma3 := ta.alma(ma3_src, ma3_len, alma3_offst, alma3_sigma)
ma3_has_len := true
else if ma3_fn == '指数移动平均'
ma3 := ta.ema(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '修正移动平均'
ma3 := ta.rma(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '简单移动平均'
ma3 := ta.sma(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '对称加权移动平均'
ma3 := ta.swma(ma3_src)
ma3_has_len := false
else if ma3_fn == '成交量加权平均价'
ma3 := ta.vwap(ma3_src)
ma3_has_len := false
else if ma3_fn == '成交量加权移动平均'
ma3 := ta.vwma(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '加权移动平均'
ma3 := ta.wma(ma3_src, ma3_len)
ma3_has_len := true
if ma4_fn != '默认'
if ma4_fn == '自适应移动平均'
ma4 := ta.alma(ma4_src, ma4_len, alma4_offst, alma4_sigma)
ma4_has_len := true
else if ma4_fn == '指数移动平均'
ma4 := ta.ema(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '修正移动平均'
ma4 := ta.rma(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '简单移动平均'
ma4 := ta.sma(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '对称加权移动平均'
ma4 := ta.swma(ma4_src)
ma4_has_len := false
else if ma4_fn == '成交量加权平均价'
ma4 := ta.vwap(ma4_src)
ma4_has_len := false
else if ma4_fn == '成交量加权移动平均'
ma4 := ta.vwma(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '加权移动平均'
ma4 := ta.wma(ma4_src, ma4_len)
ma4_has_len := true
if ma5_fn != '默认'
if ma5_fn == '自适应移动平均'
ma5 := ta.alma(ma5_src, ma5_len, alma5_offst, alma5_sigma)
ma5_has_len := true
else if ma5_fn == '指数移动平均'
ma5 := ta.ema(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '修正移动平均'
ma5 := ta.rma(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '简单移动平均'
ma5 := ta.sma(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '对称加权移动平均'
ma5 := ta.swma(ma5_src)
ma5_has_len := false
else if ma5_fn == '成交量加权平均价'
ma5 := ta.vwap(ma5_src)
ma5_has_len := false
else if ma5_fn == '成交量加权移动平均'
ma5 := ta.vwma(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '加权移动平均'
ma5 := ta.wma(ma5_src, ma5_len)
ma5_has_len := true
if ma6_fn != '默认'
if ma6_fn == '自适应移动平均'
ma6 := ta.alma(ma6_src, ma6_len, alma6_offst, alma6_sigma)
ma6_has_len := true
else if ma6_fn == '指数移动平均'
ma6 := ta.ema(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '修正移动平均'
ma6 := ta.rma(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '简单移动平均'
ma6 := ta.sma(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '对称加权移动平均'
ma6 := ta.swma(ma6_src)
ma6_has_len := false
else if ma6_fn == '成交量加权平均价'
ma6 := ta.vwap(ma6_src)
ma6_has_len := false
else if ma6_fn == '成交量加权移动平均'
ma6 := ta.vwma(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '加权移动平均'
ma6 := ta.wma(ma6_src, ma6_len)
ma6_has_len := true
if ma7_fn != '默认'
if ma7_fn == '自适应移动平均'
ma7 := ta.alma(ma7_src, ma7_len, alma7_offst, alma7_sigma)
ma7_has_len := true
else if ma7_fn == '指数移动平均'
ma7 := ta.ema(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '修正移动平均'
ma7 := ta.rma(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '简单移动平均'
ma7 := ta.sma(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '对称加权移动平均'
ma7 := ta.swma(ma7_src)
ma7_has_len := false
else if ma7_fn == '成交量加权平均价'
ma7 := ta.vwap(ma7_src)
ma7_has_len := false
else if ma7_fn == '成交量加权移动平均'
ma7 := ta.vwma(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '加权移动平均'
ma7 := ta.wma(ma7_src, ma7_len)
ma7_has_len := true
// === 均线颜色 ===
ma1_clr = color.new(color.fuchsia, 0)
ma2_clr = color.new(color.aqua, 0)
ma3_clr = color.new(color.yellow, 0)
ma4_clr = color.new(color.blue, 0)
ma5_clr = color.new(color.orange, 0)
ma6_clr = color.new(color.green, 0)
ma7_clr = color.new(color.red, 0)
// === 均线全局绘图 ===
p1 = plot(series=showPMA and ma1_on ? ma1 : na, title="均线1", color=ma1_clr, trackprice=false, offset=ma1_plt_offst, linewidth=2)
p2 = plot(series=showPMA and ma2_on ? ma2 : na, title="均线2", color=ma2_clr, trackprice=false, offset=ma2_plt_offst, linewidth=2)
p3 = plot(series=showPMA and ma3_on ? ma3 : na, title="均线3", color=ma3_clr, trackprice=false, offset=ma3_plt_offst, linewidth=2)
p4 = plot(series=showPMA and ma4_on ? ma4 : na, title="均线4", color=ma4_clr, trackprice=false, offset=ma4_plt_offst, linewidth=2)
p5 = plot(series=showPMA and ma5_on ? ma5 : na, title="均线5", color=ma5_clr, trackprice=false, offset=ma5_plt_offst, linewidth=2)
p6 = plot(series=showPMA and ma6_on ? ma6 : na, title="均线6", color=ma6_clr, trackprice=false, offset=ma6_plt_offst, linewidth=2)
p7 = plot(series=showPMA and ma7_on ? ma7 : na, title="均线7", color=ma7_clr, trackprice=false, offset=ma7_plt_offst, linewidth=2)
// === 多周期移动平均线 填充渲染 ===
fill(p1, p2, color=showPMA and ma1_on and ma2_on and fill_12_on ? color.new(color.purple, 70) : na, title="均线1-2填充")
fill(p2, p3, color=showPMA and ma2_on and ma3_on and fill_23_on ? color.new(color.blue, 70) : na, title="均线2-3填充")
fill(p3, p4, color=showPMA and ma3_on and ma4_on and fill_34_on ? color.new(color.teal, 70) : na, title="均线3-4填充")
fill(p4, p5, color=showPMA and ma4_on and ma5_on and fill_45_on ? color.new(color.green, 70) : na, title="均线4-5填充")
fill(p5, p6, color=showPMA and ma5_on and ma6_on and fill_56_on ? color.new(color.yellow, 70) : na, title="均线5-6填充")
fill(p6, p7, color=showPMA and ma6_on and ma7_on and fill_67_on ? color.new(color.orange, 70) : na, title="均线6-7填充")
// === 交易信息表格 部分 ===
// 表格参数设置 - 修改默认大小为中等
tablePos = input.string("右上角", title="表格位置", options= , group="7. 交易信息表格 设置")
tableSize = input.string("中等", title="表格大小", options= , group="7. 交易信息表格 设置")
showTargets = input.bool(true, title="显示止盈目标", group="7. 交易信息表格 设置")
showRatio = input.bool(true, title="显示盈亏比", group="7. 交易信息表格 设置")
// 辅助函数
getTablePosition() =>
switch tablePos
"右上角" => position.top_right
"右下角" => position.bottom_right
"左上角" => position.top_left
"左下角" => position.bottom_left
getTableSize() =>
switch tableSize
"小" => size.small
"中等" => size.normal
"大" => size.large
formatPrice(price) =>
if na(price)
"N/A"
else
str.tostring(price, "#.####")
calcStopLossPercentage(entryPrice, stopLoss, entryType) =>
if na(entryPrice) or na(stopLoss) or na(entryType)
""
else
pct = 0.0
if entryType == "多单"
pct := (stopLoss - entryPrice) / entryPrice * 100
else if entryType == "空单"
pct := (entryPrice - stopLoss) / entryPrice * 100
" (" + str.tostring(pct, "#.##") + "%)"
calcTakeProfitPercentage(entryPrice, takeProfit, entryType) =>
if na(entryPrice) or na(takeProfit) or na(entryType)
""
else
pct = 0.0
if entryType == "多单"
pct := (takeProfit - entryPrice) / entryPrice * 100
else if entryType == "空单"
pct := (entryPrice - takeProfit) / entryPrice * 100
" (+" + str.tostring(pct, "#.##") + "%)"
calcUnrealizedPnL(entryPrice, currentPrice, entryType) =>
if na(entryPrice) or na(currentPrice) or na(entryType)
""
else
priceDiff = currentPrice - entryPrice
pct = (currentPrice - entryPrice) / entryPrice * 100
if entryType == "多单"
if pct > 0
" (" + formatPrice(priceDiff) + ", +" + str.tostring(pct, "#.##") + "%)"
else
" (" + formatPrice(priceDiff) + ", " + str.tostring(pct, "#.##") + "%)"
else if entryType == "空单"
// 对于空单,价差符号相反
if pct < 0
" (" + formatPrice(-priceDiff) + ", +" + str.tostring(-pct, "#.##") + "%)"
else
" (" + formatPrice(-priceDiff) + ", " + str.tostring(-pct, "#.##") + "%)"
else
""
// RSI状态颜色函数
getRSIStatusColor() =>
switch rsiStatus
"动量回升" => // 绿色
"动量回落" => // 红色
"动量中性" => // 黄色
=> // 默认灰色
// 多时间框架趋势颜色函数
getTrendColor(trendDirection) =>
switch trendDirection
"多头倾向" => // 绿色
"空头倾向" => // 红色
"震荡" => // 黄色
=> // 默认灰色
// === 蓝紫科幻风格表格 ===
// 创建蓝紫色主题的表格
var infoTable = table.new(getTablePosition(), columns=2, rows=26,
bgcolor=color.new(#0f0a1a, 5),
border_width=3,
border_color=color.new(#6633ff, 40),
frame_width=2,
frame_color=color.new(#9966ff, 30))
if showTable and barstate.islast
// 确定止盈止损位
var float stopLoss = na
var float takeProfit1 = na
var float takeProfit2 = na
if not na(entryType)
if entryType == "多单"
stopLoss := na(sBot) ? entryPrice * 0.98 : sBot
takeProfit1 := na(rTop) ? entryPrice * 1.02 : rTop
takeProfit2 := entryPrice * 1.05
else if entryType == "空单"
stopLoss := na(rTop) ? entryPrice * 1.02 : rTop
takeProfit1 := na(sBot) ? entryPrice * 0.98 : sBot
takeProfit2 := entryPrice * 0.95
// 计算盈亏比
riskRewardRatio = na(entryPrice) or na(stopLoss) or na(takeProfit1) ? na :
math.abs(takeProfit1 - entryPrice) / math.abs(entryPrice - stopLoss)
riskRewardStr = na(riskRewardRatio) ? "N/A" : "1:" + str.tostring(riskRewardRatio, "#.##")
rowIndex = 0
// === 作者联系信息行 - 最顶部,大字体 ===
table.cell(infoTable, 0, rowIndex, "合作联系作者", text_color=color.new(#ffcc99, 0),
text_size=size.normal, bgcolor=color.new(#1a1a0d, 0))
table.cell(infoTable, 1, rowIndex, "qq2390107445", text_color=color.new(#66ff99, 0),
text_size=size.normal, bgcolor=color.new(#0d2619, 0))
rowIndex += 1
// === 表格标题行 - 蓝紫主题 ===
table.cell(infoTable, 0, rowIndex, "⚡ P6●智能资金概念交易系统", text_color=color.new(#ccccff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
table.cell(infoTable, 1, rowIndex, "『" + syminfo.ticker + "』", text_color=color.new(#9966ff, 0),
text_size=size.normal, bgcolor=color.new(#1a0d33, 0))
rowIndex += 1
// === 当前价格与浮盈浮亏行 - 蓝紫主题 ===
unrealizedPnL = calcUnrealizedPnL(entryPrice, close, entryType)
// 浮盈浮亏颜色逻辑
pnlColor = color.new(#ccccff, 0)
pnlBgColor = color.new(#0d0d1a, 0)
if not na(entryPrice)
if entryType == "多单"
if close > entryPrice
pnlColor := color.new(#66ff99, 0)
pnlBgColor := color.new(#0d2619, 0)
else
pnlColor := color.new(#ff6699, 0)
pnlBgColor := color.new(#260d19, 0)
else if entryType == "空单"
if close < entryPrice
pnlColor := color.new(#66ff99, 0)
pnlBgColor := color.new(#0d2619, 0)
else
pnlColor := color.new(#ff6699, 0)
pnlBgColor := color.new(#260d19, 0)
table.cell(infoTable, 0, rowIndex, "当前价格", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(close) + unrealizedPnL,
text_color=pnlColor,
text_size=getTableSize(), bgcolor=pnlBgColor)
rowIndex += 1
// === 趋势状态与进场价格行 - 蓝紫主题 ===
trendStatus = na(entryType) ? "待机中" : entryType == "多单" ? "多头执行" : "空头执行"
trendIcon = entryType == "多单" ? " ▲" : entryType == "空单" ? " ▼" : " ●"
trendBgColor = entryType == "多单" ? color.new(#1a4d1a, 0) :
entryType == "空单" ? color.new(#4d1a1a, 0) :
color.new(#1a1a4d, 0)
trendTextColor = entryType == "多单" ? color.new(#66ff99, 0) :
entryType == "空单" ? color.new(#ff6699, 0) :
color.new(#9999ff, 0)
table.cell(infoTable, 0, rowIndex, "交易状态", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trendStatus + trendIcon, text_color=trendTextColor,
text_size=getTableSize(), bgcolor=trendBgColor)
rowIndex += 1
// === 进场价格行 - 蓝紫主题 ===
table.cell(infoTable, 0, rowIndex, "进场价位", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(entryPrice),
text_color=color.new(#ffcc99, 0),
text_size=getTableSize(), bgcolor=color.new(#1a1a0d, 0))
rowIndex += 1
// === 多时间框架分析 - 独立行显示 ===
if showMTF
// 多时间框架标题行
table.cell(infoTable, 0, rowIndex, "━━ 多时间框架趋势 ━━", text_color=color.new(#ccccff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
table.cell(infoTable, 1, rowIndex, "━━━━━━━━━━━━━━━━━━━━", text_color=color.new(#6633ff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
rowIndex += 1
// 1分钟趋势
if mtfEnable1m
= getTrendColor(trend1mDir)
trend1mIcon = trend1mDir == "多头倾向" ? " ▲" : trend1mDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "1分钟", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend1mDir + trend1mIcon, text_color=trend1mTextColor,
text_size=getTableSize(), bgcolor=trend1mBgColor)
rowIndex += 1
// 5分钟趋势
if mtfEnable5m
= getTrendColor(trend5mDir)
trend5mIcon = trend5mDir == "多头倾向" ? " ▲" : trend5mDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "5分钟", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend5mDir + trend5mIcon, text_color=trend5mTextColor,
text_size=getTableSize(), bgcolor=trend5mBgColor)
rowIndex += 1
// 15分钟趋势
if mtfEnable15m
= getTrendColor(trend15mDir)
trend15mIcon = trend15mDir == "多头倾向" ? " ▲" : trend15mDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "15分钟", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend15mDir + trend15mIcon, text_color=trend15mTextColor,
text_size=getTableSize(), bgcolor=trend15mBgColor)
rowIndex += 1
// 1小时趋势
if mtfEnable1h
= getTrendColor(trend1hDir)
trend1hIcon = trend1hDir == "多头倾向" ? " ▲" : trend1hDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "1小时", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend1hDir + trend1hIcon, text_color=trend1hTextColor,
text_size=getTableSize(), bgcolor=trend1hBgColor)
rowIndex += 1
// 4小时趋势
if mtfEnable4h
= getTrendColor(trend4hDir)
trend4hIcon = trend4hDir == "多头倾向" ? " ▲" : trend4hDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "4小时", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend4hDir + trend4hIcon, text_color=trend4hTextColor,
text_size=getTableSize(), bgcolor=trend4hBgColor)
rowIndex += 1
// === RSI 动量状态行 - 蓝紫主题 ===
rsiTextColor = color.new(#ccccff, 0)
rsiBgColor = color.new(#0d0d1a, 0)
if rsiStatus == "动量回升"
rsiTextColor := color.new(#66ff99, 0)
rsiBgColor := color.new(#0d2619, 0)
else if rsiStatus == "动量回落"
rsiTextColor := color.new(#ff6699, 0)
rsiBgColor := color.new(#260d19, 0)
else
rsiTextColor := color.new(#ffcc99, 0)
rsiBgColor := color.new(#1a1a0d, 0)
rsiIcon = rsiStatus == "动量回升" ? " ▲" : rsiStatus == "动量回落" ? " ▼" : " ●"
rsiDisplayText = rsiStatus + rsiIcon + " (" + str.tostring(rsiValue, "#.#") + ")"
table.cell(infoTable, 0, rowIndex, "RSI动量", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, rsiDisplayText, text_color=rsiTextColor,
text_size=getTableSize(), bgcolor=rsiBgColor)
rowIndex += 1
// === 风险管理分割线 ===
table.cell(infoTable, 0, rowIndex, "━━ 风险管理 ━━", text_color=color.new(#ccccff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
table.cell(infoTable, 1, rowIndex, "━━━━━━━━━━━━━━━━━━━━", text_color=color.new(#6633ff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
rowIndex += 1
// === 止损行 - 蓝紫主题 ===
slPct = calcStopLossPercentage(entryPrice, stopLoss, entryType)
table.cell(infoTable, 0, rowIndex, "止损价位", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(stopLoss) + slPct,
text_color=color.new(#ff6699, 0),
text_size=getTableSize(), bgcolor=color.new(#330d1a, 0))
rowIndex += 1
// 止盈目标行
if showTargets
// === 目标位1 - 蓝紫主题 ===
tp1Pct = calcTakeProfitPercentage(entryPrice, takeProfit1, entryType)
tp1Reached = na(takeProfit1) ? false :
(entryType == "多单" ? high >= takeProfit1 : low <= takeProfit1)
tp1Icon = tp1Reached ? " ✓" : ""
tp1Color = tp1Reached ? color.new(#66ff99, 0) : color.new(#99ccff, 0)
tp1BgColor = tp1Reached ? color.new(#0d2619, 0) : color.new(#0d1a26, 0)
table.cell(infoTable, 0, rowIndex, "止盈目标1", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(takeProfit1) + tp1Pct + tp1Icon,
text_color=tp1Color,
text_size=getTableSize(), bgcolor=tp1BgColor)
rowIndex += 1
// === 目标2 - 蓝紫主题 ===
tp2Pct = calcTakeProfitPercentage(entryPrice, takeProfit2, entryType)
tp2Reached = na(takeProfit2) ? false :
(entryType == "多单" ? high >= takeProfit2 : low <= takeProfit2)
tp2Icon = tp2Reached ? " ✓" : ""
tp2Color = tp2Reached ? color.new(#66ff99, 0) : color.new(#cc99ff, 0)
tp2BgColor = tp2Reached ? color.new(#0d2619, 0) : color.new(#1a0d26, 0)
table.cell(infoTable, 0, rowIndex, "止盈目标2", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(takeProfit2) + tp2Pct + tp2Icon,
text_color=tp2Color,
text_size=getTableSize(), bgcolor=tp2BgColor)
rowIndex += 1
// === 盈亏比行 - 蓝紫主题 ===
if showRatio
rrColor = color.new(#9999ff, 0)
rrBgColor = color.new(#0d0d1a, 0)
if not na(riskRewardRatio)
if riskRewardRatio >= 2
rrColor := color.new(#66ff99, 0)
rrBgColor := color.new(#0d2619, 0)
else if riskRewardRatio >= 1
rrColor := color.new(#ffcc99, 0)
rrBgColor := color.new(#1a1a0d, 0)
else
rrColor := color.new(#ff9966, 0)
rrBgColor := color.new(#1a1a0d, 0)
table.cell(infoTable, 0, rowIndex, "盈亏比例", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, riskRewardStr,
text_color=rrColor,
text_size=getTableSize(), bgcolor=rrBgColor)
rowIndex += 1
// === 免责声明行 - 蓝紫主题 ===
table.cell(infoTable, 0, rowIndex, "⚠ 风险提示", text_color=color.new(#9999ff, 0),
text_size=size.small, bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, "仅供参考,不构成投资建议,盈亏自负",
text_color=color.new(#9999ff, 0),
text_size=size.small, bgcolor=color.new(#1a1a4d, 0))
LE LevelsGENERAL OVERVIEW:
The LE Levels indicator plots yesterday’s high/low and today’s pre-market high/low directly on your chart, then layers signal logic around those levels and a set of EMA waves. You can choose “Inside” setups, “Outside” setups, or both. You can also pick entries that trigger at levels, entries that trigger off the EMA wave, or both.
This indicator was developed by Flux Charts in collaboration with Ellis Dillinger (Ellydtrades).
What is the purpose of the indicator?:
The purpose of the LE Levels indicator is to give traders a clear view of how price is behaving around key session levels and EMA structure. It follows the same model EllyD teaches by showing where price is relative to the Previous Day High and Low and the Pre-Market High and Low, then printing signals when specific reactions occur around those levels.
What is the theory behind the indicator?:
The theory behind the LE Levels indicator is based on the concept of inside and outside days. An inside day occurs when price trades within the previous day’s high and low, signaling compression and potential breakout conditions. An outside day occurs when price moves beyond those boundaries, confirming expansion and directional bias. When price trades above the PDH or PMH, it reflects bullish control and potential continuation if supported by volume and momentum. When price trades below the PDL or PML, it shows bearish control and possible downside continuation. The idea is to combine this logic with tickers that have catalysts or news, since these events often bring higher-than-normal volume.
LE SCANNER FEATURES:
Key Levels
Signals
EMA Waves
Key Levels:
The LE Levels indicator automatically plots four key levels each day:
Previous Day High (PDH)
Previous Day Low (PDL)
Pre-Market High (PMH)
Pre-Market Low (PML)
🔹How are Key Levels used in the indicator?:
The key levels are a crucial factor in determining if the trend is bullish, bearish, or neutral trend bias. The indicator uses the key levels as a condition for identifying inside or outside setups (explained below). After determining a trend bias and setup type, the indicator prints long and short entry signals based on how price interacts with the key levels and 8 EMA Wave. (explained below).
These levels define where price previously reacted or reversed, helping traders visualize how current price action relates to prior session structure. They update automatically each day and pre-market session, allowing traders to see if price is trading inside, above, or below prior key ranges without manually drawing them.
Please Note: Pre-market times are based on U.S. market hours (Eastern Standard Time) and may vary for non-U.S. tickers or exchanges.
🔹Previous Day High (PDH):
The PDH marks the highest price reached during the previous regular trading session. It shows where buyers pushed price to its highest point before the market closed. This value is automatically pulled from the daily chart and projected forward onto intraday timeframes.
🔹Previous Day Low (PDL):
The PDL marks the lowest price reached during the previous regular trading session. It shows where selling pressure reached its lowest point before buyers stepped in. Like the PDH, this level is retrieved from the prior day’s data and extended into the current session.
🔹Pre-Market High (PMH):
The PMH is the highest price reached between 4:00 AM and 9:29 AM EST, before the regular market open. It shows how far buyers managed to push price up during the pre-market session.
🔹Pre-Market Low (PML):
The PML is the lowest price reached between 4:00 AM and 9:29 AM EST, before the regular market open. It shows how far sellers were able to drive price down during the pre-market session.
🔹Customization Options:
Extend Levels:
Extends each plotted line a user-defined number of bars into the future, keeping them visible even as new candles print. This helps maintain a clear visual reference as the session progresses.
Extend PDH/L Left & Extend PMH/L Left:
These settings let you extend the Previous Day and Pre-Market levels back to their origin point, so you can see exactly where each level was formed on the prior trading day. This makes it easy to understand the context of each level and how it developed. When this option is disabled, the lines begin at the regular session open instead of extending backward into the previous day’s data.
Show Name / Show Price:
Enabling Show Name displays labels (PDH, PDL, PMH, PML) beside each line, while Show Price adds the exact price value. You can choose to show just the name, just the price, or both for a complete label format.
Line Color and Style:
Each level can be fully customized. You can change the line color and select between solid, dashed, or dotted styles to visually distinguish each level type.
At the bottom of the indicator settings, under the ‘Miscellaneous’ section, two additional options allow further control over how levels are displayed:
Hide Previous Day Highs/Lows:
When enabled, the previous day’s high and low levels aren’t shown. When disabled, users can view previous day levels without using replay mode. By default, this setting is enabled.
Disabled:
Enabled:
Hide Previous Pre-Market Highs/Lows:
When enabled, the previous pre-market high and low levels aren’t shown. When disabled, users can view previous pre-market levels without using replay mode. By default, this setting is enabled.
Disabled:
Enabled:
Signals:
The LE Levels indicator automatically prints long and short entry signals based on how price interacts with its key levels (PDH, PDL, PMH, PML) and the EMA Waves. It identifies moments when price either breaks out beyond prior ranges or retests those levels in alignment with momentum shown by the EMA Waves.
There are two types of setups (Inside and Outside) and two entry types ((L)evels and (E)MAs). Together, these settings allow traders to customize the type of structure the indicator recognizes and how signals are generated.
🔹What is an Inside Setup?
An Inside Setup occurs when the current trading session forms entirely within the previous day’s range, meaning price has not yet broken above the Previous Day High (PDH) or below the Previous Day Low (PDL). In the LE Levels indicator, inside setups are recognized when price trades within the previous day’s boundaries while also considering the pre-market range (Pre-Market High and Pre-Market Low).
Inside Setups have two main conditions, depending on directional bias:
Bullish Inside Setup:
Price trades above the Pre-Market High (PMH) and above the Previous Day Low (PDL), while still below the Previous Day High (PDH).
Bearish Inside Setup:
Price trades below the Pre-Market Low (PML) and below the Previous Day High (PDH), while still above the Previous Day Low (PDL).
🔹What is an Outside Setup?
An Outside Setup occurs when the current trading session extends beyond the previous day’s range, meaning price has broken above the Previous Day High (PDH) or below the Previous Day Low (PDL). This structure reflects expansion and directional control, showing that either buyers or sellers have taken price into new territory beyond the prior session’s boundaries.
In the indicator, an Outside Setup forms once price closes beyond both the previous day and pre-market boundaries, showing bias in one direction.
Bullish Outside Setup:
Price closes above both the PDH and the PMH, confirming buyers have pushed through every key resistance from the prior session and the pre-market.
Bearish Outside Setup:
Price closes below both the PDL and the PML, showing sellers have pushed price beneath all key support levels from the previous session and the pre-market.
🔹Entry Types: (L)evels and (E)MAs
Once a setup type (Inside or Outside) has been established, the LE Levels indicator generates trade signals using one of two entry confirmation methods: (L) for Key Level based Entries and (E) for EMA Wave based Entries. These determine how the signal prints and what triggers it within.
🔹(L)evels Entry:
The (L)evels entry type is built around how price reacts to the key levels (PDH, PDL, PMH, PML). It prints when price retests those levels during an active setup. The logic focuses on retests, where price returns to confirm a previous breakout or breakdown before continuing in the same direction.
Bullish Outside (L)evels Setup:
A Bullish Outside Setup forms when price breaks above both the PDH and PMH. Once this breakout occurs, the indicator waits for a pullback to one of those levels. For a signal to print, the 8 EMA Wave must also be near that level, showing momentum is supporting the structure. A small buffer is applied between price and the level so that even if price only comes close, without fully touching, the retest still counts. When price holds above the PDH or PMH with the 8 EMA nearby, the indicator prints an (L) ▲ entry.
Bearish Outside (L)evels Setup:
A Bearish Outside Setup forms when price breaks below both the PDL and PML. Once this breakdown occurs, the indicator waits for a pullback to one of those levels. For a signal to print, the 8 EMA Wave must also be near that area, confirming momentum is aligned with the move. A small buffer is included so that even if price comes close but doesn’t fully touch the level, the retest still qualifies. When price holds below the PDL or PML with the 8 EMA nearby, the indicator prints an (L) ▼ entry.
Bullish Inside (L)evels Setup:
A Bullish Inside Setup forms when price trades above the PMH but stays below the PDH and above the PDL. Once this condition is met, the indicator waits for a pullback to the PMH. For a signal to print, the 8 EMA Wave must also be near that level. A small buffer is applied so that even if price only comes close to the level, the retest still counts. When price holds above the PMH with the 8 EMA nearby, the indicator prints an (L) ▲ entry.
Bearish Inside (L)evels Setup:
A Bearish Inside Setup forms when price trades below the PML but stays above the PDL and below the PDH. Once this condition is met, the indicator waits for a pullback to the PML. For a signal to print, the 8 EMA Wave must also be near that level. A small buffer is applied so that even if price only comes close, the retest still counts. When price holds below the PML with the 8 EMA nearby, the indicator prints an (L) ▼ entry.
🔹(E)MAs Entry:
The (E)MA Entry type focuses on how price reacts to the 8 EMA Wave. It identifies when price first interacts with the EMAs, then confirms continuation once momentum resumes in the setup’s direction. The first candle that touches the EMA prints an (E) marker, and the confirmation signal triggers only after price breaks above or below that candle, depending on the bias.
Bullish Outside (E)MA Setup:
A Bullish Outside Setup forms when price is trading above both the PDH and PMH. Once this breakout occurs, the indicator waits for price to pull back and touch the 8 EMA Wave, which prints the initial (E) label. If price then breaks above that candle’s high, the continuation setup is confirmed.
Bearish Outside (E)MA Setup:
A Bearish Outside Setup forms when price is trading below both the PDL and PML. After the breakdown, the indicator waits for price to pull back to the 8 EMA Wave, marking the candle that touches it with an (E) label. If price then breaks below that candle’s low, the continuation setup is confirmed.
Bullish Inside (E)MA Setup:
A Bullish Inside Setup forms when price trades above the PMH but remains below the PDH and above the PDL. The indicator waits for price to retrace and touch the 8 EMA Wave, which prints the initial (E) label. If price then breaks above that candle’s high, the continuation setup is confirmed.
Bearish Inside (E)MA Setup:
A Bearish Inside Setup forms when price trades below the PML but remains above the PDL and below the PDH. Once price touches the 8 EMA Wave, the indicator prints an (E) marker. If price then breaks below that candle’s low, the continuation setup is confirmed.
🔹Signal Settings:
At the bottom of the indicator settings panel, three core controls define how signals are displayed and which setups the indicator actively scans for. These settings allow you to refine signal generation based on your trading approach and chart preference.
Setup Type:
This setting determines which structural conditions the indicator tracks.
Inside Setups: Signals only appear when price is trading within the previous day’s range (between PDH and PDL).
Outside Setups: Signals only appear when price breaks outside the previous day’s range (above PDH/PMH or below PDL/PML).
Both: Enables signals for both Inside and Outside setups.
Entry Type:
Controls how the indicator confirms entries.
(E)MAs: Prints signals based on price interacting with the 8 EMA Wave.
(L)evels: Prints signals based on price retesting key levels such as PDH, PDL, PMH, or PML.
Both: Allows both EMA and Level-based signals to appear on the same chart.
Signal Filters (Long, Short, and Re-Entry):
These toggles let you control which trade directions are active.
Long: Displays only bullish entries and ignores all short setups.
Short: Displays only bearish entries and ignores long setups.
Re-Entry: Enables or disables repeated signals in the same direction after the first valid setup has printed. When off, only the initial signal is shown until conditions reset.
EMA Waves:
The EMA Waves help identify potential entries and show directional bias. They’re made of grouped EMAs that form shaded areas to create a “wave” look. The color-coding on the waves allows users to view when price is consolidating, in a bullish trend, or in a bearish trend. The wave updates in real time as new candles form and does not repaint historical data.
🔹8 EMA Wave
The 8 EMA Wave is used directly in the indicator’s signal logic described earlier. It reacts fastest to price compared to the other EAM Waves and determines when (L) and (E) signals can trigger.
How It Works:
The wave is made from the 8, 9, and 10 EMAs and fills the space between them to create a “wave” look. The 8 EMA Wave continuously updates its color based on where price trades relative to the key levels (PDH, PDL, PMH, PML). The color changes are conditional and based solely on price position relative to key levels.
Price is above both PDH and PMH: The wave is bright green, and the top half is purple.
Price is between PDH and PMH: The wave is dark green, and the top half is purple.
Price is below both PDL and PML: The wave is bright red, and the bottom half is purple.
Price is between PDL and PML: The wave is dark red, and the bottom half is purple.
Price is between all four levels: The wave is gray to represent consolidation or neutral bias.
🔹8 EMA Wave Signal Function:
For (L)evels entries, the 8 EMA must be close to the key level being retested, with a small buffer that allows near touches to qualify.
For (E)MA entries, the first candle that touches the wave prints an (E), and the confirmation signal appears when price breaks that candle’s high or low.
🔹8 EMA Wave Customization:
Users can customize all colors for bullish, bearish, and neutral conditions directly in the settings. The purple overlay color cannot be changed, as it is hard-coded into the indicator. The 8 EMA Wave can also be toggled on or off. Turning it off only removes the visual display from the chart and does not affect signals.
🔹20 EMA Wave
The 20 EMA Wave measures medium-term momentum and helps visualize larger pullbacks. It reacts more slowly than the 8 EMA Wave, giving a smoother wave look. No signals are generated from it. It’s purely a visual guide for spotting potential pullback areas for continuation setups.
How It Works:
The wave is made from the 19, 20, and 21 EMAs and fills the space between them to create a shaded “wave.” The color updates continuously based on where price trades relative to the key levels (PDH, PDL, PMH, PML). The color changes are conditional and based only on price position relative to these levels.
Price is above both PDH and PMH: The wave is bright green, and the top half is blue.
Price is between PDH and PMH: The wave is dark green, and the top half is blue.
Price is below both PDL and PML: The wave is bright red, and the bottom half is blue.
Price is between PDL and PML: The wave is dark red, and the bottom half is blue.
Price is between all four levels: The wave is gray to represent consolidation or neutral bias.
🔹20 EMA Wave Use Case:
After 12:00 PM EST, the 20 EMA Wave is used to spot larger pullbacks that form later in the session. No signals are generated from it; it only serves as a visual guide for identifying potential continuation areas.
Bullish Continuation Pullback:
Bearish Continuation Pullback:
🔹20 EMA Wave Customization:
Users can customize all colors for bullish, bearish, and neutral conditions directly in the settings. The blue overlay color cannot be changed, as it is hard-coded into the indicator. The 20 EMA Wave can also be toggled on or off.
🔹200 EMA Wave
The 200 EMA Wave is used to determine long-term trend bias. When price is above it, the bias is bullish; when price is below it, the bias is bearish. It updates automatically in real time and is used to define the broader directional bias for the day.
How it Works:
The 200 EMA Wave is created using the 190, 199, and 200 EMAs, with the area between them shaded to form a “wave.”
🔹200 EMA Wave Use Case:
When price is above the 200 EMA Wave and both the 8 and 20 EMA Waves are stacked above it, the overall trend is bullish.
When price is below the 200 EMA Wave and both shorter-term waves are also below it, the overall trend is bearish.
🔹200 EMA Wave Customization:
Users can customize both colors that form the 200 EMA Wave. The entire wave can also be toggled on or off in the settings.
Uniqueness:
The LE Levels indicator is unique because it combines signal logic with a clear visual structure. It automatically detects inside and outside setups, printing (L) and (E) entries based on how price reacts to key levels and the EMA Waves. Each signal follows strict conditions tied to the 8 EMA and key levels. The color-coded EMA Waves make it simple to understand where price is in relation to the key levels and getting a quick trend bias overview.
ORB Dashboard for the TFLX Strategy# ORB Range/ATR Dashboard - Technical Indicator Description
## Main Function
This indicator analyzes Opening Range Breakout (ORB) patterns by calculating a defined time period and its relation to historical volatility. The indicator combines multiple technical analysis methods and presents results in a configurable dashboard format.
**Purpose:** This indicator automates the manual calculation steps of the TFLX analysis methodology, providing real-time computation of volatility ratios, trend filters, and risk management parameters that would otherwise require manual calculation and monitoring.
## Requirements and Limitations
**Additional Indicator Required:** This dashboard indicator works in conjunction with a separate ORB range visualization indicator that displays the actual high/low range levels on the chart. The dashboard provides analysis and calculations, while the range indicator provides visual reference points.
**Important Notice:** This indicator serves as an analytical tool and calculation assistant for the TFLX methodology. It does not execute trades automatically but provides data analysis to support manual decision-making processes.
## TFLX Analysis Methodology Framework
### Core Analysis Rules (Discretionary Implementation)
**Primary Conditions:**
- Market position relative to neutral zones (BB analysis)
- Volatility range between 15-60% of ATR(3)
- News event screening (high-impact economic releases)
- Market session timing constraints (before calculated session end)
- US Bank Holiday considerations
**Exception Conditions:**
- High-impact news with rebreak patterns
- Reversal patterns during neutral market conditions
### Technical Specifications of the Methodology
**Range Definition:**
- Time Period: First 15 minutes after market open
- Measurement: High-Low range calculation
- Breakout Trigger: 5-minute close outside established range
**Volatility Analysis:**
- Formula: (Range Points / ATR(3) Previous Day) × 100
- Threshold Ranges:
- <15%: Below minimum threshold
- 15-20%: Low volatility range
- 25-30%: Moderate volatility range
- 30-40%: Good volatility range
- 40-50%: High volatility range
- 50-60%: Very high volatility range
- >60%: Above maximum threshold
**News Event Categories:**
- Major Events: NFP, CPI, PPI, FOMC releases
- Minor Events: All significant economic releases during market hours
- Impact Assessment: Market reaction analysis framework
**Trend Analysis Framework (1H Bollinger Bands):**
- Base Calculation: EMA(200) with standard deviation bands
- Reference Points: Market Open, ORB Close, Trigger Bar
- Decision Logic: 2 out of 3 reference points determine bias
- Zone Classifications:
- Within 0.5 multiplier: Neutral zone
- Within 1.5 multiplier: Directional bias zone
- Outside 1.5 multiplier: Strong directional zone
**Timing Constraints:**
- Session Window: Market open to calculated session end (typically 4.5 hours)
- Retracement Analysis: Maximum adverse movement before breakeven or stop loss
**Manual Calculation Process (Automated by Indicator):**
1. Measure range in points using chart measurement tools
2. Switch to daily timeframe
3. Set ATR period to 3
4. Extract previous day's ATR value
5. Calculate: (Range Points ÷ ATR Value) × 100
6. Apply percentage thresholds for analysis
## Core Components and Calculation Methods
### 1. Opening Range Calculation
**Data Source:** High/Low/Close prices of current timeframe
**Calculation:**
- Defines a configurable time period (default: 15 minutes)
- Collects during this period: `range_high = max(high)` and `range_low = min(low)`
- Calculates Range Size: `range_size = range_high - range_low`
- Stores the last close price of the period: `final_orb_close`
### 2. ATR (Average True Range) Integration
**Data Source:** Daily True Range values
**Calculation:**
```
daily_atr = ta.atr(length) // Default 3 periods
atr_yesterday = daily_atr // Previous trading day
```
**Available Methods:** RMA (default), SMA, EMA, WMA
### 3. Volatility Ratio Calculation
**Formula:**
```
ratio = (range_size / atr_yesterday) * 100
```
**Purpose:** Normalization of current range against historical volatility
**Configurable Parameters:** Min/Max thresholds (default: 15-60%)
### 4. Bollinger Bands Integration (1H Timeframe)
**Data Source:** 1-hour chart data via `request.security()`
**Calculation:**
```
bb_ema = ta.ema(close, 200) // 1H timeframe
bb_std = ta.stdev(close, 200) // 1H timeframe
bb_upper = bb_ema + (bb_std * multiplier)
bb_lower = bb_ema - (bb_std * multiplier)
```
**Configurable Multipliers:**
- Neutral Zone: 0.5x standard deviation
- Strong Zone: 1.5x standard deviation
### 5. Trend Filter System (2/3 Method)
**Components:**
1. **NY Open Signal:** Compares 1H open price with BB levels
2. **ORB Close Signal:** Compares final ORB close with BB levels
3. **Trigger Signal:** Compares breakout price with BB levels
**Logic:**
```
if (bullish_signals >= 2) → "BULLISH"
if (bearish_signals >= 2) → "BEARISH"
else → "MIXED" or "NO TREND"
```
## Component Interaction
### Trade Signal Generation
**Algorithm:**
```
trade_allowed = (orb_ratio >= min_threshold AND orb_ratio <= max_threshold)
AND (bb_signal != "NEUTRAL")
AND (trend_filter_result contains "BULLISH" OR "BEARISH")
```
### Risk Management Calculation
**Entry Points:**
- Long Entry: `range_high`
- Short Entry: `range_low`
**Stop Loss Calculation:**
```
sl_level = range_low + (range_size * sl_position_percent / 100)
```
**Take Profit Calculation:**
```
tp_distance = range_size * tp_factor_percent / 100
long_tp = long_entry + tp_distance
short_tp = short_entry - tp_distance
```
**Position Sizing (CFD-optimized):**
```
risk_per_contract = avg_risk_points * contract_value * lot_size
max_contracts = max_risk_amount / risk_per_contract
```
**Margin Calculation (CFDs):**
```
position_value = total_units * entry_price
margin_required = position_value / leverage
```
## Dashboard Elements
### 1. Volatility Filter Section
- **ORB Range:** Current range in points
- **ATR Previous:** Yesterday's ATR values
- **ORB Ratio:** Calculated ratio with color coding
### 2. Trend Filter Section
- **NY Open vs BB:** Position of 1H open relative to BB
- **ORB Close vs BB:** Position of ORB close relative to BB
- **Trigger Bar vs BB:** Position of breakout price relative to BB
- **Trend Result:** Summary of 2/3 filter
### 3. Risk Management Section (optional)
- **R/R Ratio:** Calculated from TP/SL distances
- **Risk per Lot:** Based on instrument type
- **Max Lot Packages:** Automatic position sizing calculation
- **Margin Required:** For CFD instruments
### 4. Journal Section (optional)
- **Breakout Timing:** Categorization by bars (1-3, 4-6, 7-9, 10-12, 13+)
- **Direction Tracking:** Bullish/Bearish breakout direction
- **Position Analysis:** Distance of breakout to ORB range
## Automatic Instrument Detection
**CFD/Index Treatment:**
```
if (syminfo.type == "cfd" OR syminfo.type == "index")
contract_value = 1.0 * cfd_lot_size
```
**Forex Treatment:**
```
if (syminfo.type == "forex")
contract_value = syminfo.pointvalue * cfd_lot_size
```
**Futures/Stocks:**
```
contract_value = syminfo.pointvalue
```
## Timezone Handling
- All time calculations based on configurable timezone
- Session End Time: ORB Start + 4.5 hours
- Automatic overflow handling for 24h format
## Alert System
**ORB Formation Alert:**
- Triggered upon completion of ORB period
- Includes: Range size, high/low values
**Breakout Alert:**
- Triggered on close price outside ORB range
- Includes: Direction, trade status based on filters
## Configuration Options
- **ORB Period:** Start/end time in hours/minutes
- **ATR Parameters:** Period and calculation method
- **Volatility Thresholds:** Min/max percentage limits
- **BB Parameters:** Period and multipliers
- **Risk Management:** Risk amount, SL/TP positions
- **Dashboard Layout:** Position, size, colors, visibility
## Data Integrity
- State variables with `var` declaration for persistence
- Daily reset of all relevant variables
- Lookahead bias prevention through `barmerge.lookahead_off`
- Multi-timeframe safety through `request.security()` functions
This technical implementation provides a comprehensive analysis framework for Opening Range Breakout patterns with integrated volatility, trend, and risk management components.
coinbot_ICT_Unicorn(AUTOTRADE)1. 🎯 핵심 기능: 자동매매 신호 전송 (Webhook)
이 스크립트는 매매 신호가 발생할 때마다, 사용자가 '자동매매 설정(Autotrade Settings)'에 입력한 값들을 조합하여 구체적인 JSON 메시지를 생성하고 alert() 함수를 통해 웹훅으로 전송합니다.
입력 설정: user_id, exchange(거래소), leverage(레버리지), capital_percent(투입 시드 %), sl_percent(손절 %), 그리고 3단계 분할 익절(tp1_price_percent, tp1_qty_percent 등) 설정을 입력받습니다.
신호 종류:
ENTRY (진입): 매수(buy) 또는 매도(sell) 신호가 발생하면, 위 모든 설정값을 포함한 진입 명령을 보냅니다.
CLOSE (손절): 전략의 내부 로직에 의해 손절가에 도달하면(slAlertTick), 포지션을 종료하라는 신호를 보냅니다.
TAKE_PROFIT (익절): 목표가에 도달하면(tpAlertTick), 설정된 물량만큼 익절하라는 신호를 보냅니다.
2. 📈 작동 원리: "ICT 유니콘" 매매 전략
이 스크립트의 진입 로직은 ICT(Inner Circle Trader) 개념 중 하나인 **'유니콘 모델'**을 따릅니다.
구성 요소 식별:
Breaker Block (BB): '브레이커 블록'을 식별합니다. 이는 특정 고점/저점을 만든 후 그 방향으로 가지 못하고 반대 방향으로 돌파(Break)된 오더 블록(Order Block)입니다.
Fair Value Gap (FVG): '공정 가치 갭' (가격 불균형 영역)을 식별합니다.
핵심 진입 신호 (Unicorn): 이 전략의 핵심 진입 조건은 **Breaker Block(BB)과 Fair Value Gap(FVG)이 중첩(Overlap)**되는, 소위 '유니콘'이라 불리는 강력한 지지/저항 영역이 발생하는 것입니다.
Long (매수) 진입:
가격이 하락하며 **'하락형 브레이커 블록(Bearish Breaker Block)'**을 만듭니다.
이후 가격이 상승 돌파하며 이 브레이커 블록 영역과 중첩되는 **'상승형 FVG(Bullish FVG)'**를 생성합니다.
이 중첩 영역(FVG-BB Overlap)이 바로 매수 진입의 근거가 됩니다. (코드가 dbgRequireRetracement 설정에 따라 FVG로의 되돌림을 기다리거나 즉시 진입 신호를 보냅니다.)
Short (매도) 진입:
가격이 상승하며 **'상승형 브레이커 블록(Bullish Breaker Block)'**을 만듭니다.
이후 가격이 하락 돌파하며 이 브레이커 블록 영역과 중첩되는 **'하락형 FVG(Bearish FVG)'**를 생성합니다.
이 중첩 영역이 매도 진입의 근거가 됩니다.
3. 📊 부가 기능
시각화: 차트 상에 FVG 영역과 Breaker Block 영역을 박스로 그려주어(설정에 따라 표시/숨김 가능) 매매 근거를 시각적으로 확인할 수 있게 합니다.
백테스팅 대시보드: 차트 우측 상단(기본값)에 이 전략의 누적 성과(총 진입 횟수, 승/패, 승률, 총수익률)를 보여주는 대시보드를 표시합니다.
요약
이 스크립트는 **"Breaker Block과 FVG의 중첩(유니콘 모델)"**을 유일한 진입 조건으로 사용하는 매우 구체적인 ICT 전략입니다. 이 조건이 충족되면, 사용자가 미리 설정한 상세한 리스크 관리 값들을 담아 자동매매 봇으로 즉시 실행 가능한 주문 신호를 전송하는 '올인원(All-in-One)' 전략 스크립트입니다.
요청하신 대로, 해당 지표 요약본을 영어로 번역하여 제공합니다.
This script is an automated trading (Autotrade) strategy signal generator based on the ICT "Unicorn" trading model.
As the "AUTOTRADE" in its name implies, the core purpose of this indicator is to detect specific conditions on the chart and send JSON-formatted order signals (webhooks) to an external automated trading bot.
Here are the core mechanics and features of this script:
1. 🎯 Core Feature: Automated Signal Transmission (Webhook)
Whenever a trade signal occurs, this script generates a specific JSON message by combining the values entered by the user in the "Autotrade Settings" and sends it via webhook using the alert() function.
Input Settings: It takes inputs for user_id, exchange, leverage, capital_percent (equity %), sl_percent (stop loss %), and settings for 3-stage split take-profits (e.g., tp1_price_percent, tp1_qty_percent).
Signal Types:
ENTRY: When a "buy" or "sell" signal occurs, it sends an entry command including all the settings above.
CLOSE (Stop-Loss): If the price hits the stop loss according to the strategy's internal logic (slAlertTick), it sends a signal to close the position.
TAKE_PROFIT: When a profit target is reached (tpAlertTick), it sends a signal to take profit on the specified quantity.
2. 📈 How It Works: The "ICT Unicorn" Strategy
The script's entry logic follows the "Unicorn Model," one of the concepts from ICT (Inner Circle Trader).
Identifying Components:
Breaker Block (BB): It identifies a "Breaker Block." This is an Order Block that, after creating a specific high/low, fails to continue in that direction and is instead broken through in the opposite direction.
Fair Value Gap (FVG): It identifies a "Fair Value Gap" (a price imbalance area).
Core Entry Signal (The Unicorn): The core entry condition for this strategy is the overlap of a Breaker Block (BB) and a Fair Value Gap (FVG), which creates a powerful support/resistance zone known as the "Unicorn."
Long Entry:
Price moves down, creating a "Bearish Breaker Block."
Subsequently, price breaks upward, creating a "Bullish FVG" that overlaps with this Breaker Block area.
This overlapping area (FVG-BB Overlap) becomes the basis for the long entry. (Depending on the dbgRequireRetracement setting, the code either waits for a retracement to the FVG or sends an immediate entry signal.)
Short Entry:
Price moves up, creating a "Bullish Breaker Block."
Subsequently, price breaks downward, creating a "Bearish FVG" that overlaps with this Breaker Block area.
This overlapping area becomes the basis for the short entry.
3. 📊 Additional Features
Visualization: It draws the FVG and Breaker Block zones as boxes on the chart (can be toggled in settings), allowing for visual confirmation of the trade setup.
Backtesting Dashboard: It displays a dashboard in the top-right corner (by default) showing the strategy's cumulative performance (total entries, wins/losses, win rate, total profit).
Summary
This script is a highly specific ICT strategy that uses the "overlap of a Breaker Block and an FVG (the Unicorn Model)" as its sole entry condition. When this condition is met, it transmits an immediately executable order signal to an automated trading bot, complete with all the detailed risk management values preset by the user. It is an "all-in-one" strategy script.
Katz Exploding PowerBand FilterUnderstanding the Katz Exploding PowerBand Filter (EPBF) v2.4
1. Indicator Overview
The Katz Exploding PowerBand Filter (EPBF) is an advanced technical indicator designed to identify moments of expanding bullish or bearish momentum, often referred to as "power." It operates as a standalone oscillator in a separate pane below the main price chart.
Its primary goal is to measure underlying market strength by calculating custom "Bull" and "Bear" power components. These components are then filtered through a versatile moving average and a dual signal line system to generate clear entry and exit signals. This indicator is not a simple momentum oscillator; it uses a unique calculation based on exponential envelopes of both price and squared price to derive its values.
2. On-Chart Lines and Components
The indicator pane consists of five main lines:
Bullish Component (Thick Green/Blue/Yellow/Gray Line): This is the core of the indicator. It represents the calculated bullish "power" or momentum in the market.
Bright Green: Indicates a strong, active long signal condition.
Blue: Shows the bull component is above the MA filter, but the filter itself is still pointing down—a potential sign of a reversal or weakening downtrend.
Yellow: A warning sign that bullish power is weakening and has fallen below the primary signal lines.
Gray: Represents neutral or insignificant bullish power.
Bearish Component (Thick Red/Purple/Yellow/Gray Line): This line represents the calculated bearish "power" or downward momentum.
Bright Red: Indicates a strong, active short signal condition.
Purple: Shows the bear component is above the MA filter, but the filter itself is still pointing down—a sign of potential trend continuation.
Yellow: A warning sign that bearish power is weakening.
Gray: Represents neutral or insignificant bearish power.
MA Filter (Purple Line): This is the main filter, calculated using the moving average type and length you select in the settings (e.g., HullMA, EMA). The Bull and Bear components are compared against this line to determine the underlying trend bias.
Signal Line 1 (Orange Line): A fast Exponential Moving Average (EMA) of the stronger power component. It acts as the first level of dynamic support or resistance for the power lines.
Signal Line 2 (Lime/Gray Line): A slower EMA that acts as a confirmation filter.
Lime Green: The line turns lime when it is rising and the faster Signal Line 1 is above it, indicating a confirmed bullish trend in momentum.
Gray: Indicates a neutral or bearish momentum trend.
3. On-Chart Symbols and Their Meanings
Various characters are plotted at the bottom of the indicator pane to provide clear, actionable signals.
L (Pre-Long Signal): The first sign of a potential long entry. It appears when the Bullish Component rises and crosses above both signal lines for the first time.
S (Pre-Short Signal): The first sign of a potential short entry. It appears when the Bearish Component rises and crosses above both signal lines for the first time.
▲ (Post-Long Signal): A stronger confirmation for a long entry. It appears with the 'L' signal only if the momentum trend is also confirmed bullish (i.e., the slower Signal Line 2 is lime green).
▼ (Post-Short Signal): A stronger confirmation for a short entry. It appears with the 'S' signal only if the momentum trend is confirmed bullish.
Exit / Take-Profit Symbols:
These symbols appear when a power component crosses below a line, suggesting that momentum is fading and it may be time to take profit.
⚠️ (Exit Signal 1): The Bull/Bear component has crossed below the main MA Filter. This is the first and most sensitive take-profit signal.
☣️ (Exit Signal 2): The Bull/Bear component has crossed below the faster Signal Line 1. This is a moderate take-profit signal.
🚼 (Exit Signal 3): The Bull/Bear component has crossed below the slower Signal Line 2. This is the slowest take-profit signal, suggesting the trend is more definitively exhausted.
4. Trading Strategy and Rules
Long Entry Rules:
Initial Signal: Wait for an L to appear at the bottom of the indicator. This confirms that bullish power is expanding.
Confirmation (Recommended): For a higher-probability trade, wait for a green ▲ symbol to appear. This confirms the underlying momentum trend aligns with the signal.
Entry: Enter a long (buy) position on the opening of the next candle after the signal appears.
Short Entry Rules:
Initial Signal: Wait for an S to appear at the bottom of the indicator. This confirms that bearish power is expanding.
Confirmation (Recommended): For a higher-probability trade, wait for a maroon ▼ symbol to appear. This confirms the underlying momentum trend aligns with the signal.
Entry: Enter a short (sell) position on the opening of the next candle after the signal appears.
Take Profit (TP) Rules:
The indicator provides three levels of take-profit signals. You can choose to exit your entire position or scale out at each level.
For a long trade, exit when you see ⚠️, ☣️, or 🚼 appear below the Bullish Component.
For a short trade, exit when you see ⚠️, ☣️, or 🚼 appear below the Bearish Component.
Stop Loss (SL) Rules:
The indicator does not provide an explicit stop loss. You must use your own risk management rules. Common methods include:
Swing High/Low: For a long position, place your stop loss below the most recent significant swing low on the price chart. For a short position, place it above the most recent swing high.
ATR-Based: Use an Average True Range (ATR) indicator to set a volatility-based stop loss.
Fixed Percentage: Risk a fixed percentage (e.g., 1-2%) of your account on the trade.
5. Disclaimer
This indicator is a tool for technical analysis and should not be considered financial advice. All trading involves significant risk, and past performance is not indicative of future results. The signals generated by this indicator are probabilistic and can result in losing trades. Always use proper risk management, such as setting a stop loss, and never risk more than you are willing to lose. It is recommended to backtest this indicator and use it in conjunction with other forms of analysis before trading with real capital. The indicator should only be used for educational purposes.
EAOBS by MIGVersion 1
1. Strategy Overview Objective: Capitalize on breakout movements in Ethereum (ETH) price after the Asian open pre-market session (7:00 PM–7:59 PM EST) by identifying high and low prices during the session and trading breakouts above the high or below the low.
Timeframe: Any (script is timeframe-agnostic, but align with session timing).
Session: Pre-market session (7:00 PM–7:59 PM EST, adjustable for other time zones, e.g., 12:00 AM–12:59 AM GMT).
Risk-Reward Ratios (R:R): Targets range from 1.2:1 to 5.2:1, with a fixed stop loss.
Instrument: Ethereum (ETH/USD or ETH-based pairs).
2. Market Setup Session Monitoring: Monitor ETH price action during the pre-market session (7:00 PM–7:59 PM EST), which aligns with the Asian market open (e.g., 9:00 AM–9:59 AM JST).
The script tracks the highest high and lowest low during this session.
Breakout Triggers: Buy Signal: Price breaks above the session’s high after the session ends (7:59 PM EST).
Sell Signal: Price breaks below the session’s low after the session ends.
Visualization: The session is highlighted on the chart with a white background.
Horizontal lines are drawn at the session’s high and low, extended for 30 bars, along with take-profit (TP) and stop-loss (SL) levels.
3. Entry Rules Long (Buy) Entry: Enter a long position when the price breaks above the session’s high price after 7:59 PM EST.
Entry price: Just above the session high (e.g., add a small buffer, like 0.1–0.5%, to avoid false breakouts, depending on volatility).
Short (Sell) Entry: Enter a short position when the price breaks below the session’s low price after 7:59 PM EST.
Entry price: Just below the session low (e.g., subtract a small buffer, like 0.1–0.5%).
Confirmation: Use a candlestick close above/below the breakout level to confirm the entry.
Optionally, add volume confirmation or a momentum indicator (e.g., RSI or MACD) to filter out weak breakouts.
Position Size: Calculate position size based on risk tolerance (e.g., 1–2% of account per trade).
Risk is determined by the stop-loss distance (10 points, as defined in the script).
4. Exit Rules Take-Profit Levels (in points, based on script inputs):TP1: 12 points (1.2:1 R:R).
TP2: 22 points (2.2:1 R:R).
TP3: 32 points (3.2:1 R:R).
TP4: 42 points (4.2:1 R:R).
TP5: 52 points (5.2:1 R:R).
Example for Long: If session high is 3000, TP levels are 3012, 3022, 3032, 3042, 3052.
Example for Short: If session low is 2950, TP levels are 2938, 2928, 2918, 2908, 2898.
Strategy: Scale out of the position (e.g., close 20% at TP1, 20% at TP2, etc.) or take full profit at a preferred TP level based on market conditions.
Stop-Loss: Fixed at 10 points from the entry.
Long SL: Session high - 10 points (e.g., entry at 3000, SL at 2990).
Short SL: Session low + 10 points (e.g., entry at 2950, SL at 2960).
Trailing Stop (Optional):After reaching TP2 or TP3, consider trailing the stop to lock in profits (e.g., trail by 10–15 points below the current price).
5. Risk Management per Trade: Limit risk to 1–2% of your trading account per trade.
Calculate position size: Account Size × Risk % ÷ (Stop-Loss Distance × ETH Price per Point).
Example: $10,000 account, 1% risk = $100. If SL = 10 points and 1 point = $1, position size = $100 ÷ 10 = 0.1 ETH.
Daily Risk Limit: Cap daily losses at 3–5% of the account to avoid overtrading.
Maximum Exposure: Avoid taking both long and short positions simultaneously unless using separate accounts or strategies.
Volatility Consideration: Adjust position size during high-volatility periods (e.g., major news events like Ethereum upgrades or macroeconomic announcements).
6. Trade Management Monitoring :Watch for breakouts after 7:59 PM EST.
Monitor price action near TP and SL levels using alerts or manual checks.
Trade Duration: Breakout lines extend for 30 bars (script parameter). Close trades if no TP or SL is hit within this period, or reassess based on market conditions.
Adjustments: If the market shows strong momentum, consider holding beyond TP5 with a trailing stop.
If the breakout fails (e.g., price reverses before TP1), exit early to minimize losses.
7. Additional Considerations Market Conditions: The 7:00 PM–7:59 PM EST session aligns with the Asian market open (e.g., Tokyo Stock Exchange open at 9:00 AM JST), which may introduce higher volatility due to Asian trading activity.
Avoid trading during low-liquidity periods or extreme volatility (e.g., major crypto news).
Check for upcoming events (e.g., Ethereum network upgrades, ETF decisions) that could impact price.
Backtesting: Test the strategy on historical ETH data using the session high/low breakouts for the 7:00 PM–7:59 PM EST window to validate performance.
Adjust TP/SL levels based on backtest results if needed.
Broker and Fees: Use a low-fee crypto exchange (e.g., Binance, Kraken, Coinbase Pro) to maximize R:R.
Account for trading fees and slippage in your position sizing.
Time zone Adjustment: Adjust session time input for your time zone (e.g., "0000-0059" for GMT).
Ensure your trading platform’s clock aligns with the script’s time zone (default: America/New_York).
8. Example Trade Scenario: Session (7:00 PM–7:59 PM EST) records a high of 3050 and a low of 3000.
Long Trade: Entry: Price breaks above 3050 (e.g., enter at 3051).
TP Levels: 3063 (TP1), 3073 (TP2), 3083 (TP3), 3093 (TP4), 3103 (TP5).
SL: 3040 (3050 - 10).
Position Size: For a $10,000 account, 1% risk = $100. SL = 11 points ($11). Size = $100 ÷ 11 = ~0.09 ETH.
Short Trade: Entry: Price breaks below 3000 (e.g., enter at 2999).
TP Levels: 2987 (TP1), 2977 (TP2), 2967 (TP3), 2957 (TP4), 2947 (TP5).
SL: 3010 (3000 + 10).
Position Size: Same as above, ~0.09 ETH.
Execution: Set alerts for breakouts, enter with limit orders, and monitor TPs/SL.
9. Tools and Setup Platform: Use TradingView to implement the Pine Script and visualize breakout levels.
Alerts: Set price alerts for breakouts above the session high or below the session low after 7:59 PM EST.
Set alerts for TP and SL levels.
Chart Settings: Use a 1-minute or 5-minute chart for precise session tracking.
Overlay the script to see high/low lines, TP levels, and SL levels.
Optional Indicators: Add RSI (e.g., avoid overbought/oversold breakouts) or volume to confirm breakouts.
10. Risk Warnings Crypto Volatility: ETH is highly volatile; unexpected news can cause rapid price swings.
False Breakouts: Breakouts may fail, especially in low-volume sessions. Use confirmation signals.
Leverage: Avoid high leverage (e.g., >5x) to prevent liquidation during volatile moves.
Session Accuracy: Ensure correct session timing for your time zone to avoid misaligned entries.
11. Performance Tracking Journaling :Record each trade’s entry, exit, R:R, and outcome.
Note market conditions (e.g., trending, ranging, news-driven).
Review: Weekly: Assess win rate, average R:R, and adherence to the plan.
Monthly: Adjust TP/SL or session timing based on performance.
ai quant oculusAI QUANT OCULUS
Version 1.0 | Pine Script v6
Purpose & Innovation
AI QUANT OCULUS integrates four distinct technical concepts—exponential trend filtering, adaptive smoothing, momentum oscillation, and Gaussian smoothing—into a single, cohesive system that delivers clear, objective buy and sell signals along with automatically plotted stop-loss and three profit-target levels. This mash-up goes beyond a simple EMA crossover or standalone TRIX oscillator by requiring confluence across trend, adaptive moving averages, momentum direction, and smoothed price action, reducing false triggers and focusing on high‐probability turning points.
How It Works & Why Its Components Matter
Trend Filter: EMA vs. Adaptive MA
EMA (20) measures the prevailing trend with fixed sensitivity.
Adaptive MA (also EMA-based, length 10) approximates a faster-responding moving average, standing in for a KAMA-style filter.
Bullish bias requires AMA > EMA; bearish bias requires AMA < EMA. This ensures signals align with both the underlying trend and a more nimble view of recent price action.
Momentum Confirmation: TRIX
Calculates a triple-smoothed EMA of price over TRIX Length (15), then converts it to a percentage rate-of-change oscillator.
Positive TRIX reinforces bullish entries; negative TRIX reinforces bearish entries. Using TRIX helps filter whipsaws by focusing on sustained momentum shifts.
Gaussian Price Smoother
Applies two back-to-back 5-period EMAs to the price (“gaussian” smoothing) to remove short-term noise.
Price above the smoothed line confirms strength for longs; below confirms weakness for shorts. This layer avoids entries on erratic spikes.
Confluence Signals
Buy Signal (isBull) fires only when:
AMA > EMA (trend alignment)
TRIX > 0 (momentum support)
Close > Gaussian (price strength)
Sell Signal (isBear) fires under the inverse conditions.
Requiring all three conditions simultaneously sharply reduces false triggers common to single-indicator systems.
Automatic Risk & Reward Plotting
On each new buy or sell signal (edge detection via not isBull or not isBear ), the script:
Stores entryPrice at the signal bar’s close.
Draws a stop-loss line at entry minus ATR(14) × Stop Multiplier (1.5) by default.
Plots three profit-target lines at entry plus ATR × Target Multiplier (1×, 1.5×, and 2×).
All previous labels and lines are deleted on each new signal, keeping the chart uncluttered and focusing only on the current trade.
Inputs & Customization
Input Description Default
EMA Length Period for the main trend EMA 20
Adaptive MA Length Period for the faster adaptive EM A substitute 10
TRIX Length Period for the triple-smoothed momentum oscillator 15
Dominant Cycle Length (Reserved) 40
Stop Multiplier ATR multiple for stop-loss distance 1.5
Target Multiplier ATR multiple for first profit target 1.5
Show Buy/Sell Signals Toggle on-chart labels for entry signals On
How to Use
Apply to Chart: Best on 15 m–1 h timeframes for swing entries or 5 m for agile scalps.
Wait for Full Confluence:
Look for the AMA to cross above/below the EMA and verify TRIX and Gaussian conditions on the same bar.
A bright “LONG” or “SHORT” label marks your entry.
Manage the Trade:
Place your stop where the red or green SL line appears.
Scale or exit at the three yellow TP1/TP2/TP3 lines, automatically drawn by volatility.
Repeat Cleanly: Each new signal clears prior annotations, ensuring you only track the active setup.
Why This Script Stands Out
Multi-Layer Confluence: Trend, momentum, and noise-reduction must all align, addressing the weaknesses of single-indicator strategies.
Automated Trade Management: No manual plotting—stop and target lines appear seamlessly with each signal.
Transparent & Customizable: All logic is open, adjustable, and clearly documented, allowing traders to tweak lengths and multipliers to suit different instruments.
Disclaimer
No indicator guarantees profit. Always backtest AI QUANT OCULUS extensively, combine its signals with your own analysis and risk controls, and practice sound money management before trading live.
AI QUANT OCULUSAI QUANT OCULUS
Version 1.0 | Pine Script v6
Purpose & Innovation
AI QUANT OCULUS integrates four distinct technical concepts—exponential trend filtering, adaptive smoothing, momentum oscillation, and Gaussian smoothing—into a single, cohesive system that delivers clear, objective buy and sell signals along with automatically plotted stop-loss and three profit-target levels. This mash-up goes beyond a simple EMA crossover or standalone TRIX oscillator by requiring confluence across trend, adaptive moving averages, momentum direction, and smoothed price action, reducing false triggers and focusing on high‐probability turning points.
How It Works & Why Its Components Matter
Trend Filter: EMA vs. Adaptive MA
EMA (20) measures the prevailing trend with fixed sensitivity.
Adaptive MA (also EMA-based, length 10) approximates a faster-responding moving average, standing in for a KAMA-style filter.
Bullish bias requires AMA > EMA; bearish bias requires AMA < EMA. This ensures signals align with both the underlying trend and a more nimble view of recent price action.
Momentum Confirmation: TRIX
Calculates a triple-smoothed EMA of price over TRIX Length (15), then converts it to a percentage rate-of-change oscillator.
Positive TRIX reinforces bullish entries; negative TRIX reinforces bearish entries. Using TRIX helps filter whipsaws by focusing on sustained momentum shifts.
Gaussian Price Smoother
Applies two back-to-back 5-period EMAs to the price (“gaussian” smoothing) to remove short-term noise.
Price above the smoothed line confirms strength for longs; below confirms weakness for shorts. This layer avoids entries on erratic spikes.
Confluence Signals
Buy Signal (isBull) fires only when:
AMA > EMA (trend alignment)
TRIX > 0 (momentum support)
Close > Gaussian (price strength)
Sell Signal (isBear) fires under the inverse conditions.
Requiring all three conditions simultaneously sharply reduces false triggers common to single-indicator systems.
Automatic Risk & Reward Plotting
On each new buy or sell signal (edge detection via not isBull or not isBear ), the script:
Stores entryPrice at the signal bar’s close.
Draws a stop-loss line at entry minus ATR(14) × Stop Multiplier (1.5) by default.
Plots three profit-target lines at entry plus ATR × Target Multiplier (1×, 1.5×, and 2×).
All previous labels and lines are deleted on each new signal, keeping the chart uncluttered and focusing only on the current trade.
Inputs & Customization
Input Description Default
EMA Length Period for the main trend EMA 20
Adaptive MA Length Period for the faster adaptive EM A substitute 10
TRIX Length Period for the triple-smoothed momentum oscillator 15
Dominant Cycle Length (Reserved) 40
Stop Multiplier ATR multiple for stop-loss distance 1.5
Target Multiplier ATR multiple for first profit target 1.5
Show Buy/Sell Signals Toggle on-chart labels for entry signals On
How to Use
Apply to Chart: Best on 15 m–1 h timeframes for swing entries or 5 m for agile scalps.
Wait for Full Confluence:
Look for the AMA to cross above/below the EMA and verify TRIX and Gaussian conditions on the same bar.
A bright “LONG” or “SHORT” label marks your entry.
Manage the Trade:
Place your stop where the red or green SL line appears.
Scale or exit at the three yellow TP1/TP2/TP3 lines, automatically drawn by volatility.
Repeat Cleanly: Each new signal clears prior annotations, ensuring you only track the active setup.
Why This Script Stands Out
Multi-Layer Confluence: Trend, momentum, and noise-reduction must all align, addressing the weaknesses of single-indicator strategies.
Automated Trade Management: No manual plotting—stop and target lines appear seamlessly with each signal.
Transparent & Customizable: All logic is open, adjustable, and clearly documented, allowing traders to tweak lengths and multipliers to suit different instruments.
Disclaimer
No indicator guarantees profit. Always backtest AI QUANT OCULUS extensively, combine its signals with your own analysis and risk controls, and practice sound money management before trading live.
Volume Strength IndicatorThis Indicator is built to give you an edge into the market. Given volume, volatility and price-action, it compares market conditions against the maximum that have occurred so far in the session. Useful for intraday and day trading for timing entries with the smart money.
The green/red histogram gives us a view into the relative strength of the current bar, whether they have strong buying or selling power.
The orange signal line gives us a view of the recent trend, which can be modified using the various inputs.
DeepFlow Zones SNIPER# DeepFlow Zones SNIPER - Documentation & Cheatsheet
## 🎯 DeepFlow Zones - SNIPER Edition
**Horizontal Limit Order Zones | Institutional FVG + Single Prints**
> **Philosophy:** *Only mark the zones where institutions MUST have orders. Everything else is noise.*
---
## ⚡ QUICK CHEATSHEET
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ DEEPFLOW ZONES SNIPER - QUICK REFERENCE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 🎯 ZONE CREATION REQUIREMENTS (ALL MUST BE TRUE): │
│ ══════════════════════════════════════════════════ │
│ ✓ FVG exists → Gap between candle low and 2-bar-ago high │
│ ✓ Gap Size → At least 30% of ATR (significant gap) │
│ ✓ Impulse Candle → 1.8x average range + 65% body ratio │
│ ✓ Volume → 2.0x+ average on impulse candle │
│ ✓ Direction → Middle candle confirms gap direction │
│ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 📊 ZONE TYPES: │
│ ══════════════ │
│ 🟢 BULLISH ZONE → Green box BELOW price (buy zone) │
│ 🔴 BEARISH ZONE → Red box ABOVE price (sell zone) │
│ ⚫ TESTED ZONE → Gray box (CE level touched) │
│ ⬛ BROKEN ZONE → Dark gray (price closed through) │
│ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ⭐ SINGLE PRINT LINES: │
│ ══════════════════════ │
│ Requirements: │
│ • Range 1.8x+ average │
│ • Body 65%+ of range │
│ • Volume 2.0x+ average │
│ • Delta 60%+ confirms direction │
│ │
│ Usage: │
│ • Gold lines at HIGH and LOW of impulse candle │
│ • Price often returns to these levels │
│ • Use as support/resistance for entries │
│ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 🚨 ENTRY SIGNALS: │
│ ═══════════════════ │
│ BUY🎯 appears when: │
│ • Price is inside BULLISH zone │
│ • Delta shows 60%+ buy dominance │
│ • Volume is 1.5x+ average │
│ │
│ SELL🎯 appears when: │
│ • Price is inside BEARISH zone │
│ • Delta shows 60%+ sell dominance │
│ • Volume is 1.5x+ average │
│ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 📐 ZONE ANATOMY: │
│ ═════════════════ │
│ │
│ BULLISH FVG ZONE: BEARISH FVG ZONE: │
│ │
│ Current Low ───────────────── ───────────────── 2-bar-ago Low │
│ ┌─────────────────────────┐ ┌─────────────────────────┐ │
│ │ █████ ZONE █████████████│ │ █████ ZONE █████████████│ │
│ │- - - CE (50%) - - - - - │ │- - - CE (50%) - - - - - │ │
│ │ ████████████████████████│ │ ████████████████████████│ │
│ └─────────────────────────┘ └─────────────────────────┘ │
│ 2-bar-ago High ────────────── ───────────────── Current High │
│ │
│ Entry: At or near CE line Entry: At or near CE line │
│ Stop: Below zone bottom Stop: Above zone top │
│ Target: 1:1 or 2:1 R:R Target: 1:1 or 2:1 R:R │
│ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ⛔ ZONE IS INVALID WHEN: │
│ ═════════════════════════ │
│ ✗ Gap size < 30% of ATR (too small) │
│ ✗ No impulse candle (weak move) │
│ ✗ Volume < 2x average (retail move) │
│ ✗ Zone age > 50 bars (stale) │
│ ✗ Price already closed through zone │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 📋 DETAILED DOCUMENTATION
### What Makes SNIPER Zones Different?
Standard FVG indicators create zones everywhere. SNIPER zones only appear when there's **institutional footprint**:
| Filter | Standard FVG | SNIPER Zones | Why It Matters |
|--------|-------------|--------------|----------------|
| Gap Size | Any gap | **≥30% ATR** | Significant imbalance |
| Volume | Optional | **2.0x+ avg** | Institutional volume |
| Impulse | None | **1.8x range** | Real momentum |
| Body | None | **65%+ ratio** | Conviction candle |
| Max Zones | 20-50 | **10 max** | Only the best |
| Zone Life | 100 bars | **50 bars** | Fresh zones only |
---
### How Zones Are Created
```
BULLISH FVG FORMATION:
═══════════════════════
Bar 0 (2 bars ago): Bar 1 (Impulse): Bar 2 (Current):
┌─────┐ ┌─────┐ ┌─────┐
│ │ │█████│ │ │
│ │ HIGH ────── │█████│ │ │
│ │ │ │█████│ │ │
└─────┘ │ │█████│ │ │── LOW
│ └─────┘ └─────┘
│ │
└──────── GAP ────────────────┘
(FVG ZONE)
Requirements Met:
✓ Current LOW > 2-bar-ago HIGH (gap exists)
✓ Gap ≥ 30% of ATR (significant)
✓ Bar 1 range ≥ 1.8x average (impulse)
✓ Bar 1 body ≥ 65% of range (conviction)
✓ Bar 1 volume ≥ 2x average (institutional)
✓ Bar 1 was bullish (direction confirms)
RESULT: VALID SNIPER BULLISH ZONE CREATED
```
---
### Single Print Lines Explained
Single Prints mark **institutional impulse candles** where price moved so fast that no orders were filled at those levels. These levels often act as magnets for price.
```
SINGLE PRINT CANDLE:
════════════════════
HIGH ═══════════════════════════════ (Gold Line)
│
┌─────────────────┤
│█████████████████│ ← Large body (65%+)
│█████████████████│ ← Strong volume (2x+)
│█████████████████│ ← Clear delta (60%+)
│█████████████████│
└─────────────────┤
│
LOW ═══════════════════════════════ (Gold Line)
These horizontal lines extend 500 bars into the future.
Price often returns to test these levels.
```
---
### Entry Strategy
#### Zone Entry Checklist
```
□ Zone is active (green/red, not gray)
□ Price enters zone from outside
□ Wait for entry signal (BUY🎯 or SELL🎯)
□ Verify: Delta + Volume confirming
□ Enter at CE line (dotted white line)
□ Stop below/above zone
□ Target: Opposite side of zone (1:1) or 2:1
```
#### Single Print Entry
```
□ Price returns to single print level
□ Look for reaction (rejection candle)
□ Combine with GRA signal if possible
□ Enter on confirmation candle
□ Stop beyond the single print line
```
---
### Table Legend
| Field | Reading | Color Meaning |
|-------|---------|---------------|
| **Delta** | Buy/Sell % | 🟢 Buy dom, 🔴 Sell dom, ⚪ Neutral |
| **Vol** | Volume ratio | 🟢 ≥2x, ⚪ <2x |
| **Buy ⬚** | Active buy zones | Count of bullish zones |
| **Sell ⬚** | Active sell zones | Count of bearish zones |
| **Zone** | Current position | AT BUY / AT SELL / --- |
| **Impulse** | Current bar status | 🟡 Yes (impulse), ⚫ No |
---
### Zone States
| State | Visual | Meaning | Action |
|-------|--------|---------|--------|
| **Fresh** | Bright color | Never tested | Best entries |
| **Tested** | Gray | CE touched | Still valid, less reliable |
| **Broken** | Dark gray | Price closed through | Invalid, ignore |
---
### Integration with GRA v5
The magic happens when you combine both indicators:
```
HIGHEST PROBABILITY SETUP:
══════════════════════════
1. DeepFlow shows active zone (green/red box)
2. Price enters the zone
3. GRA5 fires a signal INSIDE the zone
4. Delta confirms on both indicators
5. Volume confirms on both indicators
This is your SNIPER entry. Take it.
Example:
┌─────────────────────────────────────────┐
│ Price enters BULLISH zone │
│ GRA5 shows: A🎯 LONG │
│ DFZ shows: BUY🎯 │
│ Table: Vol 2.1x, Delta 67%B │
│ │
│ ACTION: Full size LONG at CE │
│ STOP: Below zone bottom │
│ TARGET: 2:1 R:R │
└─────────────────────────────────────────┘
```
---
### Settings by Instrument
| Instrument | Vol Mult | Gap ATR | Impulse | Max Zones |
|------------|----------|---------|---------|-----------|
| **NQ/ES** | 2.0x | 30% | 1.8x | 10 |
| **YM** | 2.0x | 30% | 1.8x | 10 |
| **GC** | 2.5x | 40% | 2.0x | 8 |
| **BTC** | 2.0x | 25% | 1.5x | 10 |
---
### Common Mistakes
| Mistake | Why It's Bad | Solution |
|---------|-------------|----------|
| Trading every zone | Most zones fail | Wait for entry signal |
| Entering at zone edge | Wrong R:R | Enter at CE (middle) |
| Ignoring broken zones | Already invalidated | Gray = don't trade |
| No delta confirmation | Could be false zone | BUY🎯/SELL🎯 required |
| Too many zones | Chart noise | Max 10 zones |
---
### Alert Configuration
| Alert | Priority | Action |
|-------|----------|--------|
| 🎯 BUY/SELL ZONE ENTRY | 🔴 High | Check chart immediately |
| NEW BULL/BEAR ZONE | 🟠 Medium | Note new zone location |
| 🎯 SINGLE PRINT | 🟢 Low | Mark potential S/R |
---
### Pine Script v6 Notes
This indicator uses Pine Script v6 features:
- Array-based zone management
- `request.security_lower_tf()` for delta
- Dynamic zone state tracking
- Efficient garbage collection
**Minimum TradingView Plan:** Pro (for intrabar data)
---
## 🏆 Golden Rules
1. **Fewer zones = Better zones.** If you see more than 5 active zones, your settings are too loose.
2. **Fresh zones > Tested zones.** The first touch is always the best.
3. **CE is king.** The middle of the zone (50% level) is your entry point.
4. **Zone + GRA signal = Sniper entry.** This confluence is what we're hunting for.
5. **Gray zones don't exist.** Once broken, pretend the zone was never there.
---
*© Alexandro Disla - DeepFlow Zones SNIPER*
*Pine Script v6 | TradingView*
SK Alpha SuiteTrend Dots
Aqua Level 1 Bullish Entry1
Green Level 2 Bullish Entry2
Lime Leve 3 Bullish Entry3 (Full Position)
Light Red Level 1 Bearish : Partial Close 10%-30%
Full Red Level 3 Bearish: Major Close
No StopLoss line hit or its already ended: Full close.
Purple/White Lines
Stop loss line, distance specific to each asset volatility, not fixed distance for all assets.
Close, Medium, Relaxed based on how close you want your stop loss to be.
With in bullish sentiment, if stoploss hits, stoploss will reset again on that bar, shown with white separation
Contrarian Period High & LowContrarian Period High & Low
This indicator pairs nicely with the Contrarian 100 MA and can be located here:
Overview
The "Contrarian Period High & Low" indicator is a powerful technical analysis tool designed for traders seeking to identify key support and resistance levels and capitalize on contrarian trading opportunities. By tracking the highest highs and lowest lows over user-defined periods (Daily, Weekly, or Monthly), this indicator plots historical levels and generates buy and sell signals when price breaks these levels in a contrarian manner. A unique blue dot counter and action table enhance decision-making, making it ideal for swing traders, trend followers, and those trading forex, stocks, or cryptocurrencies. Optimized for daily charts, it can be adapted to other timeframes with proper testing.
How It Works
The indicator identifies the highest high and lowest low within a specified period (e.g., daily, weekly, or monthly) and draws horizontal lines for the previous period’s extremes on the chart. These levels act as dynamic support and resistance zones. Contrarian signals are generated when the price crosses below the previous period’s low (buy signal) or above the previous period’s high (sell signal), indicating potential reversals. A blue dot counter tracks consecutive buy signals, and a table displays the count and recommended action, helping traders decide whether to hold or flip positions.
Key Components
Period High/Low Levels: Tracks the highest high and lowest low for each period, plotting red lines for highs and green lines for lows from the bar where they occurred, extending for a user-defined length (default: 200 bars).
Contrarian Signals: Generates buy signals (blue circles) when price crosses below the previous period’s low and sell signals (white circles) when price crosses above the previous period’s high, designed to capture potential reversals.
Blue Dot Tracker: Counts consecutive buy signals (“blue dots”). If three or more occur, it suggests a stronger trend, with the table recommending whether to “Hold Investment” or “Flip Investment.”
Action Table: A 2x2 table in the bottom-right corner displays the blue dot count and action (“Hold Investment” if count ≥ 4, else “Flip Investment”) for quick reference.
Mathematical Concepts
Period Detection: Uses an approximate bar count to define periods (1 bar for Daily, 5 bars for Weekly, 20 bars for Monthly on a daily chart). When a new period starts, the previous period’s high/low is finalized and plotted.
High/Low Tracking:
Highest high (periodHigh) and lowest low (periodLow) are updated within the period.
Lines are drawn at these levels when the period ends, starting from the bar where the extreme occurred (periodHighBar, periodLowBar).
Signal Logic:
Buy signal: ta.crossunder(close , prevPeriodLow) and not lowBroken and barstate.isconfirmed
Sell signal: ta.crossover(close , prevPeriodHigh) and not highBroken and barstate.isconfirmed
Flags (highBroken, lowBroken) prevent multiple signals for the same level within a period.
Blue Dot Counter: Increments on each buy signal, resets on a sell signal or if price exceeds the entry price after three or more buy signals.
Entry and Exit Rules
Buy Signal (Blue Circle): Triggered when the price crosses below the previous period’s low, suggesting a potential oversold condition and buying opportunity. The signal appears as a blue circle below the price bar.
Sell Signal (White Circle): Triggered when the price crosses above the previous period’s high, indicating a potential overbought condition and selling opportunity. The signal appears as a white circle above the price bar.
Blue Dot Tracker:
Increments blueDotCount on each buy signal and sets an entryPrice on the first buy.
Resets on a sell signal or if price exceeds entryPrice after three or more buy signals.
If blueDotCount >= 3, the table suggests holding; if >= 4, it reinforces “Hold Investment.”
Exit Rules: Exit a buy position on a sell signal or when price exceeds the entry price after three or more buy signals. Combine with other tools (e.g., trendlines, support/resistance) for additional confirmation. Always apply proper risk management.
Recommended Usage
The "Contrarian Period High & Low" indicator is optimized for daily charts but can be adapted to other timeframes (e.g., 1H, 4H) with adjustments to the period bar count. It excels in markets with clear support/resistance levels and potential reversal zones. Traders should:
Backtest the indicator on their chosen asset and timeframe to validate signal reliability.
Combine with other technical tools (e.g., moving averages, Fibonacci levels) for stronger trade confirmation.
Adjust barsPerPeriod (e.g., ~120 bars for Weekly on hourly charts) based on the chart timeframe and market volatility.
Monitor the action table to guide position management based on blue dot counts.
Customization Options
Period Type: Choose between Daily, Weekly, or Monthly periods (default: Monthly).
Line Length: Set the length of high/low lines in bars (default: 200).
Show Highs/Lows: Toggle visibility of period high (red) and low (green) lines.
Max Lines to Keep: Limit the number of historical lines displayed (default: 10).
Hide Signals: Toggle buy/sell signal visibility for a cleaner chart.
Table Display: A fixed table in the bottom-right corner shows the blue dot count and action, with yellow (Hold) or green (Flip) backgrounds based on the count.
Why Use This Indicator?
The "Contrarian Period High & Low" indicator offers a unique blend of support/resistance visualization and contrarian signal generation, making it a versatile tool for identifying potential reversals. Its clear visual cues (lines and signals), blue dot tracker, and actionable table provide traders with an intuitive way to monitor market structure and manage trades. Whether you’re a beginner or an experienced trader, this indicator enhances your ability to spot key levels and time entries/exits effectively.
Tips for Users
Test the indicator thoroughly on your chosen market and timeframe to optimize settings (e.g., adjust barsPerPeriod for non-daily charts).
Use in conjunction with price action or other indicators for stronger trade setups.
Monitor the action table to decide whether to hold or flip positions based on blue dot counts.
Ensure your chart timeframe aligns with the selected period type (e.g., daily chart for Monthly periods).
Apply strict risk management to protect against false breakouts.
Happy trading with the Contrarian Period High & Low indicator! Share your feedback and strategies in the TradingView community!
Polaris Trend All-in-One📘 Polaris Trend Indicator: Trading Rules & Strategy
Guide
The Polaris Trend Indicator is designed to simplify trading decisions by identifying key entry
and exit signals without the need for excessive technical analysis. This system combines the
Polaris Trend with the Polaris Golden Wave and Market Bias tools to give you confidence
across multiple timeframes.
This guide outlines clear trading rules for two use cases:
● Swing Trading
● Long-Term Investing and Holding
⚡ Swing Trading Strategy
Swing trading can be challenging when the market direction is unclear. The Polaris Trend helps
traders stay on the right side of momentum with straightforward visual signals. This approach is
best used on the Daily or Weekly chart.
✅ Entry Criteria (Bullish Trades)
● A solid green column appears above the zero line.
● A green upward arrow confirms bullish momentum.
● Enter your trade immediately when the green column first appears.
● Hold the trade until a red column appears, signaling a shift in momentum.
🚫 Exit Criteria (Bullish Trades)
● The first appearance of a red column after a green run.
● Multiple green columns followed by a red column.
● Do not enter trades mid-trend; always enter on the first green flip.
***Recommended Swing Strategy
● When a new daily green column appears but the weekly columns are still red, stay
nimble. Enter your position when the Polaris Trend Indicator turns green and displays an
upward-pointing arrow.
● If the price pulls back to a higher low but a red daily column forms, sell 50% of your
position and move your stop loss to your original entry. Then, wait for the next daily
green column and arrow to reappear, this is your signal to reenter the 50% you exited.
● If the price continues to rise and the weekly columns also turn green, shift your focus
to the weekly chart. Ignore daily signals and hold the trade until the weekly column
turns red, which will be your cue to exit. The weekly green column is your confirmation of
a stronger uptrend and a potential longer hold.
🔻 Entry Criteria (Bearish Trades)
● A solid red column appears below the zero line.
● A red downward arrow confirms bearish momentum.
● Enter your short trade immediately when the red column first appears.
● Hold until a green column appears, indicating momentum has shifted.
🔁 Exit Criteria (Bearish Trades)
● The first green column that follows a red sequence.
● Same rule applies: enter only on the initial flip, not mid-trend.
Note: The first color flip is the most reliable entry point. Avoid entering positions
deep into a trend, wait for the clear signal from Polaris.
🧭 Long-Term Investing Strategy
This approach combines the Polaris Golden Wave, Polaris Trend, and Market Bias to help
long-term investors buy at deep value levels and scale into positions over time.
📉 Ideal Entry: Golden Zone + Polaris Trend Signal
● Use the Golden Wave to identify the monthly 0.618–0.826 retracement zone
(significant discount levels).
● When price enters the Golden Zone and the Polaris Trend shows a green column on
the Daily or Weekly, this is your optimal entry point.
● If the trend turns red inside the zone, consider trimming positions and re-entering on the
next bullish signal.
If price drops below the Golden Zone, the stock becomes even more undervalued,
wait for the next green Polaris Trend signal to enter.
💰 Secondary Entry: Market Bias Rebounds
● If you miss the Golden Zone entry or are dollar-cost averaging:
○ Use the Market Bias on a Weekly timeframe.
○ Wait for price to retrace into the Market Bias band after moving higher.
○ Look for a red Polaris Trend column, then wait for price to enter the Market
Bias band and once it enters, wait for Polaris Trend signal to flip back to green
for your entry. If the trend turns red inside the zone, consider trimming positions
and re-entering on the next bullish signal.
Think of the Market Bias like a lake and price like a skipping stone—you want to
buy when the stone comes down and touches the surface.
📊 Indicator Explanations
🔶 Golden Wave (Monthly Fibonacci Retracement Zones)
● Highlights key monthly retracement zones (0.618 to 0.826).
● Helps identify deep-value entries on longer timeframes.
● Visible across all chart timeframes for consistent macro reference.
🔴 Market Bias (Smoothed Heikin-Ashi Trend Filter)
● Measures trend direction and strength using smoothed Heikin-Ashi candles and
oscillation logic.
● Customizable smoothing, oscillator period, and timeframe inputs.
● Option to display trend signals in a separate pane with dynamic coloring.
This combined approach empowers traders to make high-quality decisions with clarity and
discipline. Whether you're entering short-term swings or building long-term positions, the
Polaris Trend system guides you with timely, data-driven signals.






















