Supertrend Indicator by Mobius for ThinkorSwim

Hi everyone, is there a version of supertrend that has the auto buy and sell with the profit/loss floating box , so you can backtest the strategy and see the outcome?

So, from the first post, this is what the script would look like.

Code:
input showSignals = yes;
input showLabels  = yes;
input showBubbles = yes;
input useStops = no;

############################################
##  Create Signals - FILL IN THIS SECTION
############################################

input AtrMult = 1.0;
input nATR = 4;
input AvgType = AverageType.HULL;
input PaintBars = yes;
def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR);
def UP = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP else DN;
plot SuperTrend = ST;
SuperTrend.AssignValueColor(if close < ST then Color.RED else Color.GREEN);
AssignPriceColor(if PaintBars and close < ST
                 then Color.RED
                 else if PaintBars and close > ST
                      then Color.GREEN
                      else Color.CURRENT);

def BuySignal = close crosses above ST ; # insert condition to create long position
def SellSignal = close crosses below ST; # insert condition to create short position
def BuyStop  = if !useStops then 0 else 0  ; # insert condition to stop in place of the 0 after else
def SellStop = if !useStops then 0 else 0  ; # insert condition to stop in place of the 0 after else



#######################################
##  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){
                CurrentPosition = 0;
            } else {
                CurrentPosition = CurrentPosition[1];
            }
       } else if CurrentPosition[1] == -1 {     # SHORT
            if (BuySignal){
                CurrentPosition = 1;
            } else if (SellStop){
                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;

#######################################
##  Plot the Signals
#######################################

Plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(color.yellow);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(3);

Plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(color.white);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(3);

Plot BuyStpSig = if (BuyStop and isLong[1] and showSignals) then 1 else 0;
BuyStpSig.AssignValueColor(color.gray);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

Plot SellStpSig = if (SellStop and isShort[1] and showSignals) then 1 else 0;
SellStpSig.AssignValueColor(color.gray);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);



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

def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Status changed so it's a new order
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then open[-1] else orderPrice[1];


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

def profitLoss;

if (!isOrder){
    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;
}

def profitLossSum = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);
def profitWinners = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);
def TradePL = If isLong then Round(((close - orderprice)/TickSize())*TickValue()) else if isShort then Round(((orderPrice - close)/TickSize())*TickValue()) else 0; # current trade p/l
def dollarProfitLoss = round((profitLoss/Ticksize())*Tickvalue()); # per trade for chart bubbles
def biggestWin = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

def orderCount = (profitWinners+profitLosers+profitPush);
def PCTWin = round((profitWinners/orderCount)*100,2);

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

AddLabel(yes, GetSymbol()+" Tick Size: "+TickSize()+" Value: "+TickValue(), color.white);
AddLabel(showSignals and showLabels, "Orders: " + orderCount + " P/L: " + AsDollars(profitLossSum), if profitLossSum > 0 then Color.GREEN else if profitLossSum < 0 then Color.RED else Color.GRAY);
AddLabel(yes, "Winners: "+ PCTWin +"%",if PCTWin > 50 then color.green else if PCTWin > 40 then color.yellow else color.gray);
AddLabel(yes, "MaxUp: "+ AsDollars(biggestWin) +" MaxDown: "+AsDollars(biggestLoss), color.white);
AddLabel(if !IsNan(CurrentPosition) then 1 else 0, "Current: "+ (If isLong then "Bought" else "Sold") + " @ "+orderPrice, color.white);
AddLabel(if !IsNan(orderPrice) then 1 else 0, "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, 1);
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, 0);
 
Last edited:

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

Hi All - Where can I find the link which allows me to create a daily scan list for supertrend? I have added it for my charts and can see them, but is there a script that flashes/scans all eligible stocks for supertrend buy indicator?

Kindly let me know, I appreciate the inputs!
 
Hi All - Where can I find the link which allows me to create a daily scan list for supertrend? I have added it for my charts and can see them, but is there a script that flashes/scans all eligible stocks for supertrend buy indicator?

Kindly let me know, I appreciate the inputs!
The scan script is just below the study script in the 1st post of this thread.
 
You can try this template I use for my studies, pieced it together and modified it from here and there, most from linus' SuperCombo. Basically, just plug in what triggers your buy and sell signals (and stops if you use them) and it will put a bar on top with your overall p/l for the given timeframe. This isn't a strategy so a report isn't given, but it does give a quick p/l so you can change settings and instantly see the effect. Note, this won't account for any fees or commissions, so if doing futures, have to take off the fees per order.

XB5HSmK.png



Code:
input showSignals = yes;
input showLabels  = yes;
input showBubbles = yes;
input useStops = no;

############################################
##  Create Signals - FILL IN THIS SECTION
############################################


def BuySignal  ; # insert condition to create long position
def SellSignal ; # insert condition to create short position
def BuyStop  = if !useStops then 0 else 0  ; # insert condition to stop in place of the 0 after else
def SellStop = if !useStops then 0 else 0  ; # insert condition to stop in place of the 0 after else



