0% found this document useful (0 votes)
39 views18 pages

Market Maker

The document is a TradingView Pine Script for a Market Maker Indicator that includes various customizable settings for trend analysis, including color settings, moving averages, and alert conditions. It calculates market trends and signals for buy and sell conditions based on price movements and includes features for visual representation on charts. The script also incorporates additional filters like RSI and ADX to enhance trading signals.

Uploaded by

Ankit Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views18 pages

Market Maker

The document is a TradingView Pine Script for a Market Maker Indicator that includes various customizable settings for trend analysis, including color settings, moving averages, and alert conditions. It calculates market trends and signals for buy and sell conditions based on price movements and includes features for visual representation on charts. The script also incorporates additional filters like RSI and ADX to enhance trading signals.

Uploaded by

Ankit Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 18

//@version=5

indicator(title=" Market Maker Indicator [V1.0]", shorttitle=" Market Maker",


overlay=true,max_bars_back = 2000,max_boxes_count = 500, max_labels_count = 500,
max_lines_count = 500)

// Color variables
upColor = color.rgb(33, 248, 40)
midColor = color.rgb(151, 0, 143)
downColor = color.rgb(255, 24, 24)

// Source
src = close // input(defval=close, title="Source")

per = input.int(defval=200, minval=1, title="Trend Period",group = "Buy Sell


Settings")
mult = input.float(defval=6, minval=0.1, title="Sensitivity",group = "Buy Sell
Settings")

channelBal = input.bool(true, "Reversal Zones",group = "Indicator Overlay")

spb = input.bool(true,"Show Price Bands",group = "Indicator Overlay")

//showLowADXArea = input(true, 'Show Low ADX Area', inline='display',


group='Display')
showLowADXArea = true
// Range Multiplier

//Showrevp = input.bool(true,"Show Reversal Points")

showma1 = input.bool(true,"EDCSS 1",group = "Ema Settings")


//input.bool(false,"Ema 1",group = "Ema Settings")
showma2 = input.bool(true,"EDCSS 2",group = "Ema Settings")
//em1per = input.int(21,"Ema1 Length",group = "Ema Settings")
//emacol1 = input.color(color.red,"Ema 1 Color",group = "Ema Settings")

//showma2 = input.bool(false,"Ema 2",group = "Ema Settings")


//em2per = input.int(50,"Ema2 Length",group = "Ema Settings")
//emacol2 = input.color(color.white,"Ema 2 Color",group = "Ema Settings")

//ema1 = ta.ema(close,em1per)
//ema2 = ta.ema(close,em2per)

//plot(showma1 ? ema1 : na , "Ema 1" , color = emacol1 ,linewidth = 2)


//plot(showma2 ? ema2 : na , "Ema 2" , color = emacol2 , linewidth = 2)

showDashboard = input(false, "Multitimeframe Sentiment dashboard", group="TREND


DASHBOARD")
locationDashboard = input.string("Middle Right", "Table Location", ["Top Right",
"Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center",
"Top Left", "Middle Left", "Bottom Left"], group="TREND DASHBOARD")
tableTextColor = input(color.white, "Table Text Color", group="TREND DASHBOARD")
tableBgColor = input(#2A2A2A, "Table Background Color", group="TREND
DASHBOARD")
sizeDashboard = input.string("Normal", "Table Size", ["Large", "Normal",
"Small", "Tiny"], group="TREND DASHBOARD")

color_bars = input(true, "Color bars?", group = "Addons")


// Smooth Average Range
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult/2)

// Market Maker
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r
:
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(src, smrng)

// Filter Direction
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 :
nz(downward[1])

// Target Bands
hband = filt + smrng
lband = filt - smrng
Trendtr = input.bool(true,"Trend tracer",group = "Indicator Overlay")
// Colors
filtcolor = upward > 0 ? upColor : downward > 0 ? downColor : midColor
barcolor = src > filt and src > src[1] and upward > 0 ? upColor :
src > filt and src < src[1] and upward > 0 ? upColor :
src < filt and src < src[1] and downward > 0 ? downColor :
src < filt and src > src[1] and downward > 0 ? downColor : midColor

filtplot = plot(Trendtr ? filt : na, color=filtcolor, linewidth=2, title=" Market


Maker")
// Target
hbandplot = plot(spb ? hband : na, color=color.new(upColor, 70), title="High
Target")
lbandplot = plot(spb ? lband : na, color=color.new(downColor, 70), title="Low
Target")

// Fills
fill(hbandplot, filtplot, color=color.new(upColor, 90), title="High Target Range")
fill(lbandplot, filtplot, color=color.new(downColor, 90), title="Low Target Range")
// Bar Color

// Break Outs
longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src[1] and upward > 0 or
src > filt and src < src[1] and upward > 0
shortCond := src < filt and src < src[1] and downward > 0 or
src < filt and src > src[1] and downward > 0

CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1

//Alerts

alertcondition(longCondition, title="Buy alert on Market Maker", message="Buy alert


on Market Maker")
alertcondition(shortCondition, title="Sell alert on Market Maker", message="Sell
alert on Market Maker")
alertcondition(longCondition or shortCondition, title="Buy and Sell alert on
Market Maker", message="Buy and Sell alert on Market Maker")

// Length of moving average for calculating the center line


maLength = 34

// Display settings
showFlat = true
lowADXTransparency = input.float(35, 'Flat Area Transparency', group="Addons")
//flatColor = input.color(#ff5d00, 'Flat Market Color', inline='flat', group='Color
Settings')
lowADXColor = input.color(#be00bb, 'Flat Area Color', inline='flat',
group="Addons")
//flatTransparency = input.float(90, 'Flat Area Transparency', group='Ranges
Settings')

// RSI filter settings


useRSIFilter = true
rsiMax = 60
rsiMin = 40
rsiLength = 14

// ADX filter settings


threshold = 20
adxLength = 14
diLength = 14

// Calculate the high and low values for the range


var highRange = 0.0
var lowRange = 0.0
highRange := na(highRange[1]) ? hlc3 : (highRange[1] * (maLength - 1) + high) /
maLength
lowRange := na(lowRange[1]) ? hlc3 : (lowRange[1] * (maLength - 1) + low) /
maLength

// Calculate the middle value of the range


middle = 2 * ta.ema(hlc3, maLength) - ta.ema(ta.ema(hlc3, maLength), maLength)

// Determine if the market is flat


rsiFilter = (ta.rsi(close, rsiLength) >= rsiMin) and (ta.rsi(close, rsiLength) <=
rsiMax)
marketDirection = (middle > highRange) or (middle < lowRange) ? 1 : 0
isFlat = marketDirection == 1 ? 0 : marketDirection == 0 and rsiFilter == false and
useRSIFilter == true ? 0 : marketDirection == 0 and rsiFilter == true and
useRSIFilter == true ? 1 : marketDirection == 0 and useRSIFilter == false ? 1 : 0
flatMarket = showFlat and isFlat ? 1 : 0

// Calculate ADX and determine if it's in low area


upMove = ta.change(high)
downMove = -ta.change(low)
plusDM = na(upMove) ? na : upMove > downMove and upMove > 0 ? upMove : 0
minusDM = na(downMove) ? na : downMove > upMove and downMove > 0 ? downMove : 0
truRange = ta.rma(ta.tr, diLength)
plusDI = fixnan(100 * ta.rma(plusDM, diLength) / truRange)
minusDI = fixnan(100 * ta.rma(minusDM, diLength) / truRange)
sumDI = plusDI + minusDI
sig = 100 * ta.rma(math.abs(plusDI - minusDI) / (sumDI == 0 ? 1 : sumDI),
adxLength)
var os2 = 1
os2 := sig > threshold ? 0 : sig < threshold ? 1 : os2[1]
barcolor(color_bars ? (flatMarket==1? color.new(lowADXColor,
lowADXTransparency):na):na)
barcolor(color_bars ? (os2==1 and showLowADXArea? color.new(lowADXColor,
lowADXTransparency):na):na)
//barcolor(color_bars ? colour : na)

barcolor(color_bars ? barcolor : na)

plotshape(longCondition and ((os2==1 and showLowADXArea) or flatMarket), title="Buy


Signal", text="▲", textcolor=color.white, style=shape.labelup, size=size.small,
location=location.belowbar, color=color.green)
plotshape(shortCondition and ((os2==1 and showLowADXArea) or flatMarket),
title="Sell Signal", text="▼", textcolor=color.white, style=shape.labeldown,
size=size.small, location=location.abovebar, color=color.red)

plotshape(longCondition and not ((os2==1 and showLowADXArea) or flatMarket),


title="Strong Buy Signal", text="▲+", textcolor=color.white, style=shape.labelup,
size=size.small, location=location.belowbar, color=upColor)
plotshape(shortCondition and not ((os2==1 and showLowADXArea) or flatMarket),
title="Strong Sell Signal", text="▼+", textcolor=color.white,
style=shape.labeldown, size=size.small, location=location.abovebar,
color=downColor)
sensitivity = "Medium" //input.string("Low", "Sensitivity", ["Low", "Medium",
"High"] , group = "Extra Features")

//channelBal = input.bool(true, "Price Channel", group = "Extra Features")

// Functions
supertrend(_src, factor, atrLen) =>
atr = ta.atr(atrLen)
upperBand = _src + factor * atr
lowerBand = _src - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ?
lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ?
upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
lr_slope(_src, _len) =>
x = 0.0, y = 0.0, x2 = 0.0, xy = 0.0
for i = 0 to _len - 1
val = _src[i]
per = i + 1
x += per
y += val
x2 += per * per
xy += val * per
_slp = (_len * xy - x * y) / (_len * x2 - x * x)
_avg = y / _len
_int = _avg - _slp * x / _len + _slp
[_slp, _avg, _int]
lr_dev(_src, _len, _slp, _avg, _int) =>
upDev = 0.0, dnDev = 0.0
val = _int
for j = 0 to _len - 1
price = high[j] - val
if price > upDev
upDev := price
price := val - low[j]
if price > dnDev
dnDev := price
price := _src[j]
val += _slp
[upDev, dnDev]
[middleKC1, upperKC1, lowerKC1] = ta.kc(close, 80, 10.5)
[middleKC2, upperKC2, lowerKC2] = ta.kc(close, 80, 9.5)
[middleKC3, upperKC3, lowerKC3] = ta.kc(close, 80, 8)
[middleKC4, upperKC4, lowerKC4] = ta.kc(close, 80, 3)
[supertrend, direction] = supertrend(close, sensitivity == "Low" ? 5 : sensitivity
== "Medium" ? 2.5 : 2, 11)
barsL = 10
barsR = 10
pivotHigh = fixnan(ta.pivothigh(barsL, barsR)[1])
pivotLow = fixnan(ta.pivotlow(barsL, barsR)[1])
source = close, period = 150
[s, a, i] = lr_slope(source, period)
[upDev, dnDev] = lr_dev(source, period, s, a, i)
// Colors
green = #2BBC4D, green2 = #00DD00
red = #C51D0B, red2 = #DD0000
//emaEnergyColor(ma) => emaEnergy ? (close >= ma ? green : red) : na
// Plots
k1 = plot(ta.ema(upperKC1, 50), "", na, editable=false)
k2 = plot(ta.ema(upperKC2, 50), "", na, editable=false)
k3 = plot(ta.ema(upperKC3, 50), "", na, editable=false)
k4 = plot(ta.ema(upperKC4, 50), "", na, editable=false)
k5 = plot(ta.ema(lowerKC4, 50), "", na, editable=false)
k6 = plot(ta.ema(lowerKC3, 50), "", na, editable=false)
k7 = plot(ta.ema(lowerKC2, 50), "", na, editable=false)
k8 = plot(ta.ema(lowerKC1, 50), "", na, editable=false)
fill(k1, k2, channelBal ? color.new(red2, 40) : na, editable=false)
fill(k2, k3, channelBal ? color.new(red2, 65) : na, editable=false)
fill(k3, k4, channelBal ? color.new(red2, 90) : na, editable=false)
fill(k5, k6, channelBal ? color.new(green2, 90) : na, editable=false)
fill(k6, k7, channelBal ? color.new(green2, 65) : na, editable=false)
fill(k7, k8, channelBal ? color.new(green2, 40) : na, editable=false)

//outside_bb_up = ta.crossunder(high,ta.ema(upperKC2, 50)) and close[1] >


ta.ema(upperKC2, 50) and close < ta.ema(upperKC2, 50)
//outside_bb_down = ta.crossunder(close, ta.ema(lowerKC2, 50)) and close[1] <
ta.ema(upperKC2, 50) and close > ta.ema(lowerKC2, 50)

//outside_bb_up = close < ta.ema(upperKC2, 50) and close[1] > ta.ema(upperKC2, 50)
//outside_bb_down = close > ta.ema(lowerKC2, 50) and close[1] < ta.ema(lowerKC2,
50)

//plotshape(outside_bb_down and Showrevp and channelBal, title="Reversal Signal",


location=location.belowbar, color=color.green, style= shape.labelup ,text =
"▲",textcolor = color.white)

//plotshape(outside_bb_up and Showrevp and channelBal, title="Reversal Signal",


location=location.abovebar, color=color.red, style= shape.labeldown,text =
"▼",textcolor = color.white)
percentStop = input.float(0.1, "Stop Loss %", 0, group="Risk & Reward
Settings")

showsl = input.bool(false,"Show Risk-Reward Levels", group="Risk & Reward


Settings")

bullCond = bool(na), bullCond := longCondition


bearCond = bool(na), bearCond := shortCondition
lastCond = 0, lastCond := bullCond ? 1 : bearCond ? -1 : lastCond[1]
bulls = bullCond
bears = bearCond
countBull = ta.barssince(bulls)
countBear = ta.barssince(bears)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
srcStop = close
atrBand = srcStop * (percentStop / 100)
atrStop = trigger ? srcStop - atrBand : srcStop + atrBand
lastTrade(src) => ta.valuewhen(bulls or bears, src, 0)
entry_y = lastTrade(srcStop)
stop_y = lastTrade(atrStop)
tp1_y = (entry_y - lastTrade(atrStop)) * 1 + entry_y
tp2_y = (entry_y - lastTrade(atrStop)) * 2 + entry_y
tp3_y = (entry_y - lastTrade(atrStop)) * 3 + entry_y
labelTpSl(y, txt, color) =>
label labelTpSl = showsl ? label.new(bar_index + 1, y, txt, xloc.bar_index,
yloc.price, color, label.style_label_left, color.white, size.normal) : na
label.delete(labelTpSl[1])
labelTpSl(entry_y, "Entry: " + str.tostring(math.round_to_mintick(entry_y)),
color.gray)
labelTpSl(stop_y , "Stop Loss: " + str.tostring(math.round_to_mintick(stop_y)),
downColor)
labelTpSl(tp1_y, "Take Profit 1: " + str.tostring(math.round_to_mintick(tp1_y)),
upColor)
labelTpSl(tp2_y, "Take Profit 2: " + str.tostring(math.round_to_mintick(tp2_y)),
upColor)
labelTpSl(tp3_y, "Take Profit 3: " + str.tostring(math.round_to_mintick(tp3_y)),
upColor)
lineTpSl(y, color) =>
line lineTpSl = showsl ? line.new(bar_index - (trigger ? countBull : countBear)
+ 4, y, bar_index + 1, y, xloc.bar_index, extend.none, color, line.style_solid) :
na
line.delete(lineTpSl[1])
lineTpSl(entry_y, color.gray)
lineTpSl(stop_y, downColor)
lineTpSl(tp1_y, upColor)
lineTpSl(tp2_y, upColor)
lineTpSl(tp3_y, upColor)
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)

ema = ta.ema(close, 144)


emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes() and not
timeframe.isseconds
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes() or timeframe.isseconds
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and
str.tonumber(res) < 10)
securityNoRep1(sym, res, src) =>
bool bull_ = na
bull_ := equal_tf(res) ? src : bull_
bull_ := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off,
barmerge.lookahead_on) : bull_
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ?
str.tostring(f_chartTfInMinutes()) + (timeframe.isseconds ? "S" : "") :
too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull_ := array.pop(bull_array)
array.clear(bull_array)
bull_
TF1Bull = securityNoRep1(syminfo.tickerid, "1" , emaBull)
TF3Bull = securityNoRep1(syminfo.tickerid, "3" , emaBull)
TF5Bull = securityNoRep1(syminfo.tickerid, "5" , emaBull)
TF15Bull = securityNoRep1(syminfo.tickerid, "15" , emaBull)
TF30Bull = securityNoRep1(syminfo.tickerid, "30" , emaBull)
TF60Bull = securityNoRep1(syminfo.tickerid, "60" , emaBull)
TF120Bull = securityNoRep1(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep1(syminfo.tickerid, "240" , emaBull)
TF480Bull = securityNoRep1(syminfo.tickerid, "480" , emaBull)
TFDBull = securityNoRep1(syminfo.tickerid, "1440", emaBull)

var dashboard_loc = locationDashboard == "Top Right" ? position.top_right :


locationDashboard == "Middle Right" ? position.middle_right : locationDashboard ==
"Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ?
position.top_center : locationDashboard == "Middle Center" ? position.middle_center
: locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard
== "Top Left" ? position.top_left : locationDashboard == "Middle Left" ?
position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard ==
"Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard = showDashboard ? table.new(dashboard_loc, 2, 15, tableBgColor,
#000000, 2, tableBgColor, 1) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column,
row, txt, 0, 0, signal ? #000000 : tableTextColor, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column,
row, col)
if barstate.islast and showDashboard
dashboard_cell(0, 0 , "Market Maker Signals")
dashboard_cell(0, 1 , "Current Position")
dashboard_cell(0, 2 , "Current Trend")
dashboard_cell(0, 3 , "Volume")
dashboard_cell(0, 4 , "Timeframe")
dashboard_cell(0, 5 , "1 min:")
dashboard_cell(0, 6 , "3 min:")
dashboard_cell(0, 7 , "5 min:")
dashboard_cell(0, 8 , "15 min:")
dashboard_cell(0, 9 , "30 min:")
dashboard_cell(0, 10, "1 H:")
dashboard_cell(0, 11, "2 H:")
dashboard_cell(0, 12, "4 H:")
dashboard_cell(0, 13, "8 H:")
dashboard_cell(0, 14, "Daily:")
dashboard_cell(1, 0 , "Chart")
dashboard_cell(1, 1 , trigger ? "Buy" : "Sell", true), dashboard_cell_bg(1, 1,
trigger ? upColor : downColor)
dashboard_cell(1, 2 , emaBull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 2, emaBull ? upColor : downColor)
dashboard_cell(1, 3 , str.tostring(volume))
dashboard_cell(1, 4 , "Trends")
dashboard_cell(1, 5 , TF1Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 5 , TF1Bull ? upColor : downColor)
dashboard_cell(1, 6 , TF3Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 6 , TF3Bull ? upColor : downColor)
dashboard_cell(1, 7 , TF5Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 7 , TF5Bull ? upColor : downColor)
dashboard_cell(1, 8 , TF15Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 8 , TF15Bull ? upColor : downColor)
dashboard_cell(1, 9 , TF30Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 9 , TF30Bull ? upColor : downColor)
dashboard_cell(1, 10, TF60Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 10, TF60Bull ? upColor : downColor)
dashboard_cell(1, 11, TF120Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 11, TF120Bull ? upColor : downColor)
dashboard_cell(1, 12, TF240Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 12, TF240Bull ? upColor : downColor)
dashboard_cell(1, 13, TF480Bull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 13, TF480Bull ? upColor : downColor)
dashboard_cell(1, 14, TFDBull ? "Bullish" : "Bearish", true),
dashboard_cell_bg(1, 14, TFDBull ? upColor : downColor)

show_fib_entries = input(false, "Trend Catcher",group = "Indicator Overlay")


trailType = input.string("modified", "Trailtype", options = ["modified",
"unmodified"],group = "Trend Catcher Settings")
ATRPerio = input.int(14,"Trend Strength Length",group = "Trend Catcher
Settings")
ATRFactor = input.float(5,"Catch Number",group = "Trend Catcher Settings")
norm_o = request.security(syminfo.tickerid, timeframe.period, open)
norm_h = request.security(syminfo.tickerid, timeframe.period, high)
norm_l = request.security(syminfo.tickerid, timeframe.period, low)
norm_c = request.security(syminfo.tickerid, timeframe.period, close)
//}
ATRPeriod = ATRPerio*2
//////// FUNCTIONS //////////////
//{
// Wilders ma //
Wild_ma(_src, _malength) =>
_wild = 0.0
_wild := nz(_wild[1]) + (_src - nz(_wild[1])) / _malength

/////////// TRUE RANGE CALCULATIONS /////////////////


HiLo = math.min(norm_h - norm_l, 1.5 * nz(ta.sma((norm_h - norm_l), ATRPeriod)))

HRef = norm_l<= norm_h[1] ?


norm_h - norm_c[1] :
(norm_h - norm_c[1]) - 0.5 * (norm_l- norm_h[1])

LRef = norm_h >= norm_l[1] ?


norm_c[1] - norm_l:
(norm_c[1] - norm_l) - 0.5 * (norm_l[1] - norm_h)

trueRanges =
trailType == "modified" ? math.max(HiLo, HRef, LRef) :
math.max(norm_h - norm_l, math.abs(norm_h - norm_c[1]), math.abs(norm_l -
norm_c[1]))
//}

/////////// TRADE LOGIC ////////////////////////


//{
loss = ATRFactor * Wild_ma(trueRanges, ATRPeriod)

Up = norm_c - loss
Dn = norm_c + loss

TrendUp = Up
TrendDown = Dn
Trend = 1

TrendUp := norm_c[1] > TrendUp[1] ? math.max(Up, TrendUp[1]) : Up


TrendDown := norm_c[1] < TrendDown[1] ? math.min(Dn, TrendDown[1]) : Dn

Trend := norm_c > TrendDown[1] ? 1 : norm_c < TrendUp[1]? -1 : nz(Trend[1],1)


trail = Trend == 1? TrendUp : TrendDown

ex = 0.0
ex :=
ta.crossover(Trend, 0) ? norm_h :
ta.crossunder(Trend, 0) ? norm_l :
Trend == 1 ? math.max(ex[1], norm_h) :
Trend == -1 ? math.min(ex[1], norm_l) : ex[1]
//}

// //////// PLOT TP and SL /////////////


//{
//plot(trail, "Trailingstop", style = plot.style_line, color = Trend == 1 ? upColor
: Trend == -1 ? downColor : na)
//plot(ex, "Extremum", style = plot.style_circles, color = Trend == 1? color.lime :
Trend == -1? color.fuchsia : na)
//}

////// FIBONACCI LEVELS ///////////


//{
state = Trend == 1 ? "long" : "short"

fib1Level = 61.8
fib2Level = 78.6
fib3Level = 88.6

f1 = ex + (trail - ex) * fib1Level / 100


f2 = ex + (trail - ex) * fib2Level / 100
f3 = ex + (trail - ex) * fib3Level / 100
l100 = trail + 0

Fib1 = plot(show_fib_entries ? f1 : na, "Fib 1", style = plot.style_line, color =


color.black)
Fib2 = plot(show_fib_entries ? f2: na , "Fib 2", style = plot.style_line, color =
color.black)
Fib3 = plot(show_fib_entries ? f3 : na, "Fib 3", style = plot.style_line, color =
color.black)
L100 = plot(show_fib_entries ? l100 : na, "l100", style = plot.style_line, color =
color.black)

fill(Fib1, Fib2, color = state == "long"? color.new(#4caf4f, 74) : state ==


"short"? color.new(#ff5252, 70) : na)
fill(Fib2, Fib3, color = state == "long"? color.new(#4caf4f, 80) : state ==
"short"? color.new(downColor, 70) : na)
fill(Fib3, L100, color = state == "long"? color.rgb(76, 175, 79, 58) : state ==
"short"? color.rgb(255, 82, 82, 49) : na)

// -----------------------------------------------------------------------------
//

// Use Alternate Anchor TF for MAs


anchor = 4//input.int(4,minval=0,maxval=100,title="Relative TimeFrame
multyiplier for Second MA Ribbon (0=none, max=100)")
//
showAvgs = input(false,title="Show QQEX",group = "Indicator Overlay")
tf = input.timeframe("","QQEX TimeFrame",group = "Indicator Overlay")
// - INPUTS START
// Fast MA - type, source, length

type1 = "EMA"//input.string(defval="EMA", title="Fast MA Type: ", options=["SMA",


"EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"])
len1 = 16//input.int(defval=16, title="Fast - Length", minval=1)
gamma1 = 0.33
// Medium Fast MA - type, source, length
type2 = "EMA"//input.string(defval="EMA", title="Medium MA Type: ",
options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA",
"TMA", "SSMA"])
len2 = 21//input.int(defval=21, title="Medium - Length", minval=1)
gamma2 = 0.55
// Slow MA - type, source, length
type3 ="EMA"//input.string(defval="EMA", title="Slow MA Type: ", options=["SMA",
"EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"])
len3 = 26//input.int(defval=26, title="Slow Length", minval=1)
gamma3 = 0.77
//
// QQE rsi Length, Smoothing, fast ATR factor, source
RSILen = 14//input.int(14,title='RSI Length')
SF = 8//input.int(8,title='RSI Smoothing Factor')
QQEfactor = 5.0//input.float(5.0,title='Fast QQE Factor')
threshhold = 10//input.int(10, title="RSI Threshhold")
//
sQQEx = false//input(true,title="Show QQE Signal crosses")
sQQEz = false//input(false,title="Show QQE Zero crosses")
sQQEc = false//input(true,title="Show QQE Thresh Hold Channel Exits")
//
tradeSignal = "XC"//input.string("XC", title="Select which QQE signal to Buy/Sell",
options=["XC","XQ","XZ"])
closeSignal = "XQ"//input.string("XQ", title="Select which QQE signal to Close
Order", options=["XC","XQ","XZ"])
//
xfilter = true//input(true, title="Filter XQ Buy/Sell Orders by Threshold" )
filter = false//input(false,title="Use Moving Average Filter")
dfilter = true//input(true, title="Use Trend Directional Filter" )
ufirst = false//input(false, title="Only Alert First Buy/Sell in a new Trend")
RSIsorc = close//input(close,title="Source")

