helioendo
helioendo

Reputation: 11

turn an indicator to a strategy on trading view

To be honest I have no programming skills and trying to turn an indicator to a strategy in trading view, I want to use the indicator below.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HoanGhetti

//@version=5
indicator("Sushi Trend [HG]", overlay = true)

factor = input.int(defval = 5, title = 'Engulfing Factor')
bullC  = input.color(defval = color.green, title = 'Bull')
bearC  = input.color(defval = color.red, title = 'Bear')
var stMatrix = matrix.new<float>(4, factor)

setMinMax(float value, int row, bool set = false) =>
    bool result = na
    for i = 0 to factor - 1
        if set
            int j = factor + i
            stMatrix.set(0, i, high[i])
            stMatrix.set(1, i, low[i])
            stMatrix.set(2, i, high[j])
            stMatrix.set(3, i, low[j])
        if value == stMatrix.get(row, i)
            result := true
            break
    result

setMinMax(na, na, true)
bool max = setMinMax(stMatrix.max(), 0)
bool min = setMinMax(stMatrix.min(), 1)
bool valid = min and max and (stMatrix.min() == stMatrix.get(1, factor - 1) or stMatrix.max() == stMatrix.get(0,  factor - 1))
bool sushi = valid and ta.barssince(valid[1]) >= factor and barstate.isconfirmed

float lastMax = fixnan(ta.change(sushi) and sushi and max ? stMatrix.max() : na)
float lastMin = fixnan(ta.change(sushi) and sushi ? stMatrix.min() : na)
var int direction = na

if ta.crossover(close, lastMax)
    direction := 1
if ta.crossunder(close, lastMin)
    direction := 0

float sushiTrend = switch direction
    1 => lastMin
    0 => lastMax

color dirColor = direction == 1 ? bullC : bearC
stPlot = plot(sushiTrend, title = 'Sushi Trend', color = not ta.change(direction) ? dirColor : na, linewidth = 3, style = plot.style_linebr)
hlPlot = plot(hl2, display = display.none, editable = false)
fill(stPlot, hlPlot, color.new(dirColor, 90))
plotshape(ta.change(direction) and direction == 1 ? sushiTrend : na, title = 'Bull', style = shape.labelup, color = dirColor, location = location.absolute, text = 'Bull', textcolor = color.white, size = size.tiny)
plotshape(ta.change(direction) and direction == 0 ? sushiTrend : na, title = 'Bear', style = shape.labeldown, color = dirColor, location = location.absolute, text = 'Bear', textcolor = color.white, size = size.tiny)

The criteria are

  1. Bull sign long entry with the stop loss at the trend line and a profit factor 1.5
  2. Bear sign short entry with the stop loss at the trend line and a profit factor 1.5
  3. When in a short/long position and the trend changes close the position

below is the code I was trying to run

//@version=4
strategy("Sushi Trend Strategy", overlay = true)

factor = input(5, title="Engulfing Factor")
bullC = color.new(color.green, 90)
bearC = color.new(color.red, 90)

var float lastMax = na
var float lastMin = na
var int direction = na
var int barsSinceValid = 0
var bool directionChanged = false

setMinMax(value, rowHigh, rowLow, set) =>
    var bool result = na
    for i = 0 to factor - 1
        if set
            j = factor + i
            high_i = security(syminfo.tickerid, "D", value[i])
            low_i = security(syminfo.tickerid, "D", value[j])
            result := true

    result

setMinMax(high, 0, factor, true)
max = setMinMax(high, 0, factor, false)
min = setMinMax(low, 1, factor, false)
valid = min and max and (min == low[factor - 1] or max == high[factor - 1])
sushi = valid and barsSinceValid >= factor

lastMax := na(lastMax) ? (directionChanged and sushi ? high : na) : high
lastMin := na(lastMin) ? (directionChanged and sushi ? low : na) : low

if crossover(close, lastMax)
    direction := 1
    directionChanged := true