#######################################
##  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){
                CurrentPosition = 0;
            } else {
                CurrentPosition = CurrentPosition[1];
            }
       } else if CurrentPosition[1] == -1 {     # SHORT
            if (BuySignal){
                CurrentPosition = 1;
            } else if (SellStop){
                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;

#######################################
##  Plot the Signals
#######################################

Plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(color.yellow);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(3);

Plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(color.white);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(3);

Plot BuyStpSig = if (BuyStop and isLong[1] and showSignals) then 1 else 0;
BuyStpSig.AssignValueColor(color.gray);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

Plot SellStpSig = if (SellStop and isShort[1] and showSignals) then 1 else 0;
SellStpSig.AssignValueColor(color.gray);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);



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

def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Status changed so it's a new order
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then open[-1] else orderPrice[1];


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

def profitLoss;

if (!isOrder){
    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;
}

def profitLossSum = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);
def profitWinners = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);
def TradePL = If isLong then Round(((close - orderprice)/TickSize())*TickValue()) else if isShort then Round(((orderPrice - close)/TickSize())*TickValue()) else 0; # current trade p/l
def dollarProfitLoss = round((profitLoss/Ticksize())*Tickvalue()); # per trade for chart bubbles
def biggestWin = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = compoundValue(1, if isNaN(isOrder) then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

def orderCount = (profitWinners+profitLosers+profitPush);
def PCTWin = round((profitWinners/orderCount)*100,2);

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

AddLabel(yes, GetSymbol()+" Tick Size: "+TickSize()+" Value: "+TickValue(), color.white);
AddLabel(showSignals and showLabels, "Orders: " + orderCount + " P/L: " + AsDollars(profitLossSum), if profitLossSum > 0 then Color.GREEN else if profitLossSum < 0 then Color.RED else Color.GRAY);
AddLabel(yes, "Winners: "+ PCTWin +"%",if PCTWin > 50 then color.green else if PCTWin > 40 then color.yellow else color.gray);
AddLabel(yes, "MaxUp: "+ AsDollars(biggestWin) +" MaxDown: "+AsDollars(biggestLoss), color.white);
AddLabel(if !IsNan(CurrentPosition) then 1 else 0, "Current: "+ (If isLong then "Bought" else "Sold") + " @ "+orderPrice, color.white);
AddLabel(if !IsNan(orderPrice) then 1 else 0, "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, 1);
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, 0);
Sorry if this is a dumb question, but new to scripting...

What is it I'm putting in the BuySignal and stop criteria if I'm using the Super Trend? Thanks!
Am using the one on the first page of this post.
 
Last edited by a moderator:
Thanks JoeDV. Was using the one on the first page of this post.

Then it looks like it would be def BuySignal = close crosses above ST; def SellSignal = close crosses below ST; For the latest version I have your code to insert at the bottom of your study code would be:

Ruby:
###------------------------------------------------------------------------------------------

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 = close crosses above ST; # insert condition to create long position
def SellSignal = close crosses below ST; # 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(3);

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.orange);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(3);

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);
 
Then it looks like it would be def BuySignal = close crosses above ST; def SellSignal = close crosses below ST; For the latest version I have your code to insert at the bottom of your study code would be:

Ruby:
###------------------------------------------------------------------------------------------

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 = close crosses above ST; # insert condition to create long position
def SellSignal = close crosses below ST; # 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(3);

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.orange);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(3);

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);

I've played around with that and I'm not getting favorable P/L. I was thinking I could add an AND statement stating to only buy if the CLOSE is above the ST AND the CLOSE is above the 200 EMA. But it's not working. Here's what I put.

def MAVG = movingAverage (AverageType.EXPONENTIAL, 200);

and modified the BuySignal:

def BuySignal = close crosses above ST and close > MAVG; # insert condition to create long position
 
I've played around with that and I'm not getting favorable P/L. I was thinking I could add an AND statement stating to only buy if the CLOSE is above the ST AND the CLOSE is above the 200 EMA. But it's not working. Here's what I put.

def MAVG = movingAverage (AverageType.EXPONENTIAL, 200);

and modified the BuySignal:

def BuySignal = close crosses above ST and close > MAVG; # insert condition to create long position

Change your definition to

def MAVG = MovAvgExponential(close,200);

yours didn't define an element to use so it was always equal to 200
 
ST is not defined and gives error

You have to append my code to the bottom of the script from the original post (or any study that can have buy and sell signals). I only gave him the code to do the P/L labels.
 
Is there a way to receive a text alert when the Supertrend generates a buy or a sell signal
Is there a way to receive sms alerts when price crosses the supertrend line
 
Last edited by a moderator:
  • Can we auto trade with this strategy?
  • thanks for the code, does this work for day trading?
  • does this code work for intraday, do I need to check extended hours trading ? when i trade during trading hours?
 
Last edited by a moderator:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
211 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