Repaints Trend Following Strategy with Stop Loss and Take Profit For ThinkOrSwim

Repaints

QUIKTDR1

Active member
VIP
Author states: The main idea of the strategy is to determine the direction of long and short based on the price trend.
In an uptrend, it goes long when there is a bullish candlestick pattern.
It takes profit when the price rises to the preset take profit level and stops loss when it falls to the preset stop loss level.
HN8bcte.png

read more: https://medium.com/@FMZQuant/trend-following-strategy-with-stop-loss-and-take-profit-140be022a0ce

Converted ToS indicator below.
 
Last edited by a moderator:
Can this be converted?
https://medium.com/@FMZQuant/trend-following-strategy-with-stop-loss-and-take-profit-140be022a0ce

Strategy source code
Ruby:
/*backtest
start: 2024-01-01 00:00:00
end: 2024-01-24 23:59:59
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]

*/
//@version=5
strategy("Trend Following Strategy with Stop Loss and Take Profit", overlay=true)
// Function to get previous day's close and open

getPrevDayClose() =>
request.security(syminfo.tickerid, "D", close[1])
getPrevDayOpen() =>
request.security(syminfo.tickerid, "D", open[1])

// Determine weekly trend
isUptrend = close > close[1]
isDowntrend = close < close[1]

// Determine daily conditions for buy
buyCondition = getPrevDayClose() > getPrevDayOpen() and getPrevDayOpen() > getPrevDayClose()[1] and isUptrend

// Calculate stop loss and take profit
stopLoss = getPrevDayClose() - 1.382 * (getPrevDayClose() - getPrevDayOpen())
takeProfit = getPrevDayClose() + 2 * (getPrevDayClose() - stopLoss)

// Strategy logic
if (isUptrend)
strategy.entry("Buy", strategy.long, when = buyCondition)
strategy.exit("Take Profit/Stop Loss", from_entry="Buy", loss=stopLoss, profit=takeProfit)

if (isDowntrend)
strategy.entry("Sell", strategy.short)

// Plotting the trend on the chart
plotshape(series=isUptrend, title="Uptrend", color=color.green, style=shape.triangleup, location=location.abovebar)

plotshape(series=isDowntrend, title="Downtrend", color=color.red, style=shape.triangledown, location=location.belowbar)

// Plotting stop loss and take profit levels on the chart
plot(stopLoss, color=color.red, title="Stop Loss", linewidth=2, style=plot.style_cross)

plot(takeProfit, color=color.green, title="Take Profit", linewidth=2, style=plot.style_cross)




Strategy Logic

The strategy first defines the conditions for judging the weekly trend:

isUptrend = close > close[1]

isDowntrend = close < close[1]

If the current close is higher than the previous close, it is judged as an uptrend. Otherwise, it is a downtrend.

Then the intraday trading signal is defined:

buyCondition = getPrevDayClose() > getPrevDayOpen() and getPrevDayOpen() > getPrevDayClose()[1] and isUptrend

That is, the previous close is higher than the previous open (bullish candle), and the previous open is higher than the close before previous day (gap up), and it is in an uptrend. These criteria meet the long entry condition.

After entering the position, the stop loss is set to the previous close minus 1.382 times the previous day’s real body:

stopLoss = getPrevDayClose() - 1.382 * (getPrevDayClose() - getPrevDayOpen())

The take profit is set to the previous close plus 2 times the difference between the previous close and stop loss:

takeProfit = getPrevDayClose() + 2 * (getPrevDayClose() - stopLoss)

This realizes the stop loss and profit taking strategy.
check the below:

CSS:
#//Indicator for TOS
#strategy("Trend Following Strategy with Stop Loss and Take Profit", overlay=true)
# - Converted by Sam4Cok@Samer800    - 07/2024 - Request from useThinkScript.com member
input showSlTpLines = yes;
input timeframe = AggregationPeriod.DAY;
input stopLossMulti = 1.382;
input takeProfitMulti = 2.0;

def na = Double.NaN;
def last = isNaN(close);

def slFact = stopLossMulti;
def tpFact = takeProfitMulti;
#// Function to get previous day's close and open
def getPrevDayCl = if !last then close(Period = timeframe)[1] else getPrevDayCl[1];
def getPrevDayClose = if getPrevDayCl!=getPrevDayCl[1] then getPrevDayCl[1] else getPrevDayClose[1];
def getPrevDayOp = if !last then open(Period = timeframe)[1] else getPrevDayOp[1];
def getPrevDayOpen = if getPrevDayOp!=getPrevDayOp[1] then getPrevDayOp[1] else getPrevDayOpen[1];

#// Determine weekly trend
def isUptrend   = close > close[1];
def isDowntrend = close < close[1];

