Indicators That We Are Using In Our Algos

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
mode note:
ATTENTION ALGO TRADERS:
Be careful with your coding, folks!

The common mistake that n00b algo traders make is to trade on the current bar.

When you write triggers on the current bar, obviously false signals will occur since the current bar doesn't know what the final close, high, and low is going to be until it's finished forming.
Therefore, by definition, you are asking it to repaint with new information on every tick.

To avoid false signals, use of the previous bar [1] for your calculations within your code.
You, macro recorders, be especially careful to filter your ADDLabel statements using the prior bar [1].

Follow the above simple steps and never experience disappearing signals again!
FYI, for backtesting results, In your ADDORDER statements only: use the open of the next bar open[-1] for accurate non-repainted backtesting data.

We have an on-going thread to discuss the mechanical process of HOW to set up ALGOs with ToS here:
https://usethinkscript.com/threads/auto-trade-algo-in-tos.7546/

This thread focuses on WHAT studies to use in your algo system.
 
Last edited:
thank you all for sharing your jobs, I am using a mac osx, I ask you……. What is the study that best approaches the perfect output? ?????
I am looking for a script for my algo system.
 
Last edited by a moderator:

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

For several months now, I have been programming algos in easyLanguage. Based on that experience, I believe the most difficult aspect isn't coding entry criteria. It's coding the exit because there can be so many nuances to closing a trade. The longer I work on the project, the more I am attracted to very simple strategies such as crossovers for entry and profit targets (in dollars) for exits if allowing the algo to manage the trade.

Lately I have moved away from allowing the program to manage the exit. It is more profitable to let the algo open the trade with a bracket order and then I adjust the stop loss and profit target based on structure and price action. That kind of exit criteria is something I will never have the skills to code but can easily adjust manually once the trade has been opened by the ago.

Best wishes and happy trading!
 
For several months now, I have been programming algos in easyLanguage. Based on that experience, I believe the most difficult aspect isn't coding entry criteria. It's coding the exit because there can be so many nuances to closing a trade. The longer I work on the project, the more I am attracted to very simple strategies such as crossovers for entry and profit targets (in dollars) for exits if allowing the algo to manage the trade.

Lately I have moved away from allowing the program to manage the exit. It is more profitable to let the algo open the trade with a bracket order and then I adjust the stop loss and profit target based on structure and price action. That kind of exit criteria is something I will never have the skills to code but can easily adjust manually once the trade has been opened by the ago.

Best wishes and happy trading!
i absolutely agree with you , so far I have managed to automate everything but as it is used in the existing indicators I cannot find the right one and I conclude that it is better to be all automatic but the output makes it manual when it creates this satisfied
 
@Goingdark365 I'm still learning here as well. I think that has to do with the way tos calculates. If you use the close of the bar... That means the next bar will get the notification. I'm away from computer right now. But if we had more of your strat I bet we could figure it out.
 
Here's an older strategy that should work with my AHK script shown here:
https://usethinkscript.com/threads/auto-trade-algo-in-tos.7546/page-13#post-114283

Strategy is Fractal Chaos, but I also have some range trading stuff as an option so if you break out of a range to the upside or downside, it will take a trade. I didn't really comment it up and have directions because I never really had intentions of anyone else using it... most should be pretty self explanatory, but this should get your started. Note: Points only works on backtesting, and does not work on live trading. The strategy below was designed for trading a range with renko bars, typically 10 on MES and 20 on MNQ. It kinda ****s with time charts (eg: 5 min, 10 min, etc), but should give you some ideas for your own. This will show you how I do my labels as well.

Code:
# Range Trader
# Author Kevin N 10-11-22 21:55


def CCI                     = reference CCI();
def nan                        = Double.NaN;
#plot trend                = MovingAverage(AverageType.EXPONENTIAL, 100);
input tradeOpenRange        = no;
input marketOpenTime        = 0930;
input openRangeMinutes      = 15;
input tradeCloseRange        = no;
input marketCloseTime       = 1530;
input closeRangeMinutes     = 90;
input useGoFlat                = yes;
input goFlatTime1            = 0815;
input goFlatTime2            = 1550;
input debug                 = yes;
input closeLabelOn            = yes;
input useWaitBars            = yes;
input waitBars                = 10;
input useVariableSlope        = yes;
input varMA                    = 150;
input varSlopeBars            = 20;
input varSlopeAngle            = .100;
input useLossCount            = no;
input useMultiplyContracts    = no;
input maxLossWait            = 3;
input maxContracts            = 8;
input contractsMultiplier    = 2;
input usePriceRange            = no;
input topRange                = 3800;
input bottomRange            = 3700;
input stopType                = {default "Opposite Bar", Points, Strategy};
input stopPoints            = 5;
input tradingHours             = {default Both, Regular, GlobeX};

plot varMovAvg;
varMovAvg               = MovingAverage(AverageType.EXPONENTIAL, close, varMA);

###################################
# Fractal Chaos
###################################
input sequenceCount = 1;

def maxSideLength = sequenceCount + 10;
def upRightSide = fold i1 = 1 to maxSideLength + 1 with count1 while count1 != sequenceCount and count1 != -1 do
    if GetValue(high, -i1) > high or (GetValue(high, -i1) == high and count1 == 0) then -1
    else if GetValue(high, -i1) < high then count1 + 1 else count1;
def upLeftSide = fold i2 = 1 to maxSideLength + 1 with count2 while count2 != sequenceCount and count2 != -1 do
    if GetValue(high, i2) > high or (GetValue(high, i2) == high and count2 >= 1) then -1
    else if GetValue(high, i2) < high then count2 + 1 else count2;

def downRightSide = fold i3 = 1 to maxSideLength + 1 with count3 while count3 != sequenceCount and count3 != -1 do
    if GetValue(low, -i3) < low or (GetValue(low, -i3) == low and count3 == 0) then -1
    else if GetValue(high, -i3) > low then count3 + 1 else count3;
def downLeftSide = fold i4 = 1 to maxSideLength + 1 with count4 while count4 != sequenceCount and count4 != -1 do
    if GetValue(low, i4) < low or (GetValue(low, i4) == low and count4 >= 1) then -1
    else if GetValue(low, i4) > low then count4 + 1 else count4;

def fractalUp = if upRightSide == sequenceCount and upLeftSide == sequenceCount then high else fractalUp[1];
def fractalDown = if downRightSide == sequenceCount and downLeftSide == sequenceCount then low else fractalDown[1];

plot UpFractal = fractalUp;
plot DownFractal = fractalDown;

###################################
# Time Related Stuff
###################################
def RTH                    = if (SecondsFromTime(0930) > 0 and SecondsTillTime(1800) > 0, 1, 0);

def ONH                    = if SecondsFromTime(1800) == 0
                             then high
                             else if
                             !RTH and high > ONH[1]
                             then high
                             else ONH[1];
                           
def ONL                    = if SecondsFromTime(1800) == 0
                             then low
                             else if
                             !RTH and low < ONL[1]
                             then low
                             else ONL[1];
                           
def firstMinute           = if SecondsFromTime(0930) < 60 then 1 else 0;
def openRangeTime         = if SecondsFromTime(0930) < 60 * openRangeMinutes then 1 else 0;
def ORHigh                = if firstMinute
                            then high
                            else if openRangeTime
                            and high > ORHigh[1]
                            then high
                            else ORHigh[1];
def ORLow                 = if firstMinute
                            then low
                            else if openRangeTime
                            and low < ORLow[1]
                            then low
                            else ORLow[1];

###################################
# Buy/Sell Conditions
###################################                          
def buyCondition        = if (close > fractalUp and close > ORHigh, 1, 0);
def sellCondition       = if (close < fractalDown and close < ORLow, 1, 0);


###################################
# Conditions
###################################
def waitBarsCondition        = if (buyCondition
                                and useWaitBars
                                and high > highest(close[1], waitBars)
                                or sellCondition
                                and useWaitBars
                                and low < lowest(close[1], waitBars)
                                or !useWaitBars, 1, 0);
def openRangeCondition        = if tradeOpenRange
                                or secondsTillTime(marketOpenTime) >= 0 and !tradeOpenRange
                                or secondsFromTime(marketOpenTime) > 60 * openRangeMinutes and !tradeOpenRange
                                then 1
                                else 0;
def closeRangeCondition       = if tradeCloseRange
                                or secondsTillTime(marketCloseTime) >= 0 and !tradeCloseRange
                                or secondsFromTime(marketCloseTime) > 60 * closeRangeMinutes and !tradeCloseRange
                                then 1
                                else 0;
# def goFlatTimes            = if SecondsTillTime(goFlatTime1) == 0 or SecondsTillTime(goFlatTime2) == 0 then 1 else 0;
def goFlatTimes                  = if useGoFlat
                                and secondsFromTime(goFlatTime1) > 0
                                and secondsFromTime(goFlatTime1) <= 60 * 15
                                or useGoFlat
                                and secondsFromTime(goFlatTime2) > 0
                                and secondsFromTime(goFlatTime2) <= 60 * 15
                                then 1
                                else 0;
def priceRangeCondition        = if (usePriceRange
                                 and close > topRange
                                 or usePriceRange
                                 and close < bottomRange
                                 or !usePriceRange, 1, 0);                              
def varMovAvgSlopeCondition    = if (useVariableSlope
                                and buyCondition
                                and (varMovAvg - varMovAvg[varSlopeBars]) / varSlopeBars > varSlopeAngle
                            or sellCondition
                                and (varMovAvg - varMovAvg[varSlopeBars]) / varSlopeBars < -varSlopeAngle
                            or !useVariableSlope, 1, 0);
def maxLossCount;
# def contracts             = 1;
def tmpContracts            = if maxLossCount[1] != maxLossCount[2]
                                and maxLossCount[1] >= maxLossWait
                                then maxLossCount[1]
                                else maxLossCount[2];
def contractsCalc            = if useMultiplyContracts
                                and tmpContracts >= maxLossWait
                                then tmpContracts * contractsMultiplier
                                else if maxLossCount[1] <= 1
                                then 1
                                else 1;
def lossCountCondition        = if useLossCount
                                and tmpContracts >= maxLossWait
                                or !useLossCount then 1 else 0;
                               
def contracts                = if contractsCalc > maxContracts then maxContracts else contractsCalc;                              


# Hours To Trade ----------------------
def selectedHours;

switch (tradingHours) {
case Both:
    selectedHours         = 1;
case Regular:
    selectedHours         = if (SecondsFromTime(marketOpenTime) > 0 and SecondsTillTime(1600) > 0, 1, 0);
case GlobeX:
    selectedHours         = if (SecondsFromTime(marketOpenTime) > 0 and SecondsTillTime(1600) > 0, 0, 1);
}

def buySignal            = if ( buyCondition
                                and waitBarsCondition
                                and openRangeCondition
                                and closeRangeCondition
                                and selectedHours
                                and varMovAvgSlopeCondition
                                and priceRangeCondition
                                , 1, 0);
def sellSignal            = if ( sellCondition
                                and waitBarsCondition
                                and openRangeCondition
                                and closeRangeCondition
                                and selectedHours
                                and varMovAvgSlopeCondition
                                and priceRangeCondition
                                , 1, 0);
                               