sorc = RSIsorc // MA source


sorcclose= RSIsorc

///////////////////////////////////////////////
//* Backtesting Period Selector | Component *//
///////////////////////////////////////////////

//* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-
Component *//
//* https://www.tradingview.com/u/pbergden/ *//
//* Modifications made by JustUncleL*//

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>//
//*** START of COMMENT OUT [Alerts]

//*** END of COMMENT OUT [Alerts]


//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//

// - INPUTS END

gold = #FFD700
AQUA = #00FFFFFF
BLUE = #0000FFFF
RED = #FF0000FF
LIME = #00FF00FF
GRAY = #808080FF

// - FUNCTIONS

// - variant(type, sorc, len, gamma)


// Returns MA input selection variant, default to SMA if blank or typo.
// SuperSmoother filter
// © 2013 John F. Ehlers
variant_supersmoother(sorc,len) =>
a1 = math.exp(-1.414*3.14159 / len)
b1 = 2*a1*math.cos(1.414*3.14159 / len)
c2 = b1
c3 = (-a1)*a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1*(sorc + nz(sorc[1])) / 2 + c2*nz(v9[1]) + c3*nz(v9[2])
v9

variant_smoothed(sorc,len) =>
v5 = 0.0
v5 := na(v5[1]) ? ta.sma(sorc, len) : (v5[1] * (len - 1) + sorc) / len
v5

