B3 20/50 MeanSimple MA's 20 and 50 are averaged to produce a mean MA line. I like the smoothness of it, and it can help you stay in a trade in the slow moving trends. Also if you start to see a large cloud in your favor, it could be a great time take the profits.
在脚本中搜索"科创50成分股"
UO_30-50-70Ultimate Oscillator with bands present at the 30, 50, and 70 pt levels.
Personally use this every time, created a script to hard code these lines so I wouldn't need to redraw them all the time.
Enjoy
The Lazy Trader - Index (ETF) Trend Following Robot50/150 moving average, index (ETF) trend following robot. Coded for people who cannot psychologically handle dollar-cost-averaging through bear markets and extreme drawdowns (although DCA can produce better results eventually), this robot helps you to avoid bear markets. Be a fair-weathered friend of Mr Market, and only take up his offer when the sun is shining! Designed for the lazy trader who really doesn't care...
Recommended Chart Settings:
Asset Class: ETF
Time Frame: Daily
Necessary ETF Macro Conditions:
a) Country must have healthy demographics, good ratio of young > old
b) Country population must be increasing
c) Country must be experiencing price-inflation
Default Robot Settings:
Slow Moving Average: 50 (integer) //adjust to suit your underlying index
Fast Moving Average: 150 (integer) //adjust to suit your underlying index
Bullish Slope Angle: 5 (degrees) //up angle of moving averages
Bearish Slope Angle: -5 (degrees) //down angle of moving averages
Average True Range: 14 (integer) //input for slope-angle formula
Risk: 100 (%) //100% risk means using all equity per trade
ETF Test Results (Default Settings):
SPY (1993 to 2020, 27 years), 332% profit, 20 trades, 6.4 profit factor, 7% drawdown
EWG (1996 to 2020, 24 years), 310% profit, 18 trades, 3.7 profit factor, 10% drawdown
EWH (1996 to 2020, 24 years), 4% loss, 26 trades, 0.9 profit factor, 36% drawdown
QQQ (1999 to 2020, 21 years), 232% profit, 17 trades, 3.6 profit factor, 2% drawdown
EEM (2003 to 2020, 17 years), 73% profit, 17 trades, 1.1 profit factor, 3% drawdown
GXC (2007 to 2020, 13 years), 18% profit, 14 trades, 1.3 profit factor, 26% drawdown
BKF (2009 to 2020, 11 years), 11% profit, 13 trades, 1.2 profit factor, 33% drawdown
A longer time in the markets is better, with the exception of EWH. 6 out of 7 tested ETFs were profitable, feel free to test on your favourite ETF (default settings) and comment below.
Risk Warning:
Not tested on commodities nor other financial products like currencies (code will not work), feel free to leave comments below.
Moving Average Slope Angle Formula:
Reproduced and modified from source:
50-Line Oscillator // (\_/)
// ( •.•)
// (")_(")
25-Line Oscillator
Description:
The 25-Line Oscillator is a sophisticated technical analysis tool designed to visualize market trends through the use of multiple Simple Moving Averages (SMAs). This indicator computes a series of 26 SMAs, incrementally increasing the base length, providing traders with a comprehensive view of price dynamics.
Features:
Customizable Base Length: Adjust the base length of the SMAs according to trading preferences, enhancing versatility for different market conditions.
Rainbow Effect: The indicator employs a visually appealing rainbow color scheme to differentiate between the various trend lines, making it easy to identify crossovers and momentum shifts.
Crossovers Detection: The script includes logic to detect crossover events between consecutive trend lines, which can serve as signals for potential entry or exit points in trading.
Clear Visualization: Suitable for both novice and seasoned traders, the plots enable quick interpretation of trends and market behavior.
How to Use:
Add the indicator to your chart and customize the base length as desired.
Observe the rainbow-colored lines for trend direction.
Look for crossover events between the SMAs as potential trading signals.
Application: This indicator is particularly useful for swing traders and trend followers who aim to capitalize on market momentum and identify reversals. By monitoring the behavior of multiple SMAs, traders can gain insights into the strength and direction of price movements over various time frames.
AK Simple Moving Average 50 days Simple Moving average suitable for Intraday on 1Hr,30Min.15Min Time frames
1. When candle crossing above SMA Line - Go for Long Entries
2. When candle crossing below SMA Line - Go for short Entries
50 SMA / 200 EMA / 128EMA Moving Average CrossFound success using 50SMA vs 200EMA.
128 EMA also charted for it's BTC relevance.
50/100/200 Moving Averages (Pine Script For Copy)by fresca
SCRIPT LANGUAGE
Copy script below and adjust based on your preferences.
-function (change function from "sma" to "ema", "wma" and more)
-length (25 Day, 150 Day or add more averages to the three in this script.)
-color, (red, yellow, etc. or use color hex codes i.e. #FEDA15, #FFAD8F, etc.)
-transparency (set to desired level 1-100)
Or add more options.
RESOURCES
Color hex codes site: www.canva.com
Trading View Pine Script Editor Reference Guide: www.tradingview.com
Taint's Multi Time Frame MA50-100-200 SMA with two 200 EMA's all with the ability choose a time frame for each.
Hidden Divergence with S/R & TP// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © Gemini
// @version=5
// This indicator combines Hidden RSI Divergence with Support & Resistance detection
// and provides dynamic take-profit targets based on ATR. It also includes alerts.
indicator("Hidden Divergence with S/R & TP", overlay=true)
// === INPUTS ===
rsiLengthInput = input.int(14, "RSI Length", minval=1)
rsiSMALengthInput = input.int(5, "RSI SMA Length", minval=1)
pivotLookbackLeft = input.int(5, "Pivot Left Bars", minval=1)
pivotLookbackRight = input.int(5, "Pivot Right Bars", minval=1)
atrPeriodInput = input.int(14, "ATR Period", minval=1)
atrMultiplierTP1 = input.float(1.5, "TP1 ATR Multiplier", minval=0.1)
atrMultiplierTP2 = input.float(3.0, "TP2 ATR Multiplier", minval=0.1)
atrMultiplierTP3 = input.float(5.0, "TP3 ATR Multiplier", minval=0.1)
// === CALCULATIONS ===
// Calculate RSI and its SMA
rsiValue = ta.rsi(close, rsiLengthInput)
rsiSMA = ta.sma(rsiValue, rsiSMALengthInput)
// Calculate Average True Range for Take Profits
atrValue = ta.atr(atrPeriodInput)
// Identify pivot points for Support and Resistance
pivotLow = ta.pivotlow(pivotLookbackLeft, pivotLookbackRight)
pivotHigh = ta.pivothigh(pivotLookbackLeft, pivotLookbackRight)
// Define variables to track divergence and TP levels
var bool bullishDivergence = false
var bool bearishDivergence = false
var float tp1Buy = na
var float tp2Buy = na
var float tp3Buy = na
var float tp1Sell = na
var float tp2Sell = na
var float tp3Sell = na
// Reset divergence flags at each new bar
bullishDivergence := false
bearishDivergence := false
// === HIDDEN DIVERGENCE LOGIC ===
// Hidden Bullish Divergence (Higher low in price, lower low in RSI)
// Price makes a higher low, while RSI makes a lower low, suggesting trend continuation.
for i = 1 to 50 // Look back up to 50 bars for a confirmed pivot low
if not na(pivotLow ) and close < close and rsiValue < rsiValue
// Check if price is making a higher low than the pivot low, and RSI is making a lower low
if low > low and rsiValue < rsiValue
bullishDivergence := true
break // Exit loop once divergence is found
// Hidden Bearish Divergence (Lower high in price, higher high in RSI)
// Price makes a lower high, while RSI makes a higher high, suggesting trend continuation.
for i = 1 to 50 // Look back up to 50 bars for a confirmed pivot high
if not na(pivotHigh ) and close > close and rsiValue > rsiValue
// Check if price is making a lower high than the pivot high, and RSI is making a higher high
if high < high and rsiValue > rsiValue
bearishDivergence := true
break // Exit loop once divergence is found
// === SETTING TP LEVELS AND ALERTS ===
if bullishDivergence
buySignalPrice = low - atrValue * 0.5 // Entry below the low
tp1Buy := buySignalPrice + atrValue * atrMultiplierTP1
tp2Buy := buySignalPrice + atrValue * atrMultiplierTP2
tp3Buy := buySignalPrice + atrValue * atrMultiplierTP3
// Alert for buying signal
alert("Hidden Bullish Divergence Detected on " + syminfo.ticker + " - Buy Signal", alert.freq_once_per_bar_close)
else
tp1Buy := na
tp2Buy := na
tp3Buy := na
if bearishDivergence
sellSignalPrice = high + atrValue * 0.5 // Entry above the high
tp1Sell := sellSignalPrice - atrValue * atrMultiplierTP1
tp2Sell := sellSignalPrice - atrValue * atrMultiplierTP2
tp3Sell := sellSignalPrice - atrValue * atrMultiplierTP3
// Alert for selling signal
alert("Hidden Bearish Divergence Detected on " + syminfo.ticker + " - Sell Signal", alert.freq_once_per_bar_close)
else
tp1Sell := na
tp2Sell := na
tp3Sell := na
// === PLOTTING SIGNALS AND TAKE PROFITS ===
// Plotting shapes for buy/sell signals
plotshape(bullishDivergence, title="Buy Signal", style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), text="Buy", textcolor=color.black)
plotshape(bearishDivergence, title="Sell Signal", style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), text="Sell", textcolor=color.black)
// Plotting take-profit lines
plot(tp1Buy, "TP1 Buy", color=color.new(color.lime, 0), style=plot.style_linebr)
plot(tp2Buy, "TP2 Buy", color=color.new(color.lime, 0), style=plot.style_linebr)
plot(tp3Buy, "TP3 Buy", color=color.new(color.lime, 0), style=plot.style_linebr)
plot(tp1Sell, "TP1 Sell", color=color.new(color.orange, 0), style=plot.style_linebr)
plot(tp2Sell, "TP2 Sell", color=color.new(color.orange, 0), style=plot.style_linebr)
plot(tp3Sell, "TP3 Sell", color=color.new(color.orange, 0), style=plot.style_linebr)
// Plotting the RSI and its SMA on a sub-pane
plot(rsiValue, "RSI", color.new(color.fuchsia, 0))
plot(rsiSMA, "RSI SMA", color.new(color.yellow, 0))
hline(50, "50 Midline", color=color.new(color.gray, 50))
// Plotting background for signals
bullishColor = color.new(color.green, 90)
bearishColor = color.new(color.red, 90)
bgcolor(bullishDivergence ? bullishColor : na, title="Bullish Divergence Zone")
bgcolor(bearishDivergence ? bearishColor : na, title="Bearish Divergence Zone")
// === EXPLANATION OF CONCEPTS ===
// Deep Knowledge of Market from AI:
// This indicator is based on a powerful, yet often misunderstood, concept: divergence.
// While standard divergence signals a potential trend reversal, hidden divergence signals a
// continuation of the prevailing trend. This is crucial for traders who want to capitalize
// on the momentum of a move rather than trying to catch tops and bottoms.
// Hidden Bullish Divergence: Occurs in an uptrend when price makes a higher low, but the
// RSI makes a lower low. This suggests that while there was a brief period of weakness, the
// underlying buying pressure is returning to push the trend higher. It’s a "re-energizing"
// of the bullish momentum.
// Hidden Bearish Divergence: Occurs in a downtrend when price makes a lower high, but the
// RSI makes a higher high. This indicates that while the sellers paused, the underlying
// selling pressure remains strong and is likely to continue pushing the price down. It's a
// subtle signal that the bears are regaining control.
// Combining Divergence with S/R: The true power of this indicator comes from its
// "confluence" principle. A divergence signal alone can be noisy. By requiring it to occur
// at a key support or resistance level (identified using pivot points), we are filtering
// out weaker signals and only focusing on high-probability setups where the market is
// likely to respect a previous area of interest. This tells us that not only is the trend
// likely to continue, but it is doing so from a strategic, well-defined point on the chart.
// Dynamic Take-Profit Targets: The take-profit targets are based on the Average True Range (ATR).
// ATR is a measure of market volatility. Using it to set targets ensures that your profit
// levels are dynamic and adapt to current market conditions. In a volatile market, your
// targets will be wider, while in a calm market, they will be tighter, helping you avoid
// unrealistic expectations and improving your risk management.
さくらんぼーい//@version=6
indicator("さくらんぼーい", overlay=true, max_labels_count=500, max_lines_count=500)
//==================== Inputs ====================//
// ---- Anchor (shared) ----
grpA = "Anchor (shared)"
anchorMode = input.string("Time", "Anchor Mode", options= , group=grpA)
anchorTime = input.time(timestamp("2025-06-24T20:31:00"), "Anchor Time (exchange)", group=grpA)
anchorBarsAgo = input.int(100, "Anchor Bars Ago", minval=1, group=grpA)
anchorPriceMode = input.string("Close", "Anchor Price", options= , group=grpA)
anchorPriceManual = input.float(0.0, "Manual Anchor Price (0=auto)", step=0.0001, group=grpA)
// ---- Light-Cone ----
grpLC = "Light-Cone ATR"
atrLen = input.int(14, "ATR Length", minval=1, group=grpLC)
atrTF = input.timeframe("", "ATR Timeframe (blank=same)", group=grpLC)
projBars = input.int(60, "Projection Horizon (bars)", minval=1, group=grpLC)
coneMode = input.string("Diffusive √n", "Cone Growth Mode", options= , group=grpLC)
mult = input.float(1.0, "ATR Multiplier (σ-ish)", step=0.1, minval=0.0, group=grpLC)
wickMode = input.string("Close", "Height uses", options= , group=grpLC)
coneFillCol= input.color(color.new(color.teal, 90), "Cone Fill", group=grpLC)
coneLineCol= input.color(color.new(color.aqua, 40), "Cone Edge", group=grpLC)
// ---- Light-Cone guide lines ----
grpFan = "Light-Cone Guides (0.5c / 1.5c)"
showFan = input.bool(true, "Show 0.5c & 1.5c guide lines", group=grpFan)
fan05Color = input.color(color.new(color.aqua, 75), "0.5c line", group=grpFan)
fan15Color = input.color(color.new(color.aqua, 60), "1.5c line", group=grpFan)
fanWidth = input.int(1, "Guide line width", minval=1, maxval=3, group=grpFan)
// ---- √n Stripes ----
grpZ = "Convergence (√n stripes)"
stepBars = input.int(20, "Base Step (bars)", minval=1, group=grpZ)
maxOrderM = input.int(8, "Max Order M (m²)", minval=1, maxval=50, group=grpZ)
halfWindow = input.int(2, "Stripe Half-Width (bars)", minval=0, group=grpZ)
stripeColor = input.color(color.new(color.fuchsia, 86), "Stripe Color", group=grpZ)
showCenters = input.bool(false, "Draw Stripe Center Lines", group=grpZ)
// ---- Fractal ----
grpF = "Fractal (Pivot) Detector"
leftP = input.int(2, "Left bars (L)", minval=1, group=grpF)
rightP = input.int(2, "Right bars (R)", minval=1, group=grpF)
hitColHi = input.color(color.new(color.lime, 0), "Pivot High Mark", group=grpF)
hitColLo = input.color(color.new(color.red, 0), "Pivot Low Mark", group=grpF)
// ---- Display / Limits ----
grpO = "Display / Limits"
showHitTable = input.bool(true, "Show m² Hit Table", group=grpO)
limitScreen = input.bool(true, "Reduce drawing near screen", group=grpO)
screenPastBars = input.int(5000, "Screen past window (bars)", minval=100, group=grpO)
futureLimitBars= input.int(500, "FUTURE draw limit (TV max 500)", minval=0, maxval=500, group=grpO)
// ---- Bias Panel ----
grpB = "Bias Panel"
showBiasPanel = input.bool(true, "Show Bias Panel", group=grpB)
biasTf = input.timeframe("15", "HTF timeframe", group=grpB)
emaFast = input.int(20, "HTF EMA fast", minval=1, group=grpB)
emaSlow = input.int(50, "HTF EMA slow", minval=2, group=grpB)
zThresh = input.float(0.30, "Z threshold (±)", step=0.05, group=grpB)
railLookback = input.int(20, "Rail lookback bars", minval=5, group=grpB)
railPct = input.float(0.40, "Rail touch ratio (0–1)", minval=0.1, maxval=0.9, step=0.05, group=grpB)
// ---- Positions (NEW) ----
panelCorner = input.string("Top-Right", "Bias Panel Position",
options= , group=grpB)
hitsCorner = input.string("Top-Left", "Hits Table Position",
options= , group=grpO)
// ---- Helpers: table positions ----
f_pos(s) =>
p = position.top_left
if s == "Top-Right"
p := position.top_right
else if s == "Bottom-Left"
p := position.bottom_left
else if s == "Bottom-Right"
p := position.bottom_right
p
//==================== Anchor Resolve ====================//
var int anchorBar = na
var float anchorPrice = na
var label anchorLbl = na
// 初バー保護付きタイム検索
f_find_anchor_bar_by_time(_t) =>
ta.valuewhen(nz(time , time ) < _t and time >= _t, bar_index, 0)
if anchorMode == "Time"
anchorBar := f_find_anchor_bar_by_time(anchorTime)
else
// バッファ下限保護
anchorBar := math.max(0, bar_index - anchorBarsAgo)
// アンカー価格(安全取得)
f_price_at_anchor(_bar) =>
float _v = na
if anchorPriceMode == "Close"
_v := ta.valuewhen(bar_index == _bar, close, 0)
else if anchorPriceMode == "High"
_v := ta.valuewhen(bar_index == _bar, high, 0)
else if anchorPriceMode == "Low"
_v := ta.valuewhen(bar_index == _bar, low, 0)
else if anchorPriceMode == "Open"
_v := ta.valuewhen(bar_index == _bar, open, 0)
_v
float autoPrice = na
if not na(anchorBar) and anchorBar <= bar_index
autoPrice := f_price_at_anchor(anchorBar)
anchorPrice := (anchorPriceMode == "Manual" and anchorPriceManual != 0.0) ? anchorPriceManual : autoPrice
bool anchorOK = not na(anchorBar) and anchorBar >= 0 and anchorBar <= bar_index + futureLimitBars and not na(anchorPrice)
// ラベル
if anchorOK
if na(anchorLbl)
anchorLbl := label.new(anchorBar, anchorPrice, "Anchor", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_down, textcolor=color.black, color=color.yellow, size=size.tiny)
else
label.set_x(anchorLbl, anchorBar), label.set_y(anchorLbl, anchorPrice)
//==================== Light-Cone (ATR-based) ====================//
float atrSame = ta.atr(atrLen)
float atrOther = request.security(syminfo.tickerid, atrTF, ta.atr(atrLen), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
float baseATR = (na(atrTF) or atrTF == "") ? atrSame : atrOther
float c_main = mult * baseATR
int horizon = math.min(projBars, futureLimitBars)
var line upL = na
var line dnL = na
var line up05 = na
var line dn05 = na
var line up15 = na
var line dn15 = na
var linefill coneFill = na
f_growth(_n) =>
coneMode == "Linear n" ? _n : math.sqrt(_n)
if anchorOK
if not na(coneFill)
linefill.delete(coneFill)
if not na(upL)
line.delete(upL)
if not na(dnL)
line.delete(dnL)
if not na(up05)
line.delete(up05)
if not na(dn05)
line.delete(dn05)
if not na(up15)
line.delete(up15)
if not na(dn15)
line.delete(dn15)
int x1 = anchorBar + horizon
float dyPer= (wickMode == "Wick (High/Low)") ? c_main * 0.5 : c_main
float grow = f_growth(horizon)
float upY = anchorPrice + dyPer * grow
float dnY = anchorPrice - dyPer * grow
float upY05 = anchorPrice + (dyPer * 0.5) * grow
float dnY05 = anchorPrice - (dyPer * 0.5) * grow
float upY15 = anchorPrice + (dyPer * 1.5) * grow
float dnY15 = anchorPrice - (dyPer * 1.5) * grow
upL := line.new(anchorBar, anchorPrice, x1, upY, xloc=xloc.bar_index, extend=extend.none, color=coneLineCol, width=2)
dnL := line.new(anchorBar, anchorPrice, x1, dnY, xloc=xloc.bar_index, extend=extend.none, color=coneLineCol, width=2)
coneFill := linefill.new(upL, dnL, color=coneFillCol)
if showFan
up05 := line.new(anchorBar, anchorPrice, x1, upY05, xloc=xloc.bar_index, extend=extend.none, color=fan05Color, width=fanWidth)
dn05 := line.new(anchorBar, anchorPrice, x1, dnY05, xloc=xloc.bar_index, extend=extend.none, color=fan05Color, width=fanWidth)
up15 := line.new(anchorBar, anchorPrice, x1, upY15, xloc=xloc.bar_index, extend=extend.none, color=fan15Color, width=fanWidth)
dn15 := line.new(anchorBar, anchorPrice, x1, dnY15, xloc=xloc.bar_index, extend=extend.none, color=fan15Color, width=fanWidth)
//==================== √n Stripes ====================//
var array centers = array.new_int()
array.clear(centers)
if not na(anchorBar)
for m = 1 to maxOrderM
array.push(centers, anchorBar + stepBars * m * m)
f_in_any_stripe(_bi) =>
sz = array.size(centers)
if sz == 0
false
else
bool hit = false
for i = 0 to sz - 1
int c0 = array.get(centers, i)
if _bi >= c0 - halfWindow and _bi <= c0 + halfWindow
hit := true
hit
// どの m² ストライプか(なければ na)
f_stripe_index(_bi) =>
int mFound = na
if array.size(centers) > 0
for m = 1 to maxOrderM
int cCenter = array.get(centers, m - 1)
if _bi >= cCenter - halfWindow and _bi <= cCenter + halfWindow
mFound := m
mFound
bgcolor(f_in_any_stripe(bar_index) ? stripeColor : na)
if showCenters and array.size(centers) > 0
for i = 0 to array.size(centers) - 1
int c0 = array.get(centers, i)
bool withinFutureLimit = c0 <= bar_index + futureLimitBars
bool nearScreen = not limitScreen or (c0 >= bar_index - screenPastBars and c0 <= bar_index + futureLimitBars)
if withinFutureLimit and nearScreen
line.new(c0, high, c0, low, xloc=xloc.bar_index, extend=extend.both, color=color.new(color.white, 70), width=1)
//==================== Fractal Detection ====================//
isPH = not na(ta.pivothigh(high, leftP, rightP))
isPL = not na(ta.pivotlow (low , leftP, rightP))
int pivotCenter = bar_index - rightP
hitPH = isPH and f_in_any_stripe(pivotCenter)
hitPL = isPL and f_in_any_stripe(pivotCenter)
//==================== m² Hit Table (robust) ====================//
var table tbHits = na
var hitsHi = array.new_int()
var hitsLo = array.new_int()
f_sync_len_int(_arr, _n, _fill) =>
while array.size(_arr) < _n
array.push(_arr, _fill)
while array.size(_arr) > _n
array.pop(_arr)
_arr
f_safe_get_int(_arr, _idx) =>
(_idx >= 0 and _idx < array.size(_arr)) ? array.get(_arr, _idx) : 0
// 毎バー長さ同期
f_sync_len_int(hitsHi, maxOrderM, 0)
f_sync_len_int(hitsLo, maxOrderM, 0)
// 集計
if (hitPH or hitPL) and array.size(centers) > 0
int nC = array.size(centers)
int nM = math.min(maxOrderM, nC)
for m = 1 to nM
int c0 = array.get(centers, m - 1)
if pivotCenter >= c0 - halfWindow and pivotCenter <= c0 + halfWindow
if hitPH
array.set(hitsHi, m - 1, f_safe_get_int(hitsHi, m - 1) + 1)
if hitPL
array.set(hitsLo, m - 1, f_safe_get_int(hitsLo, m - 1) + 1)
// 表示
if showHitTable and barstate.islast
if na(tbHits)
tbHits := table.new(f_pos(hitsCorner), 3, maxOrderM + 1, border_width=1)
table.cell(tbHits, 0, 0, "m²", bgcolor=color.new(color.blue, 20), text_color=color.white)
table.cell(tbHits, 1, 0, "PH▲", bgcolor=color.new(color.green,10), text_color=color.white)
table.cell(tbHits, 2, 0, "PL▼", bgcolor=color.new(color.red, 10), text_color=color.white)
int rows = array.size(hitsHi)
int nRow = math.min(maxOrderM, rows)
for m = 1 to nRow
table.cell(tbHits, 0, m, str.tostring(m) + "²")
table.cell(tbHits, 1, m, str.tostring(f_safe_get_int(hitsHi, m - 1)))
table.cell(tbHits, 2, m, str.tostring(f_safe_get_int(hitsLo, m - 1)))
//==================== Bias Components ====================//
// 1) HTF trend
bool htfBull = request.security(syminfo.tickerid, biasTf, ta.ema(close, emaFast) > ta.ema(close, emaSlow), gaps=barmerge.gaps_off)
bool htfBear = request.security(syminfo.tickerid, biasTf, ta.ema(close, emaFast) < ta.ema(close, emaSlow), gaps=barmerge.gaps_off)
int scHTF = htfBull ? 1 : (htfBear ? -1 : 0)
string stHTF = htfBull ? "Bull" : (htfBear ? "Bear" : "—")
// 2) Cone Z
float z = 0.0
if anchorOK
int barsFromAnchor = math.max(1, bar_index - anchorBar)
float dyPerNow = (wickMode == "Wick (High/Low)") ? (mult * baseATR * 0.5) : (mult * baseATR)
float growNow = f_growth(math.min(barsFromAnchor, horizon))
float denom = dyPerNow * growNow
z := denom != 0 ? (close - anchorPrice) / denom : 0.0
int scZ = z > zThresh ? 1 : (z < -zThresh ? -1 : 0)
string stZ = anchorOK ? ("z=" + str.tostring(z, "#.00")) : "no anchor"
// 3) Rail-hug(0.5c〜1.0c帯を High/Low の“タッチ”で判定)
// ← 初期バー安全:参照本数を bar_index にクリップ
int effLookback = math.min(railLookback, bar_index) // bar_index 本目までは 0..bar_index しか参照不可
int upTouch = 0, dnTouch = 0
if anchorOK and effLookback > 0
for i = 0 to effLookback - 1
int barsFA = math.max(1, (bar_index - i) - anchorBar)
float growI = f_growth(math.min(barsFA, horizon))
float dyPerI = (wickMode == "Wick (High/Low)") ? (mult * baseATR * 0.5) : (mult * baseATR)
float up05I = anchorPrice + dyPerI * 0.5 * growI
float up10I = anchorPrice + dyPerI * 1.0 * growI
float dn05I = anchorPrice - dyPerI * 0.5 * growI
float dn10I = anchorPrice - dyPerI * 1.0 * growI
upTouch += (high >= up05I and low <= up10I) ? 1 : 0
dnTouch += (low <= dn05I and high >= dn10I) ? 1 : 0
float upRatio = effLookback > 0 ? (upTouch * 1.0) / effLookback : 0.0
float dnRatio = effLookback > 0 ? (dnTouch * 1.0) / effLookback : 0.0
bool railUp = upRatio > railPct
bool railDn = dnRatio > railPct
int scRail = railUp ? 1 : (railDn ? -1 : 0)
string stRail = anchorOK ? (railUp ? ("Up " + str.tostring(upRatio*100, "#") + "%") : (railDn ? ("Dn " + str.tostring(dnRatio*100, "#") + "%") : "—")) : "no anchor"
// 4) Stripe entry → 最初のフラクタル(帯を出た後確定も拾う)
var bool stripeIn = false
var int stripeIdxActive = na
var int stripeEnterBar = na
var int stripeLastStart = na
var int stripeLastEnd = na
var int stripeLastIdx = na
var string firstFrac = "" // "PL" or "PH" or ""
int nowIdx = f_stripe_index(bar_index)
bool nowInStripe = not na(nowIdx)
if nowInStripe and not stripeIn
stripeIn := true
stripeIdxActive := nowIdx
stripeEnterBar := bar_index
firstFrac := ""
else if not nowInStripe and stripeIn
stripeIn := false
stripeLastStart := stripeEnterBar
stripeLastEnd := bar_index - 1
stripeLastIdx := stripeIdxActive
if (isPH or isPL)
int pc = pivotCenter
int pcIdx = f_stripe_index(pc)
bool inActive = stripeIn and not na(stripeIdxActive) and pcIdx == stripeIdxActive and pc >= nz(stripeEnterBar, pc)
bool inClosed = (not stripeIn) and not na(stripeLastIdx) and pcIdx == stripeLastIdx and pc >= nz(stripeLastStart, pc) and pc <= nz(stripeLastEnd, pc)
if firstFrac == "" and (inActive or inClosed)
firstFrac := isPL ? "PL" : (isPH ? "PH" : "")
int scFrac = firstFrac == "PL" ? 1 : (firstFrac == "PH" ? -1 : 0)
string stFrac = firstFrac == "" ? "—" : ("1st " + firstFrac + (not stripeIn and not na(stripeLastIdx) ? " @m=" + str.tostring(stripeLastIdx) : (not na(stripeIdxActive) ? " @m=" + str.tostring(stripeIdxActive) : "")))
// 5) Structure break(簡易)
var float lastPH = na
var float lastPL = na
float ph = ta.pivothigh(high, 2, 2)
float pl = ta.pivotlow (low , 2, 2)
if not na(ph)
lastPH := ph
if not na(pl)
lastPL := pl
bool bullBreak = not na(lastPH) and close > lastPH
bool bearBreak = not na(lastPL) and close < lastPL
int scStruct = bullBreak ? 1 : (bearBreak ? -1 : 0)
string stStruct = bullBreak ? "Break ↑" : (bearBreak ? "Break ↓" : "—")
// ---- Total ----
int biasScore = scHTF + scZ + scRail + scFrac + scStruct
string biasDir = biasScore >= 3 ? "UP" : (biasScore <= -3 ? "DOWN" : "NEUTRAL")
//==================== Bias Panel (table, corner selectable) ====================//
var table tbBias = na
color colG = color.new(color.green, 10)
color colR = color.new(color.red, 10)
color colN = color.new(color.gray, 70)
f_col(v) =>
v > 0 ? colG : (v < 0 ? colR : colN)
if showBiasPanel and barstate.islast
if na(tbBias)
tbBias := table.new(f_pos(panelCorner), 3, 8, border_width=1)
table.cell(tbBias, 0, 0, "Bias Panel", text_color=color.white, bgcolor=color.new(color.blue, 20), text_halign=text.align_center)
table.merge_cells(tbBias, 0, 0, 2, 0)
table.cell(tbBias, 0, 1, "Card", text_halign=text.align_center)
table.cell(tbBias, 1, 1, "State", text_halign=text.align_center)
table.cell(tbBias, 2, 1, "±1", text_halign=text.align_center)
// rows
table.cell(tbBias, 0, 2, "HTF ("+biasTf+")")
table.cell(tbBias, 1, 2, stHTF)
table.cell(tbBias, 2, 2, str.tostring(scHTF), bgcolor=f_col(scHTF), text_halign=text.align_center)
table.cell(tbBias, 0, 3, "Cone z")
table.cell(tbBias, 1, 3, stZ)
table.cell(tbBias, 2, 3, str.tostring(scZ), bgcolor=f_col(scZ), text_halign=text.align_center)
table.cell(tbBias, 0, 4, "Rail 0.5c")
table.cell(tbBias, 1, 4, stRail)
table.cell(tbBias, 2, 4, str.tostring(scRail), bgcolor=f_col(scRail), text_halign=text.align_center)
table.cell(tbBias, 0, 5, "Fractal")
table.cell(tbBias, 1, 5, stFrac)
table.cell(tbBias, 2, 5, str.tostring(scFrac), bgcolor=f_col(scFrac), text_halign=text.align_center)
table.cell(tbBias, 0, 6, "Structure")
table.cell(tbBias, 1, 6, stStruct)
table.cell(tbBias, 2, 6, str.tostring(scStruct), bgcolor=f_col(scStruct), text_halign=text.align_center)
color totCol = biasScore>=3?colG:(biasScore<=-3?colR:colN)
table.cell(tbBias, 0, 7, "TOTAL", bgcolor=color.new(color.black, 0), text_color=color.white, text_halign=text.align_center)
table.cell(tbBias, 1, 7, biasDir, bgcolor=totCol, text_color=color.white, text_halign=text.align_center)
table.cell(tbBias, 2, 7, str.tostring(biasScore), bgcolor=totCol, text_color=color.white, text_halign=text.align_center)
//==================== Alerts ====================//
alertcondition(biasScore >= 3, "Bias UP", "Bias score >= +3")
alertcondition(biasScore <= -3, "Bias DOWN", "Bias score <= -3")
alertcondition(hitPH, "Fractal High in Convergence", "Pivot High detected inside √n convergence stripe.")
alertcondition(hitPL, "Fractal Low in Convergence", "Pivot Low detected inside √n convergence stripe.")