def closeAllCondition     = if (useGoFlat and goFlatTimes, 1, 0);
                               
# End Conditions --------------------

def bought              = if bought[1] != bought[2]
                            and buySignal
                            then 1
                            else if bought[1] != bought[2]
                            and sellSignal then -1 else bought[1];
def sellToClose         = buyCondition;
def buyToClose          = sellCondition;
def ahk                 = 0;
def isLong              = if buySignal then 1 else if sellSignal then 0 else isLong[1];
def isShort             = if sellSignal then 1 else if buySignal then 0 else isShort[1];
def useLong             = 1;
def useShort            = 1;
def hasEntry1           = 0;

def closeLong;
def closeShort;  

switch (stopType) {
case "Opposite Bar":
    closeLong            = if (isLong and close < open, 1, 0);
    closeShort            = if (isShort and close > open, 1, 0);
case Strategy:
    closeLong            = if (isLong and close < fractalDown, 1, 0);
    closeShort            = if (isShort and close > fractalUp, 1, 0);
case Points:
    closeLong            = if (EntryPrice() and low < highest(high, 10) - stopPoints, 1, 0);
    closeShort            = if (EntryPrice() and high > lowest(low, 10) + stopPoints, 1, 0);
}

#ORDERS
AddOrder(type = OrderType.BUY_TO_OPEN, buySignal, open[-1], tradeSize = Contracts, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long");
AddOrder(type = OrderType.SELL_TO_CLOSE, closeLong, open[-1], tradeSize = Contracts, name = "Close", tickcolor = Color.GRAY, arrowcolor = Color.GRAY);

AddOrder(type = OrderType.SELL_TO_OPEN, sellSignal, open[-1], tradeSize = Contracts, name = "Short", tickcolor = Color.RED, arrowcolor = Color.RED);

AddOrder(type = OrderType.BUY_TO_CLOSE, closeShort, open[-1], tradeSize = Contracts, name = "Close", tickcolor = Color.GRAY, arrowcolor = Color.GRAY);

AddOrder(type = OrderType.Sell_TO_CLOSE, closeAllCondition, price = close, tickcolor = Color.ORANGE, arrowcolor = Color.ORANGE, name = "Go Flat");

# Alerts
Alert(if (buySignal, 1, 0), "Buy",  Alert.BAR, Sound.Bell);
Alert(if (sellSignal[1], 1, 0), "Close",  Alert.BAR, Sound.Bell);
# End Alerts

###################################################################################################
# Labels
# IMPORTANT - do not allow two signals to display at the same time or AHK will get stuck in a loop.
# Looks Odd, but we want the spacing to be the same for the blank labels for AutoHotKey
# if you are NOT using AutoHotKey to manage your trades, these lables are not needed.
###################################################################################################
#Debug
AddLabel(0,
"                                           "
, Color.BLUE); # Use to debug

#------------------------------------
# Go Flat ---------------------------
#------------------------------------
def goFlatLabel = if useGoFlat and goFlatTimes then 1 else 0;
AddLabel(if (goFlatLabel[1], 1, 0),
"                                           "
, Color.BLUE);

#------------------------------------
# Buy Signal ------------------------
#------------------------------------
def buySignalLabel;
if (ahk) {
    buySignalLabel = if (buySignal and useLong and !sellToClose and !hasEntry1 and !goFlatLabel
                        or buySignal and useLong and isNan(sellToClose) and isNan(hasEntry1) and !goFlatLabel, 1, 0);
} else  {
   buySignalLabel = buySignal and !sellSignal;
}
AddLabel(if (lossCountCondition and buySignalLabel[1], 1, 0),
if debug then
"BuySignal                                  "
else
"                                           "
, Color.WHITE);

#------------------------------------
# Close The Trade      --------------
#------------------------------------
    def closeLongTradeLabel;
    if (ahk) {
        closeLongTradeLabel = if (closeLabelOn and closeLong
                                    or closeLabelOn and closeShort, 1, 0);
    } else  {
        closeLongTradeLabel = if (closeLabelOn and closeLong
                                    or closeLabelOn and closeShort, 1, 0);
    }
    AddLabel(if (closeLongTradeLabel[1], 1, 0),
if debug then
"Close Trade                                "
else
"                                           "
, Color.BLUE);

#------------------------------------
# Sell Short ------------------------
#------------------------------------
    def sellSignalLabel;
    if (ahk) {
        sellSignalLabel = if (sellSignal and useShort and !buyToClose and !hasEntry1 and !goFlatLabel
                            or sellSignal and useShort and isNan(buyToClose) and isNan(hasEntry1) and !goFlatLabel, 1, 0);
                           
    } else  {
        sellSignalLabel = sellSignal and !buySignal;
    }
    AddLabel(if (lossCountCondition and sellSignalLabel[1], 1, 0),
if debug then
"SellSignal                                 "
else
"                                           "
, Color.DARK_ORANGE);

#------------------------------------
#No Trade (PlaceHolder) -------------
#------------------------------------
    def placeHolderLabel;
    if (ahk) {
        placeHolderLabel = !sellSignal and !buySignal and !closeLongTradeLabel and !goFlatLabel;
    } else  {
        placeHolderLabel = !sellSignal and !buySignal and !closeLongTradeLabel and !goFlatLabel;
    }
    AddLabel(if (placeHolderLabel[1], 1, 0),
"                                           "
, Color.BLACK);

#------------------------------------
# Status Label ----------------------
#------------------------------------

AddLabel(if (hasEntry1, 1, 0),
"                  "
, Color.PLUM);

#####################################
# Debug
#####################################

AddLabel(if (debug, 1, 0),
"isLong: " + isLong
, Color.Gray);

AddLabel(if (debug, 1, 0),
"isShort: " + isShort
, Color.Gray);

AddLabel(if (debug, 1, 0),
"CCI: " + CCI
, Color.Gray);

# AddLabel(if (debug, 1, 0),
# "close_order: " + close_order
# , Color.Gray);

AddLabel(if (debug, 1, 0),
"Stop Type: " + stopType
, Color.Gray);

AddLabel(if (debug, 1, 0),
"Hours: " + tradingHours
, Color.Gray);

AddLabel(if (debug, 1, 0),
"Loss Cnt: " + maxLossCount[1]
, Color.Gray);

AddLabel(if (debug, 1, 0),
"FPL: " + FPL()
, Color.Gray);

# AddLabel(if (debug, 1, 0),
# "Sec From Time: " +  secondsFromTime(goFlatTime2)
# , Color.Gray);

# AddLabel(if (debug, 1, 0),
# "Sec Till Time: " +  secondsTillTime(goFlatTime2)
# , Color.Gray);

# AddLabel(if (debug, 1, 0),
# "GoFlatLabel: " +  !goFlatLabel
# , Color.Gray);

def tRange = if usePriceRange then topRange else ONH;
def bRange = if usePriceRange then bottomRange else ONL;
AddCloud(tRange, bRange, Color.LIGHT_GRAY, Color.BLACK);

plot openRangeHigh = if RTH then ORHigh else 0;
plot openRangeLow  = if RTH then ORLow else 0;

openRangeLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
openRangeLow.SetDefaultColor(Color.YELLOW);
openRangeLow.SetLineWeight(1);

openRangeHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
openRangeHigh.SetDefaultColor(Color.YELLOW);
openRangeHigh.SetLineWeight(1);


############################
# FPL Extended
# Extended Floating P&L study.
# Author: Eddielee394
# Version: 1.2
# inspired by FPL Dashboard script developed by Mobius
# Found At: https://usethinkscript.com/threads/extended-floating-profit-loss-backtesting-data-utility-for-thinkorswim.1624/
############################

#An extended floating P&L study to be used alongside TOS strategies for measuring hypothetical strategy performance.\nThis is a work in progress.  And may contain some bugs or other programming issues.

############################
# Instructions
# - Due to limitations with the thinkscript public api, this specific script must be added to a "strategy" study.
#   Generally best practice is to append this script to the end of your custom strategy (ensuring it runs AFTER the
#   `AddOrder()` function is called from the strategy).  A better method would be to use as a lower study but unless
#    a workaround is implemented to handle the `Entry()` function in a lower study, it can only be applied to upper strategies.
#
# - the script uses the `HidePrice()` function which will hide the actual price candles within the upper study,
#   only displaying the FPL histogram.
#
############################


############################
#    Metrics            
#  - Active Trade return %
#  - Entry Count        
#  - Winning Entry Count
#  - Win rate            
#  - Avg return          
#  - avg win            
#  - avg loss            
#  - peak to valley dd  
#  - largest equity dd  
#  - P&L low            
#  - P&L high            
#  - Highest return    
#  - Lowest return    
############################

############################
#     Todo:              
# - Sharpe Ratio    
# - Sortino Ratio    
# - Calmar Ratio    
# - Avg trade        
#   duration            
# -Buy/hold comparison  
############################


#Globals
    input showStats = no;
    def bn = if !IsNaN(close) and !IsNaN(close[1]) and !IsNaN(close[-1]) then BarNumber() else bn[1];

#Inputs
    def fplBegin = 0000;
#hint fplBegin: start time: the time in which then dailyHighLow profit should consider the day start.  Recommended value is 0000.

    def fplTargetWinLoss = .50;
#hint fplTargetWinLoss: sets the target winlossRatio (in percent) which determines display colors of the W/L label.

    def fplTargetWinRate = 1;
#hint fplTargetWinRate: sets the target winRate (float) which determines display colors of the WinRate label;

    def fplHidePrice = no;
#hint fplHidePrice: hide's the underlying price graph. \nDefault is no.

    def fplHideFPL = yes;
#hint fplHideFPL: hide's the underlying P&L graph.\nDefault is yes.

    def fplShowEntryBubbles = no;
#hint fplShowEntryBubbles: display bubbles on the FPL showing the entry and exit P&L values

    def fplEnableDebugging = no;
#hint fplEnableDebugging: displays various debugging labels and chart bubbles. \nIt's recommended to hide the price chart & set the fpl hide fpl setting to yes, when enabling.

#temp input var references
    def begin = fplBegin;
    def targetWinLoss = fplTargetWinLoss;
    def targetWinRate = fplTargetWinRate;
    def hidePrice = fplHidePrice;
    def hideFPL = fplHideFPL;
    def showEntryBubbles = fplShowEntryBubbles;
    def enableDebugging = fplEnableDebugging;

#hide chart candles
    HidePricePlot(hidePrice);

#Plot default Floating P&L
    plot FPL = FPL();
    FPL.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
    FPL.DefineColor("Positive and Up", Color.GREEN);
    FPL.DefineColor("Positive and Down", Color.DARK_GREEN);
    FPL.DefineColor("Negative and Down", Color.RED);
    FPL.DefineColor("Negative and Up", Color.DARK_RED);
    FPL.AssignValueColor(if FPL >= 0
                            then if FPL > FPL[1]
                            then FPL.Color("Positive and Up")
                            else FPL.Color("Positive and Down")
                            else if FPL < FPL[1]
                            then FPL.Color("Negative and Down")
                            else FPL.Color("Negative and Up"));
    FPL.SetHiding(hideFPL);

    plot ZeroLine = if IsNaN(close)
                then nan
                else 0;
    ZeroLine.SetDefaultColor(Color.GRAY);
    ZeroLine.SetHiding(hideFPL);

#Global Scripts
    script calculateDrawdown {
        input plLow = 1;
        input plHigh = 1;

        def _drawdown = if plHigh == 0
                   then 0 #handles the divide by zero error
                   else (plLow - plHigh) / plHigh;
        plot calculateDrawdown = _drawdown;
    }

    script incrementValue {
        input condition = yes;
        input increment =  1;
        input startingValue = 0;

        def _value = CompoundValue(1,
                 if condition
                 then _value[1] + increment
                 else _value[1], startingValue);

        plot incrementValue = _value;
    }
    ;

    script getDurationInMins {
        input gdimBarCount = 1;

    #get the aggregation period (MS per bar)
        def aggPeriod = GetAggregationPeriod();

    #multiply length of bars by aggPeriod to determine total milliseconds then convert to minutes
        def _getDurationInMins = Floor((gdimBarCount * aggPeriod) / 60000);
        plot getDurationInMins = _getDurationInMins;
    }

    script formatDuration {
        input fdBarCount = 1;
        def _fdDuration = getDurationInMins(fdBarCount);
        def _formatDuration = if _fdDuration >= 60 and _fdDuration < 1440 #hours but not days
                         then 1
                         else if _fdDuration >= 1440 #days
                         then 2
                         else 0;

        plot formatDuration = _formatDuration;
    }

    script calculateDuration {
        input cdBarCount = 1;
        def _cdDurationFormat = formatDuration(cdBarCount);
        def _cdDuration = getDurationInMins(cdBarCount);
 
    #if minutes > hour convert to hour, else if minutes > day, then convert to days
        def _calculateDuration = if _cdDurationFormat == 1
                             then _cdDuration / 60 #convert to hours if greater than 60min but less than a day (1440)
                             else if  _cdDurationFormat == 2
                             then Ceil(_cdDuration / 1440) #convert to days if greater than 1440mins
                             else _cdDuration; #fallback to minutes

        plot calculateDuration = _calculateDuration;
    }

# Entry Calculations.  Note: Only parses on a Strategy Chart
    def entry = EntryPrice();
    #def entry = if ahk then avgPrice else EntryPrice(); # used with Kevin AHK script
    def entryPrice = if !IsNaN(entry)
                 then entry
                 else entryPrice[1];

    def hasEntry = !IsNaN(entry);

    def isNewEntry = entryPrice != entryPrice[1];

#is active trade
    def Active = if SecondsTillTime(begin) == 0 and
                SecondsFromTime(begin) == 0
             then 1
             else 0;

    def highFPL = HighestAll(FPL);
    def lowFPL = LowestAll(FPL);

    def fplreturn = (FPL - FPL[1]) / FPL[1];
    def cumsum = Sum(fplreturn);

    def highBarNumber = CompoundValue(1, if FPL == highFPL
                                     then bn
                                     else highBarNumber[1], 0);

    def lowBarNumber = CompoundValue(1, if FPL == lowFPL
                                    then bn
                                    else lowBarNumber[1], 0);


#Win/Loss ratios
    def entryBarsTemp = if hasEntry
                    then bn
                    else nan;

    def entryBarNum = if hasEntry and isNewEntry
                  then bn
                  else entryBarNum[1];

    def isEntryBar = entryBarNum != entryBarNum[1];

    def entryBarPL = if isEntryBar
                 then FPL
                 else entryBarPL[1];

    def exitBarsTemp = if !hasEntry
                   and bn > entryBarsTemp[1]
                   then bn
                   else nan;

    def exitBarNum = if !hasEntry and !IsNaN(exitBarsTemp[1])
                 then bn
                 else exitBarNum[1];

    def isExitBar = exitBarNum != exitBarNum[1];

    def exitBarPL = if isExitBar
                then FPL
                else exitBarPL[1];

    def entryReturn = if isExitBar then exitBarPL - exitBarPL[1] else entryReturn[1];
    def isWin = if isExitBar and entryReturn >= 0 then 1 else 0;
    def isLoss = if isExitBar and entryReturn < 0 then 1 else 0;
    def entryReturnWin = if lossCountCondition and isWin then entryReturn else entryReturnWin[1];
    def entryReturnLoss = if lossCountCondition and isLoss then entryReturn else entryReturnLoss[1];
    def entryFPLWins = if lossCountCondition and isWin then entryReturn else 0;
    def entryFPLLosses = if lossCountCondition and isLoss then entryReturn else 0;
    def entryFPLAll = if isLoss or isWin then entryReturn else 0;


#Counts
    def isWinC        = if isWin and lossCountCondition then 1 else 0;
    def isLossC        = if isLoss and lossCountCondition then 1 else 0;
    def entryFPLAllC = if entryFPLAll and lossCountCondition then 1 else 0;

    def entryCount     = incrementValue(entryFPLAllC);
    def winCount     = incrementValue(isWinC);
    def lossCount     = incrementValue(isLossC);

    def highestReturn = if entryReturnWin[1] > highestReturn[1]
                    then entryReturnWin[1]
                    else highestReturn[1];

    def lowestReturn = if entryReturnLoss[1] < lowestReturn[1]
                   then entryReturnLoss[1]
                   else lowestReturn[1];


    def winRate = winCount / lossCount;
    def winLossRatio = winCount / entryCount;
    def avgReturn = TotalSum(entryFPLAllC) / entryCount;
    def avgWin = TotalSum(entryFPLWins) / winCount;
    def avgLoss = TotalSum(entryFPLLosses) / lossCount;

#Drawdown
    def lowestLowBarNumber = HighestAll(if FPL == lowFPL then bn else 0);
    def highestHighBarNumber = HighestAll(if FPL == highFPL and FPL != FPL[1] then bn else 0);
    def hasPrevLow = lowestLowBarNumber < highestHighBarNumber;

    def isPeak = FPL > Highest(FPL[1], 12) and FPL > Highest(FPL[-12], 12);
    def isTrough = FPL < Lowest(FPL[1], 12) and FPL < Lowest(FPL[-12], 12);
    def _peak = if isPeak then FPL else nan;
    def _trough = if isTrough then FPL else nan;
    def peak = if !IsNaN(_peak) then FPL else peak[1];
    def trough = if !IsNaN(_trough) then FPL else trough[1];
    def peakBN = if isPeak then bn else peakBN[1];
    def troughBN = if isTrough then bn else troughBN[1];

    def ptvDrawdown = if !hasPrevLow then calculateDrawdown(lowFPL, highFPL) else ptvDrawdown[1];
    def equityDrawdown = if isTrough and trough < peak then trough - peak else equityDrawdown[1];
    def equityDrawdownPercent = if isTrough and trough < peak then calculateDrawdown(trough, peak) else equityDrawdownPercent[1];
    def largestEquityDrawdown = LowestAll(equityDrawdown);
    def largestEquityDrawdownPercent = LowestAll(equityDrawdownPercent);

    def drawdown = if hasPrevLow
               then largestEquityDrawdownPercent
               else ptvDrawdown;

# Drawdown Durations
    def equityDrawdownLength = if bn >= peakBN and bn <= troughBN
                           then troughBN - peakBN
                           else equityDrawdownLength[1];

    def ptvDrawdownLength = if bn >= highestHighBarNumber and bn <= lowestLowBarNumber
                        then lowestLowBarNumber - highestHighBarNumber
                        else ptvDrawdownLength[1];

    def equityDrawdownDuration = calculateDuration(HighestAll(equityDrawdownLength));
    def equityDrawdownDurationFormat = formatDuration(HighestAll(equityDrawdownLength));
    def ptvDrawdownDuration = calculateDuration(ptvDrawdownLength);

    def ptvDrawdownDurationFormat = formatDuration(ptvDrawdownLength);

#Daily profit
    def Midnight = if Active then FPL else Midnight[1];
    def DaysProfit = FPL - Midnight;

#Plots

    AddChartBubble(!hideFPL and showEntryBubbles and isEntryBar, FPL, "Entry: " + entryBarPL + " | " + bn, Color.WHITE);
    AddChartBubble(!hideFPL and showEntryBubbles and isExitBar, FPL, "Exit: " + exitBarPL,
               color = if isWin
                       then Color.LIGHT_GREEN
                       else if isLoss
                       then Color.DARK_RED
                       else Color.GRAY,
               up = no
              );

#Labels


# test -----------------------------------------
#def tmpMaxLossCount = if isLoss then tmpMaxLossCount[1] + 1 else 0;
    def tmpMaxLossCount = if isWin then 0 else if isLoss then tmpMaxLossCount[1] + 1 else tmpMaxLossCount[1];

#Use this line to see highest amount of sequential losses.#
#def maxLossCount  = if tmpMaxLossCount > maxLossCount[1] then tmpMaxLossCount else MaxLossCount[1];

#Use this line to see hightest amount of sequential losses since the last win.#
    # defining up top.  >= will keep going until we hit another loser, != will reset after one win and wait for x losers.
    maxLossCount  = if tmpMaxLossCount >= tmpMaxLossCount[1] then tmpMaxLossCount else maxLossCount[1];

    # AddLabel(debug,
         # text = "MaxLossCount " + maxLossCount,
         # Color.ORANGE
         # );
    AddChartBubble(if (maxLossCount[0] != maxLossCount[1] and maxLossCount > 0 , 1, 0), low[3], maxLossCount, if useLossCount and maxLossCount <= maxLossWait then color.RED else color.YELLOW, no);
# End test -------------------------------------


    AddLabel(showStats,
         text = "LastEntry: " + AsPrice(entryPrice)
         );

    AddLabel(showStats and hasEntry,
         text = "Current Trade % Return:  " + AsPercent(cumsum),
         color = if cumsum > 0
         then Color.GREEN
         else Color.RED
        );

    AddLabel(showStats,
         text = "Total Trades: " + entryCount,
         color = Color.WHITE
         );

    AddLabel(showStats,
         text = "WinCount: " + winCount +
                " | LossCount: " + lossCount +
                " | WinRate: " + winRate,
         color = if winRate >= targetWinRate
                 then Color.GREEN
                 else Color.RED
         );

    AddLabel(showStats,
         text = "W/L: " + AsPercent(winLossRatio),
         color = if winLossRatio > targetWinLoss
                 then Color.GREEN
                 else Color.RED
         );

    AddLabel(showStats,
        text = "HighestReturn: " +  AsDollars(highestReturn),
        color = if highestReturn > 0
                then Color.GREEN
                else Color.RED
        );

    AddLabel(showStats,
        text = "LowestReturn: " +  AsDollars(lowestReturn),
        color = if lowestReturn > 0
                then Color.GREEN
                else Color.RED
        );

    AddLabel(showStats,
         text = "AvgReturn: " + AsDollars(avgReturn) +
                " | AvgWin: " + AsDollars(avgWin) +
                " | AvgLoss: " + AsDollars(avgLoss),
         color = if avgReturn >= 0
                 then Color.LIGHT_GREEN
                 else Color.RED
         );

    AddLabel(showStats,
        text = "PeakToValley DD: " +  AsPercent(drawdown) +
               " | Duration: " + ptvDrawdownDuration +
                if ptvDrawdownDurationFormat == 1
                then " hours"
                else if ptvDrawdownDurationFormat == 2
                then " days"
                else " mins" ,
        color = if drawdown > 0
                then Color.GREEN
                else Color.RED
        );


    AddLabel(showStats and largestEquityDrawdown < 0,
        text = "Largest Equity DD: " +  AsDollars(largestEquityDrawdown) +
               " | Duration: " + equityDrawdownDuration +
                if equityDrawdownDurationFormat == 1
                then " hours"
                else if equityDrawdownDurationFormat == 2
                then " days"
                else " mins",
        color = if largestEquityDrawdown > 0
                then Color.GREEN
                else Color.RED
        );

    AddLabel(showStats,
         text = "P&L High" +
                (if enableDebugging
                then " at bar " + highBarNumber
                else "") +
                ":  " + AsDollars(highFPL),
        color = Color.GREEN
       );

    AddLabel(showStats,
         text = "P&L Low" +
                (if enableDebugging
                then " at bar " + lowBarNumber
                else "") +
                ":  " + AsDollars(lowFPL),
        color = Color.RED
       );

    AddLabel(showStats,
         text = "Days Profit: $" + DaysProfit,
         color = if DaysProfit > 0
                 then Color.GREEN
                 else Color.RED
        );

    AddLabel(showStats,
         text = "Total Profit: " + AsDollars(if useLossCount then avgWin * winCount else FPL),
         color = if FPL > 0
                 then Color.GREEN
                 else Color.RED
        );

#debugging

#peaks & troughs
    AddChartBubble(enableDebugging and isPeak, FPL,
               text = "FPL: " + FPL
                      + " | Peak: " + peak
                      + " | Trough: " + trough[-1]
                      + " | Drawdown: " + AsPercent(calculateDrawdown(trough, peak))
                      + " | PeakBN: " + peakBN
                      + " | BarNumber: " + bn,
               color = Color.LIME
              );

    AddChartBubble(enableDebugging and isTrough, FPL,
               text = "FPL: " + FPL
                      + " | Peak: " + peak
                      + " | Trough: " + trough
                      + " | Drawdown: " + AsPercent(calculateDrawdown(trough, peak))
                      + " | TroughBN: " + troughBN
                      + " | BarNumber: " + bn,
              color = Color.LIGHT_RED,
              up = no
             );

    AddVerticalLine(enableDebugging and isEntryBar,
                text = "EntryBarNum: " + entryBarNum
                       + " | ExitBarNum: " + exitBarNum[-1]
                       + " | BarNumber: " + bn,
                color = Color.WHITE
);

    AddVerticalLine(enableDebugging and isExitBar,
                text =  "EntryBarNum: " + entryBarNum[1]
                        + " | ExitbarNum: " + exitBarNum
                        + " | BarNumber: " + bn
                        + " | EntryReturn: " + entryReturn,
                color = if isWin
                        then Color.LIGHT_GREEN
                        else if isLoss
                        then Color.LIGHT_RED
                        else Color.LIGHT_GREEN
);
 
thanks @Kevin N for sharing ill have a look
@SilverWolf here is the code I use a 12 range with a fixed 9PT-3 stop best I got this code to do was 68% w/L rate without taking a lot of trades
Code:
def na = Double.NaN;
def h = high ;
def l = low;
def c = close ;
def o = open ;
def v = volume;
def up  = h > h[1] and l >= l[1];
def down  = h <= h[1] and l < l[1];
def red = c < o;
def green = c > o;
def down_green =  down and c > o;
def up_red =  up and c < o;

input target = 9.00;
input stop = 3.00;


#___________________________________Rvol__________________________
input rvol_Type = AverageType.SIMPLE;
input RVol_length = 10 ;
input rv_min = 2.0;
def rvolpaint = yes;
def rvol_color_id = yes;
def rvpoint = no;
def AvgVol = MovingAverage(rvol_Type, v, RVol_length);
def CurrentToAvg = Round(v / AvgVol);

def rv1 = 1.6;
def rv2 = 2.0;
def rv3 = 2.6;
def rv1x = CurrentToAvg > rv1 ;
def rv2x = CurrentToAvg > rv2 ;
def rv3x = CurrentToAvg > rv3;

AssignPriceColor( if
  rvolpaint and  rv3x then Color.YELLOW else if
  rvolpaint and  rv2x then Color.GREEN else if
  rvolpaint and  rv1x then Color.DARK_ORANGE
  else COLOR.CURRENT);

def entryprice1 = entryprice();

DEF LONGv    = down_green and  CurrentToAvg > rv_min ;
def SHORTV    = up_red and CurrentToAvg > rv_min ;
def longexit =   h[-1] crosses entryprice1[-1] + target;
def longstop =   l[-1] crosses entryprice1[-1] - stop;
DEF SHORTexit =  l[-1] crosses entryprice1[-1] - target ;
def SHORTstop =  h[-1] crosses entryprice1[-1] + stop ;
DEF longstopPRICE =  l[0] <= entryprice1[0] - stop;
DEF longexitPRICE =  h[0] >= entryprice1[0] + target;
DEF shortStopPrice = h[0] >= entryprice1[0] + stop ;
DEF SHORTexitPRICE = l[0] <= entryprice1[0] - target ;
input quantity = 1;

INPUT LONG_V = YES;

AddOrder(OrderType.BUY_auto,long_V AND LONGv
, tradeSize = quantity, name = ";LE-V;", tickcolor = GetColor(9), arrowcolor = GetColor(9) );

AddOrder(OrderType.SELL_TO_CLOSE, longexit, name = ";LT;",price = entryPrice1[-1] + target , tickcolor = GetColor(6), arrowcolor =     GetColor(6));

AddOrder(OrderType.SELL_TO_CLOSE, longstop, name = ";LS;", price = entryPrice1[-1] - stop ,tickcolor = GetColor(5), arrowcolor = GetColor(5));


INPUT SHORT_V = YES;


AddOrder(OrderType.SELL_auto,SHORT_V AND SHORTV
, tradeSize = quantity, name = ";SE-V;",tickcolor = GetColor(9), arrowcolor = GetColor(9) );

AddOrder(OrderType.BUY_TO_CLOSE,SHORTexit, name = ";ST;", price = entryPrice1[-1] - target , tickcolor = GetColor(6), arrowcolor = GetColor(6));

AddOrder(OrderType.BUY_TO_CLOSE,SHORTstop, name = ";SS;", price = entryPrice1[-1] + stop , tickcolor = GetColor(5), arrowcolor = GetColor(5));


def longtargetx =  if longv then  close + target  else 0;
    plot longtargetxx = longtargetx;
      longtargetxx.SetDefaultColor(Color.green);
      longtargetxx.SetPaintingStrategy(PaintingStrategy.hoRIZONTAL);

def longstopx = if longv  then close - stop else 0 ;
    plot longstopxx = longstopx;
       longstopxx.SetDefaultColor(Color.light_RED);
       longstopxx.SetPaintingStrategy(PaintingStrategy.hoRIZONTAL);

def shorttargetx =  if shortv then  close - target  else 0;
    plot shorttargetxx = shorttargetx;
     shorttargetxx.SetDefaultColor(Color.green);
     shorttargetxx.SetPaintingStrategy(PaintingStrategy.hoRIZONTAL);

def shortstopx = if shortv  then close + stop else 0 ;
    plot shortstopxx = shortstopx;
       shortstopxx.SetDefaultColor(Color.light_RED);
       shortstopxx.SetPaintingStrategy(PaintingStrategy.hoRIZONTAL);

def LE = LONGV[1];
def LS =  if longstopPRICE then 1 else 0;
def LX = if  longEXITPRICE then 1 else 0 ;
def SE = SHORTV[1];
def SX = if SHORTEXITPRICE then 1 else 0 ;
DEF SS = if SHORTSTOPPrice then 1 else 0;

def Long;
if LE {
Long = 1;
} else if !LE {
Long = 0;
} else {
Long = Long[1];
}

AddLabel(yes, if Long == 1 then "      " else "      ", if Long == 1 then Color.GREEN else Color.magENTA);

def Short;
if SE == 1 {
Short = 1;
} else if !SE {
Short = 0;
} else {
Short = Short[1];
}

AddLabel(yes, if Short == 1 then "      " else "      ", if Short == 1 then COLOR.RED ELSE COLOR.YELLOW);


def l_stop;
if ls == 1 {
l_stop = 1;
} else if !ls {
l_stop = 0;
} else {
l_stop = l_stop[1];
}
def s_stop;
if ss == 1 {
s_stop = 1;
} else if !ss {
s_stop = 0;
} else {
s_stop = s_stop[1];
}

AddLabel(yes, if ls == 1 then "      " else "      ", if ss == 1 then COLOR.BLUE ELSE COLOR.CYAN);

def NewBar = if close[1] != close[2] or high[1] != high[2] or low[1] != low[2] then yes else Double.NaN;
def Clock = if !IsNaN(NewBar) and Clock[1] == 1 then 0 else if !IsNaN(NewBar) and Clock[1] == 0 then 1 else Clock[1];
AddLabel(yes, "       ", if Clock == 0 then Color.VIOLET else Color.Gray);
 
Last edited:
@Goingdark365 I'm still learning here as well. I think that has to do with the way tos calculates. If you use the close of the bar... That means the next bar will get the notification. I'm away from computer right now. But if we had more of your strat I bet we could figure it out.
Repainting is a problem with TOS, so for example, lets say you have something super simple that says something like this.

buySignal = close > somePrice;

AddLabel(buySignal, 1, 0), " Buy Signal Label ", Color.WHITE);