variant_zerolagema(sorc,len) =>
ema1 = ta.ema(sorc, len)
ema2 = ta.ema(ema1, len)
v10 = ema1+(ema1-ema2)
v10

variant_doubleema(sorc,len) =>
v2 = ta.ema(sorc, len)
v6 = 2 * v2 - ta.ema(v2, len)
v6

variant_tripleema(sorc,len) =>
v2 = ta.ema(sorc, len)
v7 = 3 * (v2 - ta.ema(v2, len)) + ta.ema(ta.ema(v2, len), len) //
Triple Exponential
v7

//calc Laguerre
variant_lag(p,g) =>
L0 = 0.0
L1 = 0.0
L2 = 0.0
L3 = 0.0
L0 := (1 - g)*p+g*nz(L0[1])
L1 := -g*L0+nz(L0[1])+g*nz(L1[1])
L2 := -g*L1+nz(L1[1])+g*nz(L2[1])
L3 := -g*L2+nz(L2[1])+g*nz(L3[1])
f = (L0 + 2*L1 + 2*L2 + L3)/6
f

// return variant, defaults to SMA


variant(type, sorc, len, g) =>
type=="EMA" ? ta.ema(sorc,len) :
type=="WMA" ? ta.wma(sorc,len):
type=="VWMA" ? ta.vwma(sorc,len) :
type=="SMMA" ? variant_smoothed(sorc,len) :
type=="DEMA" ? variant_doubleema(sorc,len):
type=="TEMA" ? variant_tripleema(sorc,len):
type=="LAGMA" ? variant_lag(sorc,g) :
type=="HullMA"? ta.wma(2 * ta.wma(sorc, len / 2) - ta.wma(sorc, len),
math.round(math.sqrt(len))) :
type=="SSMA" ? variant_supersmoother(sorc,len) :
type=="ZEMA" ? variant_zerolagema(sorc,len) :
type=="TMA" ? ta.sma(ta.sma(sorc,len),len) :
ta.sma(sorc,len)

