Breakeven stop loss after TP1 is reached

Viewed 119

I want to add breakeven stop loss. Basically, there are TP1, TP2 and TP3 (3 exits). When TP1 is reached, it should set the stop loss at the entry position, but it doesn't.

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

//@version=5
strategy("Easy Algo Cloud strategy", overlay=true, initial_capital=1000, currency=currency.USD, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, precision=2, commission_type=strategy.commission.percent, commission_value=0.1000)

//Moving Average Type Input
ema = "EMA"
sma = "SMA"
hma = "HMA"
vwma = "VWMA"
wma = "WMA"
rma = "RMA"

//Fill Color Variables
greenFill = #4caf5010
redFill = #ff525210
var string TPG = "TPS entry +- atr * multiplier * atrRiskInput"
var string RM = "Risk management"
float   i_tp1Quantity       = input.float(33, "Take Profit #1 Quantity", minval = 0.0, step = 1.0, group= TPG)
float   i_tp2Quantity       = input.float(33, "Take Profit #2 Quantity", minval = 0.0, step = 1.0, group= TPG)
float   i_tp3Quantity       = input.float(100, "Take Profit #3 Quantity", minval = 0.0, step = 1.0, group= TPG)
float   i_tp1Multiplier     = input.float(1, "Take Profit #1 Multiplier", minval = 0.0, step = 0.1, group = TPG)
float   i_tp2Multiplier     = input.float(2, "Take Profit #2 Multiplier", minval = 0.0, step = 0.1, group = TPG)
float   i_tp3Multiplier     = input.float(3, "Take Profit #3 Multiplier", minval = 0.0, step = 0.1, group = TPG)
float   i_slMultiplier     = input.float(1, "Stop Loss Multiplier", minval = 0.0, step = 0.1, group = TPG)

bool tpSlSwitchInput = input.bool(true, "TL/SL Levels?", group=RM)
int atrLengthInput = input.int(14, "ATR Length", group=RM)
int atrRiskInput = input.int(2, "ATR / Risk", group=RM)

//Length, Source & Color Inputs
source = input.source(close, title="Moving Average Source", group="Moving Average Source")
ma1On = input.bool(true, title="Turn MA #1 On/Off", group="Moving Average #1")
maChoice1 = input.string("EMA", title="Type of MA #1", options=[ema, sma, hma, vwma, wma, rma], group="Moving Average #1")
length1 = input.int(16, title="Moving Average #1 Length", group="Moving Average #1")
ma1Linewidth = input.int(1, title="MA #1 Linewidth", group="Moving Average #1")
ma1Color1 = input.color(color.green, title="Line #1 Color Price Above", group="Moving Average #1")
ma1Color2 = input.color(color.red, title="Line #1 Color Price Below", group="Moving Average #1")
ma1Fill1 = input.color(greenFill, title="Line #1 Color Fill Price Above", group="Moving Average #1")
ma1Fill2 = input.color(redFill, title="Line #1 Color Fill Price Below", group="Moving Average #1")

ma2On = input.bool(true, title="Turn MA #2 On/Off", group="Moving Average #2")
maChoice2 = input.string("EMA", title="Type of MA #2", options=[ema, sma, hma, vwma, wma, rma], group="Moving Average #2")
length2 = input.int(28, title="Moving Average #2 Length", group="Moving Average #2")
ma2Linewidth = input.int(1, title="MA #2 Linewidth", group="Moving Average #2")
ma2Color1 = input.color(color.green, title="Line #2 Color Price Above", group="Moving Average #2")
ma2Color2 = input.color(color.red, title="Line #2 Color Price Below", group="Moving Average #2")
ma2Fill1 = input.color(greenFill, title="Line #2 Color Fill Price Above", group="Moving Average #2")
ma2Fill2 = input.color(redFill, title="Line #2 Color Fill Price Below", group="Moving Average #2")