If at anytime the price goes above somePrice during the current bar, it will flash up the label, but if it closes below somePrice it will turn the label off, this is called repainting. So a simple way to stop that is to check the condition on the last bar.

AddLabel(buySignal[1], 1, 0), " Buy Signal Label ", Color.WHITE);

The other thing, EntryPrice() is used by TOS during backtesting, but it will not give any results when trading live. If you are trading a chart using a time frame, you can do a test with GetAveragePrice() to see if it's true, has a value, etc. Neither of those work on range bars.

mod note: use of [1] causes the script to look at the PREVIOUS bar not the LAST bar
Be aware that while this does solve the repainting issue, it causes a one bar lag.
 
Last edited by a moderator:
@Kevin N i don’t have a problem with entry because it doesn’t repaint problem is the the exit. if entryprice() doesn’t work maybe i can use atr multiple and just go back candles to come up with the entry and exit

You may have to get creative with your exit strategies. ToS restricts us by waiting for candle closing when triggering exits. I have gotten around this by applying a priceline study and entering into a pixelsearch() loop during a trade which will trigger an exit if the priceline reaches a certain Y-value of pixels away from the entry coordinate of the priceline. This makes backtesting difficult but working with it live, it has saved a number of trades from turning on me.
 
@Jonessw1 thanks for the suggestion
I’ve got couple things in mind not sure if it will work
1 use oco bracket orders (and use image search to know if it’s in a trade or not )
2 the use of atr (not sure this will work )
3 getting the high and low of the (this would be great)
 