// - /variant

// If have anchor specified, calculate the base multyiplier, base on time in mins
//multy = isintraday ? anchor==0 or interval<=0 or interval>=anchor or
anchor>1440? 1 : round(anchor/interval) : 1
//multy := not isintraday? 1 : multy // Only available Daily or less

// Anchor is a relative multyiplier based on current TF.


multy = anchor>0 ? anchor : 1

// - FUNCTIONS END

// - Fast ATR QQE


//
Wilders_Period = RSILen * 2 - 1
//
Rsi = ta.rsi(RSIsorc,RSILen)
RSIndex = ta.ema(Rsi, SF)
AtrRsi = math.abs(RSIndex[1] - RSIndex)
MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ta.ema(MaAtrRsi,Wilders_Period) * QQEfactor
//
newshortband= RSIndex + DeltaFastAtrRsi
newlongband= RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband=0.0
trend = 0
longband:=RSIndex[1] > longband[1] and RSIndex > longband[1] ?
math.max(longband[1],newlongband) : newlongband
shortband:=RSIndex[1] < shortband[1] and RSIndex < shortband[1] ?
math.min(shortband[1],newshortband) : newshortband
trend:=ta.cross(RSIndex, shortband[1])? 1 : ta.cross(longband[1], RSIndex) ? -1 :
nz(trend[1],1)
FastAtrRsiTL = trend==1 ? longband : shortband

