Stop loss value in strategy

thePetester

New member
Hello,

I have been reading this forum for a long time and while I have found what appears to be a solution to my issue, it is not working in my strategy. As the title indicates, I am attempting to set a stop loss at the previous candle's high if going short or at the previous candle's low if going long. This is a P-Sar strategy, not that it makes any difference. I have read several variations of the following:
Code:
# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if BuySignal == 1 then low[1] else buyStopLoss[0];

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if SellSignal == 1 then high[1] else sellStopLoss[0];

...

#if sar crossed above price and close is less than the initial buyStopLoss

def BuyExit = if (ParabolicSAR().SAR crosses above price) or (CLOSE <= buyStopLoss)

then 1

else Double.NaN;

def SellExit = if ParabolicSAR().SAR crosses below price or (CLOSE >= sellStopLoss)

then 1

else Double.NaN;

...

AddOrder(OrderType.SELL_TO_CLOSE, LongExt, open[1], TradeSize, Color.RED, Color.RED);

AddOrder(OrderType.BUY_TO_CLOSE, ShortExt, open[1], TradeSize, Color.WHITE, Color.WHITE);


This is the entire script. I am trying to modify several things in it. This is my first sticking point and I cannot seem to get it right.

Code:
# 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/


# =====================================================

declare upper;

input TradeSize = 10;


input price = close;

input fastLength = 50;

input slowLength = 200;

input displace = 0;

# Using the code from the default Simple Moving Average

# I was able to set the slow/fast moving averages below


plot FastMA = Average(price[-displace], fastLength);

plot SlowMA = Average(price[-displace], slowLength);

FastMA.SetDefaultColor(GetColor(1));

SlowMA.SetDefaultColor(GetColor(2));


# A buy signal is generated if and only if the 2 factors are true, the fastMA is above the slowMA

# and the ParabolicSAR plots below the closing price

# The inverse is also true. A sell signal is generated when the slowMA is above

# the fastMA and the ParabolicSAR plots above the closing price

# The buy exit is generated at the first instance that the ParabolicSAR plots above the close price after the buy signal

# The sell exit is generated at the first instance that the ParabolicSAR plots below the close price after the sell signal


def BuySignal = if (LOW > FastMA) and (FastMA > SlowMA) and (ParabolicSAR().SAR crosses below close)

then 1

else Double.NaN;

def SellSignal = if (HIGH < SlowMA) and (FastMA < SlowMA) and (ParabolicSAR().SAR crosses above close)

then 1

else Double.NaN;


# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if BuySignal == 1 then low[1] else buyStopLoss[0];

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if SellSignal == 1 then high[1] else sellStopLoss[0];


#if sar crossed above price and close is less than the initial buyStopLoss

def BuyExit = if (ParabolicSAR().SAR crosses above price) or (CLOSE <= buyStopLoss)

then 1

else Double.NaN;

def SellExit = if ParabolicSAR().SAR crosses below price or (CLOSE >= sellStopLoss)

then 1

else Double.NaN;


plot ArrowUp = if (LOW > FastMA) and FastMA > SlowMA and ParabolicSAR().SAR crosses below price

then low

else Double.NaN;

ArrowUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

ArrowUp.SetLineWeight(3);

ArrowUp.SetDefaultColor(Color.GREEN);

plot ArrowDN = if (HIGH > FastMA) and FastMA < SlowMA and ParabolicSAR().SAR crosses above price

then high

else Double.NaN;

ArrowDN.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

ArrowDN.SetLineWeight(3);

ArrowDN.SetDefaultColor(Color.RED);

Alert(ArrowUp, " ", Alert.BAR, Sound.Chimes);

Alert(ArrowDN, " ", Alert.BAR, Sound.Bell);


AddCloud(FastMA, SlowMA, Color.GREEN, Color.RED);

# End Code



def LongEnt = BuySignal is equal to 1;

def ShortEnt = SellSignal is equal to 1 ;

def LongExt = BuyExit is equal to 1;

def ShortExt = SellExit is equal to 1;


AddOrder(OrderType.BUY_TO_OPEN, LongEnt, open[-1], TradeSize, Color.GREEN, Color.GREEN);

AddOrder(OrderType.SELL_TO_CLOSE, LongExt, open[1], TradeSize, Color.RED, Color.RED);

AddOrder(OrderType.SELL_TO_OPEN, ShortEnt, open[-1], TradeSize, Color.ORANGE, Color.ORANGE);

AddOrder(OrderType.BUY_TO_CLOSE, ShortExt, open[1], TradeSize, Color.WHITE, Color.WHITE);

#==============================================