I am currently developing/testing these two systems. Both are created from indicators shared here on the site.


CSS:
#https://usethinkscript.com/threads/ut-bot-for-thinkorswim.12640/post-107944


declare upper;

input Key_Vaule = 3.0;
def a = Key_Vaule;# input(3, title = "Key Vaule. 'This changes the sensitivity'")
input atr_period = 2;
def c = atr_period; # input(2, title = "ATR Period")
input Signals_from_Heikin_Ashi_Candles = no;
def h = Signals_from_Heikin_Ashi_Candles; # input(false, title = "Signals from Heikin Ashi Candles")

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 21;
input TrendTriggerAvgLength = 50;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#========       ATR       ======================================================================

def xATR = ATR(c);
def nLoss = a * xATR;

def src = if h then (open + high + low + close) / 4 else close;

script nz {
    input x = close;
    input y = 0;
    plot result = if IsNaN(x) then y else x;
}

#xATRTrailingStop = 0.0
def xATRTrailingStop = CompoundValue(1, If(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), Max(nz(xATRTrailingStop[1]), src - nLoss),
If(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), Min(nz(xATRTrailingStop[1]), src + nLoss),
If(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))), 0);

#pos = 0
def pos = CompoundValue(1, If(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1,
If(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) , 0);

def ema = ExpAverage(src, 1);
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

def buy = src > xATRTrailingStop and above ;
def sell = src < xATRTrailingStop and below;

def barbuy = src > xATRTrailingStop ;
def barsell = src < xATRTrailingStop ;

#======== PLOTS ============================================================================

input show_labels = no;
DefineGlobalColor("Green", Color.GREEN);
DefineGlobalColor("Red", Color.RED);
AddChartBubble(show_labels and buy, low, "B", GlobalColor("Green"), no);
AddChartBubble(show_labels and sell, high, "S", GlobalColor("Red"), yes);

input mobile_arrows_on = yes;
plot mobile_arrows_buy = if buy and mobile_arrows_on then 1 else 0;
mobile_arrows_buy.SetLineWeight(5);
mobile_arrows_buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
mobile_arrows_buy.SetDefaultColor(Color.UPTICK);

plot mobile_arrows_sell = if sell and mobile_arrows_on then 1 else 0;
mobile_arrows_sell.SetLineWeight(5);
mobile_arrows_sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
mobile_arrows_sell.SetDefaultColor(Color.DOWNTICK);

#======== Paint Bars =======================================================================

input PaintBars= yes;
AssignPriceColor(if !PaintBars then Color.CURRENT else if barbuy then GlobalColor("Green") else Color.CURRENT);
AssignPriceColor(if !PaintBars then Color.CURRENT else if barsell then GlobalColor("Red") else Color.CURRENT);

#======== SIGNALS =========================================================================

def BuySignal =  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1];