// - SERIES VARIABLES
// MA's
ma_fast = variant(type1, sorcclose, len1, gamma1)
ma_medium = variant(type2, sorcclose, len2, gamma2)
ma_slow = variant(type3, sorcclose, len3, gamma3)
// MA's
ma_fast_alt = variant(type1, sorcclose, len1*multy, gamma1)
ma_medium_alt = variant(type2, sorcclose, len2*multy, gamma2)
ma_slow_alt = variant(type3, sorcclose, len3*multy, gamma3)

// Get Direction From Medium Moving Average


directin = ta.rising(ma_medium,3) ? 1 : ta.falling(ma_medium,3) ? -1 : 0
altDirection = ta.rising(ma_medium_alt,3) ? 1 : ta.falling(ma_medium_alt,3) ? -1 :
0
//
// Find all the QQE Crosses
QQExlong = 0, QQExlong := nz(QQExlong[1])
QQExshort = 0, QQExshort := nz(QQExshort[1])
QQExlong := FastAtrRsiTL< RSIndex ? QQExlong+1 : 0
QQExshort := FastAtrRsiTL> RSIndex ? QQExshort+1 : 0
// Zero cross
QQEzlong = 0, QQEzlong := nz(QQEzlong[1])
QQEzshort = 0, QQEzshort := nz(QQEzshort[1])
QQEzlong := RSIndex>=50 ? QQEzlong+1 : 0
QQEzshort := RSIndex<50 ? QQEzshort+1 : 0
//
// Thresh Hold channel Crosses give the BUY/SELL alerts.
QQEclong = 0, QQEclong := nz(QQEclong[1])
QQEcshort = 0, QQEcshort := nz(QQEcshort[1])
QQEclong := RSIndex>(50+threshhold) ? QQEclong+1 : 0
QQEcshort := RSIndex<(50-threshhold) ? QQEcshort+1 : 0

