OPEN-SOURCE SCRIPT
さくらんぼーい

//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=["Time","Bars Ago"], 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=["Close","High","Low","Open","Manual"], 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=["Linear n","Diffusive √n"], 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=["Close","Wick (High/Low)"], 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=["Top-Left","Top-Right","Bottom-Left","Bottom-Right"], group=grpB)
hitsCorner = input.string("Top-Left", "Hits Table Position",
options=["Top-Left","Top-Right","Bottom-Left","Bottom-Right"], 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[1], time[0]) < _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<int> 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.")
indicator("さくらんぼーい", overlay=true, max_labels_count=500, max_lines_count=500)
//==================== Inputs ====================//
// ---- Anchor (shared) ----
grpA = "Anchor (shared)"
anchorMode = input.string("Time", "Anchor Mode", options=["Time","Bars Ago"], 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=["Close","High","Low","Open","Manual"], 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=["Linear n","Diffusive √n"], 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=["Close","Wick (High/Low)"], 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=["Top-Left","Top-Right","Bottom-Left","Bottom-Right"], group=grpB)
hitsCorner = input.string("Top-Left", "Hits Table Position",
options=["Top-Left","Top-Right","Bottom-Left","Bottom-Right"], 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[1], time[0]) < _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<int> 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.")
סקריפט קוד פתוח
ברוח TradingView אמיתית, היוצר של הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יכולים לבדוק ולאמת את הפונקציונליות שלו. כל הכבוד למחבר! למרות שאתה יכול להשתמש בו בחינם, זכור שפרסום מחדש של הקוד כפוף לכללי הבית שלנו.
כתב ויתור
המידע והפרסומים אינם אמורים להיות, ואינם מהווים, עצות פיננסיות, השקעות, מסחר או סוגים אחרים של עצות או המלצות שסופקו או מאושרים על ידי TradingView. קרא עוד בתנאים וההגבלות.
סקריפט קוד פתוח
ברוח TradingView אמיתית, היוצר של הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יכולים לבדוק ולאמת את הפונקציונליות שלו. כל הכבוד למחבר! למרות שאתה יכול להשתמש בו בחינם, זכור שפרסום מחדש של הקוד כפוף לכללי הבית שלנו.
כתב ויתור
המידע והפרסומים אינם אמורים להיות, ואינם מהווים, עצות פיננסיות, השקעות, מסחר או סוגים אחרים של עצות או המלצות שסופקו או מאושרים על ידי TradingView. קרא עוד בתנאים וההגבלות.