def BuyExit = barsell;

def SellSignal =  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1];

def SellExit = barbuy;

#======== STRATEGY ORDERS ===================================================================

input Price = close;#{default Close, Open, high[1] + low[1]/2};
input TradeSize = 1;

AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[0], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[0], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1] then Color.GREEN else Color.MAGENTA);

#Buy Exit
AddLabel(LabelsOn, "       ", if barsell then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1] then Color.RED else Color.YELLOW);

#Sell Exit
AddLabel(LabelsOn, "       ", if barbuy then Color.LIGHT_GREEN  else Color.ORANGE);

#======== EOF =============================================================================

and

CSS:
# Parabolic_SAR_Moving_Average_Trading_Strategy

# by BabyTrader using the following article: Parabolic SAR Moving Average Trading Strategy

# https://tradingstrategyguides.com/parabolic-sar-moving-average-trade-strategy/

# ParabolicSAR_withAlerts_JQ
# 2018-04-15 Mods by Johnny Quotron
#    with a very helpful kickstart from DMonkey
# Mods include
#    1. splitting the PSAR into two visible plots so that they can be colored seperately
#    2. adding alert arrows at the PSAR to enhance visibility
#        a. original alert arrows remain available but are hidden by default
#    3. add ability to color color alert arrows
#

# Combined/Modified/Altered by SilverWolf


declare upper;

#======== Inputs ==============================================================================


input accelerationFactor = 0.012;
input accelerationLimit = 0.2;
input extremeoffset = 0.0;

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 9;
input TrendTriggerAvgLength = 21;

input TradeClosingMethod = {default "SAR", "MOVAVG"};
input TradeSize = 1;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

def Closer = if TradeClosingMethod == TradeClosingMethod."SAR" then 1 else
             if TradeClosingMethod == TradeClosingMethod."MOVAVG" then 2 else 0;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#======== ParabolicSAR =========================================================================

Assert(accelerationFactor > 0, "'acceleration factor' must be positive: " + accelerationFactor);
Assert(accelerationLimit >= accelerationFactor, "'acceleration limit' (" + accelerationLimit + ") must be greater than or equal to 'acceleration factor' (" + accelerationFactor + ")");

def state = {default init, long, short};
def extreme;
def SAR;
def acc;

switch (state[1]) {
case init:
    state = state.long;
    acc = accelerationFactor;
    extreme = high;
    SAR = low;
case short:
    if (SAR[1] < high)
    then {
        state = state.long;
        acc = accelerationFactor;
        extreme = high + extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.short;
        if (low < extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = low - extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Max(Max(high, high[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
case long:
    if (SAR[1] > low)
    then {
        state = state.short;
        acc = accelerationFactor;
        extreme = low - extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.long;
        if (high > extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = high + extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Min(Min(low, low[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
}

#======== SIGNALS =========================================================================

def BuySignal = if Trend == 1 and (close > TriggerAVG ) and (SAR crosses below close)

then 1

else if Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR crosses below close)

then 1

else Double.NaN;


def SellSignal = if Trend == 1 and (close < TriggerAVG ) and (SAR crosses above close)

then 1

else if Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR crosses above close)

then 1

else Double.NaN;


def BuyExit = if Closer == 1 and (close crosses below SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses above CrossingAVG)

then 1

else Double.NaN;


def SellExit = if Closer == 1 and (close crosses above SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses below CrossingAVG)

then 1

else Double.NaN;

#======== STRATEGY ORDERS ===================================================================


input Price = close;#{default Close, Open, high[1] + low[1]/2};


AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[1], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[1], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");


#======== PLOTS ============================================================================

plot BullPSAR = if SAR < close then SAR else Double.NaN;
BullPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BullPSAR.SetDefaultColor(Color.LIME);

plot BearPSAR = if SAR > close then SAR else Double.NaN;
BearPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BearPSAR.SetDefaultColor(Color.PINK);

#---

def BullSignalAtCandle = Crosses(SAR, close, CrossingDirection.BELOW);
plot BullSignalAtPSAR = if close crosses above SAR
                     then SAR
                     else Double.NaN;
BullSignalAtPSAR.SetLineWeight(1);
BullSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BullSignalAtPSAR.SetDefaultColor(Color.LIME);

def BearSignalAtCandle = Crosses(SAR, close, CrossingDirection.ABOVE);
plot BearSignalAtPSAR = if close crosses below SAR
                     then SAR
                     else Double.NaN;
BearSignalAtPSAR.SetLineWeight(1);
BearSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
BearSignalAtPSAR.SetDefaultColor(Color.PINK);

#---

plot LongEntrySignal = if BuySignal then BuySignal else Double.NaN;
LongEntrySignal.SetDefaultColor(Color.UPTICK);
LongEntrySignal.SetLineWeight(5);
LongEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);


plot ShortEntrySignal = if SellSignal then SellSignal else Double.NaN;
ShortEntrySignal.SetDefaultColor(Color.DOWNTICK);
ShortEntrySignal.SetLineWeight(5);
ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

plot LongExitSignal = if BuyExit then BuyExit else Double.NaN;
LongExitSignal.SetDefaultColor(Color.White);
LongExitSignal.SetLineWeight(1);
LongExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);


plot ShortExitSignal = if SellExit then SellExit else Double.NaN;
ShortExitSignal.SetDefaultColor(Color.White);
ShortExitSignal.SetLineWeight(1);
ShortExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

#======== ALERTS ===========================================================================

input AlertsOn = No;
Alert(AlertsOn and BullSignalAtCandle, "Bullish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BearSignalAtCandle, "Bearish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BuySignal, "Bullish PSAR above AVG", Alert.BAR, Sound.Ring);
Alert(AlertsOn and SellSignal, "Bullish PSAR below AVG", Alert.BAR, Sound.Ring);

#======== Paint Bars =======================================================================

input paintBars = No;
AssignPriceColor(if !paintBars
    then Color.CURRENT
    else if SAR < close
        then Color.GREEN
        else if  SAR > close
            then Color.RED
            else Color.CURRENT);

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if Trend == 1 and (close > TriggerAVG) and (SAR < close) or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR < close) then Color.GREEN else Color.MAGENTA);

#Buy Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR > close) or  Closer == 2 and (low < TriggerAVG) then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if Trend == 1 and (close < TriggerAVG) and (SAR > close) or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR > close) then Color.RED else Color.YELLOW);

#Sell Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR < close) or Closer == 2 and (high > TriggerAVG) then Color.LIGHT_GREEN  else Color.ORANGE);


#======== EOF =============================================================================
 
@Jonessw1 thanks for the suggestion
I’ve got couple things in mind not sure if it will work
1 use oco bracket orders (and use image search to know if it’s in a trade or not )
2 the use of atr (not sure this will work )
3 getting the high and low of the (this would be great)

I use these images to keep AHK and TOS on the same page. You may be able to use them to know if youre in a trade.

CSS:
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w59 *h26 Images\Positive.tiff
        if (ErrorLevel = 0){
            status = 1
            ;tooltip Status: Positive Image Cords: %FoundX% x %FoundY%, %statusCoord%, %buttonsHorizontal%
            sleep 100
        }
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w58 *h26 Images\Negative.tiff
        if (ErrorLevel = 0){
            status = 2
            ;tooltip Status: Negative Image Cords: %FoundX% x %FoundY%, %statusCoord%, %buttonsHorizontal%
            sleep 100
        }
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w71 *h26 Images\FlatPic.tiff
        if (ErrorLevel = 0){
            status = 0
            sleep 100

xLpuD7G.png


YVM6kVk.png


J4Dj6rO.png
 
I use these images to keep AHK and TOS on the same page. You may be able to use them to know if youre in a trade.

CSS:
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w59 *h26 Images\Positive.tiff
        if (ErrorLevel = 0){
            status = 1
            ;tooltip Status: Positive Image Cords: %FoundX% x %FoundY%, %statusCoord%, %buttonsHorizontal%
            sleep 100
        }
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w58 *h26 Images\Negative.tiff
        if (ErrorLevel = 0){
            status = 2
            ;tooltip Status: Negative Image Cords: %FoundX% x %FoundY%, %statusCoord%, %buttonsHorizontal%
            sleep 100
        }
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w71 *h26 Images\FlatPic.tiff
        if (ErrorLevel = 0){
            status = 0
            sleep 100

xLpuD7G.png


YVM6kVk.png


J4Dj6rO.png
@SilverWolf thank you ive been trying this method but no luck(at least with my script) if im in a short pos -1, if a green or red lable come up it will flatten then enter the new trade
im going to try your script and report back
thanks again
 
I am currently developing/testing these two systems. Both are created from indicators shared here on the site.


CSS:
#https://usethinkscript.com/threads/ut-bot-for-thinkorswim.12640/post-107944


declare upper;

input Key_Vaule = 3.0;
def a = Key_Vaule;# input(3, title = "Key Vaule. 'This changes the sensitivity'")
input atr_period = 2;
def c = atr_period; # input(2, title = "ATR Period")
input Signals_from_Heikin_Ashi_Candles = no;
def h = Signals_from_Heikin_Ashi_Candles; # input(false, title = "Signals from Heikin Ashi Candles")

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 21;
input TrendTriggerAvgLength = 50;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#========       ATR       ======================================================================

def xATR = ATR(c);
def nLoss = a * xATR;

def src = if h then (open + high + low + close) / 4 else close;

script nz {
    input x = close;
    input y = 0;
    plot result = if IsNaN(x) then y else x;
}

#xATRTrailingStop = 0.0
def xATRTrailingStop = CompoundValue(1, If(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), Max(nz(xATRTrailingStop[1]), src - nLoss),
If(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), Min(nz(xATRTrailingStop[1]), src + nLoss),
If(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))), 0);

#pos = 0
def pos = CompoundValue(1, If(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1,
If(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) , 0);

def ema = ExpAverage(src, 1);
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

def buy = src > xATRTrailingStop and above ;
def sell = src < xATRTrailingStop and below;

def barbuy = src > xATRTrailingStop ;
def barsell = src < xATRTrailingStop ;

#======== PLOTS ============================================================================

input show_labels = no;
DefineGlobalColor("Green", Color.GREEN);
DefineGlobalColor("Red", Color.RED);
AddChartBubble(show_labels and buy, low, "B", GlobalColor("Green"), no);
AddChartBubble(show_labels and sell, high, "S", GlobalColor("Red"), yes);

input mobile_arrows_on = yes;
plot mobile_arrows_buy = if buy and mobile_arrows_on then 1 else 0;
mobile_arrows_buy.SetLineWeight(5);
mobile_arrows_buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
mobile_arrows_buy.SetDefaultColor(Color.UPTICK);

plot mobile_arrows_sell = if sell and mobile_arrows_on then 1 else 0;
mobile_arrows_sell.SetLineWeight(5);
mobile_arrows_sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
mobile_arrows_sell.SetDefaultColor(Color.DOWNTICK);

#======== Paint Bars =======================================================================

input PaintBars= yes;
AssignPriceColor(if !PaintBars then Color.CURRENT else if barbuy then GlobalColor("Green") else Color.CURRENT);
AssignPriceColor(if !PaintBars then Color.CURRENT else if barsell then GlobalColor("Red") else Color.CURRENT);

#======== SIGNALS =========================================================================

def BuySignal =  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1];

def BuyExit = barsell;

def SellSignal =  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1];

def SellExit = barbuy;

#======== STRATEGY ORDERS ===================================================================

input Price = close;#{default Close, Open, high[1] + low[1]/2};
input TradeSize = 1;

AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[0], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[0], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1] then Color.GREEN else Color.MAGENTA);

#Buy Exit
AddLabel(LabelsOn, "       ", if barsell then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1] then Color.RED else Color.YELLOW);