//
// Check Filtering.
QQEflong = multy == 1 ? (not filter or (sorcclose>ma_medium and ma_medium>ma_slow
and ma_fast>ma_medium)) and (not dfilter or (directin>0 )) :
(not filter or (ma_medium>ma_medium_alt and
sorcclose>ma_fast and ma_fast>ma_medium)) and (not dfilter or (directin>0 and
altDirection>0 and sorcclose>ma_medium))
QQEfshort = multy == 1 ? (not filter or (sorcclose<ma_medium and ma_medium<ma_slow
and ma_fast<ma_medium)) and (not dfilter or (directin<0 )) :
(not filter or (ma_medium<ma_medium_alt and
sorcclose<ma_fast and ma_fast<ma_medium)) and (not dfilter or (directin<0 and
altDirection<0 and sorcclose<ma_medium))

QQExfilter = (not xfilter or RSIndex>(50+threshhold) or RSIndex<(50-threshhold))


//
// Get final BUY / SELL alert determination
buy_ = 0, buy_ := nz(buy_[1])
sell_ = 0, sell_ := nz(sell_[1])

// Make sure Buy/Sell are non-repaint and occur after close signal.
buy_ := tradeSignal=="XC"? (QQEclong[1]==1 and QQEflong[1] ? buy_+1 : 0) :
tradeSignal=="XQ"? (QQExlong[1]==1 and QQEflong[1] and QQExfilter[1]?
buy_+1 : 0) :
tradeSignal=="XZ"? (QQEzlong[1]==1 and QQEflong[1] ? buy_+1 : 0) : 0
sell_ := tradeSignal=="XC"? (QQEcshort[1]==1 and QQEfshort[1] ? sell_+1 : 0) :
tradeSignal=="XQ"? (QQExshort[1]==1 and QQEfshort[1] and QQExfilter[1]?
sell_+1 : 0) :
tradeSignal=="XZ"? (QQEzshort[1]==1 and QQEfshort[1] ? sell_+1 : 0) : 0
//
// Find the first Buy/Sell in trend swing.
Buy = 0, Buy := nz(Buy[1])
Sell = 0, Sell := nz(Sell[1])
Buy := sell_>0 ? 0 : buy_==1 or Buy>0 ? Buy+1 : Buy
Sell := buy_>0 ? 0 : sell_==1 or Sell>0 ? Sell+1 : Sell