plot LongEntrySignal = if LongEnt then LongEnt else Double.NaN;

LongEntrySignal.SetDefaultColor(Color.UPTICK);

LongEntrySignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


plot LongExitSignal = if LongExt then LongExt else Double.NaN;

LongExitSignal.SetDefaultColor(Color.UPTICK);

LongExitSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


plot ShortEntrySignal = if ShortEnt then ShortEnt else Double.NaN;

ShortEntrySignal.SetDefaultColor(Color.UPTICK);

ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);


plot ShortExitSignal = if ShortExt then ShortExt else Double.NaN;

ShortExitSignal.SetDefaultColor(Color.UPTICK);

ShortExitSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

Thank you for any help.
 
Solution
Hello,

I have been reading this forum for a long time and while I have found what appears to be a solution to my issue, it is not working in my strategy. As the title indicates, I am attempting to set a stop loss at the previous candle's high if going short or at the previous candle's low if going long. This is a P-Sar strategy, not that it makes any difference. I have read several variations of the following:
Code:
# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if BuySignal == 1 then low[1] else buyStopLoss[0];

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if SellSignal == 1 then high[1] else sellStopLoss[0];

...
Hello,

I have been reading this forum for a long time and while I have found what appears to be a solution to my issue, it is not working in my strategy. As the title indicates, I am attempting to set a stop loss at the previous candle's high if going short or at the previous candle's low if going long. This is a P-Sar strategy, not that it makes any difference. I have read several variations of the following:
Code:
# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if BuySignal == 1 then low[1] else buyStopLoss[0];

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if SellSignal == 1 then high[1] else sellStopLoss[0];

...

#if sar crossed above price and close is less than the initial buyStopLoss

def BuyExit = if (ParabolicSAR().SAR crosses above price) or (CLOSE <= buyStopLoss)

then 1

else Double.NaN;

def SellExit = if ParabolicSAR().SAR crosses below price or (CLOSE >= sellStopLoss)

then 1

else Double.NaN;

...

AddOrder(OrderType.SELL_TO_CLOSE, LongExt, open[1], TradeSize, Color.RED, Color.RED);

AddOrder(OrderType.BUY_TO_CLOSE, ShortExt, open[1], TradeSize, Color.WHITE, Color.WHITE);


This is the entire script. I am trying to modify several things in it. This is my first sticking point and I cannot seem to get it right.

Code:
# 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/


# =====================================================

declare upper;

input TradeSize = 10;


input price = close;

input fastLength = 50;

input slowLength = 200;

input displace = 0;

# Using the code from the default Simple Moving Average

# I was able to set the slow/fast moving averages below


plot FastMA = Average(price[-displace], fastLength);

plot SlowMA = Average(price[-displace], slowLength);

FastMA.SetDefaultColor(GetColor(1));

SlowMA.SetDefaultColor(GetColor(2));


# A buy signal is generated if and only if the 2 factors are true, the fastMA is above the slowMA

# and the ParabolicSAR plots below the closing price

# The inverse is also true. A sell signal is generated when the slowMA is above

# the fastMA and the ParabolicSAR plots above the closing price

# The buy exit is generated at the first instance that the ParabolicSAR plots above the close price after the buy signal

# The sell exit is generated at the first instance that the ParabolicSAR plots below the close price after the sell signal


def BuySignal = if (LOW > FastMA) and (FastMA > SlowMA) and (ParabolicSAR().SAR crosses below close)

then 1

else Double.NaN;

def SellSignal = if (HIGH < SlowMA) and (FastMA < SlowMA) and (ParabolicSAR().SAR crosses above close)

then 1

else Double.NaN;


# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if BuySignal == 1 then low[1] else buyStopLoss[0];

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if SellSignal == 1 then high[1] else sellStopLoss[0];


#if sar crossed above price and close is less than the initial buyStopLoss

def BuyExit = if (ParabolicSAR().SAR crosses above price) or (CLOSE <= buyStopLoss)

then 1

else Double.NaN;

def SellExit = if ParabolicSAR().SAR crosses below price or (CLOSE >= sellStopLoss)

then 1

else Double.NaN;


plot ArrowUp = if (LOW > FastMA) and FastMA > SlowMA and ParabolicSAR().SAR crosses below price

then low

else Double.NaN;

ArrowUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

ArrowUp.SetLineWeight(3);

ArrowUp.SetDefaultColor(Color.GREEN);

plot ArrowDN = if (HIGH > FastMA) and FastMA < SlowMA and ParabolicSAR().SAR crosses above price

then high

else Double.NaN;

ArrowDN.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

ArrowDN.SetLineWeight(3);