#Sell Exit
AddLabel(LabelsOn, "       ", if barbuy then Color.LIGHT_GREEN  else Color.ORANGE);

#======== EOF =============================================================================

and

CSS:
# Parabolic_SAR_Moving_Average_Trading_Strategy

# by BabyTrader using the following article: Parabolic SAR Moving Average Trading Strategy

# https://tradingstrategyguides.com/parabolic-sar-moving-average-trade-strategy/

# ParabolicSAR_withAlerts_JQ
# 2018-04-15 Mods by Johnny Quotron
#    with a very helpful kickstart from DMonkey
# Mods include
#    1. splitting the PSAR into two visible plots so that they can be colored seperately
#    2. adding alert arrows at the PSAR to enhance visibility
#        a. original alert arrows remain available but are hidden by default
#    3. add ability to color color alert arrows
#

# Combined/Modified/Altered by SilverWolf


declare upper;

#======== Inputs ==============================================================================


input accelerationFactor = 0.012;
input accelerationLimit = 0.2;
input extremeoffset = 0.0;

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 9;
input TrendTriggerAvgLength = 21;

input TradeClosingMethod = {default "SAR", "MOVAVG"};
input TradeSize = 1;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

def Closer = if TradeClosingMethod == TradeClosingMethod."SAR" then 1 else
             if TradeClosingMethod == TradeClosingMethod."MOVAVG" then 2 else 0;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#======== ParabolicSAR =========================================================================

Assert(accelerationFactor > 0, "'acceleration factor' must be positive: " + accelerationFactor);
Assert(accelerationLimit >= accelerationFactor, "'acceleration limit' (" + accelerationLimit + ") must be greater than or equal to 'acceleration factor' (" + accelerationFactor + ")");

def state = {default init, long, short};
def extreme;
def SAR;
def acc;

switch (state[1]) {
case init:
    state = state.long;
    acc = accelerationFactor;
    extreme = high;
    SAR = low;
case short:
    if (SAR[1] < high)
    then {
        state = state.long;
        acc = accelerationFactor;
        extreme = high + extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.short;
        if (low < extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = low - extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Max(Max(high, high[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
case long:
    if (SAR[1] > low)
    then {
        state = state.short;
        acc = accelerationFactor;
        extreme = low - extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.long;
        if (high > extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = high + extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Min(Min(low, low[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
}

#======== SIGNALS =========================================================================

def BuySignal = if Trend == 1 and (close > TriggerAVG ) and (SAR crosses below close)

then 1

else if Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR crosses below close)

then 1

else Double.NaN;


def SellSignal = if Trend == 1 and (close < TriggerAVG ) and (SAR crosses above close)

then 1

else if Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR crosses above close)

then 1

else Double.NaN;


def BuyExit = if Closer == 1 and (close crosses below SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses above CrossingAVG)

then 1

else Double.NaN;


def SellExit = if Closer == 1 and (close crosses above SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses below CrossingAVG)

then 1

else Double.NaN;

#======== STRATEGY ORDERS ===================================================================


input Price = close;#{default Close, Open, high[1] + low[1]/2};


AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[1], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[1], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");


#======== PLOTS ============================================================================

plot BullPSAR = if SAR < close then SAR else Double.NaN;
BullPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BullPSAR.SetDefaultColor(Color.LIME);

plot BearPSAR = if SAR > close then SAR else Double.NaN;
BearPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BearPSAR.SetDefaultColor(Color.PINK);

#---

def BullSignalAtCandle = Crosses(SAR, close, CrossingDirection.BELOW);
plot BullSignalAtPSAR = if close crosses above SAR
                     then SAR
                     else Double.NaN;
BullSignalAtPSAR.SetLineWeight(1);
BullSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BullSignalAtPSAR.SetDefaultColor(Color.LIME);

def BearSignalAtCandle = Crosses(SAR, close, CrossingDirection.ABOVE);
plot BearSignalAtPSAR = if close crosses below SAR
                     then SAR
                     else Double.NaN;
BearSignalAtPSAR.SetLineWeight(1);
BearSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
BearSignalAtPSAR.SetDefaultColor(Color.PINK);

#---

plot LongEntrySignal = if BuySignal then BuySignal else Double.NaN;
LongEntrySignal.SetDefaultColor(Color.UPTICK);
LongEntrySignal.SetLineWeight(5);
LongEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);


plot ShortEntrySignal = if SellSignal then SellSignal else Double.NaN;
ShortEntrySignal.SetDefaultColor(Color.DOWNTICK);
ShortEntrySignal.SetLineWeight(5);
ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

plot LongExitSignal = if BuyExit then BuyExit else Double.NaN;
LongExitSignal.SetDefaultColor(Color.White);
LongExitSignal.SetLineWeight(1);
LongExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);


plot ShortExitSignal = if SellExit then SellExit else Double.NaN;
ShortExitSignal.SetDefaultColor(Color.White);
ShortExitSignal.SetLineWeight(1);
ShortExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

#======== ALERTS ===========================================================================

input AlertsOn = No;
Alert(AlertsOn and BullSignalAtCandle, "Bullish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BearSignalAtCandle, "Bearish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BuySignal, "Bullish PSAR above AVG", Alert.BAR, Sound.Ring);
Alert(AlertsOn and SellSignal, "Bullish PSAR below AVG", Alert.BAR, Sound.Ring);

#======== Paint Bars =======================================================================

input paintBars = No;
AssignPriceColor(if !paintBars
    then Color.CURRENT
    else if SAR < close
        then Color.GREEN
        else if  SAR > close
            then Color.RED
            else Color.CURRENT);

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if Trend == 1 and (close > TriggerAVG) and (SAR < close) or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR < close) then Color.GREEN else Color.MAGENTA);

#Buy Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR > close) or  Closer == 2 and (low < TriggerAVG) then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if Trend == 1 and (close < TriggerAVG) and (SAR > close) or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR > close) then Color.RED else Color.YELLOW);

#Sell Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR < close) or Closer == 2 and (high > TriggerAVG) then Color.LIGHT_GREEN  else Color.ORANGE);


#======== EOF =============================================================================
Very interesting strategy (post 12) I've named it Silver Wolf Strat is there a way to change position size to be generated by amount of capital attributed to each position?
 
I am currently developing/testing these two systems. Both are created from indicators shared here on the site.


CSS:
#https://usethinkscript.com/threads/ut-bot-for-thinkorswim.12640/post-107944


declare upper;

input Key_Vaule = 3.0;
def a = Key_Vaule;# input(3, title = "Key Vaule. 'This changes the sensitivity'")
input atr_period = 2;
def c = atr_period; # input(2, title = "ATR Period")
input Signals_from_Heikin_Ashi_Candles = no;
def h = Signals_from_Heikin_Ashi_Candles; # input(false, title = "Signals from Heikin Ashi Candles")

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 21;
input TrendTriggerAvgLength = 50;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#========       ATR       ======================================================================

def xATR = ATR(c);
def nLoss = a * xATR;

def src = if h then (open + high + low + close) / 4 else close;

script nz {
    input x = close;
    input y = 0;
    plot result = if IsNaN(x) then y else x;
}

#xATRTrailingStop = 0.0
def xATRTrailingStop = CompoundValue(1, If(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), Max(nz(xATRTrailingStop[1]), src - nLoss),
If(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), Min(nz(xATRTrailingStop[1]), src + nLoss),
If(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))), 0);

#pos = 0
def pos = CompoundValue(1, If(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1,
If(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) , 0);

def ema = ExpAverage(src, 1);
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

def buy = src > xATRTrailingStop and above ;
def sell = src < xATRTrailingStop and below;

def barbuy = src > xATRTrailingStop ;
def barsell = src < xATRTrailingStop ;

#======== PLOTS ============================================================================

input show_labels = no;
DefineGlobalColor("Green", Color.GREEN);
DefineGlobalColor("Red", Color.RED);
AddChartBubble(show_labels and buy, low, "B", GlobalColor("Green"), no);
AddChartBubble(show_labels and sell, high, "S", GlobalColor("Red"), yes);

input mobile_arrows_on = yes;
plot mobile_arrows_buy = if buy and mobile_arrows_on then 1 else 0;
mobile_arrows_buy.SetLineWeight(5);
mobile_arrows_buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
mobile_arrows_buy.SetDefaultColor(Color.UPTICK);

plot mobile_arrows_sell = if sell and mobile_arrows_on then 1 else 0;
mobile_arrows_sell.SetLineWeight(5);
mobile_arrows_sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
mobile_arrows_sell.SetDefaultColor(Color.DOWNTICK);

#======== Paint Bars =======================================================================

input PaintBars= yes;
AssignPriceColor(if !PaintBars then Color.CURRENT else if barbuy then GlobalColor("Green") else Color.CURRENT);
AssignPriceColor(if !PaintBars then Color.CURRENT else if barsell then GlobalColor("Red") else Color.CURRENT);

#======== SIGNALS =========================================================================

def BuySignal =  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1];

def BuyExit = barsell;

def SellSignal =  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1];

def SellExit = barbuy;

#======== STRATEGY ORDERS ===================================================================

input Price = close;#{default Close, Open, high[1] + low[1]/2};
input TradeSize = 1;

AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[0], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[0], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1] then Color.GREEN else Color.MAGENTA);