// Select First or all buy/sell alerts.


buy = ufirst ? Buy : buy_
sell = ufirst ? Sell : sell_

closeLong = 0, closeLong := nz(closeLong[1])


closeShort = 0, closeShort := nz(closeShort[1])
closeLong := closeSignal=="XC" ? (QQEcshort==1 ? closeLong+1 : 0) :
closeSignal=="XQ" ? tradeSignal=="XQ" ? (QQExshort==1 ? closeLong+1 :
0) : ((QQExshort==1 or QQEzshort or QQEcshort) ? closeLong+1 : 0) :
closeSignal=="XZ" ? (QQEzshort==1 ? closeLong+1 : 0) : 0
closeShort := closeSignal=="XC" ? (QQEclong==1 ? closeShort+1 : 0) :
closeSignal=="XQ" ? tradeSignal=="XQ" ? (QQExlong==1 ? closeShort+1 :
0) : ((QQExlong==1 or QQEzlong or QQEclong==1) ? closeShort+1 : 0) :
closeSignal=="XZ" ? (QQEzlong==1 ? closeShort+1 : 0) : 0

tradestate = 0, tradestate := nz(tradestate[1])


tradestate := tradestate==0 ? (buy==1 ? 1 : sell==1 ? 2 : 0) : (tradestate==1 and
closeLong==1) or (tradestate==2 and closeShort==1)? 0 : tradestate