ma3On = input.bool(true, title="Turn MA #3 On/Off", group="Moving Average #3")
maChoice3 = input.string("EMA", title="Type Of MA #3", options=[ema, sma, hma, vwma, wma, rma], group="Moving Average #3")
length3 = input.int(40, title="Moving Average #3 Length", group="Moving Average #3")
ma3Linewidth = input.int(2, title="MA #3 Linewidth", group="Moving Average #3")
ma3Color1 = input.color(color.green, title="Line #3 Color Price Above", group="Moving Average #3")
ma3Color2 = input.color(color.red, title="Line #3 Color Price Below", group="Moving Average #3")
ma3Fill1 = input.color(greenFill, title="Line #3 Color Fill Price Above", group="Moving Average #3")
ma3Fill2 = input.color(redFill, title="Line #3 Color Fill Price Below", group="Moving Average #3")

//Moving Average Type Logic
ma1 = 0.0
ma2 = 0.0
ma3 = 0.0

if maChoice1 == ema
    if ma1On
        ma1 := ta.ema(source, length1)
    else
        ma1 := na
if maChoice2 == ema
    if ma2On
        ma2 := ta.ema(source, length2)
    else
        ma2 := na
if maChoice3 == ema
    if ma3On
        ma3 := ta.ema(source, length3)
    else
        ma3 := na

if maChoice1 == sma
    if ma1On
        ma1 := ta.sma(source, length1)
    else
        ma1 := na
if maChoice2 == sma
    if ma2On
        ma2 := ta.sma(source, length2)
    else
        ma2 := na
if maChoice3 == sma
    if ma3On
        ma3 := ta.sma(source, length3)
    else
        ma3 := na

if maChoice1 == hma
    if ma1On
        ma1 := ta.hma(source, length1)
    else
        ma1 := na
if maChoice2 == hma
    if ma2On
        ma2 := ta.hma(source, length2)
    else
        ma2 := na
if maChoice3 == hma
    if ma3On
        ma3 := ta.hma(source, length3)
    else
        ma3 := na

if maChoice1 == wma
    if ma1On
        ma1 := ta.wma(source, length1)
    else
        ma1 := na
if maChoice2 == wma
    if ma2On
        ma2 := ta.wma(source, length2)
    else
        ma2 := na
if maChoice3 == wma
    if ma3On
        ma3 := ta.wma(source, length3)
    else
        ma3 := na

if maChoice1 == vwma
    if ma1On
        ma1 := ta.vwma(source, length1)
    else
        ma1 := na
if maChoice2 == vwma
    if ma2On
        ma2 := ta.vwma(source, length2)
    else
        ma2 := na
if maChoice3 == vwma
    if ma3On
        ma3 := ta.vwma(source, length3)
    else
        ma3 := na

if maChoice1 == rma
    if ma1On
        ma1 := ta.rma(source, length1)
    else
        ma1 := na
if maChoice2 == rma
    if ma2On
        ma2 := ta.rma(source, length2)
    else
        ma2 := na
if maChoice3 == rma
    if ma3On
        ma3 := ta.rma(source, length3)
    else
        ma3 := na