ArrowDN.SetDefaultColor(Color.RED);

Alert(ArrowUp, " ", Alert.BAR, Sound.Chimes);

Alert(ArrowDN, " ", Alert.BAR, Sound.Bell);


AddCloud(FastMA, SlowMA, Color.GREEN, Color.RED);

# End Code



def LongEnt = BuySignal is equal to 1;

def ShortEnt = SellSignal is equal to 1 ;

def LongExt = BuyExit is equal to 1;

def ShortExt = SellExit is equal to 1;


AddOrder(OrderType.BUY_TO_OPEN, LongEnt, open[-1], TradeSize, Color.GREEN, Color.GREEN);

AddOrder(OrderType.SELL_TO_CLOSE, LongExt, open[1], TradeSize, Color.RED, Color.RED);

AddOrder(OrderType.SELL_TO_OPEN, ShortEnt, open[-1], TradeSize, Color.ORANGE, Color.ORANGE);

AddOrder(OrderType.BUY_TO_CLOSE, ShortExt, open[1], TradeSize, Color.WHITE, Color.WHITE);

#==============================================


plot LongEntrySignal = if LongEnt then LongEnt else Double.NaN;

LongEntrySignal.SetDefaultColor(Color.UPTICK);

LongEntrySignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


plot LongExitSignal = if LongExt then LongExt else Double.NaN;

LongExitSignal.SetDefaultColor(Color.UPTICK);

LongExitSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


plot ShortEntrySignal = if ShortEnt then ShortEnt else Double.NaN;

ShortEntrySignal.SetDefaultColor(Color.UPTICK);

ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);


plot ShortExitSignal = if ShortExt then ShortExt else Double.NaN;

ShortExitSignal.SetDefaultColor(Color.UPTICK);

ShortExitSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

Thank you for any help.

Here are the lines that were changed for stoplosses. Plots of these were added so that you could test your script.

The isnan(close)... extended the lines. The !isnan(...)... was used as the signals were a boolean 1.

Ruby:
# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if IsNaN(close) then buyStopLoss[1] else if !IsNaN(BuySignal) == 1 then low[1] else buyStopLoss[1];

plot xbuystoploss = buyStopLoss;
xbuystoploss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if IsNaN(close) then sellStopLoss[1] else if !IsNaN(SellSignal) then high[1] else sellStopLoss[1];

plot xsellloss = sellStopLoss;
xsellloss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

Here is the entire revised script that has not been thoroughly tested. The orders were revised to more clearly denote buy and sell orders.

Screenshot-2022-10-14-124812.png
Ruby:
# 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/


# =====================================================

declare upper;

input TradeSize = 10;


input price = close;

input fastLength = 50;

input slowLength = 200;

input displace = 0;

# Using the code from the default Simple Moving Average

# I was able to set the slow/fast moving averages below


plot FastMA = Average(price[-displace], fastLength);

plot SlowMA = Average(price[-displace], slowLength);

FastMA.SetDefaultColor(GetColor(1));

SlowMA.SetDefaultColor(GetColor(2));


# A buy signal is generated if and only if the 2 factors are true, the fastMA is above the slowMA

# and the ParabolicSAR plots below the closing price

# The inverse is also true. A sell signal is generated when the slowMA is above

# the fastMA and the ParabolicSAR plots above the closing price

# The buy exit is generated at the first instance that the ParabolicSAR plots above the close price after the buy signal

# The sell exit is generated at the first instance that the ParabolicSAR plots below the close price after the sell signal


def BuySignal = if (low > FastMA) and (FastMA > SlowMA) and (ParabolicSAR().SAR crosses below close)

then 1

else Double.NaN;

def SellSignal = if (high < SlowMA) and (FastMA < SlowMA) and (ParabolicSAR().SAR crosses above close)

then 1

else Double.NaN;


# set stop losses -

#  if the buy signal was set, then set the stop loss to yesterday's low.

def buyStopLoss = if IsNaN(close) then buyStopLoss[1] else if !IsNaN(BuySignal) == 1 then low[1] else buyStopLoss[1];

plot xbuystoploss = buyStopLoss;
xbuystoploss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

#  if the sell signal was set, then set the stop loss to yesterday's high.

def sellStopLoss = if IsNaN(close) then sellStopLoss[1] else if !IsNaN(SellSignal) then high[1] else sellStopLoss[1];

plot xsellloss = sellStopLoss;
xsellloss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

#if sar crossed above price and close is less than the initial buyStopLoss

def BuyExit = if (ParabolicSAR().SAR crosses above price) or (close <= buyStopLoss)

then 1

else Double.NaN;

