Range Filter Buy & Sell 5 min for ThinkOrSwim

Added a Profit/Loss to the study



#//Original Script > @DonovanWall
#// Actual Version > @guikroth
#https://fr.tradingview.com/script/vkyFo1sQ/
#// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
#study(title="Range Filter 5min", overlay=true)
# Converted by Sam4Cok @ 07/2022

#https://usethinkscript.com/threads/range-filter-buy-sell-5-min-for-thinkorswim.12020/


input ShowTarget = yes;
input BarColor = yes;
input ShowBubble = yes;
input src = close; #, title="Source")
input RFLength = 100; #, minval=1, title="Sampling Period")
input RangeMulti = 3.0;#, minval=0.1, title="Range Multiplier")

def na = Double.NaN;
########## Colors ########
DefineGlobalColor("lime" , CreateColor(0,230,118));
DefineGlobalColor("red" , CreateColor(247,12,24));
DefineGlobalColor("aqua" , CreateColor(124,252,0));
DefineGlobalColor("maroon" , CreateColor(132,0,0));
DefineGlobalColor("green" , CreateColor(22,96,69));
DefineGlobalColor("orange" , CreateColor(255,152,0));
DefineGlobalColor("fuchsia" , CreateColor(140,5,79));;
DefineGlobalColor("white" , CreateColor(255,255,255));;

############
script nz {
input data = 0;
input data1 = 0;
def ret_val = if isNaN(data) then data1 else data;
plot return = ret_val;
}
#// Smooth Average Range
#smoothrng(x, t, m)
script smoothrng {
input src = close;
input per = 100;
input mult = 3;
def wper = per * 2 - 1;
def avrng = ExpAverage(AbsValue(src - src[1]), per);
def smoothrng = ExpAverage(avrng, wper) * mult;
plot result = smoothrng;
}
#// Range Filter
#rngfilt(x, r) =>
script rngfilt {
input x = close;
input r = 0;
def rngfilt = if x > nz(rngfilt[1]) then if x - r < nz(rngfilt[1]) then nz(rngfilt[1]) else x - r else
if x + r > nz(rngfilt[1]) then nz(rngfilt[1]) else x + r;
plot result = rngfilt;
}
#########
def smrng = smoothrng(src, RFLength, RangeMulti);
def filt = rngfilt(src, smrng);
#// Filter Direction
def upward = if filt > filt[1] then nz(upward[1]) + 1 else if filt < filt[1] then 0 else nz(upward[1]);
def downward = if filt < filt[1] then nz(downward[1]) + 1 else if filt > filt[1] then 0 else nz(downward[1]);

#// Colors & plot
def filtcolor = if upward > 0 then 1 else if downward > 0 then -1 else 0;

plot filtplot = nz(filt, close); #"Range Filter"
filtplot.AssignValueColor( if filtcolor > 0 then GlobalColor("lime") else
if filtcolor < 0 then GlobalColor("red") else GlobalColor("orange"));
filtplot.SetLineWeight(2);
filtplot.HideTitle();

#// Target Bands
def hband = filt + smrng;
def lband = filt - smrng;
#// Target
def hbandplot = hband;
def lbandplot = lband;

#// Break Outs
def longCond = src > filt and src > src[1] and upward > 0 or
src > filt and src < src[1] and upward > 0;
def shortCond = src < filt and src < src[1] and downward > 0 or
src < filt and src > src[1] and downward > 0;
def CondIni = if longCond then 1 else if !shortCond then -1 else CondIni[1];
def longCondition = filtcolor > 0 and filtcolor[1] < 0;
def shortCondition = filtcolor < 0 and filtcolor[1] > 0;

#//Alerts & Fills
Addcloud(if ShowTarget then hbandplot else na, filtplot, GlobalColor("aqua"), GlobalColor("aqua"), no);
Addcloud(if ShowTarget then lbandplot else na, filtplot, GlobalColor("white"), GlobalColor("white"), no);

#AssignPriceColor(if BarColor then if src > filt and src > src[1] and upward > 0 then GlobalColor("lime") else
# if src > filt and src < src[1] and upward > 0 then GlobalColor("green") else
# if src < filt and src < src[1] and downward > 0 then GlobalColor("red") else
# if src < filt and src > src[1] and downward > 0 then GlobalColor("maroon") else
# GlobalColor("orange") else Color.CURRENT);

AddChartBubble(if ShowBubble then longCondition else na, low, "Buy", GlobalColor("green"), no);
AddChartBubble(if ShowBubble then shortCondition else na, high, "Sell", GlobalColor("red"), yes);

AddLabel(yes, if filtcolor > 0 then "RangeFilter-Bullish " else
if filtcolor < 0 then "RangeFilter-Bearish" else "",
if filtcolor > 0 then Color.green else
if filtcolor < 0 then Color.red else color.black);

Alert(filtcolor[1] < 0 and filtcolor > 0, "RangeFilter-Bullish ", Alert.Bar, Sound.ring);
Alert(filtcolor[1] > 0 and filtcolor < 0, "RangeFilter-Bearish ", Alert.Bar, Sound.ring);













############################################
## Define BuySignal and SellSignal above
## or uncomment them out below and set
## them to your buy/sell conditions
##
## If using stops, define them below
############################################

###------------------------------------------------------------------------------------------

input showSignals = yes;
input showLabels = yes;
input showBubbles = yes;
input useStops = no;
input useAlerts = no;

###------------------------------------------------------------------------------------------

############################################
## Create Signals -
## FILL IN THIS SECTION IF NOT DEFINED ABOVE
##
############################################


def BuySignal = longcondition; # insert condition to create long position
def SellSignal = shortcondition; # insert condition to create short position

def BuyStop = if !useStops then 0 else if 0<0 then 1 else 0 ; # insert condition to stop in place of the 0<0
def SellStop = if !useStops then 0 else if 0<0 then 1 else 0 ; # insert condition to stop in place of the 0>0

#######################################
## Maintain the position of trades
#######################################

def CurrentPosition; # holds whether flat = 0 long = 1 short = -1