if crossunder(close, lastMin)
    direction := 0
    directionChanged := true

sushiTrend = direction == 1 ? lastMin : direction == 0 ? lastMax : na

dirColor = direction == 1 ? bullC : bearC
plot(sushiTrend, title="Sushi Trend", color=dirColor, linewidth=3)

// RSI calculation (You can adjust the parameters accordingly)
rsiLength = input(14, title="RSI Length")
rsiValue = rsi(close, rsiLength)

// Trading conditions
longCondition = crossover(rsiValue, 50) and direction == 1
shortCondition = crossunder(rsiValue, 50) and direction == 0

strategy.entry("Long", strategy.long, when=longCondition)
strategy.entry("Short", strategy.short, when=shortCondition)

// Exit conditions (You can adjust the stop loss and take profit logic accordingly)
stopLossLevel = lowest(low, 5)  // Using the lowest low of the last 5 bars as a simple example, adjust as needed
takeProfitLevel = close + 1.5 * (close - stopLossLevel)

strategy.exit("Take Profit/Stop Loss", from_entry="Long", loss=stopLossLevel, profit=takeProfitLevel)

// Reverse position if trend changes
reverseCondition = directionChanged and ((direction == 0 and crossover(close, sushiTrend)) or (direction == 1 and crossunder(close, sushiTrend)))

strategy.close("Long", when=reverseCondition)
strategy.close("Short", when=reverseCondition)

// Update barsSinceValid
barsSinceValid := sushi ? 0 : barsSinceValid + 1
directionChanged := false

// Debugging Plots
plot(barsSinceValid, title="Bars Since Valid")
plot(directionChanged ? 1 : na, color=color.red, style=plot.style_histogram, title="Direction Changed")

I was able to compile without errors and attach to the chart but the strategy tester give no valid enters.

screenshot example

here's the takeprofit and stoploss example

Stoploss&takeprofit

Upvotes: 1

Views: 119

Answers (1)

Rakesh Poluri
Rakesh Poluri

Reputation: 355

There are several issues here.

First, you changed the indicator code to v4 from v5 and made some unnecessary additions.

Second, your stop loss and take profit were coded somewhat incorrectly and will only trigger for Long Entries, if at all.

Third, in the strategy.exit() function, loss and profit arguments require tick values. The way you coded the stop loss and profit values, you will need to use stop and limit arguments.

I have coded the strategy for v5 and made the corrections, please go through them:

//@version=5
strategy("Sushi Trend Strategy", overlay = true)

factor = input.int(defval = 5, title = 'Engulfing Factor')
bullC  = input.color(defval = color.green, title = 'Bull')
bearC  = input.color(defval = color.red, title = 'Bear')
var stMatrix = matrix.new<float>(4, factor)

setMinMax(float value, int row, bool set = false) =>
    bool result = na
    for i = 0 to factor - 1
        if set
            int j = factor + i
            stMatrix.set(0, i, high[i])
            stMatrix.set(1, i, low[i])
            stMatrix.set(2, i, high[j])
            stMatrix.set(3, i, low[j])
        if value == stMatrix.get(row, i)
            result := true
            break
    result

setMinMax(na, na, true)
bool max = setMinMax(stMatrix.max(), 0)
bool min = setMinMax(stMatrix.min(), 1)
bool valid = min and max and (stMatrix.min() == stMatrix.get(1, factor - 1) or stMatrix.max() == stMatrix.get(0,  factor - 1))
bool sushi = valid and ta.barssince(valid[1]) >= factor and barstate.isconfirmed

float lastMax = fixnan(ta.change(sushi) and sushi and max ? stMatrix.max() : na)
float lastMin = fixnan(ta.change(sushi) and sushi ? stMatrix.min() : na)
var int direction = na

if ta.crossover(close, lastMax)
    direction := 1
if ta.crossunder(close, lastMin)
    direction := 0

float sushiTrend = switch direction
    1 => lastMin
    0 => lastMax