isLong = ta.change(tradestate) and tradestate==1


isShort = ta.change(tradestate) and tradestate==2
isCloseLong = ta.change(tradestate) and tradestate==0 and nz(tradestate[1])==1
isCloseShort = ta.change(tradestate) and tradestate==0 and nz(tradestate[1])==2

// - SERIES VARIABLES END

maa_fast = request.security(symbol = syminfo.tickerid,timeframe = tf , expression


=ma_fast )
maa_medium = request.security(symbol = syminfo.tickerid,timeframe = tf , expression
=ma_medium)
maa_slow = request.security(symbol = syminfo.tickerid,timeframe = tf , expression
=ma_slow)

maa_fast_alt = request.security(symbol = syminfo.tickerid,timeframe = tf ,


expression =ma_fast_alt)
maa_medium_alt = request.security(symbol = syminfo.tickerid,timeframe = tf ,
expression =ma_medium_alt)
maa_slow_alt = request.security(symbol = syminfo.tickerid,timeframe = tf ,
expression =ma_slow_alt)

// Ma's
tcolor = directin<0? color.red:color.green
ftcolor = directin<0? color.new(color.red,90):color.new(color.green,90)
ma1=plot(showAvgs?maa_fast:na, title="MA Fast", color=tcolor, linewidth=1,
transp=0)
ma2=plot(showAvgs?maa_medium:na, title="MA Medium Fast", color=tcolor, linewidth=2,
transp=0)
ma3=plot(showAvgs?maa_slow:na, title="MA Slow", color=tcolor, linewidth=1,
transp=0)
fill(ma1,ma3,color=ftcolor)
// Ma's
altTcolor=altDirection<0?color.blue:color.aqua
altfTcolor=altDirection<0?color.new(color.blue,90):color.new(color.aqua,90)
ma4=plot(showAvgs and multy>1?maa_fast_alt:na, title="MA Fast", color=altTcolor,
linewidth=1, transp=0)
ma5=plot(showAvgs and multy>1?maa_medium_alt:na, title="MA Medium Fast",
color=altTcolor, linewidth=2, transp=0)
ma6=plot(showAvgs and multy>1?maa_slow_alt:na, title="MA Slow", color=altTcolor,
linewidth=1, transp=0)
fill(ma4,ma6,color=altfTcolor)
import loxx/loxxmas/1

greencolor = #2DD204
redcolor = #D2042D

_corMa(src, work, per)=>


out = 0.
v1 = math.pow(ta.stdev(src, per), 2)
v2 = math.pow(nz(out[1]) - work, 2)
c = (v2 < v1 or v2 == 0) ? 0 : 1 - v1 / v2
out := nz(out[1]) + c * (work - nz(out[1]))
out

//src = input.source(close, "Source", group = "Basic Settings")


per1 = input.int(10, "Period 1", group = "Ema Settings")
per2= input.int(20, "Period 2", group = "Ema Settings")
per3 = 50//input.int(50, "Period", group = "Basic Settings")
per4 = 100//input.int(100, "Period", group = "Basic Settings")

//colorbars = input.bool(true, "Color bars?", group = "UI Options")


showsignals = true //input.bool(true, "Show signals?", group = "UI Options")

[work1, _, _] = loxxmas.super(src, per1)

out1 = _corMa(src, work1, per1)

[work2, _, _] = loxxmas.super(src, per2)

out2 = _corMa(src, work2, per2)

[work3, _, _] = loxxmas.super(src, per3)

out3 = _corMa(src, work3, per3)

[work4, _, _] = loxxmas.super(src, per4)

out4 = _corMa(src, work4, per4)

goLong1 = ta.crossover(work1, out1)


goShort1 = ta.crossunder(work1, out1)

goLong2 = ta.crossover(work2, out2)


goShort2 = ta.crossunder(work2, out2)

goLong3 = ta.crossover(work3, out3)


goShort3 = ta.crossunder(work3, out3)

goLong4 = ta.crossover(work4, out4)


goShort4 = ta.crossunder(work4, out4)

colorout1 = work1 > out1 ? greencolor : redcolor


colorout2 = work2 > out2 ? greencolor : redcolor
colorout3 = work3 > out3 ? greencolor : redcolor
colorout4 = work4 > out4 ? greencolor : redcolor

colorot2 = work1 > out1 ? color.yellow : color.fuchsia

plot(showma1 ? out1 : na, "Corrected Super Smoother", color = colorout1, linewidth


= 3)
plot(showma2 ? out2 : na, "Corrected Super Smoother", color = colorout2, linewidth
= 3)
//plot(out3, "Corrected Super Smoother", color = colorout3, linewidth = 3)
//plot(out4, "Corrected Super Smoother", color = colorout4, linewidth = 3)

plot(work1, "Super Smoother", color = colorot2, linewidth = 1)

//barcolor(colorbars ? colorout1 : na)


//plotshape(goLong1 and showsignals, title = "Long", color = color.yellow,
textcolor = color.yellow, text = "L", style = shape.triangleup, location =
location.belowbar, size = size.tiny)
//plotshape(goShort1 and showsignals, title = "Short", color = color.fuchsia,
textcolor = color.fuchsia, text = "S", style = shape.triangledown, location =
location.abovebar, size = size.tiny)

You might also like