if (BarNumber()==1) OR isNaN(CurrentPosition[1]) {
CurrentPosition = 0;
}else{
if CurrentPosition[1] == 0 { # FLAT
if (BuySignal) {
CurrentPosition = 1;
} else if (SellSignal){
CurrentPosition = -1;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == 1 { # LONG
if (SellSignal){
CurrentPosition = -1;
} else if (BuyStop and useStops){
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == -1 { # SHORT
if (BuySignal){
CurrentPosition = 1;
} else if (SellStop and useStops){
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else {
CurrentPosition = CurrentPosition[1];
}
}


def isLong = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat = if CurrentPosition == 0 then 1 else 0;

# If not already long and get a BuySignal
Plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(color.cyan);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(5);

Alert(BuySig and useAlerts, "Buy Signal",Alert.bar,sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal",Alert.bar,sound.Ding);

# If not already short and get a SellSignal
Plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(color.cyan);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(5);

Alert(SellSig and useAlerts, "Sell Signal",Alert.bar,sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal",Alert.bar,sound.Ding);

# If long and get a BuyStop
Plot BuyStpSig = if (BuyStop and isLong[1] and showSignals and useStops) then 1 else 0;
BuyStpSig.AssignValueColor(color.light_gray);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

# If short and get a SellStop
Plot SellStpSig = if (SellStop and isShort[1] and showSignals and useStops) then 1 else 0;
SellStpSig.AssignValueColor(color.light_gray);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);


#######################################
## Orders
#######################################

def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Position changed so it's a new order

# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then close else orderPrice[1];

#######################################
## Price and Profit
#######################################

def profitLoss;


if (!isOrder or orderPRice[1]==0){
profitLoss = 0;
} else if ((isOrder and isLong[1]) and (SellSig or BuyStpSig)){
profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
profitLoss = orderPrice[1] - close;
} else {
profitLoss = 0;
}


# Total Profit or Loss
def profitLossSum = compoundValue(1, if isNaN(isOrder) or barnumber()==1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);

# How many trades won or lost
def profitWinners = compoundValue(1, if isNaN(profitWinners[1]) or barnumber()==1 then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = compoundValue(1, if isNaN(profitLosers[1]) or barnumber()==1 then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = compoundValue(1, if isNaN(profitPush[1]) or barnumber()==1 then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);

def orderCount = (profitWinners + profitLosers + profitPush) - 1;

# Current Open Trade Profit or Loss
def TradePL = If isLong then Round(((close - orderprice)/TickSize())*TickValue()) else if isShort then Round(((orderPrice - close)/TickSize())*TickValue()) else 0;

# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPRice[1]==0 or isNaN(orderPrice[1]) then 0 else round((profitLoss/Ticksize())*Tickvalue());

# Closed Orders dollar P/L
def dollarPLSum = round((profitLossSum/Ticksize())*Tickvalue());


# Split profits or losses by long and short trades
def profitLong = compoundValue(1, if isNan(profitLong[1]) or barnumber()==1 then 0 else if isOrder and isLong[1] then profitLong[1]+dollarProfitLoss else profitLong[1],0);
def profitShort = compoundValue(1, if isNan(profitShort[1]) or barnumber()==1 then 0 else if isOrder and isShort[1] then profitShort[1]+dollarProfitLoss else profitShort[1],0);
def countLong = compoundValue(1, if isNaN(countLong[1]) or barnumber()==1 then 0 else if isOrder and isLong[1] then countLong[1]+1 else countLong[1],0);
def countShort = compoundValue(1, if isNaN(countShort[1]) or barnumber()==1 then 0 else if isOrder and isShort[1] then countShort[1]+1 else countShort[1],0);

# What was the biggest winning and losing trade
def biggestWin = compoundValue(1, if isNaN(biggestWin[1]) or barnumber()==1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = compoundValue(1, if isNaN(biggestLoss[1]) or barnumber()==1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

# What percent were winners
def PCTWin = round((profitWinners/orderCount)*100,2);


# Average trade
def avgTrade = round((dollarPLSum/orderCount),2);


#######################################
## Create Labels
#######################################

AddLabel(showLabels, GetSymbol()+" Tick Size: "+TickSize()+" Value: "+TickValue(), color.white);
AddLabel(showLabels, "Closed Orders: " + orderCount + " P/L: " + AsDollars(dollarPLSum), if dollarPLSum > 0 then Color.GREEN else if dollarPLSum< 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNan(orderPrice) and showLabels then 1 else 0, "Closed+Open P/L: "+ AsDollars(TradePL+dollarPLSum), if ((TradePL+dollarPLSum) > 0) then color.green else if ((TradePL+dollarPLSum) < 0) then color.red else color.gray);

AddLabel(showLabels, "Avg per Trade: "+ AsDollars(avgTrade), if avgTrade > 0 then Color.Green else if avgTrade < 0 then Color.RED else Color.GRAY);
AddLabel(showLabels, "Winners: "+ PCTWin +"%",if PCTWin > 50 then color.green else if PCTWin > 40 then color.yellow else color.gray);

AddLabel(showLabels, "MaxUp: "+ AsDollars(biggestWin) +" MaxDown: "+AsDollars(biggestLoss), color.white);
AddLabel(showLabels, "Long Profit: " +AsDollars(profitLong), if profitLong > 0 then color.green else if profitLong < 0 then color.red else color.gray);
AddLabel(showLabels, "Short Profit: " +AsDollars(profitShort), if profitShort > 0 then color.green else if profitShort < 0 then color.red else color.gray);
AddLabel(if !IsNan(CurrentPosition) and showLabels then 1 else 0, "Open: "+ (If isLong then "Bought" else "Sold") + " @ "+orderPrice, color.white);
AddLabel(if !IsNan(orderPrice) and showLabels then 1 else 0, "Open Trade P/L: "+ AsDollars(TradePL), if (TradePL > 0) then color.green else if (TradePl < 0) then color.red else color.gray);



#######################################
## Chart Bubbles for Profit/Loss
#######################################


AddChartBubble(showSignals and showBubbles and isOrder and isLong[1], low, "$"+dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else color.Red, 0);
AddChartBubble(showSignals and showBubbles and isOrder and isShort[1], high, "$"+dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else color.Red, 1);

#AssignPriceColor(if CurrentPosition == 1 then color.green else if CurrentPosition == -1 then color.red else color.gray);
#### END
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Added a Profit/Loss to the study


Please use the "code" feature next time.

6jsKl7C.png



I changed up the labels from red to yellow because I couldn't read the text with a red label.

I'm going to try to add a budget feature to your study.


Code:
#//Original Script > @DonovanWall
#// Actual Version > @guikroth
#https://fr.tradingview.com/script/vkyFo1sQ/
#// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
#study(title="Range Filter 5min", overlay=true)
# Converted by Sam4Cok @ 07/2022

#https://usethinkscript.com/threads/range-filter-buy-sell-5-min-for-thinkorswim.12020/


input ShowTarget = yes;
input BarColor = yes;
input ShowBubble = yes;
input src = close; #, title="Source")
input RFLength = 100; #, minval=1, title="Sampling Period")
input RangeMulti = 3.0;#, minval=0.1, title="Range Multiplier")

def na = Double.NaN;
########## Colors ########
DefineGlobalColor("lime" , CreateColor(0,230,118));
DefineGlobalColor("red" , CreateColor(247,12,24));
DefineGlobalColor("aqua" , CreateColor(124,252,0));
DefineGlobalColor("maroon" , CreateColor(132,0,0));
DefineGlobalColor("green" , CreateColor(22,96,69));
DefineGlobalColor("orange" , CreateColor(255,152,0));
DefineGlobalColor("fuchsia" , CreateColor(140,5,79));;
DefineGlobalColor("white" , CreateColor(255,255,255));;

############
script nz {
input data = 0;
input data1 = 0;
def ret_val = if isNaN(data) then data1 else data;
plot return = ret_val;
}
#// Smooth Average Range
#smoothrng(x, t, m)
script smoothrng {
input src = close;
input per = 100;
input mult = 3;
def wper = per * 2 - 1;
def avrng = ExpAverage(AbsValue(src - src[1]), per);
def smoothrng = ExpAverage(avrng, wper) * mult;
plot result = smoothrng;
}
#// Range Filter
#rngfilt(x, r) =>
script rngfilt {
input x = close;
input r = 0;
def rngfilt = if x > nz(rngfilt[1]) then if x - r < nz(rngfilt[1]) then nz(rngfilt[1]) else x - r else
if x + r > nz(rngfilt[1]) then nz(rngfilt[1]) else x + r;
plot result = rngfilt;
}
#########
def smrng = smoothrng(src, RFLength, RangeMulti);
def filt = rngfilt(src, smrng);
#// Filter Direction
def upward = if filt > filt[1] then nz(upward[1]) + 1 else if filt < filt[1] then 0 else nz(upward[1]);
def downward = if filt < filt[1] then nz(downward[1]) + 1 else if filt > filt[1] then 0 else nz(downward[1]);

#// Colors & plot
def filtcolor = if upward > 0 then 1 else if downward > 0 then -1 else 0;

plot filtplot = nz(filt, close); #"Range Filter"
filtplot.AssignValueColor( if filtcolor > 0 then GlobalColor("lime") else
if filtcolor < 0 then GlobalColor("red") else GlobalColor("orange"));
filtplot.SetLineWeight(2);
filtplot.HideTitle();

#// Target Bands
def hband = filt + smrng;
def lband = filt - smrng;
#// Target
def hbandplot = hband;
def lbandplot = lband;

#// Break Outs
def longCond = src > filt and src > src[1] and upward > 0 or
src > filt and src < src[1] and upward > 0;
def shortCond = src < filt and src < src[1] and downward > 0 or
src < filt and src > src[1] and downward > 0;
def CondIni = if longCond then 1 else if !shortCond then -1 else CondIni[1];
def longCondition = filtcolor > 0 and filtcolor[1] < 0;
def shortCondition = filtcolor < 0 and filtcolor[1] > 0;

#//Alerts & Fills
Addcloud(if ShowTarget then hbandplot else na, filtplot, GlobalColor("aqua"), GlobalColor("aqua"), no);
Addcloud(if ShowTarget then lbandplot else na, filtplot, GlobalColor("white"), GlobalColor("white"), no);

#AssignPriceColor(if BarColor then if src > filt and src > src[1] and upward > 0 then GlobalColor("lime") else
# if src > filt and src < src[1] and upward > 0 then GlobalColor("green") else
# if src < filt and src < src[1] and downward > 0 then GlobalColor("red") else
# if src < filt and src > src[1] and downward > 0 then GlobalColor("maroon") else
# GlobalColor("orange") else Color.CURRENT);

AddChartBubble(if ShowBubble then longCondition else na, low, "Buy", GlobalColor("green"), no);
AddChartBubble(if ShowBubble then shortCondition else na, high, "Sell", GlobalColor("white"), yes);

AddLabel(yes, if filtcolor > 0 then "RangeFilter-Bullish " else
if filtcolor < 0 then "RangeFilter-Bearish" else "",
if filtcolor > 0 then Color.green else
if filtcolor < 0 then Color.white else color.black);

Alert(filtcolor[1] < 0 and filtcolor > 0, "RangeFilter-Bullish ", Alert.Bar, Sound.ring);
Alert(filtcolor[1] > 0 and filtcolor < 0, "RangeFilter-Bearish ", Alert.Bar, Sound.ring);



############################################
## Define BuySignal and SellSignal above
## or uncomment them out below and set
## them to your buy/sell conditions
##
## If using stops, define them below
############################################

###------------------------------------------------------------------------------------------

input showSignals = yes;
input showLabels = yes;
input showBubbles = yes;
input useStops = no;
input useAlerts = no;

###------------------------------------------------------------------------------------------

############################################
## Create Signals -
## FILL IN THIS SECTION IF NOT DEFINED ABOVE
##
############################################


def BuySignal = longcondition; # insert condition to create long position
def SellSignal = shortcondition; # insert condition to create short position

def BuyStop = if !useStops then 0 else if 0<0 then 1 else 0 ; # insert condition to stop in place of the 0<0
def SellStop = if !useStops then 0 else if 0<0 then 1 else 0 ; # insert condition to stop in place of the 0>0

#######################################
## Maintain the position of trades
#######################################

def CurrentPosition; # holds whether flat = 0 long = 1 short = -1

if (BarNumber()==1) OR isNaN(CurrentPosition[1]) {
CurrentPosition = 0;
}else{
if CurrentPosition[1] == 0 { # FLAT
if (BuySignal) {
CurrentPosition = 1;
} else if (SellSignal){
CurrentPosition = -1;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == 1 { # LONG
if (SellSignal){
CurrentPosition = -1;
} else if (BuyStop and useStops){
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == -1 { # SHORT
if (BuySignal){
CurrentPosition = 1;
} else if (SellStop and useStops){
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else {
CurrentPosition = CurrentPosition[1];
}
}


def isLong = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat = if CurrentPosition == 0 then 1 else 0;

# If not already long and get a BuySignal
Plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(color.cyan);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(5);

Alert(BuySig and useAlerts, "Buy Signal",Alert.bar,sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal",Alert.bar,sound.Ding);

# If not already short and get a SellSignal
Plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(color.cyan);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(5);

Alert(SellSig and useAlerts, "Sell Signal",Alert.bar,sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal",Alert.bar,sound.Ding);

# If long and get a BuyStop
Plot BuyStpSig = if (BuyStop and isLong[1] and showSignals and useStops) then 1 else 0;
BuyStpSig.AssignValueColor(color.light_gray);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

# If short and get a SellStop
Plot SellStpSig = if (SellStop and isShort[1] and showSignals and useStops) then 1 else 0;
SellStpSig.AssignValueColor(color.light_gray);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);


#######################################
## Orders
#######################################

def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Position changed so it's a new order

# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then close else orderPrice[1];

#######################################
## Price and Profit
#######################################

def profitLoss;


if (!isOrder or orderPRice[1]==0){
profitLoss = 0;
} else if ((isOrder and isLong[1]) and (SellSig or BuyStpSig)){
profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
profitLoss = orderPrice[1] - close;
} else {
profitLoss = 0;
}


# Total Profit or Loss
def profitLossSum = compoundValue(1, if isNaN(isOrder) or barnumber()==1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);

# How many trades won or lost
def profitWinners = compoundValue(1, if isNaN(profitWinners[1]) or barnumber()==1 then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = compoundValue(1, if isNaN(profitLosers[1]) or barnumber()==1 then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = compoundValue(1, if isNaN(profitPush[1]) or barnumber()==1 then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);

def orderCount = (profitWinners + profitLosers + profitPush) - 1;

# Current Open Trade Profit or Loss
def TradePL = If isLong then Round(((close - orderprice)/TickSize())*TickValue()) else if isShort then Round(((orderPrice - close)/TickSize())*TickValue()) else 0;

# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPRice[1]==0 or isNaN(orderPrice[1]) then 0 else round((profitLoss/Ticksize())*Tickvalue());

# Closed Orders dollar P/L
def dollarPLSum = round((profitLossSum/Ticksize())*Tickvalue());


# Split profits or losses by long and short trades
def profitLong = compoundValue(1, if isNan(profitLong[1]) or barnumber()==1 then 0 else if isOrder and isLong[1] then profitLong[1]+dollarProfitLoss else profitLong[1],0);
def profitShort = compoundValue(1, if isNan(profitShort[1]) or barnumber()==1 then 0 else if isOrder and isShort[1] then profitShort[1]+dollarProfitLoss else profitShort[1],0);
def countLong = compoundValue(1, if isNaN(countLong[1]) or barnumber()==1 then 0 else if isOrder and isLong[1] then countLong[1]+1 else countLong[1],0);
def countShort = compoundValue(1, if isNaN(countShort[1]) or barnumber()==1 then 0 else if isOrder and isShort[1] then countShort[1]+1 else countShort[1],0);

# What was the biggest winning and losing trade
def biggestWin = compoundValue(1, if isNaN(biggestWin[1]) or barnumber()==1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = compoundValue(1, if isNaN(biggestLoss[1]) or barnumber()==1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

# What percent were winners
def PCTWin = round((profitWinners/orderCount)*100,2);


# Average trade
def avgTrade = round((dollarPLSum/orderCount),2);


#######################################
## Create Labels
#######################################

AddLabel(showLabels, GetSymbol()+" Tick Size: "+TickSize()+" Value: "+TickValue(), color.white);
AddLabel(showLabels, "Closed Orders: " + orderCount + " P/L: " + AsDollars(dollarPLSum), if dollarPLSum > 0 then Color.GREEN else if dollarPLSum< 0 then Color.yellow else Color.GRAY);
AddLabel(if !IsNan(orderPrice) and showLabels then 1 else 0, "Closed+Open P/L: "+ AsDollars(TradePL+dollarPLSum), if ((TradePL+dollarPLSum) > 0) then color.green else if ((TradePL+dollarPLSum) < 0) then color.yellow else color.gray);

AddLabel(showLabels, "Avg per Trade: "+ AsDollars(avgTrade), if avgTrade > 0 then Color.Green else if avgTrade < 0 then Color.yellow else Color.GRAY);
AddLabel(showLabels, "Winners: "+ PCTWin +"%",if PCTWin > 50 then color.green else if PCTWin > 40 then color.yellow else color.gray);

AddLabel(showLabels, "MaxUp: "+ AsDollars(biggestWin) +" MaxDown: "+AsDollars(biggestLoss), color.white);
AddLabel(showLabels, "Long Profit: " +AsDollars(profitLong), if profitLong > 0 then color.green else if profitLong < 0 then color.yellow else color.gray);
AddLabel(showLabels, "Short Profit: " +AsDollars(profitShort), if profitShort > 0 then color.green else if profitShort < 0 then color.yellow else color.gray);
AddLabel(if !IsNan(CurrentPosition) and showLabels then 1 else 0, "Open: "+ (If isLong then "Bought" else "Sold") + " @ "+orderPrice, color.white);
AddLabel(if !IsNan(orderPrice) and showLabels then 1 else 0, "Open Trade P/L: "+ AsDollars(TradePL), if (TradePL > 0) then color.green else if (TradePl < 0) then color.yellow else color.gray);



#######################################
## Chart Bubbles for Profit/Loss
#######################################


AddChartBubble(showSignals and showBubbles and isOrder and isLong[1], low, "$"+dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else color.white, 0);
AddChartBubble(showSignals and showBubbles and isOrder and isShort[1], high, "$"+dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else color.white, 1);

#AssignPriceColor(if CurrentPosition == 1 then color.green else if CurrentPosition == -1 then color.red else color.gray);
#### END
 
Last edited:
Range Filter Buy and Sell code--- I want an alert when the stock price/close pulls back and touches the "filtplot" line/plot since that is when I want to buy. I've been trying to code, but I've had no luck. Would someone kindly help?. Thank you

I came up with the solution myself. If someone requires it, add the lines below to the code. Note that the alert has not been tested because the market is currently closed.

AddVerticalLine(filtcolor > 0 and close crosses below filt, "BUY more", Color.white, Curve.FIRM);
AddVerticalLine(filtcolor < 0 and close crosses above filt, "BUY more", Color.white, Curve.FIRM);
Alert( (filtcolor > 0 and close crosses below filt) or (filtcolor < 0 and close crosses above filt), "RangeFilter-BUY more ", Alert.Bar, Sound.bell);
 
I came up with the solution myself. If someone requires it, add the lines below to the code. Note that the alert has not been tested because the market is currently closed.

AddVerticalLine(filtcolor > 0 and close crosses below filt, "BUY more", Color.white, Curve.FIRM);
AddVerticalLine(filtcolor < 0 and close crosses above filt, "BUY more", Color.white, Curve.FIRM);
Alert( (filtcolor > 0 and close crosses below filt) or (filtcolor < 0 and close crosses above filt), "RangeFilter-BUY more ", Alert.Bar, Sound.bell);
can you show the compete code with this added?
 
can you show the compete code with this added?
Code:
#//Original Script > @DonovanWall
#// Actual Version > @guikroth
#https://fr.tradingview.com/script/vkyFo1sQ/
#// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
#study(title="Range Filter 5min", overlay=true)
# Converted by Sam4Cok @ 07/2022

#https://usethinkscript.com/threads/range-filter-buy-sell-5-min-for-thinkorswim.12020/


input ShowTarget = yes;
input BarColor = yes;
input ShowBubble = yes;
input src = close; #, title="Source")
input RFLength = 100; #, minval=1, title="Sampling Period")
input RangeMulti = 3.0;#, minval=0.1, title="Range Multiplier")

def na = Double.NaN;
########## Colors ########
DefineGlobalColor("lime" , CreateColor(0,230,118));
DefineGlobalColor("red" , CreateColor(247,12,24));
DefineGlobalColor("aqua" , CreateColor(124,252,0));
DefineGlobalColor("maroon" , CreateColor(132,0,0));
DefineGlobalColor("green" , CreateColor(22,96,69));
DefineGlobalColor("orange" , CreateColor(255,152,0));
DefineGlobalColor("fuchsia" , CreateColor(140,5,79));;
DefineGlobalColor("white" , CreateColor(255,255,255));;

############
script nz {
input data = 0;
input data1 = 0;
def ret_val = if isNaN(data) then data1 else data;
plot return = ret_val;
}
#// Smooth Average Range
#smoothrng(x, t, m)
script smoothrng {
input src = close;
input per = 100;
input mult = 3;
def wper = per * 2 - 1;
def avrng = ExpAverage(AbsValue(src - src[1]), per);
def smoothrng = ExpAverage(avrng, wper) * mult;
plot result = smoothrng;
}
#// Range Filter
#rngfilt(x, r) =>
script rngfilt {
input x = close;
input r = 0;
def rngfilt = if x > nz(rngfilt[1]) then if x - r < nz(rngfilt[1]) then nz(rngfilt[1]) else x - r else
if x + r > nz(rngfilt[1]) then nz(rngfilt[1]) else x + r;
plot result = rngfilt;
}
#########
def smrng = smoothrng(src, RFLength, RangeMulti);
def filt = rngfilt(src, smrng);
#// Filter Direction
def upward = if filt > filt[1] then nz(upward[1]) + 1 else if filt < filt[1] then 0 else nz(upward[1]);
def downward = if filt < filt[1] then nz(downward[1]) + 1 else if filt > filt[1] then 0 else nz(downward[1]);

#// Colors & plot
def filtcolor = if upward > 0 then 1 else if downward > 0 then -1 else 0;

plot filtplot = nz(filt, close); #"Range Filter"
filtplot.AssignValueColor( if filtcolor > 0 then GlobalColor("lime") else
if filtcolor < 0 then GlobalColor("red") else GlobalColor("orange"));
filtplot.SetLineWeight(2);
filtplot.HideTitle();

#// Target Bands
def hband = filt + smrng;
def lband = filt - smrng;
#// Target
def hbandplot = hband;
def lbandplot = lband;

#// Break Outs
def longCond = src > filt and src > src[1] and upward > 0 or
src > filt and src < src[1] and upward > 0;
def shortCond = src < filt and src < src[1] and downward > 0 or
src < filt and src > src[1] and downward > 0;
def CondIni = if longCond then 1 else if !shortCond then -1 else CondIni[1];
def longCondition = filtcolor > 0 and filtcolor[1] < 0;
def shortCondition = filtcolor < 0 and filtcolor[1] > 0;

#//Alerts & Fills
Addcloud(if ShowTarget then hbandplot else na, filtplot, GlobalColor("aqua"), GlobalColor("aqua"), no);
Addcloud(if ShowTarget then lbandplot else na, filtplot, GlobalColor("white"), GlobalColor("white"), no);

#AssignPriceColor(if BarColor then if src > filt and src > src[1] and upward > 0 then GlobalColor("lime") else
# if src > filt and src < src[1] and upward > 0 then GlobalColor("green") else
# if src < filt and src < src[1] and downward > 0 then GlobalColor("red") else
# if src < filt and src > src[1] and downward > 0 then GlobalColor("maroon") else
# GlobalColor("orange") else Color.CURRENT);

AddChartBubble(if ShowBubble then longCondition else na, low, "Buy", GlobalColor("green"), no);
AddChartBubble(if ShowBubble then shortCondition else na, high, "Sell", GlobalColor("white"), yes);



AddLabel(yes, if filtcolor > 0 then "RangeFilter-Bullish " else
if filtcolor < 0 then "RangeFilter-Bearish" else "",
if filtcolor > 0 then Color.green else
if filtcolor < 0 then Color.red else color.black);

Alert(filtcolor[1] < 0 and filtcolor > 0, "RangeFilter-Bullish ", Alert.Bar, Sound.ring);
Alert(filtcolor[1] > 0 and filtcolor < 0, "RangeFilter-Bearish ", Alert.Bar, Sound.ring);


AddVerticalLine(filtcolor > 0 and close crosses below filt, "BUY more", Color.white, curve.firm);
AddVerticalLine(filtcolor < 0 and close crosses above filt, "BUY more", Color.white,curve.firm);

Alert( (filtcolor > 0 and close crosses below filt) or (filtcolor < 0 and close crosses above filt), "RangeFilter-BUY more ", Alert.Bar, Sound.bell);
 
Edit: I completed my edits.

THe plot lines are the target profit & stop loss that you'll enter in the config window.


q9w66MZ.png


https://tos.mx/FMnN9yk

Code:
#//Original Script > @DonovanWall
#// Actual Version > @guikroth
#https://fr.tradingview.com/script/vkyFo1sQ/
#// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
#study(title="Range Filter 5min", overlay=true)
# Converted by Sam4Cok @ 07/2022

#https://usethinkscript.com/threads/range-filter-buy-sell-5-min-for-thinkorswim.12020/

input ShowTarget = yes;
input BarColor = yes;
input ShowBubble = yes;
input src = close; #, title="Source")
input RFLength = 100; #, minval=1, title="Sampling Period")
input RangeMulti = 3.0;#, minval=0.1, title="Range Multiplier")

#budget stuff

input budget = 3500.00;
def current_price = close;
def Share_Quantity_purchase_limit =  Budget / current_price;


#######################################
#inputs for  labels for profit taking
#######################################

input dollars_being_risked = Yes;
input current_number_of_shares_that_you_can_purchase_at_the_current_price = Yes;
input tick_value = Yes;
input Stop_loss_dollar_amount = 250;
input profit_target = 100;
input profit_goal = Yes;
input Stop_Loss_targeted_max_loss = Yes;
input Stop_Loss_share_price_target = Yes;
input ticks_until_stop_loss_target = Yes;
input profit_goal_target = Yes;
INPUT Required_Price_Change_for_profit = yes;
INPUT Stock_Price_plus_Profit_goal_required_share_price_increase = yes;
input ticks_until_profit_goal = Yes;


#######################################
## labels for profit taking
#######################################

AddLabel(dollars_being_risked, Concat("dollars being risked = ", Round(budget)),(CreateColor(51, 204, 255)));

AddLabel(current_number_of_shares_that_you_can_purchase_at_the_current_price, Concat("shares available for budget = ", Round(Share_Quantity_purchase_limit)),(CreateColor(51, 204, 255)));
AddLabel(tick_value, GetSymbol() + " [Tick Size] : " +  TickSize() + " [P/L tick value] : " + Round(TickValue() * Share_Quantity_purchase_limit) , Color.orange);


AddLabel(Stop_Loss_targeted_max_loss, Concat("Stop Loss loss goal = ", Round( Stop_loss_dollar_amount)),Color.white);
AddLabel(Stop_Loss_share_price_target, Concat("required price change to hit stop loss = ", Round( Stop_loss_dollar_amount  /  Share_Quantity_purchase_limit )),Color.white);

AddLabel(Stock_Price_plus_Profit_goal_required_share_price_increase, Concat("Stock Price + Profit goal share price = ", (  current_price - Stop_loss_dollar_amount /  Share_Quantity_purchase_limit )), Color.white);

AddLabel(ticks_until_stop_loss_target, Concat("ticks until stop loss target = ",round(Stop_loss_dollar_amount / (TickValue() * Share_Quantity_purchase_limit))), Color.ORANGE);

AddLabel(profit_goal_target, Concat("profit goal = ", Round( profit_target )), Color.green);
AddLabel(Required_Price_Change_for_profit, Concat("Required Price Change for profit = ", ( profit_target /  Share_Quantity_purchase_limit )), Color.green);

AddLabel(Stock_Price_plus_Profit_goal_required_share_price_increase, Concat("Stock Price + Profit goal share price = ", Round( profit_target /  Share_Quantity_purchase_limit + current_price )), Color.green);

AddLabel(ticks_until_profit_goal, Concat("ticks until profit goal = ",    round(profit_target / (TickValue() * Share_Quantity_purchase_limit))), Color.ORANGE);

def na = Double.NaN;


########## Colors ########
DefineGlobalColor("lime" , CreateColor(0, 230, 118));
DefineGlobalColor("red" , CreateColor(247, 12, 24));
DefineGlobalColor("aqua" , CreateColor(124, 252, 0));
DefineGlobalColor("maroon" , CreateColor(132, 0, 0));
DefineGlobalColor("green" , CreateColor(22, 96, 69));
DefineGlobalColor("orange" , CreateColor(255, 152, 0));
DefineGlobalColor("fuchsia" , CreateColor(140, 5, 79));

DefineGlobalColor("white" , CreateColor(255, 255, 255));
#DefineGlobalColor("sky" , CreateColor(51, 204, 255));

############
script nz {
    input data = 0;
    input data1 = 0;
    def ret_val = if IsNaN(data) then data1 else data;
    plot return = ret_val;
}
#// Smooth Average Range
#smoothrng(x, t, m)
script smoothrng {
    input src = close;
    input per = 100;
    input mult = 3;
    def wper = per * 2 - 1;
    def avrng = ExpAverage(AbsValue(src - src[1]), per);
    def smoothrng = ExpAverage(avrng, wper) * mult;
    plot result = smoothrng;
}
#// Range Filter
#rngfilt(x, r) =>
script rngfilt {
    input x = close;
    input r = 0;
    def rngfilt = if x > nz(rngfilt[1]) then if x - r < nz(rngfilt[1]) then nz(rngfilt[1]) else x - r else
if x + r > nz(rngfilt[1]) then nz(rngfilt[1]) else x + r;
    plot result = rngfilt;
}
#########
def smrng = smoothrng(src, RFLength, RangeMulti);
def filt = rngfilt(src, smrng);
#// Filter Direction
def upward = if filt > filt[1] then nz(upward[1]) + 1 else if filt < filt[1] then 0 else nz(upward[1]);
def downward = if filt < filt[1] then nz(downward[1]) + 1 else if filt > filt[1] then 0 else nz(downward[1]);

#// Colors & plot
def filtcolor = if upward > 0 then 1 else if downward > 0 then -1 else 0;

plot filtplot = nz(filt, close); #"Range Filter"
filtplot.AssignValueColor( if filtcolor > 0 then GlobalColor("lime") else
if filtcolor < 0 then GlobalColor("red") else GlobalColor("orange"));
filtplot.SetLineWeight(2);
filtplot.HideTitle();

#// Target Bands
def hband = filt + smrng;
def lband = filt - smrng;
#// Target
def hbandplot = hband;
def lbandplot = lband;

#// Break Outs
def longCond = src > filt and src > src[1] and upward > 0 or
src > filt and src < src[1] and upward > 0;
def shortCond = src < filt and src < src[1] and downward > 0 or
src < filt and src > src[1] and downward > 0;
def CondIni = if longCond then 1 else if !shortCond then -1 else CondIni[1];
def longCondition = filtcolor > 0 and filtcolor[1] < 0;
def shortCondition = filtcolor < 0 and filtcolor[1] > 0;

#//Alerts & Fills
AddCloud(if ShowTarget then hbandplot else na, filtplot, GlobalColor("aqua"), GlobalColor("aqua"), no);
AddCloud(if ShowTarget then lbandplot else na, filtplot, GlobalColor("white"), GlobalColor("white"), no);


AddChartBubble(if ShowBubble then longCondition else na, low, "Buy", GlobalColor("green"), no);
AddChartBubble(if ShowBubble then shortCondition else na, high, "Sell", GlobalColor("white"), yes);

AddLabel(yes, if filtcolor > 0 then "RangeFilter-Bullish " else
if filtcolor < 0 then "RangeFilter-Bearish" else "",
if filtcolor > 0 then Color.GREEN else
if filtcolor < 0 then Color.white else Color.BLACK);

Alert(filtcolor[1] < 0 and filtcolor > 0, "RangeFilter-Bullish ", Alert.BAR, Sound.Ring);
Alert(filtcolor[1] > 0 and filtcolor < 0, "RangeFilter-Bearish ", Alert.BAR, Sound.Ring);


###------------------------------------------------------------------------------------------

input showSignals = yes;
input trade_odds_Labels = yes;
input showBubbles = yes;
input useStops = no;
input useAlerts = no;

###------------------------------------------------------------------------------------------

def BuySignal = longCondition; # insert condition to create long position
def SellSignal = shortCondition; # insert condition to create short position

def BuyStop = if !useStops then 0 else if 0 < 0 then 1 else 0 ; # insert condition to stop in place of the 0<0
def SellStop = if !useStops then 0 else if 0 < 0 then 1 else 0 ; # insert condition to stop in place of the 0>0

#######################################
## Maintain the position of trades
#######################################

def CurrentPosition; # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 { # FLAT
        if (BuySignal) {
            CurrentPosition = 1;
        } else if (SellSignal) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 { # LONG
        if (SellSignal) {
            CurrentPosition = -1;
        } else if (BuyStop and useStops) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 { # SHORT
        if (BuySignal) {
            CurrentPosition = 1;
        } else if (SellStop and useStops) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}


def isLong = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat = if CurrentPosition == 0 then 1 else 0;

# If not already long and get a BuySignal
plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(Color.CYAN);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(5);

Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);

# If not already short and get a SellSignal
plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(Color.CYAN);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(5);

Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);

# If long and get a BuyStop
plot BuyStpSig = if (BuyStop and isLong[1] and showSignals and useStops) then 1 else 0;
BuyStpSig.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

# If short and get a SellStop
plot SellStpSig = if (SellStop and isShort[1] and showSignals and useStops) then 1 else 0;
SellStpSig.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);


#######################################
## Orders
#######################################

def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Position changed so it's a new order

# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then close else orderPrice[1];

#######################################
## Price and Profit
#######################################

def profitLoss;


if (!isOrder or orderPrice[1] == 0) {
    profitLoss = 0;
} else if ((isOrder and isLong[1]) and (SellSig or BuyStpSig)) {
    profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
    profitLoss = orderPrice[1] - close;
} else {
    profitLoss = 0;
}


# Total Profit or Loss
def profitLossSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);

# How many trades won or lost
def profitWinners = CompoundValue(1, if IsNaN(profitWinners[1]) or BarNumber() == 1 then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = CompoundValue(1, if IsNaN(profitLosers[1]) or BarNumber() == 1 then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = CompoundValue(1, if IsNaN(profitPush[1]) or BarNumber() == 1 then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);

def orderCount = (profitWinners + profitLosers + profitPush) - 1;

# Current Open Trade Profit or Loss
def TradePL = if isLong then Round(((close - orderPrice) / TickSize()) * TickValue()) else if isShort then Round(((orderPrice - close) / TickSize()) * TickValue()) else 0;

######################### 
######################### 

# Math

######################### 
######################### 



# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPrice[1] == 0 or IsNaN(orderPrice[1]) then 0 else Round((profitLoss / TickSize()) * TickValue()) * Share_Quantity_purchase_limit;

# Closed Orders dollar P/L
def dollarPLSum = Round((profitLossSum / TickSize()) * TickValue()) * Share_Quantity_purchase_limit ;

######################### 
######################### 

#Math

######################### 
######################### 

# Split profits or losses by long and short trades
def profitLong = CompoundValue(1, if IsNaN(profitLong[1]) or BarNumber() == 1 then 0 else if isOrder and isLong[1] then profitLong[1] + dollarProfitLoss else profitLong[1], 0);
def profitShort = CompoundValue(1, if IsNaN(profitShort[1]) or BarNumber() == 1 then 0 else if isOrder and isShort[1] then profitShort[1] + dollarProfitLoss else profitShort[1], 0);
def countLong = CompoundValue(1, if IsNaN(countLong[1]) or BarNumber() == 1 then 0 else if isOrder and isLong[1] then countLong[1] + 1 else countLong[1], 0);
def countShort = CompoundValue(1, if IsNaN(countShort[1]) or BarNumber() == 1 then 0 else if isOrder and isShort[1] then countShort[1] + 1 else countShort[1], 0);

# What was the biggest winning and losing trade
def biggestWin = CompoundValue(1, if IsNaN(biggestWin[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = CompoundValue(1, if IsNaN(biggestLoss[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

# What percent were winners
def PCTWin = Round((profitWinners / orderCount) * 100, 2);

# Average trade
def avgTrade = Round((dollarPLSum / orderCount), 2);


#######################################
## Win / Loss labels
#######################################


AddLabel(trade_odds_Labels, "Closed Orders: " + orderCount + " P/L: " + AsDollars(dollarPLSum), if dollarPLSum > 0 then Color.GREEN else if dollarPLSum < 0 then Color.YELLOW else Color.GRAY);
AddLabel(if !IsNaN(orderPrice) and trade_odds_Labels then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL + dollarPLSum), if ((TradePL + dollarPLSum) > 0) then Color.GREEN else if ((TradePL + dollarPLSum) < 0) then Color.YELLOW else Color.GRAY);

AddLabel(trade_odds_Labels, "Avg per Trade: " + AsDollars(avgTrade), if avgTrade > 0 then Color.GREEN else if avgTrade < 0 then Color.YELLOW else Color.GRAY);
AddLabel(trade_odds_Labels, "Winners: " + PCTWin + "%", if PCTWin > 50 then Color.GREEN else if PCTWin > 40 then Color.YELLOW else Color.GRAY);

AddLabel(trade_odds_Labels, "MaxUp: " + AsDollars(biggestWin) + " MaxDown: " + AsDollars(biggestLoss), Color.WHITE);
AddLabel(trade_odds_Labels, "Long Profit: " + AsDollars(profitLong), if profitLong > 0 then Color.GREEN else if profitLong < 0 then Color.YELLOW else Color.GRAY);
AddLabel(trade_odds_Labels, "Short Profit: " + AsDollars(profitShort), if profitShort > 0 then Color.GREEN else if profitShort < 0 then Color.YELLOW else Color.GRAY);
AddLabel(if !IsNaN(CurrentPosition) and trade_odds_Labels then 1 else 0, "Open: " + (if isLong then "Bought" else "Sold") + " @ " + orderPrice, Color.WHITE);
AddLabel(if !IsNaN(orderPrice) and trade_odds_Labels then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL), if (TradePL > 0) then Color.GREEN else if (TradePL < 0) then Color.YELLOW else Color.GRAY);


#######################################
##  Bubbles for Profit/Loss
#######################################

AddChartBubble(showSignals and showBubbles and isOrder and isLong[1], low, "$" + dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else Color.WHITE, 0);
AddChartBubble(showSignals and showBubbles and isOrder and isShort[1], high, "$" + dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else Color.white, 1);


#######################################
#Stop loss & profit goal taking plot lines
#######################################

plot stop_loss_line = current_price -  (Stop_loss_dollar_amount  /  Share_Quantity_purchase_limit);

plot profit_target_line = profit_target /  Share_Quantity_purchase_limit + current_price;
 
Last edited:
I completed the updates. The math in the labels and bubbles change according to how big of a budget you enter in the study's config.
 
Hi Guys,

New trader here and new to TOS. Wanted to signup to thank you for creating these awesome scripts. Just tried the original script and Im loving it! Will be trying out the add-ons.
 
From my preliminary testing in a one-minute time frame, I discovered that "range multi" of 3.2 produces better results than 3 does. If someone has better input settings, kindly share.
Thanks
 
Are you guys using range filter only on /ES and other instruments that trade around the clock? Anyone using it on stocks, where you don't have much activity outside of RTH, and if so, I guess you use RTH only? Asking because it makes a difference to the filter line values and thus the signals generated.
 
i just combined Range filter with Follow line into one study

CSS:
#//Original Script > @DonovanWall
#// Actual Version > @guikroth
#https://fr.tradingview.com/script/vkyFo1sQ/
#// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
#study(title="Range Filter  5min", overlay=true)
# Converted by Sam4Cok @ 07/2022
# Combined Range Filter and Follow Line by Sam4COK @ Samer800 - 08/2022
input ShowTarget = yes;
input BarColor   = no;
input ShowLabel  = yes;
input filterLine = yes;
input MALines    = no;
input ShowBubble = yes;
input Source  = close; #, title="Source")
input RFLength   = 100; #, minval=1, title="Sampling Period")
input RangeMulti = 3.0;#, minval=0.1, title="Range Multiplier")
input MAFilter   = yes;
input AverageType   = AverageType.EXPONENTIAL;
input fastMALength = 20;
input slowMALength = 50;

def na = Double.NaN;
########## Colors ########
DefineGlobalColor("lime"    , CreateColor(0,230,118));
DefineGlobalColor("red"     , CreateColor(247,12,24));
DefineGlobalColor("aqua"    , CreateColor(4,93,95));
DefineGlobalColor("maroon"  , CreateColor(132,0,0));
DefineGlobalColor("green"   , CreateColor(22,96,69));
DefineGlobalColor("orange"  , CreateColor(255,152,0));
DefineGlobalColor("fuchsia" , CreateColor(140,5,79));
DefineGlobalColor("yellow"  , CreateColor(231,190,0));
############
script nz {
    input data  = 0;
    input data1 = 0;
    def ret_val = if isNaN(data) then data1 else data;
    plot return = ret_val;
}
#// Smooth Average Range
#smoothrng(x, t, m)
script smoothrng {
input src  = close;
input per  = 100;
input mult = 3;
def wper = per * 2 - 1;
def avrng = ExpAverage(AbsValue(src - src[1]), per);
def smoothrng = ExpAverage(avrng, wper) * mult;
    plot result = smoothrng;
}
###### EMAs #########
def FastEMA = MovingAverage(AverageType, Source, fastMALength);
def SlowEMA = MovingAverage(AverageType, Source, slowMALength);

plot FastMA = FastEMA;
FastMA.SetDefaultColor(Color.WHITE);
FastMA.SetHiding(!MALines);
plot SlowMA = SlowEMA;
SlowMA.SetDefaultColor(GlobalColor("yellow"));
SlowMA.SetHiding(!MALines);

#// Range Filter
#rngfilt(x, r) =>
script rngfilt {
input x  = close;
input r  = 0;
def  rngfilt = if x > nz(rngfilt[1]) then if x - r < nz(rngfilt[1]) then nz(rngfilt[1]) else x - r else
               if x + r > nz(rngfilt[1]) then nz(rngfilt[1]) else x + r;
 plot result = rngfilt;
}
#########
def smrng = smoothrng(Source, RFLength, RangeMulti);
def filt  = rngfilt(Source, smrng);
#// Filter Direction
def upward   = if filt > filt[1] then nz(upward[1])   + 1 else if filt < filt[1] then 0 else nz(upward[1]);
def downward = if filt < filt[1] then nz(downward[1]) + 1 else if filt > filt[1] then 0 else nz(downward[1]);

#// Colors & plot
def filtcolor = if upward > 0 then 1 else if downward > 0 then -1 else 0;

plot filtplot = if filterLine then nz(filt, close) else na; #"Range Filter"
filtplot.AssignValueColor( if filtcolor > 0 then GlobalColor("GREEN") else
                           if filtcolor < 0 then GlobalColor("orange") else GlobalColor("orange"));
filtplot.SetLineWeight(2);
filtplot.HideTitle();

#// Target Bands
def hband = filt + smrng;
def lband = filt - smrng;
#// Target
def hbandplot = hband;
def lbandplot = lband;

#// Break Outs
def longCond = Source > filt and Source > Source[1] and upward > 0 or
               Source > filt and Source < Source[1] and upward > 0;
def shortCond = Source < filt and Source < Source[1] and downward > 0 or
                Source < filt and Source > Source[1] and downward > 0;
def CondIni = if longCond then 1 else if !shortCond then -1 else CondIni[1];
def longCondition = filtcolor > 0 and filtcolor[1] < 0;
def shortCondition = filtcolor < 0 and filtcolor[1] > 0;
def BullEMA = FastEMA > SlowEMA;
def SellEMA = FastEMA < SlowEMA;

#//Alerts & Fills
Addcloud(if ShowTarget then hbandplot else na, filtplot, GlobalColor("aqua"), GlobalColor("aqua"), no);
Addcloud(if ShowTarget then lbandplot else na, filtplot, GlobalColor("fuchsia"), GlobalColor("fuchsia"), no);

AssignPriceColor(if BarColor then
   if Source > filt and Source > Source[1] and upward > 0 then GlobalColor("lime") else
   if Source > filt and Source < Source[1] and upward > 0 then GlobalColor("green") else
   if Source < filt and Source < Source[1] and downward > 0 then GlobalColor("red") else
   if Source < filt and Source > Source[1] and downward > 0 then GlobalColor("maroon") else
        GlobalColor("orange") else Color.CURRENT);

AddChartBubble(if ShowBubble then if MAFilter then longCondition and BullEMA else longCondition else na, low, "BUY", GlobalColor("lime"), no);
AddChartBubble(if ShowBubble then if MAFilter then shortCondition and SellEMA else shortCondition else na, high, "SELL", GlobalColor("red"), yes);

AddLabel(ShowLabel, if filtcolor > 0 then "RangeFilter-Bullish " else
if filtcolor < 0 then "RangeFilter-Bearish" else "",
if filtcolor > 0 then Color.green else
if filtcolor < 0 then Color.red else color.black);


# Follow Line Indicator
# Coverted to ToS from TV by bigboss. Original © Dreadblitz

input BbPeriod1      = 21;
input BbDeviations1  = 1;
input UseAtrFilter1  = yes;
input AtrPeriod1     = 5;
input HideArrows1    = no;

def BBUpper1=SimpleMovingAvg(close,BbPeriod1)+stdev(close, BbPeriod1)*BbDeviations1;
def BBLower1=SimpleMovingAvg(close,BbPeriod1)-stdev(close, BbPeriod1)*BbDeviations1;

def BBSignal1 = if close>BBUpper1 then 1 else if close<BBLower1 then -1 else 0;

def TrendLine1 =
    if BBSignal1 == 1 and UseAtrFilter1 == 1 then
        max(low-atr(AtrPeriod1),TrendLine1[1])
    else if BBSignal1 == -1 and UseAtrFilter1 == 1 then
        min(high+atr(AtrPeriod1),TrendLine1[1])
    else if BBSignal1 == 0 and UseAtrFilter1 == 1 then
        TrendLine1[1]
    else if BBSignal1 == 1 and UseAtrFilter1 == 0 then
        max(low,TrendLine1[1])
    else if BBSignal1 == -1 and UseAtrFilter1 == 0 then
        min(high,TrendLine1[1])
    else if BBSignal1 == 0 and UseAtrFilter1 == 0 then
        TrendLine1[1]
    else TrendLine1[1];

def iTrend1 = if TrendLine1>TrendLine1[1] then 1 else if TrendLine1 < TrendLine1[1] then -1 else iTrend1[1];
 
plot buy = if iTrend1[1]==-1 and iTrend1==1 and !HideArrows1 then TrendLine1 else Double.NaN;
buy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
buy.SetDefaultColor(Color.GREEN);
buy.SetLineWeight(3);

plot sell = if iTrend1[1]==1 and iTrend1==-1 and !HideArrows1 then  TrendLine1 else Double.NaN;
sell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
sell.SetDefaultColor(Color.RED);
sell.SetLineWeight(3);

plot tline1 = TrendLine1;
tline1.AssignValueColor(if iTrend1 > 0 then CreateColor(33,150,243) else CreateColor(255,82,82));
tline1.SetLineWeight(2);

# Follow Line Indicator
# Coverted to ToS from TV by bigboss. Original © Dreadblitz
#https://usethinkscript.com/threads/follow-line-indicator.9789/

input BbPeriod      = 9;
input BbDeviations  = 1;
input UseAtrFilter  = yes;
input AtrPeriod     = 5;
input HideArrows    = no;

def BBUpper=SimpleMovingAvg(close,BBperiod)+stdev(close, BBperiod)*BBdeviations;
def BBLower=SimpleMovingAvg(close,BBperiod)-stdev(close, BBperiod)*BBdeviations;

def BBSignal = if close>BBUpper then 1 else if close<BBLower then -1 else 0;

def TrendLine =
    if BBSignal == 1 and UseATRfilter == 1 then
        max(low-atr(ATRperiod),TrendLine[1])
    else if BBSignal == -1 and UseATRfilter == 1 then
        min(high+atr(ATRperiod),TrendLine[1])
    else if BBSignal == 0 and UseATRfilter == 1 then
        TrendLine[1]
    else if BBSignal == 1 and UseATRfilter == 0 then
        max(low,TrendLine[1])
    else if BBSignal == -1 and UseATRfilter == 0 then
        min(high,TrendLine[1])
    else if BBSignal == 0 and UseATRfilter == 0 then
        TrendLine[1]
    else TrendLine[1];

def iTrend = if TrendLine>TrendLine[1] then 1 else if TrendLine < TrendLine[1] then -1 else iTrend[1];
 
plot buy_price = if iTrend[1]==-1 and iTrend==1 and !HideArrows then TrendLine else Double.NaN;
buy_price.SetPaintingStrategy(PaintingStrategy.VALUES_ABOVE);
buy_price.SetDefaultColor(Color.GREEN);
buy_price.SetLineWeight(3);

plot sell_price = if iTrend[1]==1 and iTrend==-1 and !HideArrows then  TrendLine else Double.NaN;
sell_price.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW);
sell_price.SetDefaultColor(Color.white);
sell_price.SetLineWeight(3);

plot buy_arrow = if iTrend[1]==-1 and iTrend==1 and !HideArrows then TrendLine else Double.NaN;
buy_arrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
buy_arrow.SetDefaultColor(Color.GREEN);
buy_arrow.SetLineWeight(5);

plot sell_arrow = if iTrend[1]==1 and iTrend==-1 and !HideArrows then  TrendLine else Double.NaN;
sell_arrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
sell_arrow.SetDefaultColor(Color.RED);
sell_arrow.SetLineWeight(5);


plot tline = TrendLine;
tline.AssignValueColor(if iTrend > 0 then CreateColor(33,150,243) else CreateColor(255,82,82));
tline.SetPaintingStrategy(PaintingStrategy.DASHES);
tline.SetLineWeight(2);


########### Alerts


Alert(buy_arrow, "Time to buy!", Alert.Bar, Sound.Chimes);
Alert(sell_arrow, "Time to sell!", Alert.Bar, Sound.Bell);
Hi, is the indicator available with the addOrder (buy and Sell) code for TOS to be able to backtest it?
 
Hi everyone,
Thanks for the great indicator. Can I scan with the original code for the buy or sell signals?
 
Hi everyone,
Thanks for the great indicator. Can I scan with the original code for the buy or sell signals?
sure

change these lines of code to:
def longCondition = filtcolor > 0 and filtcolor[1] < 0;
def shortCondition = filtcolor < 0 and filtcolor[1] > 0;

to:
plot longCondition = filtcolor > 0 and filtcolor[1] < 0;
plot shortCondition = filtcolor < 0 and filtcolor[1] > 0;

Then your scan filter will be:
longCondition is true
or
shortCondition is true

If you need help setting up your scan filters:
https://usethinkscript.com/threads/how-to-use-thinkorswim-stock-hacker-scans.284/
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
446 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top