-
bu arada önemli bir şeyi unuttuk....
biz son 500 bar içinde en yüksek ve en düşük değeri 100 bölüme ayırıp, tepeden 15 birim aşağısına stop yazdık t ve s diye belirttik....
ama medyan yazıp, dip ve reverse kaldırmıştık....
reverse 0.85 birim di.....
kaldırılan reverse yerine bar body içinde 0.85 kullanıp.... tetikleyici unuttuk eklenmiş hali....
tetiklenen bar için zemin rengine mavi olur.....
bknz...
1 dk örnekler...
https://www.tradingview.com/x/IHwNejW3/
https://www.tradingview.com/x/L7Hinyxh/
https://www.tradingview.com/x/UQ1wM0EA/
https://www.tradingview.com/x/EkS1OmKw/
https://www.tradingview.com/x/EoRHDZbB/
https://www.tradingview.com/x/7m8tRgVk/
https://www.tradingview.com/x/hF4CY69j/
-
matriks ile tw birbirinden çok farklı....
tw de yazılanı.... matrikste yazamayacak kadar kod özürlüyüm....
belli bir yaştan sonra zor oluyor....
sadece tarama kodunu yapmaya çalışacağım....
-
son 500 barı hesaplar...isteğe göre değiştirebilirsiniz....
en yüksek ve en düşük değerin ortalamasını alır.....
1dk, 15dk, 60dk, 240dk ve gün olarak etiket gösterir.... 1dk fuşyadır....
v6 versiyondur.... yapay zeka ile yapılmıştır....
denemek isteyene kodu....
PHP Code:
//@version=6
indicator('Timeframes Simple Labels', overlay = true, max_labels_count = 50)
len = input.int(500, 'Bars Count', minval = 2)
// X ofsetleri (son barla arada boşluk olacak şekilde)
offsetX1 = input.int(-200, '1min X Offset (bars left from last)')
offsetX15 = input.int(-120, '15min X Offset')
offsetX60 = input.int(-30, '60min X Offset')
offsetX240 = input.int(30, '4h X Offset')
offsetXD = input.int(12, '1D X Offset')
offsetYStep = input.float(0.0, 'Y Step for Ladder', step = 0.1)
getMid(tf) =>
h = request.security(syminfo.tickerid, tf, ta.highest(high, len), lookahead = barmerge.lookahead_on)
l = request.security(syminfo.tickerid, tf, ta.lowest(low, len), lookahead = barmerge.lookahead_on)
(h + l) / 2
mid1 = getMid('1')
mid15 = getMid('15')
mid60 = getMid('60')
mid240 = getMid('240')
midD = getMid('D')
// X pozisyonu (son barın solunda ve arada boşluk)
x_pos1 = bar_index - offsetX1
x_pos15 = bar_index - offsetX15
x_pos60 = bar_index - offsetX60
x_pos240 = bar_index - offsetX240
x_posD = bar_index - offsetXD
var label lbl1 = na
var label lbl15 = na
var label lbl60 = na
var label lbl240 = na
var label lblD = na
delLabel(l) =>
if not na(l)
label.delete(l)
// Etiketleri oluştur / güncelle (merdiven görünümü ve yatay boşluk)
delLabel(lbl1)
lbl1 := label.new(x_pos1, mid1, '1min: ' + str.tostring(mid1, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = color.new(color.fuchsia, 0), textcolor = color.white, size = size.small)
delLabel(lbl15)
lbl15 := label.new(x_pos15, mid15 + offsetYStep * 1, '15min: ' + str.tostring(mid15, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = color.new(color.gray, 0.2), textcolor = color.white, size = size.small)
delLabel(lbl60)
lbl60 := label.new(x_pos60, mid60 + offsetYStep * 2, '60min: ' + str.tostring(mid60, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = color.new(color.gray, 0.4), textcolor = color.white, size = size.small)
delLabel(lbl240)
lbl240 := label.new(x_pos240, mid240 + offsetYStep * 3, '4h: ' + str.tostring(mid240, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = color.new(color.gray, 0.6), textcolor = color.white, size = size.small)
delLabel(lblD)
lblD := label.new(x_posD, midD + offsetYStep * 4, '1D: ' + str.tostring(midD, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = color.new(color.gray, 0.8), textcolor = color.white, size = size.small)
örnek görüntüler.....
https://www.tradingview.com/x/j78DWifi/
https://www.tradingview.com/x/Lq1PsqwO/
https://www.tradingview.com/x/ZSqSF4xd/
https://www.tradingview.com/x/ENFnUkM5/
https://www.tradingview.com/x/IZpQcLga/
-
PHP Code:
//@version=6
indicator(".", overlay=true,max_lines_count = 10)
// Настройки
predictionPeriod = input.int(50, minval=1, title="Prediction Period")
confidenceThreshold = input.float(0.7, minval=0, maxval=100, step=0.1, title="Confidence Threshold (%)")
show_additional_labels = input.bool(true, title="Additional labels")
// Функция для поиска локальных экстремумов
f_findLocalExtremes(src, period) =>
float highestPoint = na
float lowestPoint = na
int highestBarIndex = na
int lowestBarIndex = na
float avgTrueRange = ta.atr(14)
for i = 0 to period
float currentHigh = high[i]
float currentLow = low[i]
bool isLocalHigh = currentHigh > highestPoint or na(highestPoint)
bool isLocalLow = currentLow < lowestPoint or na(lowestPoint)
if (isLocalHigh)
highestPoint := currentHigh
highestBarIndex := bar_index[i]
if (isLocalLow)
lowestPoint := currentLow
lowestBarIndex := bar_index[i]
[highestPoint, lowestPoint, highestBarIndex, lowestBarIndex]
// Функция прогнозирования
f_predictNextMove(highestPoint, lowestPoint) =>
float midPointUp = lowestPoint + (highestPoint - lowestPoint) * 0.618
float midPointDown = highestPoint - (highestPoint - lowestPoint) * 0.618
float bullishTarget = midPointUp * (1 + confidenceThreshold / 100)
float bearishTarget = midPointDown * (1 - confidenceThreshold / 100)
[bullishTarget, bearishTarget]
// Основной алгоритм
[highestPoint, lowestPoint, highestBarIndex, lowestBarIndex] = f_findLocalExtremes(close, predictionPeriod)
[bullishTarget, bearishTarget] = f_predictNextMove(highestPoint, lowestPoint)
// Визуализация
// Верхняя и нижняя точки
//plot(highestPoint, "Highest Point", color=color.red, linewidth=2, style=plot.style_circles)
//plot(lowestPoint, "Lowest Point", color=color.green, linewidth=2, style=plot.style_circles)
// Цели
//plot(bullishTarget, "Bullish Target", color=color.blue, linewidth=2, style=plot.style_line)
//plot(bearishTarget, "Bearish Target", color=color.purple, linewidth=2, style=plot.style_line)
// Условия для сигналов
longCondition = close > bullishTarget and highestPoint > lowestPoint
shortCondition = close < bearishTarget and highestPoint > lowestPoint
// Сигналы на графике
//plotshape(longCondition, title="Buy Signal", location=location.belowbar, color=longCondition ? color.green : na, style=shape.arrowup, size=size.tiny, text="Buy")
//plotshape(shortCondition, title="Sell Signal", location=location.abovebar, color=shortCondition ? color.red : na, style=shape.arrowdown, size=size.tiny, text="Sell")
// Дополнительные метки
if show_additional_labels
var label lowLabel = na
var label highLabel = na
var label bullishLabel = na
var label bearishLabel = na
if barstate.islast
// Удаление предыдущих меток, если они существуют
if not na(lowLabel)
label.delete(lowLabel)
if not na(highLabel)
label.delete(highLabel)
if not na(bullishLabel)
label.delete(bullishLabel)
if not na(bearishLabel)
label.delete(bearishLabel)
// Создание новых меток на последнем баре
lowLabel := label.new(lowestBarIndex, lowestPoint, text="L: " + str.tostring(lowestPoint, format.mintick), color=color.green, style=label.style_label_up, size=size.small)
highLabel := label.new(highestBarIndex, highestPoint, text="H: " + str.tostring(highestPoint, format.mintick), color=color.red, style=label.style_label_down, size=size.small)
bullishLabel := label.new(bar_index + 1, bullishTarget, text="Boğa: " + str.tostring(bullishTarget, format.mintick), color=color.blue, style=label.style_label_left, size=size.small)
bearishLabel := label.new(bar_index + 1, bearishTarget, text="Ayı: " + str.tostring(bearishTarget, format.mintick), color=color.purple, style=label.style_label_left, size=size.small)
//plot(close)
// ———————————————————— Constants
TU1 = 'chart'
TU2 = 'seconds'
TU3 = 'minutes'
TU4 = 'hours'
TU5 = 'days'
TU6 = 'months'
TU7 = 'years'
OF1 = 'Bar\'s Open Time'
OF2 = 'Bar\'s Close Time'
OF3 = 'Current Time'
// ———————————————————— Inputs
i_n = input(50, 'Lines End At Offset n (+/-)')
i_units = input.string(TU1, ' Offset Units', options = [TU1, TU2, TU3, TU4, TU5, TU6, TU7])
i_from = input.string(OF1, ' Calculated from', options = [OF1, OF2, OF3])
i_modulo = input.int(50, 'Draw lines every n bars', minval = 1)
// ———————————————————— Functions.
// ————— Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
_resInMinutes
// ————— Calculates a +/- time offset in variable units from the current bar's time or from the current time.
// WARNING:
// This functions does not solve the challenge of taking into account irregular gaps between bars when calculating time offsets.
// Optimal behavior occurs when there are no missing bars at the chart resolution between the current bar and the calculated time for the offset.
// Holidays, no-trade periods or other irregularities causing missing bars will produce unpredictable results.
f_timeFrom(_from, _qty, _units) =>
// _from : starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time.
// _qty : the +/- qty of _units of offset required. A "series float" can be used but it will be cast to a "series int".
// _units : string containing one of the seven allowed time units: "chart" (chart's resolution), "seconds", "minutes", "hours", "days", "months", "years".
// Dependency: f_resInMinutes().
int _timeFrom = na
// Remove any "s" letter in the _units argument, so we don't need to compare singular and plural unit names.
_unit = str.replace_all(_units, 's', '')
// Determine if we will calculate offset from the bar's time or from current time.
_t = _from == 'bar' ? time : _from == 'close' ? time_close : timenow
// Calculate time at offset.
if _units == 'chart'
// Offset in chart res multiples.
_timeFrom := int(_t + f_resInMinutes() * 60 * 1000 * _qty)
_timeFrom
else // Add the required _qty of time _units to the _from starting time.
_year = year(_t) + (_unit == 'year' ? int(_qty) : 0)
_month = month(_t) + (_unit == 'month' ? int(_qty) : 0)
_day = dayofmonth(_t) + (_unit == 'day' ? int(_qty) : 0)
_hour = hour(_t) + (_unit == 'hour' ? int(_qty) : 0)
_minute = minute(_t) + (_unit == 'minute' ? int(_qty) : 0)
_second = second(_t) + (_unit == 'econd' ? int(_qty) : 0)
// Return the resulting time in ms Unix time format.
_timeFrom := timestamp(_year, _month, _day, _hour, _minute, _second)
_timeFrom
// ———————————————————— Calculations.
// Condition trigerring the display of lines.
drawLines = bar_index % i_modulo == 0 or barstate.islast
// Base to calculate offset from.
from = i_from == OF1 ? 'bar' : i_from == OF2 ? 'close' : 'now'
// Calculate offset.
TimeTo = f_timeFrom(from, i_n, i_units)
// ———————————————————— Plots
// Draw lines when required.
if drawLines
// Draw a line in the future at the `high` and `low` levels of the bar where the condition occurs.
// Note that these lines aren't drawn when loop mode is used because `x2Hi` and `x2Lo` are then `na`.
line.new(time, high, TimeTo, high, xloc.bar_time, color = color.purple, style = line.style_arrow_right, width = 1)
//line.new(time, low, TimeTo, low, xloc.bar_time, color = color.white, style = line.style_arrow_right, width = 1)
// Plot chart interval in ms in Data Window.
//plotchar(f_resInMinutes(), 'f_resInMinutes()', '', location.top, size = size.tiny)
//////////////////////////////////////////
// ================= User Inputs =================
Periods = input.int(100, title="ATR Period", minval=1)
src = input.source(ohlc4, title="Source")
Multiplier = input.float(5.7, title="ATR Multiplier")
changeATR = input.bool(true, title="Use True ATR?")
showsignals = input.bool(true, title="Show Buy/Sell Signals")
highlighting = input.bool(true, title="Enable Trend Highlighting")
// ================= ATR Calculation =================
atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
// ================= Trend Calculation =================
up = src - (Multiplier * atr)
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + (Multiplier * atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
var int trend = 1
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
// ================= Plotting Up/Down Trend Lines =================
upPlot = plot(trend == 1 ? up : na, title="Up", style=plot.style_linebr, linewidth=1, color=color.rgb(4, 255, 12))
dnPlot = plot(trend == -1 ? dn : na, title="Down", style=plot.style_linebr, linewidth=1, color=color.fuchsia)
// ================= Buy/Sell Signals =================
buySignal = trend == 1 and trend[1] == -1
sellSignal = trend == -1 and trend[1] == 1
plotshape(buySignal and showsignals ? up : na, title="Buy", text="A", style=shape.labelup, location=location.bottom, size=size.small, color=#ffbf00, textcolor=color.black)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="S", location=location.top, style=shape.labeldown, size=size.small, color=#ffbf00, textcolor=color.black)
////////////
// --- User Inputs ---
// Trendline Set Toggles
g_general = "General Settings"
show10 = input.bool(true, "Lookback 10/10", group=g_general, inline="set1")
show25 = input.bool(false, "25/25", group=g_general, inline="set1")
show50 = input.bool(false, "50/50", group=g_general, inline="set2")
show100 = input.bool(false, "100/100", group=g_general, inline="set2")
show250 = input.bool(false, "250/250", group=g_general, inline="set3")
show500 = input.bool(false, "500/500", group=g_general, inline="set3")
// Line Style
g_style = "Style Settings"
downTrendColor = input.color(color.new(color.red, 0), title="Downtrend Color", group=g_style)
upTrendColor = input.color(color.new(color.green, 0), title="Uptrend Color", group=g_style)
lineWidth = input.int(2, title="Line Width", minval=1, group=g_style)
lineStyleInput = input.string("Dotted", title="Line Style", options=["Solid", "Dashed", "Dotted"], group=g_style)
// Behavior
g_behavior = "Behavior Settings"
stopExtendOnBreak = input.bool(true, title="Stop Extend on Break", group=g_behavior)
//showPivots = input.bool(true, title="Show Pivot Points", group=g_behavior)
// --- Custom Type for Managing Trendline State ---
// This object holds all the necessary variables for a single trendline set.
type TrendlineState
// High trendline state
line highLine1 = na
line highLine2 = na
bool isHighLine1Broken = false
float lastPivotHighPrice = na
int lastPivotHighBar = na
float prevPivotHighPrice = na
int prevPivotHighBar = na
// Low trendline state
line lowLine1 = na
line lowLine2 = na
bool isLowLine1Broken = false
float lastPivotLowPrice = na
int lastPivotLowBar = na
float prevPivotLowPrice = na
int prevPivotLowBar = na
// --- State Management ---
// Create a persistent state object for each lookback period.
var state10 = TrendlineState.new()
var state25 = TrendlineState.new()
var state50 = TrendlineState.new()
var state100 = TrendlineState.new()
var state250 = TrendlineState.new()
var state500 = TrendlineState.new()
// --- Line Style Conversion Function ---
f_getLineStyle(style) =>
switch style
"Solid" => line.style_solid
"Dashed" => line.style_dashed
=> line.style_dotted
lineStyle = f_getLineStyle(lineStyleInput)
// --- Pre-calculate All Pivot Points ---
// This is more efficient than calculating them inside the function repeatedly.
pivotH10 = ta.pivothigh(high, 10, 10)
pivotL10 = ta.pivotlow(low, 10, 10)
pivotH25 = ta.pivothigh(high, 25, 25)
pivotL25 = ta.pivotlow(low, 25, 25)
pivotH50 = ta.pivothigh(high, 50, 50)
pivotL50 = ta.pivotlow(low, 50, 50)
pivotH100 = ta.pivothigh(high, 100, 100)
pivotL100 = ta.pivotlow(low, 100, 100)
pivotH250 = ta.pivothigh(high, 250, 250)
pivotL250 = ta.pivotlow(low, 250, 250)
pivotH500 = ta.pivothigh(high, 500, 500)
pivotL500 = ta.pivotlow(low, 500, 500)
// --- Core Logic Function ---
// This function calculates, draws, and manages a single set of trendlines.
processTrendlines(TrendlineState state, int rightBars, float pivotHighPrice, float pivotLowPrice) =>
// --- Draw High Trendlines ---
if not na(pivotHighPrice)
state.prevPivotHighPrice := state.lastPivotHighPrice
state.prevPivotHighBar := state.lastPivotHighBar
state.lastPivotHighPrice := pivotHighPrice
state.lastPivotHighBar := bar_index - rightBars
if not na(state.prevPivotHighPrice)
line.delete(state.highLine2)
state.highLine2 := state.highLine1
state.highLine1 := line.new(state.prevPivotHighBar, state.prevPivotHighPrice, state.lastPivotHighBar, state.lastPivotHighPrice, color=downTrendColor, width=lineWidth, style=lineStyle, extend=extend.right)
state.isHighLine1Broken := false
// --- Draw Low Trendlines ---
if not na(pivotLowPrice)
state.prevPivotLowPrice := state.lastPivotLowPrice
state.prevPivotLowBar := state.lastPivotLowBar
state.lastPivotLowPrice := pivotLowPrice
state.lastPivotLowBar := bar_index - rightBars
if not na(state.prevPivotLowPrice)
line.delete(state.lowLine2)
state.lowLine2 := state.lowLine1
state.lowLine1 := line.new(state.prevPivotLowBar, state.prevPivotLowPrice, state.lastPivotLowBar, state.lastPivotLowPrice, color=upTrendColor, width=lineWidth, style=lineStyle, extend=extend.right)
state.isLowLine1Broken := false
// --- Handle Line Breaks ---
if stopExtendOnBreak
// High line break
if not na(state.highLine1) and not state.isHighLine1Broken
linePrice = line.get_price(state.highLine1, bar_index)
if high > linePrice
x1 = line.get_x1(state.highLine1)
y1 = line.get_y1(state.highLine1)
line.delete(state.highLine1)
state.highLine1 := line.new(x1, y1, bar_index, linePrice, color=downTrendColor, width=lineWidth, style=lineStyle, extend=extend.none)
state.isHighLine1Broken := true
// Low line break
if not na(state.lowLine1) and not state.isLowLine1Broken
linePrice = line.get_price(state.lowLine1, bar_index)
if low < linePrice
x1 = line.get_x1(state.lowLine1)
y1 = line.get_y1(state.lowLine1)
line.delete(state.lowLine1)
state.lowLine1 := line.new(x1, y1, bar_index, linePrice, color=upTrendColor, width=lineWidth, style=lineStyle, extend=extend.none)
state.isLowLine1Broken := true
// --- Cleanup Function ---
cleanupLines(TrendlineState state) =>
line.delete(state.highLine1)
line.delete(state.highLine2)
line.delete(state.lowLine1)
line.delete(state.lowLine2)
state.highLine1 := na
state.highLine2 := na
state.lowLine1 := na
state.lowLine2 := na
// --- Main Execution Block ---
if show10
processTrendlines(state10, 10, pivotH10, pivotL10)
else
cleanupLines(state10)
if show25
processTrendlines(state25, 25, pivotH25, pivotL25)
else
cleanupLines(state25)
if show50
processTrendlines(state50, 50, pivotH50, pivotL50)
else
cleanupLines(state50)
if show100
processTrendlines(state100, 100, pivotH100, pivotL100)
else
cleanupLines(state100)
if show250
processTrendlines(state250, 250, pivotH250, pivotL250)
else
cleanupLines(state250)
if show500
processTrendlines(state500, 500, pivotH500, pivotL500)
else
cleanupLines(state500)
// --- Plot Pivot Points ---
// The first argument to plotshape must be a boolean condition.
// We combine the user toggles with the pivot detection to create this condition.
-
rsi değerini mtf tablo, fiyat olarak görmek isteyenler için....
RSI Dynamic Bands
https://tr.tradingview.com/v/Jd3xaoZm/
https://www.tradingview.com/x/yp0zGXhH/
-
ADVANCED COSINE PROJECTION SYSTEM — LITE Mark3
https://tr.tradingview.com/v/eEKFyQYY/
ilginç çalışma... sadeleşip kullanılabilir....
-
Dynamic Grid Range V9 (Final)
https://tr.tradingview.com/v/OiZ5MhDJ/
ayarlarda mod var...ultra safe seçtiğimde.... https://www.tradingview.com/x/fMixJS9F/
-
combine kod çalışması....stratejiyi kendiniz yazın ve test edin....
PHP Code:
//@version=6
indicator("combine", shorttitle=".", overlay=true,
max_lines_count=400, max_boxes_count=50, max_labels_count=5)
// ── Enhanced Inputs
string GRP1 = "Core Pattern Matching"
string GRP2 = "Projection & Smoothing"
string GRP3 = "Quality & Filtering"
string GRP4 = "Visuals"
int patLen = input.int(20, "Pattern Length", minval=8, maxval=200, group=GRP1)
int fLen = input.int(30, "Forecast Bars", minval=5, maxval=300, group=GRP1)
int depth = input.int(2000, "Search Depth", minval=200,maxval=6000,group=GRP1)
float minConf = input.float(0.30,"Min Confidence", minval=0.10,maxval=0.95,step=0.05,group=GRP1)
string scaling = input.string("Adaptive","Scaling Method", options=["Fixed","Adaptive","Volatility","Z-Score"], group=GRP2)
string smoothing = input.string("EMA","Projection Smoothing", options=["None","SMA","EMA","Adaptive"], group=GRP2)
int smoothLen = input.int(3, "Smoothing Length", minval=2, maxval=10, group=GRP2)
bool useQualFilter = input.bool(true, "Enable Quality Filter", group=GRP3)
float minVariance = input.float(0.001,"Min Pattern Variance", minval=0.0001, maxval=0.01, step=0.0001, group=GRP3)
int trendCheck = input.int(5, "Trend Coherence Bars", minval=3, maxval=15, group=GRP3)
bool showProj = input.bool(true, "Show Projection", group=GRP4)
bool showBands = input.bool(true, "Show Bands", group=GRP4)
bool showZones = input.bool(true, "Show Zones", group=GRP4)
// Enhanced colors
color upColor = input.color(#00FF88, "Uptrend (Green)", group=GRP4)
color dnColor = input.color(#FF4444, "Downtrend (Red)", group=GRP4)
color swColor = input.color(#FFAA00, "Sideways (Yellow)", group=GRP4)
// ── Enhanced Data buffers
var array<float> prices = array.new<float>()
var array<int> times = array.new<int>()
var array<float> highs = array.new<float>()
var array<float> lows = array.new<float>()
// handles
var array<line> hProj = array.new<line>()
var array<line> hBand = array.new<line>()
var array<box> hBox = array.new<box>()
var label hLbl = na
// ── Enhanced Helper Functions
safeDiv(float n, float d, float fb) =>
d == 0.0 ? fb : n / d
// Enhanced cosine similarity with multiple normalization methods
cosineSim(array<float> arr, int startA, int startB, int len, string method = "returns") =>
array<float> seqA = array.new<float>()
array<float> seqB = array.new<float>()
// Extract sequences
for i = 0 to len - 1
array.push(seqA, array.get(arr, startA + i))
array.push(seqB, array.get(arr, startB + i))
// Normalize based on method
if method == "returns"
// Return-based normalization (original method)
float dp = 0.0, na2 = 0.0, nb2 = 0.0
for k = 1 to len - 1
float a0 = array.get(seqA, k - 1)
float a1 = array.get(seqA, k)
float b0 = array.get(seqB, k - 1)
float b1 = array.get(seqB, k)
float ra = safeDiv(a1 - a0, a0, 0.0)
float rb = safeDiv(b1 - b0, b0, 0.0)
dp := dp + ra * rb
na2 := na2 + ra * ra
nb2 := nb2 + rb * rb
float den = math.sqrt(na2) * math.sqrt(nb2)
den == 0.0 ? 0.0 : dp / den
else
// Z-score normalization for more stable comparison
float meanA = 0.0, meanB = 0.0
for i = 0 to len - 1
meanA := meanA + array.get(seqA, i)
meanB := meanB + array.get(seqB, i)
meanA := meanA / len
meanB := meanB / len
float stdA = 0.0, stdB = 0.0
for i = 0 to len - 1
float diffA = array.get(seqA, i) - meanA
float diffB = array.get(seqB, i) - meanB
stdA := stdA + diffA * diffA
stdB := stdB + diffB * diffB
stdA := math.sqrt(stdA / len)
stdB := math.sqrt(stdB / len)
if stdA == 0.0 or stdB == 0.0
0.0
else
float dp = 0.0, na2 = 0.0, nb2 = 0.0
for i = 0 to len - 1
float za = (array.get(seqA, i) - meanA) / stdA
float zb = (array.get(seqB, i) - meanB) / stdB
dp := dp + za * zb
na2 := na2 + za * za
nb2 := nb2 + zb * zb
float den = math.sqrt(na2) * math.sqrt(nb2)
den == 0.0 ? 0.0 : dp / den
// Pattern quality validation
patternQuality(array<float> arr, int start, int len) =>
if start < 0 or start + len >= array.size(arr)
0.0
else
// Calculate variance to ensure pattern has sufficient movement
float mean = 0.0
for i = 0 to len - 1
mean := mean + array.get(arr, start + i)
mean := mean / len
float variance = 0.0
for i = 0 to len - 1
float diff = array.get(arr, start + i) - mean
variance := variance + diff * diff
variance := variance / len
// Check trend coherence - avoid choppy patterns
int trendChanges = 0
bool lastUp = false
bool firstCheck = true
for i = 1 to len - 1
bool currentUp = array.get(arr, start + i) > array.get(arr, start + i - 1)
if not firstCheck and currentUp != lastUp
trendChanges := trendChanges + 1
lastUp := currentUp
firstCheck := false
float coherence = 1.0 - (trendChanges / (len - 1))
math.sqrt(variance) * coherence
// Enhanced smoothing function
smoothProjection(array<float> proj, string method, int length) =>
array<float> smoothed = array.new<float>()
int size = array.size(proj)
if method == "None"
for i = 0 to size - 1
array.push(smoothed, array.get(proj, i))
else if method == "SMA"
for i = 0 to size - 1
float sum = 0.0
int count = 0
int start = math.max(0, i - length + 1)
for j = start to i
sum := sum + array.get(proj, j)
count := count + 1
array.push(smoothed, sum / count)
else if method == "EMA"
float alpha = 2.0 / (length + 1.0)
array.push(smoothed, array.get(proj, 0))
for i = 1 to size - 1
float prev = array.get(smoothed, i - 1)
float curr = array.get(proj, i)
array.push(smoothed, alpha * curr + (1.0 - alpha) * prev)
else // Adaptive
for i = 0 to size - 1
float sum = 0.0
float weightSum = 0.0
int adaptiveLen = i < length ? i + 1 : length
for j = 0 to adaptiveLen - 1
float weight = 1.0 / (j + 1.0)
sum := sum + array.get(proj, i - j) * weight
weightSum := weightSum + weight
array.push(smoothed, sum / weightSum)
smoothed
// Sample std of returns (enhanced for volatility scaling)
retStd(array<float> arr, int start, int len) =>
if start < 1 or start + len >= array.size(arr)
0.0
else
float s = 0.0
float c = 0.0
for k = start + 1 to start + len
float r = safeDiv(array.get(arr, k) - array.get(arr, k - 1), array.get(arr, k - 1), 0.0)
s := s + r
c := c + 1.0
float m = safeDiv(s, c, 0.0)
float ss = 0.0
for k = start + 1 to start + len
float r = safeDiv(array.get(arr, k) - array.get(arr, k - 1), array.get(arr, k - 1), 0.0)
float d = r - m
ss := ss + d * d
math.sqrt(safeDiv(ss, math.max(1.0, c - 1.0), 0.0))
// Array min/max over a range
arrMin(array<float> a, int start, int len) =>
float m = na
int stop = math.min(start + len, array.size(a))
if start >= 0 and start < array.size(a)
for i = start to stop - 1
float v = array.get(a, i)
m := na(m) ? v : math.min(m, v)
m
arrMax(array<float> a, int start, int len) =>
float m = na
int stop = math.min(start + len, array.size(a))
if start >= 0 and start < array.size(a)
for i = start to stop - 1
float v = array.get(a, i)
m := na(m) ? v : math.max(m, v)
m
// Draw cleanup
cleanup() =>
for l in hProj
line.delete(l)
array.clear(hProj)
for l in hBand
line.delete(l)
array.clear(hBand)
for b in hBox
box.delete(b)
array.clear(hBox)
if not na(hLbl)
label.delete(hLbl)
// Keep arrays bounded
keep(int maxKeep) =>
while array.size(prices) > maxKeep
array.shift(prices)
array.shift(times)
array.shift(highs)
array.shift(lows)
// ── Ingest
array.push(prices, close)
array.push(times, time)
array.push(highs, high)
array.push(lows, low)
keep(depth + patLen + fLen + 50)
// ── Enhanced Engine
if barstate.islastconfirmedhistory and array.size(prices) > patLen * 2 + fLen
cleanup()
hLbl := na
int N = array.size(prices)
int recentStart = N - patLen
int searchEnd = N - patLen - fLen
int searchStart = math.max(0, searchEnd - depth)
float bestScore = -1.0
int bestIdx = 0
float bestQuality = 0.0
// Enhanced pattern search with quality filtering
for i = searchStart to searchEnd
// Check pattern quality first if filtering enabled
float quality = useQualFilter ? patternQuality(prices, i, patLen) : 1.0
if quality >= minVariance
string simMethod = scaling == "Z-Score" ? "zscore" : "returns"
float s = cosineSim(prices, recentStart, i, patLen, simMethod)
// Weight similarity by pattern quality
float weightedScore = s * (0.7 + 0.3 * math.min(quality / (minVariance * 10.0), 1.0))
if weightedScore > bestScore
bestScore := weightedScore
bestIdx := i
bestQuality := quality
bool have = bestScore >= minConf
if have
// Enhanced scaling methods
float cur = array.get(prices, N - 1)
float baseHist = array.get(prices, bestIdx + patLen - 1)
float scale = 1.0
if scaling == "Fixed"
scale := 1.0
else if scaling == "Adaptive"
scale := safeDiv(cur, baseHist, 1.0)
else if scaling == "Volatility"
float cstd = retStd(prices, N - 1 - patLen, patLen)
float hstd = retStd(prices, bestIdx, patLen)
float vr = safeDiv(cstd, hstd, 1.0)
scale := safeDiv(cur, baseHist, 1.0) * vr
else // Z-Score
// Z-score based scaling for more stable projections
float histMean = 0.0
for i = 0 to patLen - 1
histMean := histMean + array.get(prices, bestIdx + i)
histMean := histMean / patLen
float histStd = 0.0
for i = 0 to patLen - 1
float diff = array.get(prices, bestIdx + i) - histMean
histStd := histStd + diff * diff
histStd := math.sqrt(histStd / patLen)
float currentStd = ta.stdev(close, patLen)
scale := safeDiv(currentStd, histStd, 1.0)
// Build raw projection path
array<float> rawProj = array.new<float>()
for k = 0 to fLen - 1
float src = array.get(prices, bestIdx + patLen + k)
float val = cur + (src - baseHist) * scale
array.push(rawProj, val)
// Apply smoothing to projection
array<float> proj = smoothProjection(rawProj, smoothing, smoothLen)
// Enhanced confidence bands
float baseVol = ta.atr(20)
float confMult = (1.0 - bestScore) * 2.0 + (1.0 - bestQuality / (minVariance * 20.0)) * 1.0
array<float> up = array.new<float>()
array<float> dn = array.new<float>()
for i = 0 to array.size(proj) - 1
float val = array.get(proj, i)
float dynamicConf = baseVol * confMult * (1.0 + i * 0.1 / fLen) // Expanding confidence
array.push(up, val + dynamicConf)
array.push(dn, val - dynamicConf)
// Directional analysis with smoothed values
float last = array.get(proj, array.size(proj) - 1)
float pct = safeDiv(last - cur, cur, 0.0) * 100.0
color lnColor = math.abs(pct) < 0.3 ? swColor : (pct > 0 ? upColor : dnColor)
// Draw enhanced projection
if showProj
line l0 = line.new(bar_index, cur, bar_index + 1, array.get(proj, 0), color=lnColor, width=3)
array.push(hProj, l0)
for k = 0 to array.size(proj) - 2
line lk = line.new(bar_index + k + 1, array.get(proj, k),
bar_index + k + 2, array.get(proj, k + 1),
color=lnColor, width=3)
array.push(hProj, lk)
// Enhanced bands
if showBands
color bc = color.new(lnColor, 70)
line u0 = line.new(bar_index, cur + baseVol * confMult, bar_index + 1, array.get(up, 0), color=bc, style=line.style_dashed)
line d0 = line.new(bar_index, cur - baseVol * confMult, bar_index + 1, array.get(dn, 0), color=bc, style=line.style_dashed)
array.push(hBand, u0)
array.push(hBand, d0)
for k = 0 to array.size(up) - 2
line uu = line.new(bar_index + k + 1, array.get(up, k), bar_index + k + 2, array.get(up, k + 1), color=bc, style=line.style_dashed)
line dd = line.new(bar_index + k + 1, array.get(dn, k), bar_index + k + 2, array.get(dn, k + 1), color=bc, style=line.style_dashed)
array.push(hBand, uu)
array.push(hBand, dd)
// Zones (unchanged)
if showZones
float hLow = arrMin(lows, bestIdx, patLen)
float hHigh = arrMax(highs, bestIdx, patLen)
if not na(hLow) and not na(hHigh)
box b1 = box.new(array.get(times, bestIdx), hLow, array.get(times, bestIdx + patLen - 1), hHigh,
xloc=xloc.bar_time, bgcolor=color.new(lnColor, 85), border_color=color.new(lnColor, 55))
array.push(hBox, b1)
float cLow = ta.lowest(low, patLen)
float cHigh = ta.highest(high,patLen)
box b2 = box.new(bar_index - patLen + 1, cLow, bar_index, cHigh,
bgcolor=color.new(color.blue, 85), border_color=color.new(color.blue, 55))
array.push(hBox, b2)
// Enhanced label with quality metrics
string tname = math.abs(pct) < 0.3 ? "SIDEWAYS" : (pct > 0 ? "BULLISH" : "BEARISH")
string emoji = math.abs(pct) < 0.3 ? "↔" : (pct > 0 ? "▲" : "▼")
string lbl = str.format("{0} ENHANCED PROJECTION ({1})\nConfidence: {2,number,#.0}% | Quality: {3,number,#.0}%\nTarget: {4,number,#.##} | Change: {5,number,#.1}%\nMethod: {6} | Smoothing: {7}",
emoji, tname, bestScore*100.0, bestQuality*10000.0, last, pct, scaling, smoothing)
hLbl := label.new(bar_index + math.round(array.size(proj)/2.0), math.max(cur, last) + ta.atr(10),
lbl, color=color.new(lnColor, 20), textcolor=color.white,
style=label.style_label_down, size=size.normal)
////////////////////
// UI Options for Auto Trend Detection and No Signal in Sideways Market
autoTrendDetection = input.bool(true, title = 'Auto Trend Detection')
noSignalSideways = input.bool(true, title = 'No Signal in Sideways Market')
// Color variables
upTrendColor = color.white
neutralColor = #90bff9
downTrendColor = color.blue
// Source
source = input(defval = close, title = 'Source')
// Sampling Period - Replaced with Sniper Machine
period = input.int(defval = 9, minval = 1, title = 'Sniper Machine Period')
// Trend Master - Replaced with Sniper Machine
multiplier = input.float(defval = 3.0, minval = 0.1, title = 'Sniper Machine Multiplier')
// Smooth Average Range
smoothRange(x, t, m) =>
adjustedPeriod = t * 2 - 1
avgRange = ta.ema(math.abs(x - x[1]), t)
smoothRange = ta.ema(avgRange, adjustedPeriod) * m
smoothRange
smoothedRange = smoothRange(source, period, multiplier)
// Trend Filter
trendFilter(x, r) =>
filtered = x
filtered := x > nz(filtered[1]) ? x - r < nz(filtered[1]) ? nz(filtered[1]) : x - r : x + r > nz(filtered[1]) ? nz(filtered[1]) : x + r
filtered
filter = trendFilter(source, smoothedRange)
// Filter Direction
upCount = 0.0
upCount := filter > filter[1] ? nz(upCount[1]) + 1 : filter < filter[1] ? 0 : nz(upCount[1])
downCount = 0.0
downCount := filter < filter[1] ? nz(downCount[1]) + 1 : filter > filter[1] ? 0 : nz(downCount[1])
// Colors
filterColor = upCount > 0 ? upTrendColor : downCount > 0 ? downTrendColor : neutralColor
// Buy/Sell Signals - Adapted from Clear Trend Logic
trendUp = upCount > 0 // Equivalent to REMA_up in Clear Trend
newBuySignal = trendUp and not trendUp[1] and barstate.isconfirmed
newSellSignal = not trendUp and trendUp[1] and barstate.isconfirmed
initialCondition = 0
initialCondition := newBuySignal ? 1 : newSellSignal ? -1 : initialCondition[1]
longSignal = newBuySignal and initialCondition[1] == -1
shortSignal = newSellSignal and initialCondition[1] == 1
// Alerts and Signals
plotshape(longSignal, title = 'Buy Signal', text = '🚀', textcolor = #000000, style = shape.labelup, size = size.small, location = location.belowbar, color = #fae10400) // Bright yellow for Buy
plotshape(shortSignal, title = 'Sell Signal', text = '🚨', textcolor = #000000, style = shape.labeldown, size = size.small, location = location.abovebar, color = #fb020200) // Bright red for Sell
alertcondition(longSignal, title = 'Buy alert on Sniper Machine', message = 'Buy alert on Sniper Machine')
alertcondition(shortSignal, title = 'Sell alert on Sniper Machine', message = 'Sell alert on Sniper Machine')
///////////////
// Inputs
src = input.source(hlc3, "Source")
emaLen = input.int(15, "Center EMA")
spreadN = input.int(200, "Spread Length")
kMult = input.float(3.0, "Multiplier", step=0.1)
upCol = input.color(color.rgb(251, 5, 5), "Up Color")
dnCol = input.color(color.rgb(26,221,127), "Down Color")
// Core calculation
mid = ta.ema(src, emaLen)
spread = ta.sma(high - low, spreadN)
uBand = mid + kMult * spread
lBand = mid - kMult * spread
// Crawl bands
var float upC = na
var float dnC = na
upC := na(upC[1]) ? uBand : (src[1] > upC[1] ? uBand : math.min(uBand, upC[1]))
dnC := na(dnC[1]) ? lBand : (src[1] < dnC[1] ? lBand : math.max(lBand, dnC[1]))
// Direction & guide
var int dir = na
var float guide = na
if na(dir[1])
dir := 1
else
dir := guide[1] == upC[1] ? (src > upC ? -1 : 1) : (src < dnC ? 1 : -1)
guide := dir == 1 ? upC : dnC
// Background zone fill
bgcolor(dir==1 ? color.new(upCol, 85) : color.new(dnCol, 85), title="Trend Zone")
// Guide line
plot(guide, "Trs", color=color.new(dir==1?upCol:dnCol, 0), linewidth=1)
// Signals
trendUpbn = not na(dir[1]) and dir == -1 and dir[1] != -1
trendDownbn = not na(dir[1]) and dir == 1 and dir[1] != 1
pbUp = dir==-1 and high >= upC
pbDown = dir==1 and low <= dnC
dist = 0.25 * spread
filteredPbUp = pbUp and (high - upC <= dist)
filteredPbDown = pbDown and (dnC - low <= dist)
firstPbUp = filteredPbUp and not filteredPbUp[1]
firstPbDown = filteredPbDown and not filteredPbDown[1]
// ATR for vertical spacing of signals
atrVal = ta.atr(14)
upY = low - 15 * atrVal
downY = high + 10 * atrVal
// Plot BUY/SELL arrows as labels for vertical spacing
//if trendUpbn
//label.new(bar_index, upY, text="BUY", style=label.style_triangleup, color=dnCol, textcolor=color.white, size=size.small, yloc=yloc.price)
//if trendDownbn
//label.new(bar_index, downY, text="SELL", style=label.style_triangledown, color=upCol, textcolor=color.white, size=size.small, yloc=yloc.price)
// Pullback dots
//plotshape(firstPbUp, style=shape.circle, location=location.belowbar, color=color.new(dnCol,0), size=size.small)
//plotshape(firstPbDown, style=shape.circle, location=location.abovebar, color=color.new(upCol,0), size=size.small)
//////////////////////
// --- User Inputs ---
// NEW: Added the "20/20 Profile (Ultra-Safe)" option.
profile = input.string('20/20 Profile (Ultra-Safe)', 'Select Profile', options = ['20/20 Profile (Ultra-Safe)', '16/16 Profile (Safe)', '12/12 Profile (Balanced)', '8/8 Profile (Aggressive)', 'Custom'], group = 'Grid Calculation')
// These inputs are now only used when "Custom" is selected.
customRangePercent = input.float(6.3, title = 'Custom Range as % of Price', group = 'Grid Calculation')
customGridCount = input.int(12, title = 'Custom Grid Count', group = 'Grid Calculation')
// Style Inputs
gridColor = input.color(color.new(color.gray, 60), title = 'Grid Line Color', group = 'Line Style')
gridWidth = input.int(1, title = 'Grid Line Width', minval = 1, maxval = 5, group = 'Line Style')
gridStyleString = input.string('Dotted', title = 'Grid Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Line Style')
// --- Variable Declarations ---
var array<line> gridLines = array.new_line()
var array<label> priceLabels = array.new_label()
var float finalRangePercent = 0.0
var int finalGridCount = 0
// --- Logic to select parameters based on profile ---
if profile == '20/20 Profile (Ultra-Safe)'
finalRangePercent := 10.5
finalGridCount := 20
finalGridCount
else if profile == '16/16 Profile (Safe)'
finalRangePercent := 8.4
finalGridCount := 16
finalGridCount
else if profile == '12/12 Profile (Balanced)'
finalRangePercent := 6.3
finalGridCount := 12
finalGridCount
else if profile == '8/8 Profile (Aggressive)'
finalRangePercent := 4.2
finalGridCount := 8
finalGridCount
else // Custom
finalRangePercent := customRangePercent
finalGridCount := customGridCount
finalGridCount
// --- Helper Function ---
getLineStyle(styleString) =>
styleString == 'Solid' ? line.style_solid : styleString == 'Dashed' ? line.style_dashed : line.style_dotted
// --- Drawing Logic ---
if barstate.islast
// Delete old lines and labels
if array.size(gridLines) > 0
for lineId in gridLines
line.delete(lineId)
array.clear(gridLines)
if array.size(priceLabels) > 0
for labelId in priceLabels
label.delete(labelId)
array.clear(priceLabels)
// Main Calculation
currentPrice = close
totalRange = currentPrice * (finalRangePercent / 100)
halfRange = totalRange / 2.0
upperLimit = currentPrice + halfRange
lowerLimit = currentPrice - halfRange
selectedGridStyle = getLineStyle(gridStyleString)
// Draw Lines & Labels
array.push(gridLines, line.new(bar_index - 99, upperLimit, bar_index, upperLimit, xloc = xloc.bar_index, extend = extend.none, color = color.new(color.green, 20), width = 2))
array.push(gridLines, line.new(bar_index - 99, lowerLimit, bar_index, lowerLimit, xloc = xloc.bar_index, extend = extend.none, color = color.new(color.red, 20), width = 2))
if finalGridCount > 1
stepSize = totalRange / finalGridCount
for i = 1 to finalGridCount - 1 by 1
gridLevel = lowerLimit + i * stepSize
array.push(gridLines, line.new(bar_index - 99, gridLevel, bar_index, gridLevel, xloc = xloc.bar_index, extend = extend.none, color = gridColor, width = gridWidth, style = selectedGridStyle))
array.push(priceLabels, label.new(bar_index, upperLimit, text = str.tostring(upperLimit, format.mintick), xloc = xloc.bar_index, color = color.new(color.green, 70), textcolor = color.white, style = label.style_label_left))
array.push(priceLabels, label.new(bar_index, lowerLimit, text = str.tostring(lowerLimit, format.mintick), xloc = xloc.bar_index, color = color.new(color.red, 70), textcolor = color.white, style = label.style_label_left))
////////////////////son/////////////
örnek görüntüler.....
https://www.tradingview.com/x/KjJhGhQ5/
https://www.tradingview.com/x/XxZR1eTz/
https://www.tradingview.com/x/o87KYC7G/
https://www.tradingview.com/x/b5MC9ZN6/
https://www.tradingview.com/x/n1198Qna/