color dirColor = direction == 1 ? bullC : bearC
stPlot = plot(sushiTrend, title = 'Sushi Trend', color = dirColor, linewidth = 3, style = plot.style_linebr)
hlPlot = plot(hl2, display = display.none, editable = false)
fill(stPlot, hlPlot, color.new(dirColor, 90))
plotshape(ta.crossover(ta.change(direction), 0) ? sushiTrend : na, title = 'Bull', style = shape.labelup, color = dirColor, location = location.absolute, text = 'Bull', textcolor = color.white, size = size.tiny)
plotshape(ta.crossunder(ta.change(direction), 0) ? sushiTrend : na, title = 'Bear', style = shape.labeldown, color = dirColor, location = location.absolute, text = 'Bear', textcolor = color.white, size = size.tiny)

// RSI calculation (You can adjust the parameters accordingly)
rsiLength = input(14, title="RSI Length")
rsiValue = ta.rsi(close, rsiLength)

// Trading conditions
longCondition = rsiValue > 50 and ta.crossover(ta.change(direction), 0)
longExitCondition = ta.crossunder(ta.change(direction), 0)
shortCondition = rsiValue < 50 and ta.crossunder(ta.change(direction), 0)
shortExitCondition = ta.crossover(ta.change(direction), 0)

if (longCondition)
    strategy.entry("Long", strategy.long)

// long_stopLossLevel = ta.valuewhen(longCondition, ta.lowest(low, 5), 0)
long_stopLossLevel = ta.valuewhen(longCondition, sushiTrend, 0)
long_price = ta.valuewhen(longCondition, close - long_stopLossLevel, 0)
long_takeProfitLevel = 0.0

if strategy.position_size > 0
    long_takeProfitLevel := strategy.position_avg_price + 1.5 * long_price
    strategy.exit("Take Profit/Stop Loss", from_entry="Long", stop=long_stopLossLevel, limit=long_takeProfitLevel, comment_loss = "Long_Stop", comment_profit = "Long_Profit")

plot(strategy.position_size > 0 ? long_stopLossLevel : na, "", color.red, style = plot.style_linebr)
plot(strategy.position_size > 0 ? long_takeProfitLevel : na, "", color.green, style = plot.style_linebr)

if (longExitCondition)
    strategy.close("Long")

if (shortCondition)
    strategy.entry("Short", strategy.short)

short_stopLossLevel = ta.valuewhen(shortCondition, sushiTrend, 0)
short_price = ta.valuewhen(shortCondition, short_stopLossLevel - close, 0)
short_takeProfitLevel = 0.0

if strategy.position_size < 0
    short_takeProfitLevel := strategy.position_avg_price - 1.5 * short_price
    strategy.exit("Take Profit/Stop Loss", from_entry="Short", stop=short_stopLossLevel, limit=short_takeProfitLevel, comment_loss = "Short_Stop", comment_profit = "Short_Profit")

plot(strategy.position_size < 0 ? short_stopLossLevel : na, "", color.red, style = plot.style_linebr)
plot(strategy.position_size < 0 ? short_takeProfitLevel : na, "", color.green, style = plot.style_linebr)

if (shortExitCondition)
    strategy.close("Short")

Edit 1:

Changed the following code:

longCondition = ta.crossover(rsiValue, 50) and direction == 1
shortCondition = ta.crossunder(rsiValue, 50) and direction == 0

to

longCondition = rsiValue > 50 and direction == 1
shortCondition = rsiValue < 50 and direction == 0

Based on the asker's comment below.


Edit 2:

Changed the following code:

long_stopLossLevel = ta.lowest(low, 5)
short_stopLossLevel = ta.highest(high, 5)

to

long_stopLossLevel = ta.valuewhen(longCondition, ta.lowest(low, 5), 0)
short_stopLossLevel = ta.valuewhen(shortCondition, ta.highest(high, 5), 0)

Edit 3:

Changed Stop Loss and Take Profit Rules

Upvotes: 1

Related Questions