#Buy Exit
AddLabel(LabelsOn, "       ", if barsell then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1] then Color.RED else Color.YELLOW);

#Sell Exit
AddLabel(LabelsOn, "       ", if barbuy then Color.LIGHT_GREEN  else Color.ORANGE);

#======== EOF =============================================================================

and

CSS:
# Parabolic_SAR_Moving_Average_Trading_Strategy

# by BabyTrader using the following article: Parabolic SAR Moving Average Trading Strategy

# https://tradingstrategyguides.com/parabolic-sar-moving-average-trade-strategy/

# ParabolicSAR_withAlerts_JQ
# 2018-04-15 Mods by Johnny Quotron
#    with a very helpful kickstart from DMonkey
# Mods include
#    1. splitting the PSAR into two visible plots so that they can be colored seperately
#    2. adding alert arrows at the PSAR to enhance visibility
#        a. original alert arrows remain available but are hidden by default
#    3. add ability to color color alert arrows
#

# Combined/Modified/Altered by SilverWolf


declare upper;

#======== Inputs ==============================================================================


input accelerationFactor = 0.012;
input accelerationLimit = 0.2;
input extremeoffset = 0.0;

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 9;
input TrendTriggerAvgLength = 21;

input TradeClosingMethod = {default "SAR", "MOVAVG"};
input TradeSize = 1;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

def Closer = if TradeClosingMethod == TradeClosingMethod."SAR" then 1 else
             if TradeClosingMethod == TradeClosingMethod."MOVAVG" then 2 else 0;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#======== ParabolicSAR =========================================================================

Assert(accelerationFactor > 0, "'acceleration factor' must be positive: " + accelerationFactor);
Assert(accelerationLimit >= accelerationFactor, "'acceleration limit' (" + accelerationLimit + ") must be greater than or equal to 'acceleration factor' (" + accelerationFactor + ")");

def state = {default init, long, short};
def extreme;
def SAR;
def acc;

switch (state[1]) {
case init:
    state = state.long;
    acc = accelerationFactor;
    extreme = high;
    SAR = low;
case short:
    if (SAR[1] < high)
    then {
        state = state.long;
        acc = accelerationFactor;
        extreme = high + extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.short;
        if (low < extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = low - extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Max(Max(high, high[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
case long:
    if (SAR[1] > low)
    then {
        state = state.short;
        acc = accelerationFactor;
        extreme = low - extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.long;
        if (high > extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = high + extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Min(Min(low, low[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
}

#======== SIGNALS =========================================================================

def BuySignal = if Trend == 1 and (close > TriggerAVG ) and (SAR crosses below close)

then 1

else if Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR crosses below close)

then 1

else Double.NaN;


def SellSignal = if Trend == 1 and (close < TriggerAVG ) and (SAR crosses above close)

then 1

else if Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR crosses above close)

then 1

else Double.NaN;


def BuyExit = if Closer == 1 and (close crosses below SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses above CrossingAVG)

then 1

else Double.NaN;


def SellExit = if Closer == 1 and (close crosses above SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses below CrossingAVG)

then 1

else Double.NaN;

#======== STRATEGY ORDERS ===================================================================


input Price = close;#{default Close, Open, high[1] + low[1]/2};


AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[1], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[1], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");


#======== PLOTS ============================================================================

plot BullPSAR = if SAR < close then SAR else Double.NaN;
BullPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BullPSAR.SetDefaultColor(Color.LIME);

plot BearPSAR = if SAR > close then SAR else Double.NaN;
BearPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BearPSAR.SetDefaultColor(Color.PINK);

#---

def BullSignalAtCandle = Crosses(SAR, close, CrossingDirection.BELOW);
plot BullSignalAtPSAR = if close crosses above SAR
                     then SAR
                     else Double.NaN;
BullSignalAtPSAR.SetLineWeight(1);
BullSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BullSignalAtPSAR.SetDefaultColor(Color.LIME);

def BearSignalAtCandle = Crosses(SAR, close, CrossingDirection.ABOVE);
plot BearSignalAtPSAR = if close crosses below SAR
                     then SAR
                     else Double.NaN;
BearSignalAtPSAR.SetLineWeight(1);
BearSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
BearSignalAtPSAR.SetDefaultColor(Color.PINK);

#---

plot LongEntrySignal = if BuySignal then BuySignal else Double.NaN;
LongEntrySignal.SetDefaultColor(Color.UPTICK);
LongEntrySignal.SetLineWeight(5);
LongEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);


plot ShortEntrySignal = if SellSignal then SellSignal else Double.NaN;
ShortEntrySignal.SetDefaultColor(Color.DOWNTICK);
ShortEntrySignal.SetLineWeight(5);
ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

plot LongExitSignal = if BuyExit then BuyExit else Double.NaN;
LongExitSignal.SetDefaultColor(Color.White);
LongExitSignal.SetLineWeight(1);
LongExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);


plot ShortExitSignal = if SellExit then SellExit else Double.NaN;
ShortExitSignal.SetDefaultColor(Color.White);
ShortExitSignal.SetLineWeight(1);
ShortExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

#======== ALERTS ===========================================================================

input AlertsOn = No;
Alert(AlertsOn and BullSignalAtCandle, "Bullish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BearSignalAtCandle, "Bearish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BuySignal, "Bullish PSAR above AVG", Alert.BAR, Sound.Ring);
Alert(AlertsOn and SellSignal, "Bullish PSAR below AVG", Alert.BAR, Sound.Ring);

#======== Paint Bars =======================================================================

input paintBars = No;
AssignPriceColor(if !paintBars
    then Color.CURRENT
    else if SAR < close
        then Color.GREEN
        else if  SAR > close
            then Color.RED
            else Color.CURRENT);

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if Trend == 1 and (close > TriggerAVG) and (SAR < close) or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR < close) then Color.GREEN else Color.MAGENTA);

#Buy Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR > close) or  Closer == 2 and (low < TriggerAVG) then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if Trend == 1 and (close < TriggerAVG) and (SAR > close) or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR > close) then Color.RED else Color.YELLOW);

#Sell Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR < close) or Closer == 2 and (high > TriggerAVG) then Color.LIGHT_GREEN  else Color.ORANGE);


#======== EOF =============================================================================
For the PSAR strategy, if you modify the SELL_TO_CLOSE and BUY_TO_CLOSE to reflect (H+L)/2 with [-1] it would reflect with a higher probability the results of this strategy if it was running as an algo for your exits. The reason is because you would be considering Close(live price) vs PSAR previous price. The (H+L)/2 setup for price is for TOS to represent as best as possible your exits when price crosses psar when you run the report. As this is now with Price[1] for exits it's off and the profits are super inflated and incorrect since you're seeing the future. I've provided the code modifications below. Great strategy! I've been testing it all week to come up with the code modifications below. If you add a stop loss. The results will be even better! if you do please let me know!
Code:
#======== STRATEGY ORDERS ===================================================================

input Price = close;#{default Close, Open, high[1] + low[1]/2};
input HighPrice = high;
input LowPrice = low;

AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[0], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, (HighPrice[-1] + LowPrice[-1])/ 2, TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[0], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, (HighPrice[-1] + LowPrice[-1])/ 2, TradeSize, Color.WHITE, Color.WHITE, name = "Close");
 
For the PSAR strategy, if you modify the SELL_TO_CLOSE and BUY_TO_CLOSE to reflect (H+L)/2 with [-1] it would reflect with a higher probability the results of this strategy if it was running as an algo for your exits. The reason is because you would be considering Close(live price) vs PSAR previous price. The (H+L)/2 setup for price is for TOS to represent as best as possible your exits when price crosses psar when you run the report. As this is now with Price[1] for exits it's off and the profits are super inflated and incorrect since you're seeing the future. I've provided the code modifications below. Great strategy! I've been testing it all week to come up with the code modifications below. If you add a stop loss. The results will be even better! if you do please let me know!
Code:
#======== STRATEGY ORDERS ===================================================================

input Price = close;#{default Close, Open, high[1] + low[1]/2};
input HighPrice = high;
input LowPrice = low;

AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[0], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, (HighPrice[-1] + LowPrice[-1])/ 2, TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[0], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, (HighPrice[-1] + LowPrice[-1])/ 2, TradeSize, Color.WHITE, Color.WHITE, name = "Close");
I will incorporate your modifications.. I like your explanation Thank you!
 
I am currently developing/testing these two systems. Both are created from indicators shared here on the site.


CSS:
#https://usethinkscript.com/threads/ut-bot-for-thinkorswim.12640/post-107944


declare upper;

input Key_Vaule = 3.0;
def a = Key_Vaule;# input(3, title = "Key Vaule. 'This changes the sensitivity'")
input atr_period = 2;
def c = atr_period; # input(2, title = "ATR Period")
input Signals_from_Heikin_Ashi_Candles = no;
def h = Signals_from_Heikin_Ashi_Candles; # input(false, title = "Signals from Heikin Ashi Candles")

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 21;
input TrendTriggerAvgLength = 50;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#========       ATR       ======================================================================

def xATR = ATR(c);
def nLoss = a * xATR;

def src = if h then (open + high + low + close) / 4 else close;

script nz {
    input x = close;
    input y = 0;
    plot result = if IsNaN(x) then y else x;
}

#xATRTrailingStop = 0.0
def xATRTrailingStop = CompoundValue(1, If(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), Max(nz(xATRTrailingStop[1]), src - nLoss),
If(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), Min(nz(xATRTrailingStop[1]), src + nLoss),
If(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))), 0);