#// Determine daily conditions for buy
def buyCondition  = getPrevDayClose > getPrevDayOpen and getPrevDayOpen > getPrevDayClose[1] and isUptrend;
def sellCondition = getPrevDayClose < getPrevDayOpen and getPrevDayOpen < getPrevDayClose[1] and isDowntrend;
#// Calculate stop loss and take profit
def stopLoss   = getPrevDayClose - slFact * (getPrevDayClose - getPrevDayOpen);
def takeProfit = getPrevDayClose + tpFact * (getPrevDayClose - stopLoss);
def buyCond;
def sellCond;
def inTrade;

if buyCondition and inTrade[1] <= 0 {
    buyCond = yes;
    sellCond = no;
    inTrade = 1;
} else if sellCondition and inTrade[1] > 0 {
    buyCond = no;
    sellCond = yes;
    inTrade = -1;
} else {
    inTrade = if inTrade[1]>0 then
              if close >= takeProfit or close <= stopLoss then 0 else 1 else
              if inTrade[1]<0 then
              if close <= takeProfit or close >= stopLoss then 0 else -1 else 0;
    buyCond = no;
    sellCond = no;
}
AddChartBubble(buyCond, low, "BUY", Color.GREEN, no);
AddChartBubble(sellCond, high, "SELL", Color.RED);


plot sl = if !last and showSlTpLines and stopLoss then stopLoss else na;
plot tp = if !last and showSlTpLines and takeProfit then takeProfit else na;

sl.SetDefaultColor(Color.MAGENTA);
tp.SetDefaultColor(Color.CYAN);
sl.SetPaintingStrategy(PaintingStrategy.POINTS);
tp.SetPaintingStrategy(PaintingStrategy.POINTS);

#-- END of CODE
 
check the below:

CSS:
#//Indicator for TOS
#strategy("Trend Following Strategy with Stop Loss and Take Profit", overlay=true)
# - Converted by Sam4Cok@Samer800    - 07/2024 - Request from useThinkScript.com member
input showSlTpLines = yes;
input timeframe = AggregationPeriod.DAY;
input stopLossMulti = 1.382;
input takeProfitMulti = 2.0;

def na = Double.NaN;
def last = isNaN(close);

def slFact = stopLossMulti;
def tpFact = takeProfitMulti;
#// Function to get previous day's close and open
def getPrevDayCl = if !last then close(Period = timeframe)[1] else getPrevDayCl[1];
def getPrevDayClose = if getPrevDayCl!=getPrevDayCl[1] then getPrevDayCl[1] else getPrevDayClose[1];
def getPrevDayOp = if !last then open(Period = timeframe)[1] else getPrevDayOp[1];
def getPrevDayOpen = if getPrevDayOp!=getPrevDayOp[1] then getPrevDayOp[1] else getPrevDayOpen[1];

#// Determine weekly trend
def isUptrend   = close > close[1];
def isDowntrend = close < close[1];

#// Determine daily conditions for buy
def buyCondition  = getPrevDayClose > getPrevDayOpen and getPrevDayOpen > getPrevDayClose[1] and isUptrend;
def sellCondition = getPrevDayClose < getPrevDayOpen and getPrevDayOpen < getPrevDayClose[1] and isDowntrend;
#// Calculate stop loss and take profit
def stopLoss   = getPrevDayClose - slFact * (getPrevDayClose - getPrevDayOpen);
def takeProfit = getPrevDayClose + tpFact * (getPrevDayClose - stopLoss);
def buyCond;
def sellCond;
def inTrade;

if buyCondition and inTrade[1] <= 0 {
    buyCond = yes;
    sellCond = no;
    inTrade = 1;
} else if sellCondition and inTrade[1] > 0 {
    buyCond = no;
    sellCond = yes;
    inTrade = -1;
} else {
    inTrade = if inTrade[1]>0 then
              if close >= takeProfit or close <= stopLoss then 0 else 1 else
              if inTrade[1]<0 then
              if close <= takeProfit or close >= stopLoss then 0 else -1 else 0;
    buyCond = no;
    sellCond = no;
}
AddChartBubble(buyCond, low, "BUY", Color.GREEN, no);
AddChartBubble(sellCond, high, "SELL", Color.RED);


plot sl = if !last and showSlTpLines and stopLoss then stopLoss else na;
plot tp = if !last and showSlTpLines and takeProfit then takeProfit else na;

sl.SetDefaultColor(Color.MAGENTA);
tp.SetDefaultColor(Color.CYAN);
sl.SetPaintingStrategy(PaintingStrategy.POINTS);
tp.SetPaintingStrategy(PaintingStrategy.POINTS);

#-- END of CODE
TY u are the man!!!
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
543 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

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

Frequently Asked Questions

What is useThinkScript?

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

How do I get started?

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

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

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