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.