//Candle Moving Average For Fills
candleLine = ta.sma(close, 1)
candles = plot(candleLine, title="Candle Line 1:1", color=#00000000)

//Line Plots
plotLine1 = plot(ma1, title="MA #1", color=close > ma1 ? ma1Color1 : ma1Color2, linewidth=ma1Linewidth, style=plot.style_line)
plotLine2 = plot(ma2, title="MA #2", color=close > ma2 ? ma2Color1 : ma2Color2, linewidth=ma2Linewidth, style=plot.style_line)
plotLine3 = plot(ma3, title="MA #3", color=close > ma3 ? ma3Color1 : ma3Color2, linewidth=ma3Linewidth, style=plot.style_line)

//Color Fills
fill(candles, plotLine1, color=close > ma1 ? ma1Fill1 : ma1Fill2, title="MA #1")
fill(candles, plotLine2, title="MA #2", color=close > ma2 ? ma2Fill1 : ma2Fill2)
// fill(candles, plotLine3, title="MA #3", color=close > ma3 ? ma3Fill1 : ma3Fill2)
fill(plotLine2, plotLine3, title="MA #3", color=close > ma3 ? color.green : color.red)

//Price Difference Calculations
priceDiffMa1 = 0.0
if close > ma1
    priceDiffMa1 := (close - ma1) / close * 100
if close < ma1
    priceDiffMa1 := (ma1 - close) / ma1 * 100
    
priceDiffMa2 = 0.0
if close > ma2
    priceDiffMa2 := (close - ma2) / close * 100
if close < ma2
    priceDiffMa2 := (ma2 - close) / ma2 * 100
    
priceDiffMa3 = 0.0
if close > ma3
    priceDiffMa3 := (close - ma3) / close * 100
if close < ma3
    priceDiffMa3 := (ma3 - close) / ma3 * 100
    
//Percentage Text
percentFromMa1 = str.tostring(priceDiffMa1, format.percent) + " From " + str.tostring(maChoice1) + " " + str.tostring(length1)
percentFromMa2 = str.tostring(priceDiffMa2, format.percent) + " From " + str.tostring(maChoice2) + " " + str.tostring(length2)
percentFromMa3 = str.tostring(priceDiffMa3, format.percent) + " From " + str.tostring(maChoice3) + " " + str.tostring(length3)

//Remove Percentage Text When MA Is Turned Off
if ma1On == false
    percentFromMa1 := na
if ma2On == false
    percentFromMa2 := na
if ma3On == false
    percentFromMa3 := na
 
//Shapes
bool buySignal = ta.crossover(ma1, ma2)
bool sellSignal = ta.crossunder(ma1, ma2)
plotshape(buySignal, style = shape.labelup, location = location.belowbar, color = color.new(color.green, 20), text = "BUY", textcolor = color.white, size = size.normal)
plotshape(sellSignal, style = shape.labeldown, location = location.abovebar, color = color.new(color.red, 20), text = "SELL", textcolor = color.white, size = size.normal)

// RISK MANAGEMENT
printLabel(float _y, string _text, color _color) =>
    var int labelOffset = 4
    var barSize = time_close - time
    
    var label _lbl = label.new(na, na, na, xloc.bar_time, yloc.price, color(na), label.style_label_left, color.white, size.normal, text.align_left)
    var line _ln = line.new(na, na, na, na, xloc.bar_index, extend.none, color(na), line.style_solid, 1)
    
    if barstate.islast and not na(_y)
        label.set_xy(_lbl, time + labelOffset * barSize, _y)
        label.set_text(_lbl, _text)
        label.set_color(_lbl, _color)
        
        line.set_xy1(_ln, bar_index, _y)
        line.set_xy2(_ln, bar_index + 4, _y)
        line.set_color(_ln, _color)
    
    int(na)

calculateRR(float entry, float  multiplier, bool plusSign) =>
    float atr = ta.atr(atrLengthInput)
    
    if plusSign
        entry + atr * multiplier * atrRiskInput
    else
        entry - atr * multiplier * atrRiskInput

//float entry = close
//float tp1 = calculateRR(entry, 1, true)
//float tp2 = calculateRR(entry, 2, true)
//float tp3 = calculateRR(entry, 3, true)
//float tp4 = calculateRR(entry, 4, true)
//float sl = calculateRR(entry, 1, false)
//
//if tpSlSwitchInput
//    printLabel(tp1, str.format("1:1 TP {0,number,#.##}", tp1), color.green)
//    printLabel(tp2, str.format("2:1 TP {0,number,#.##}", tp2), color.green)
//    printLabel(tp3, str.format("3:1 TP {0,number,#.##}", tp3), color.green)
//    printLabel(tp4, str.format("4:1 TP {0,number,#.##}", tp4), color.green)
//    printLabel(entry, str.format("ENTRY {0,number,#.##}", entry), color.gray)
//    printLabel(sl, str.format("SL {0,number,#.##}", sl), color.red)


// —————————— Strategy Calculations {
// ————— States
var float entryPrice = na
var bool inLong = false
var bool inShort = false
bool inTrade = inLong or inShort

// ————— Conditions
buyCondition = buySignal
enterLongCondition = not buyCondition[1] and buyCondition
sellCondition = sellSignal
enterShortCondition = not sellCondition[1] and sellCondition
exitLongCondition = enterShortCondition
exitShortCondition = enterLongCondition


// ————— States continuation
var float tp1 = na
var float tp2 = na
var float tp3 = na
var float sl = na

// TODO: Refactor this
float tp1Buy = calculateRR(close, i_tp1Multiplier, true)
float tp2Buy = calculateRR(close, i_tp2Multiplier, true)
float tp3Buy = calculateRR(close, i_tp3Multiplier, true)
float slBuy = calculateRR(close, i_slMultiplier, false)

float tp1Sell = calculateRR(close, i_tp1Multiplier, false)
float tp2Sell = calculateRR(close, i_tp2Multiplier, false)
float tp3Sell = calculateRR(close, i_tp3Multiplier, false)
float slSell = calculateRR(close, i_slMultiplier, true)

if enterLongCondition
    inLong := true
    entryPrice := close
    tp1 := tp1Buy
    tp2 := tp2Buy
    tp3 := tp3Buy
    sl := slBuy
else if enterShortCondition
    inShort := true
    entryPrice := close
    tp1 := tp1Sell
    tp2 := tp2Sell
    tp3 := tp3Sell
    sl := slSell
else if exitLongCondition
    inLong := false
    entryPrice := na
    tp1 := na
    tp2 := na
    tp3 := na
    sl := na
else if exitShortCondition
    inShort := false
    entryPrice := na
    tp1 := na
    tp2 := na
    tp3 := na
    sl := na

//if tpSlSwitchInput
//printLabel(tp1, str.format("1:1 TP {0,number,#.##}", tp1), color.green)
//printLabel(tp2, str.format("2:1 TP {0,number,#.##}", tp2), color.green)
printLabel(tp3, str.format("3:1 TP {0,number,#.##}", tp3), color.green)
printLabel(entryPrice, str.format("ENTRY {0,number,#.##}", entryPrice), color.gray)
//printLabel(sl, str.format("SL {0,number,#.##}", sl), color.red)

// DEGREES
var int x1 = 0
var float y1 = 0
if (enterLongCondition or enterShortCondition)
    x1 := bar_index
    y1 := ma3
    
float xDelta = (bar_index-x1)
float yDelta = (ma3-y1)
plotchar(xDelta, color=color.new(color.purple, 100))
plotchar(y1, color=color.new(color.blue, 100))
degreesRadians = math.atan(yDelta/xDelta)
degrees = degreesRadians * 180 / math.pi
plotchar(degrees, color=color.new(color.white, 100))

// ENTRIES
strategy.entry("BUY", strategy.long, when = enterLongCondition, stop=sl)
strategy.close("BUY", when = exitLongCondition)

strategy.exit("TP1", "BUY", limit = tp1, qty_percent = i_tp1Quantity)
strategy.exit("TP2", "BUY", limit = tp2, qty_percent = i_tp2Quantity)
strategy.exit("TP3", "BUY", limit = tp3)

strategy.entry("SELL", strategy.short, when = enterShortCondition, stop=sl)
strategy.close("SELL", when = exitShortCondition)
    
strategy.exit("TP1", "SELL", limit = tp1, qty_percent = i_tp1Quantity)
strategy.exit("TP2", "SELL", limit = tp2, qty_percent = i_tp2Quantity)
strategy.exit("TP3", "SELL", limit = tp3)

// TEST
// bool isTP1BuyCrossed = inLong and ta.crossover(close, tp1)
// bool isTP1SellCrossed = inShort and ta.crossunder(close, tp1)
// //strategy.exit("BE", "BUY", stop = entryPrice, when = isTP1BuyCrossed)
// if (isTP1BuyCrossed)
//     strategy.exit("BE", "BUY", stop = entryPrice)
// else if (isTP1SellCrossed)
//     strategy.exit("BE", "SELL", stop = entryPrice)

// plotchar(isTP1BuyCrossed,  color=color.new(color.yellow, 100))
// plotchar(entryPrice, color=color.new(color.yellow, 100))
// plotchar(tp1, color=color.new(color.green, 100))
// plotchar(tp2, color=color.new(color.green, 100))
// plotchar(tp3, color=color.new(color.green, 100))
// plotchar(sl, color=color.new(color.red, 100))
// }
0 Answers
Related