#pos = 0
def pos = CompoundValue(1, If(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1,
If(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) , 0);

def ema = ExpAverage(src, 1);
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

def buy = src > xATRTrailingStop and above ;
def sell = src < xATRTrailingStop and below;

def barbuy = src > xATRTrailingStop ;
def barsell = src < xATRTrailingStop ;

#======== PLOTS ============================================================================

input show_labels = no;
DefineGlobalColor("Green", Color.GREEN);
DefineGlobalColor("Red", Color.RED);
AddChartBubble(show_labels and buy, low, "B", GlobalColor("Green"), no);
AddChartBubble(show_labels and sell, high, "S", GlobalColor("Red"), yes);

input mobile_arrows_on = yes;
plot mobile_arrows_buy = if buy and mobile_arrows_on then 1 else 0;
mobile_arrows_buy.SetLineWeight(5);
mobile_arrows_buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
mobile_arrows_buy.SetDefaultColor(Color.UPTICK);

plot mobile_arrows_sell = if sell and mobile_arrows_on then 1 else 0;
mobile_arrows_sell.SetLineWeight(5);
mobile_arrows_sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
mobile_arrows_sell.SetDefaultColor(Color.DOWNTICK);

#======== Paint Bars =======================================================================

input PaintBars= yes;
AssignPriceColor(if !PaintBars then Color.CURRENT else if barbuy then GlobalColor("Green") else Color.CURRENT);
AssignPriceColor(if !PaintBars then Color.CURRENT else if barsell then GlobalColor("Red") else Color.CURRENT);

#======== SIGNALS =========================================================================

def BuySignal =  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1];

def BuyExit = barsell;

def SellSignal =  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1];

def SellExit = barbuy;

#======== STRATEGY ORDERS ===================================================================

input Price = close;#{default Close, Open, high[1] + low[1]/2};
input TradeSize = 1;

AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[0], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[0], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if  Trend == 1 and (close > TriggerAVG) and barbuy[1] or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and barbuy[1] then Color.GREEN else Color.MAGENTA);

#Buy Exit
AddLabel(LabelsOn, "       ", if barsell then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if  Trend == 1 and (close < TriggerAVG) and barsell[1] or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and barsell[1] then Color.RED else Color.YELLOW);

#Sell Exit
AddLabel(LabelsOn, "       ", if barbuy then Color.LIGHT_GREEN  else Color.ORANGE);

#======== EOF =============================================================================

and

CSS:
# Parabolic_SAR_Moving_Average_Trading_Strategy

# by BabyTrader using the following article: Parabolic SAR Moving Average Trading Strategy

# https://tradingstrategyguides.com/parabolic-sar-moving-average-trade-strategy/

# ParabolicSAR_withAlerts_JQ
# 2018-04-15 Mods by Johnny Quotron
#    with a very helpful kickstart from DMonkey
# Mods include
#    1. splitting the PSAR into two visible plots so that they can be colored seperately
#    2. adding alert arrows at the PSAR to enhance visibility
#        a. original alert arrows remain available but are hidden by default
#    3. add ability to color color alert arrows
#

# Combined/Modified/Altered by SilverWolf


declare upper;

#======== Inputs ==============================================================================


input accelerationFactor = 0.012;
input accelerationLimit = 0.2;
input extremeoffset = 0.0;

input MovAvgType = AverageType.EXPONENTIAL;
input MovAvgTrendMethod = {default "SINGLE", "CROSSING"};
input CrossingAvgLength = 9;
input TrendTriggerAvgLength = 21;

input TradeClosingMethod = {default "SAR", "MOVAVG"};
input TradeSize = 1;

def Trend = if MovAvgTrendMethod == MovAvgTrendMethod."SINGLE" then 1 else
            if MovAvgTrendMethod == MovAvgTrendMethod."CROSSING" then 2 else 0;

def PlotCross = if Trend == 2 then yes else no;

def Closer = if TradeClosingMethod == TradeClosingMethod."SAR" then 1 else
             if TradeClosingMethod == TradeClosingMethod."MOVAVG" then 2 else 0;

#======== Moving Averages ======================================================================

plot TriggerAVG = MovingAverage(MovAvgType, close, TrendTriggerAvgLength);
TriggerAVG.SetLineWeight(3);
TriggerAVG.SetDefaultColor(Color.WHITE);

plot CrossingAVG = MovingAverage(MovAvgType, close, CrossingAvgLength);
CrossingAVG.SetHiding(!PlotCross);
CrossingAVG.SetLineWeight(3);
CrossingAVG.SetDefaultColor(Color.PINK);

#======== ParabolicSAR =========================================================================

Assert(accelerationFactor > 0, "'acceleration factor' must be positive: " + accelerationFactor);
Assert(accelerationLimit >= accelerationFactor, "'acceleration limit' (" + accelerationLimit + ") must be greater than or equal to 'acceleration factor' (" + accelerationFactor + ")");

def state = {default init, long, short};
def extreme;
def SAR;
def acc;

switch (state[1]) {
case init:
    state = state.long;
    acc = accelerationFactor;
    extreme = high;
    SAR = low;
case short:
    if (SAR[1] < high)
    then {
        state = state.long;
        acc = accelerationFactor;
        extreme = high + extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.short;
        if (low < extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = low - extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Max(Max(high, high[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
case long:
    if (SAR[1] > low)
    then {
        state = state.short;
        acc = accelerationFactor;
        extreme = low - extremeoffset;
        SAR = extreme[1];
    } else {
        state = state.long;
        if (high > extreme[1])
        then {
            acc = Min(acc[1] + accelerationFactor, accelerationLimit);
            extreme = high + extremeoffset;
        } else {
            acc = acc[1];
            extreme = extreme[1];
        }
        SAR = Min(Min(low, low[1]), SAR[1] + acc * (extreme - SAR[1]));
    }
}

#======== SIGNALS =========================================================================

def BuySignal = if Trend == 1 and (close > TriggerAVG ) and (SAR crosses below close)

then 1

else if Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR crosses below close)

then 1

else Double.NaN;


def SellSignal = if Trend == 1 and (close < TriggerAVG ) and (SAR crosses above close)

then 1

else if Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR crosses above close)

then 1

else Double.NaN;


def BuyExit = if Closer == 1 and (close crosses below SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses above CrossingAVG)

then 1

else Double.NaN;


def SellExit = if Closer == 1 and (close crosses above SAR[-1])

then 1

else if Closer == 2 and (TriggerAVG crosses below CrossingAVG)

then 1

else Double.NaN;

#======== STRATEGY ORDERS ===================================================================


input Price = close;#{default Close, Open, high[1] + low[1]/2};


AddOrder(OrderType.BUY_TO_OPEN, BuySignal, Price[1], TradeSize, Color.GREEN, Color.GREEN, name = "Long");

AddOrder(OrderType.SELL_TO_CLOSE, BuyExit, Price[0], TradeSize, Color.RED, Color.RED, name = "Close");

AddOrder(OrderType.SELL_TO_OPEN, SellSignal, Price[1], TradeSize, Color.ORANGE, Color.ORANGE, name = "Short");

AddOrder(OrderType.BUY_TO_CLOSE, SellExit, Price[0], TradeSize, Color.WHITE, Color.WHITE, name = "Close");


#======== PLOTS ============================================================================

plot BullPSAR = if SAR < close then SAR else Double.NaN;
BullPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BullPSAR.SetDefaultColor(Color.LIME);

plot BearPSAR = if SAR > close then SAR else Double.NaN;
BearPSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
BearPSAR.SetDefaultColor(Color.PINK);

#---

def BullSignalAtCandle = Crosses(SAR, close, CrossingDirection.BELOW);
plot BullSignalAtPSAR = if close crosses above SAR
                     then SAR
                     else Double.NaN;
BullSignalAtPSAR.SetLineWeight(1);
BullSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BullSignalAtPSAR.SetDefaultColor(Color.LIME);

def BearSignalAtCandle = Crosses(SAR, close, CrossingDirection.ABOVE);
plot BearSignalAtPSAR = if close crosses below SAR
                     then SAR
                     else Double.NaN;
BearSignalAtPSAR.SetLineWeight(1);
BearSignalAtPSAR.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
BearSignalAtPSAR.SetDefaultColor(Color.PINK);

#---

plot LongEntrySignal = if BuySignal then BuySignal else Double.NaN;
LongEntrySignal.SetDefaultColor(Color.UPTICK);
LongEntrySignal.SetLineWeight(5);
LongEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);


plot ShortEntrySignal = if SellSignal then SellSignal else Double.NaN;
ShortEntrySignal.SetDefaultColor(Color.DOWNTICK);
ShortEntrySignal.SetLineWeight(5);
ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

plot LongExitSignal = if BuyExit then BuyExit else Double.NaN;
LongExitSignal.SetDefaultColor(Color.White);
LongExitSignal.SetLineWeight(1);
LongExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);


plot ShortExitSignal = if SellExit then SellExit else Double.NaN;
ShortExitSignal.SetDefaultColor(Color.White);
ShortExitSignal.SetLineWeight(1);
ShortExitSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

#======== ALERTS ===========================================================================

input AlertsOn = No;
Alert(AlertsOn and BullSignalAtCandle, "Bullish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BearSignalAtCandle, "Bearish PSAR", Alert.BAR, Sound.Ring);
Alert(AlertsOn and BuySignal, "Bullish PSAR above AVG", Alert.BAR, Sound.Ring);
Alert(AlertsOn and SellSignal, "Bullish PSAR below AVG", Alert.BAR, Sound.Ring);

#======== Paint Bars =======================================================================

input paintBars = No;
AssignPriceColor(if !paintBars
    then Color.CURRENT
    else if SAR < close
        then Color.GREEN
        else if  SAR > close
            then Color.RED
            else Color.CURRENT);

#======== Labels ===========================================================================

input LabelsOn = Yes;
#Buy
;AddLabel(LabelsOn, "       ", if Trend == 1 and (close > TriggerAVG) and (SAR < close) or Trend == 2 and (close > TriggerAVG) and (CrossingAVG > TriggerAVG) and (SAR < close) then Color.GREEN else Color.MAGENTA);

#Buy Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR > close) or  Closer == 2 and (low < TriggerAVG) then Color.BLUE else Color.CYAN);

#Sell
AddLabel(LabelsOn, "       ", if Trend == 1 and (close < TriggerAVG) and (SAR > close) or Trend == 2 and (close < TriggerAVG) and (CrossingAVG < TriggerAVG) and (SAR > close) then Color.RED else Color.YELLOW);

#Sell Close
AddLabel(LabelsOn, "       ", if Closer == 1 and (SAR < close) or Closer == 2 and (high > TriggerAVG) then Color.LIGHT_GREEN  else Color.ORANGE);


#======== EOF =============================================================================
Do these repaint? I believe I saw it repaint but wanted to ask you for clarification. I cannot understand how it’s repainting though. It prints entries and exits in past time? Am I understanding this correctly? Or is it the exits that only repaint? Thank you.
 
Last edited:
  • Like
Reactions: IPA
Do these repaint? I believe I saw it repaint but wanted to ask you for clarification. I cannot understand how it’s repainting though. It prints entries and exits in past time? Am I understanding this correctly? Or is it the exits that only repaint? Thank you.
I also believe that it repaints.
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
456 Online
Create Post

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