denemek istersen... o kodun....kombine edilmiş... farklı versiyonu....
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))
/////////////////////////////////