def SellExit = if ParabolicSAR().SAR crosses below price or (close crosses above sellStopLoss)

then 1

else Double.NaN;


plot ArrowUp = if (low > FastMA) and FastMA > SlowMA and ParabolicSAR().SAR crosses below price

then low

else Double.NaN;

ArrowUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

ArrowUp.SetLineWeight(3);

ArrowUp.SetDefaultColor(Color.GREEN);

plot ArrowDN = if (high > FastMA) and FastMA < SlowMA and ParabolicSAR().SAR crosses above price

then high

else Double.NaN;

ArrowDN.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

ArrowDN.SetLineWeight(3);

ArrowDN.SetDefaultColor(Color.RED);

Alert(ArrowUp, " ", Alert.BAR, Sound.Chimes);

Alert(ArrowDN, " ", Alert.BAR, Sound.Bell);


AddCloud(FastMA, SlowMA, Color.GREEN, Color.RED);

# End Code



def LongEnt = BuySignal is equal to 1;

def ShortEnt = SellSignal is equal to 1 ;

def LongExt = BuyExit is equal to 1;

def ShortExt = SellExit is equal to 1;


AddOrder(OrderType.BUY_TO_OPEN, LongEnt, open[-1], TradeSize, Color.GREEN, Color.GREEN, name = "BO");

AddOrder(OrderType.SELL_TO_CLOSE, LongExt, open[1], TradeSize, Color.RED, Color.RED, name = "SC");

AddOrder(OrderType.SELL_TO_OPEN, ShortEnt, open[-1], TradeSize, Color.ORANGE, Color.ORANGE, name = "SO");

AddOrder(OrderType.BUY_TO_CLOSE, ShortExt, open[1], TradeSize, Color.WHITE, Color.WHITE, name = "BC");

#==============================================


plot LongEntrySignal = if LongEnt then LongEnt else Double.NaN;

LongEntrySignal.SetDefaultColor(Color.UPTICK);

LongEntrySignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


plot LongExitSignal = if LongExt then LongExt else Double.NaN;

LongExitSignal.SetDefaultColor(Color.UPTICK);

LongExitSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


plot ShortEntrySignal = if ShortEnt then ShortEnt else Double.NaN;

ShortEntrySignal.SetDefaultColor(Color.UPTICK);

ShortEntrySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);


plot ShortExitSignal = if ShortExt then ShortExt else Double.NaN;

ShortExitSignal.SetDefaultColor(Color.UPTICK);

ShortExitSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
 
Solution
After looking at this more closely, I don't really understand why some of it is necessary...
if IsNaN(close) then buyStopLoss[1] <- this is basically saying if CLOSE is not a number, correct? Is that ever possible? Why do we need this?

else if !IsNaN(BuySignal) == 1 then low[1] else buyStopLoss[1]; <- if buySignal was set, then get yesterday's low, else use the current value set.

I guess I don't understand entirely how thinkScript operates. For instance, another thing I want to do is not enter the trade until a candle closes above the first upper or lower PSAR dot instead of just jumping into the trade. I thought it would become obvious once I saw this, but I am more confused as to how this all processes. I have a coding background (python, java, c, bash, etc), but the logic in how this loops through the candles and tracks the variables is not apparent to me. I don't feel like the thinkScript doco seems to be in depth enough to answer these questions. Is there another source that you all use to become experts?
 
After looking at this more closely, I don't really understand why some of it is necessary...
if IsNaN(close) then buyStopLoss[1] <- this is basically saying if CLOSE is not a number, correct? Is that ever possible? Why do we need this?

else if !IsNaN(BuySignal) == 1 then low[1] else buyStopLoss[1]; <- if buySignal was set, then get yesterday's low, else use the current value set.

I guess I don't understand entirely how thinkScript operates. For instance, another thing I want to do is not enter the trade until a candle closes above the first upper or lower PSAR dot instead of just jumping into the trade. I thought it would become obvious once I saw this, but I am more confused as to how this all processes. I have a coding background (python, java, c, bash, etc), but the logic in how this loops through the candles and tracks the variables is not apparent to me. I don't feel like the thinkScript doco seems to be in depth enough to answer these questions. Is there another source that you all use to become experts?

I add the isnan(close) as I like the last line to plot to the right edge of the chart in case code for the line does not extend through the expansion area. In this case it appears to not be necessary. The expansion area is the generally known as isnan(close) area.

This site provides many examples that are useful to learn.

There are also many here that have a coding background. I do not. They are an excellent resource and you will see them often helping others. Some of them are: halcyonguy, svanoy, mashume, joshua, pensar, among others.
 

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

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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