Stop loss and multi take profits

Viewed 26

I am working with strategy and try to used 3 difference indicators for stop loss and multi take profits

stop loss not work every time also multi take profits take the profits in the same time

i used 15m time frame with Crypto trading ,, for example AVAXBUSD loss 9% in Sep/14

Please how i can fix it Thank you ..


//@version=5
strategy('22.9 good', overlay=true ,
         default_qty_type=strategy.percent_of_equity,
         default_qty_value=100,initial_capital=100,
         commission_type=strategy.commission.percent,
         commission_value=0.01,
         process_orders_on_close = false,
         calc_on_order_fills=false,
         use_bar_magnifier = false)
//=============================================================
// Main Input

market           =  syminfo.tickerid 
f_sec(_market, _Timeframe, _exp) => request.security(_market, _Timeframe, _exp[barstate.isconfirmed ? 0 : 1])
//=============================================================
// TIME

usefromDate      = input.bool(defval = true, title = 'From', inline = "From Date")//, group = "Filters")
fromDate         = input.time(defval = timestamp('01 July 2022 23:59 UTC'), title = '', inline = "From Date")//, group = 'Filters')
usetoDate        = input.bool(defval = false,title = 'To  ', inline = "To Date")//, group = "Filters")
toDate           = input.time(defval = timestamp('31 Dec  2122 23:59 UTC'), title = '', inline = "To Date")//, group = 'Filters')
isWithinPeriod() =>
    (usefromDate ? time >= fromDate : true) and (usetoDate ? time <= toDate : true) // create function "within window of time"
    
Timeframe        = input.timeframe("15", "Timeframe", inline = "From Date 1")//, group = 'Filters')

//===================================================================================================================================
//Trend EMA

len1             = input.int   (title="EMA"       , defval=23   ,inline="MA #2", group="Input")
src1             = input.source(title="Source EMA", defval=low,inline="MA #2", group="Input", tooltip=" A = 20 close , B = 23 low , C = 130 low")
out1             = ta.ema(src1, len1)
ema10            = (out1 > out1[1])
ema01            = (out1 < out1[1])
out1color1       = close > out1 ? color.green : #e91e63
//plot(out1, title = "EMA", color=color.new(out1color1, 25), linewidth=2)


//===================================================================================================================================
//Trend HMA

len6             = input.int(title="HMA", defval=100      ,inline="MA #2", group="Input")
src6             = input.source(title=" EMA", defval=close,inline="MA #2", group="Input", tooltip=" ALL = 100 close ")
hma              = ta.wma(2*ta.wma(src6, len6/2)-ta.wma(src6, len6), math.floor(math.sqrt(len6)))
hmacolor         = close > hma ? #00bcd4 : #e91e63
hmau             = close > hma 
hmad             = close < hma 
//plot(hma, title  = "HMA", color=color.new(hmacolor, 25), linewidth=2)

//===================================================================================================================================
//Bollinger Bands

BBlength        = input.int   (defval=200   ,title="Boll"        ,inline="MA #2", group="Input")
priceBB         = input.source(defval=close ,title="Source Boll" ,inline="MA #2", group="Input", tooltip=" ALL = 200 closee")
BBbasis         = ta.sma(priceBB , BBlength)
//plot(BBbasis, color=color.fuchsia,title="Bollinger Bands SMA Basis Line")

//===================================================================================================================================
//Trend 2MA

wicks = true
highlightState   = true
ma(source, length, type) =>
    type  == "SMA"        ? ta.sma(source, length) :
     type == "EMA"        ? ta.ema(source, length) :
     type == "SMMA (RMA)" ? ta.rma(source, length) :
     type == "WMA"        ? ta.wma(source, length) :
     type == "VWMA"       ? ta.vwma(source,length) :
     na

show_ma1         = input       (true        ,"MA High" ,inline="MA #7", group="Trend 2MA")
ma1_type         = input.string("SMMA (RMA)", ""       ,inline="MA #7", group="Trend 2MA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma1_source       = input       (low        , ""       ,inline="MA #7", group="Trend 2MA")
ma1_length       = input.int   (6           , ""       ,inline="MA #7", group="Trend 2MA", tooltip=" ALL = EMA 200 high ")
ma1_color    = input       (color.green , ""       ,inline="MA #7", group="Trend 2MA")
ma1              = ma          (ma1_source   , ma1_length , ma1_type)

show_ma2         = input       (true        ,"MA Low"  ,inline="MA #7", group="Trend 2MA")
ma2_type         = input.string("SMMA (RMA)", ""       ,inline="MA #7", group="Trend 2MA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma2_source       = input       (high       , ""       ,inline="MA #7", group="Trend 2MA")
ma2_length       = input.int   (1           , ""       ,inline="MA #7", group="Trend 2MA", tooltip=" A = EMA 1 open , B = EMA 1 hlc3 , C = EMA 1 Close ")
ma2_color    = input       (color.red   , ""       ,inline="MA #7", group="Trend 2MA")
ma2              = ma          (ma2_source   , ma2_length , ma2_type )

Hlv1             = float(na)
Hlv1            := (wicks ? high : close) > ma1 ? 1 : (wicks ? low : close) < ma2 ? -1 : Hlv1[1]
sslUp1           = Hlv1 < 0 ? ma2 : ma1
sslDown1         = Hlv1 < 0 ? ma1 : ma2

Color1           = Hlv1 == 1 ? ma1_color : ma2_color
fillColor1       = highlightState ? (color.new(Color1, 90)) : na

// highLine1        = plot(show_ma1 ? sslUp1   : na, title="ma1"  , linewidth=2, color=color.new(color.yellow, 90))
// lowLine1         = plot(show_ma2 ? sslDown1 : na, title="ma2"  , linewidth=2, color=color.new(color.blue, 90))

ma1color         = close > ma1 ? color.yellow : #e91e63
ma2color         = close > ma2 ? color.blue   : #e91e63

//fill(highLine1, lowLine1, color = fillColor1)
// plot(ma1, title="ma1", color=color.new(ma1color, 25), linewidth=2)
// plot(ma2, title="ma2", color=color.new(ma2color, 25), linewidth=2)

show_ma3         = input       (true        ,"MA High" ,inline="MA #8", group="Trend 2MA")
ma3_type         = input.string("SMMA (RMA)", ""       ,inline="MA #8", group="Trend 2MA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma3_source       = input       (low        , ""       ,inline="MA #8", group="Trend 2MA")
ma3_length       = input.int   (200         , ""       ,inline="MA #8", group="Trend 2MA", tooltip=" ALL = EMA 200 high ")
ma3_color    = input       (color.green , ""       ,inline="MA #8", group="Trend 2MA")
ma3              = ma          (ma3_source   , ma3_length , ma3_type)

show_ma4         = input       (true        ,"MA Low"  ,inline="MA #8", group="Trend 2MA")
ma4_type         = input.string("SMMA (RMA)", ""       ,inline="MA #8", group="Trend 2MA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma4_source       = input       (high       , ""       ,inline="MA #8", group="Trend 2MA")
ma4_length       = input.int   (1           , ""       ,inline="MA #8", group="Trend 2MA", tooltip=" A = EMA 1 open , B = EMA 1 hlc3 , C = EMA 1 Close ")
ma4_color    = input       (color.red   , ""       ,inline="MA #8", group="Trend 2MA")
ma4              = ma          (ma4_source   , ma4_length , ma4_type )

Hlv2             = float(na)
Hlv2            := (wicks ? high : close) > ma3 ? 1 : (wicks ? low : close) < ma4 ? -1 : Hlv2[1]
sslUp2           = Hlv2 < 0 ? ma4 : ma3
sslDown2         = Hlv2 < 0 ? ma3 : ma4

Color2           = Hlv2 == 1 ? ma3_color : ma4_color
fillColor2       = highlightState ? (color.new(Color2, 90)) : na

// highLine2        = plot(show_ma3 ? sslUp2   : na, title="ma3"  , linewidth=2, color=color.new(color.yellow, 90))
// lowLine2         = plot(show_ma4 ? sslDown2 : na, title="ma4"  , linewidth=2, color=color.new(color.blue, 90))

ma3color         = close > ma3 ? color.yellow : #e91e63
ma4color         = close > ma4 ? color.blue   : #e91e63

//fill(highLine2, lowLine2, color = fillColor2)
// plot(ma3, title="ma3", color=color.new(ma3color, 25), linewidth=2)
// plot(ma4, title="ma4", color=color.new(ma4color, 25), linewidth=2)


show_ma5         = input       (true        ,"MA High" ,inline="MA #0", group="Trend 2MA")
ma5_type         = input.string("EMA"       , ""       ,inline="MA #0", group="Trend 2MA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma5_source       = input       (high        , ""       ,inline="MA #0", group="Trend 2MA")
ma5_length       = input.int   (200         , ""       ,inline="MA #0", group="Trend 2MA", tooltip=" ALL = EMA 200 high ")
ma5_color    = input       (color.green , ""       ,inline="MA #0", group="Trend 2MA")
ma5              = ma          (ma5_source   , ma5_length , ma5_type)

show_ma6         = input       (true        ,"MA Low"  ,inline="MA #0", group="Trend 2MA")
ma6_type         = input.string("EMA"       , ""       ,inline="MA #0", group="Trend 2MA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma6_source       = input       (hlc3       , ""       ,inline="MA #0", group="Trend 2MA")
ma6_length       = input.int   (1           , ""       ,inline="MA #0", group="Trend 2MA", tooltip=" A = EMA 1 open , B = EMA 1 hlc3 , C = EMA 1 Close ")
ma6_color    = input       (color.red   , ""       ,inline="MA #0", group="Trend 2MA")
ma6              = ma          (ma6_source   , ma6_length , ma6_type )

Hlv3             = float(na)
Hlv3            := (wicks ? high : close) > ma5 ? 1 : (wicks ? low : close) < ma6 ? -1 : Hlv3[1]
sslUp3           = Hlv3 < 0 ? ma6 : ma5
sslDown3         = Hlv3 < 0 ? ma5 : ma6

Color3           = Hlv3 == 1 ? ma5_color : ma6_color
fillColor3       = highlightState ? (color.new(Color3, 90)) : na

// highLine3        = plot(show_ma5 ? sslUp3   : na, title="ma5", linewidth=2, color=color.new(color.yellow, 90))
// lowLine3         = plot(show_ma6 ? sslDown3 : na, title="ma6", linewidth=2, color=color.new(color.blue, 90))

ma5color         = close > ma5 ? color.yellow : #e91e63
ma6color         = close > ma6 ? color.blue   : #e91e63

//fill(highLine3, lowLine3, color = fillColor3)
// plot(ma5, title="ma5", color=color.new(ma5color, 25), linewidth=2)
// plot(ma6, title="ma6", color=color.new(ma6color, 25), linewidth=2)

//===================================================================================================================================
//Take Profits
takepercent     = true
takemtf         = true

percent(pcnt) =>
    strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
TP1             =3
TP2             =5
TP3             =8
TP4             =10

SL              =input(2,inline="MA #19", group="Take Profits")
qty1            =input(5,inline="MA #19", group="Take Profits")
qty2            =input(5,inline="MA #19", group="Take Profits")
qty3            =input(5,inline="MA #19", group="Take Profits")
qty4            =input(5,inline="MA #19", group="Take Profits")
lossSTL         = percent(SL)

ema_len1        =input(10,inline="MA #19", group="Take Profits")
ema_len2        =input(300,inline="MA #19", group="Take Profits")
srct            = close
tf1             = '5'
tf2             = '15'
htf_ma1         = ta.ema(srct, ema_len1)
htf_ma2         = ta.ema(srct, ema_len2)
ema1t           = f_sec(market, tf1, htf_ma1)
ema2t           = f_sec(market, tf1, htf_ma2)
ema3t           = f_sec(market, tf2, htf_ma1)
ema4t           = f_sec(market, tf2, htf_ma2)

//Set up take profit multi timeframe
a               = array.from((ema1t), (ema2t), (ema3t), (ema4t))
tpmtf1          = array.min(a)
tpmtf2          = array.min(a, 2)
tpmtf3          = array.min(a, 3)
tpmtf4          = array.min(a, 4)

// //Set up exit
long_sl_lv      = strategy.position_avg_price - lossSTL*syminfo.mintick



//plot(strategy.position_size > 0 ? long_sl_lv : na, color=color.red, style=plot.style_linebr, title="SL Long")

//===================================================================================================================================
//limit

var limitb      = input(true,inline="MA #1", group="Strategy")
limits          = input(true, inline="MA #1", group="Strategy")
lvl1            = input.float(0.1,inline="MA #11", group="limit")
lvl2            = input.float(0.1,inline="MA #11", group="limit")
Timeframe2      = "D"
daily_atr_len   =input.int(15,inline="MA #11", group="limit",tooltip="ALL = 15 ")
atr_func        = ta.atr(daily_atr_len)
day_atr         = f_sec(market, Timeframe2, atr_func)
day_close       = f_sec(market, Timeframe2, close)

// day_atr         = request.security(syminfo.tickerid, Timeframe2, atr_func)
// day_close       = request.security(syminfo.tickerid, Timeframe2, close)

// p05 = plot( day_close + day_atr   * lvl1, color=color.new(color.red, 0)) 
// m05 = plot( day_close - day_atr/2 * lvl2, color=color.yellow)            
upl = limitb ? close > (day_close + day_atr   * lvl1) and isWithinPeriod()    : isWithinPeriod()
dnl = limits ? close < (day_close - day_atr/2 * lvl2) and isWithinPeriod()    : isWithinPeriod()
//fill(m05, p05, color=color.new(color.yellow, 90))


//===================================================================================================================================
//===================================================================================================================================
//Stop-Take Profit

stooop         = input(0.98)
bool openLongPosition = (isWithinPeriod() )
bool longIsActive     = openLongPosition or strategy.position_size > 0
longTakeProfitPerc    = input(2) / 100
enableTrailing        = true
trailingTakeProfit    = input(2) / 100
float longTakeProfitPrice = na
longTakeProfitPrice := if longIsActive
    if openLongPosition and not (strategy.position_size > 0)
        close * (1 + longTakeProfitPerc)
    else
        nz(longTakeProfitPrice[1], close * (1 + longTakeProfitPerc))
else
    na

longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfit / syminfo.mintick
var takeProfitColor = color.new(#419388, 0) 

//=============================================================
//strategy('Hammers & Stars Strategy [v1.1]', shorttitle='HSS[v1.1]', overlay=true)
// Strategy Settings
var g_strategy = 'Strategy Settings'
atrMinFilterSize = input.float(title='>= ATR Filter', defval=5, minval=0.0, group=g_strategy, inline="16", tooltip='Minimum size of entry candle compared to ATR')
atrMaxFilterSize = input.float(title='<= ATR Filter', defval=5, minval=0.0, group=g_strategy, inline="16", tooltip='Maximum size of entry candle compared to ATR')
stopMultiplier = input.float(title='Stop Loss ATR', defval=0.5, group=g_strategy, inline="16", tooltip='Stop loss multiplier (x ATR)')
rr = input.float(title='R:R', defval=5, group=g_strategy, inline="16", tooltip='Risk:Reward profile')
fibLevel = input.float(title='Fib Level', defval=0.333, group=g_strategy, inline="16", tooltip='Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)')

// Get indicator values
atr = ta.atr(14)

// Custom function to convert pips into whole numbers
toWhole(number) =>
    return_1 = atr < 1.0 ? number / syminfo.mintick / (10 / syminfo.pointvalue) : number
    return_1 := atr >= 1.0 and atr < 100.0 and syminfo.currency == 'JPY' ? return_1 * 100 : return_1
    return_1

// Custom function to convert whole numbers back into pips
toPips(number) =>
    return_2 = atr >= 1.0 ? number : number * syminfo.mintick * (10 / syminfo.pointvalue)
    return_2 := atr >= 1.0 and atr < 100.0 and syminfo.currency == 'JPY' ? return_2 / 100 : return_2
    return_2

// Custom function to truncate (cut) excess decimal places
truncate(_number, _decimalPlaces) =>
    _factor = math.pow(10, _decimalPlaces)
    int(_number * _factor) / _factor

// Check ATR filter
atrMinFilter = math.abs(high - low) >= atrMinFilterSize * atr or atrMinFilterSize == 0.0
atrMaxFilter = math.abs(high - low) <= atrMaxFilterSize * atr or atrMaxFilterSize == 0.0
atrFilter = atrMinFilter and atrMaxFilter

// Calculate 33.3% fibonacci level for current candle
bullFib = (low - high) * fibLevel + high
bearFib = (high - low) * fibLevel + low

// Determine which price source closes or opens highest/lowest
lowestBody = close < open ? close : open
highestBody = close > open ? close : open

// Determine if we have a valid setup
validHammer = lowestBody >= bullFib and atrFilter and close != open and not na(atr) //and emaFilterLong
validStar = highestBody <= bearFib and atrFilter and close != open and not na(atr) //and emaFilterShort

// Check if we have confirmation for our setup
validLong = validHammer and strategy.position_size == 0 and barstate.isconfirmed
validShort = validStar and strategy.position_size == 0  and barstate.isconfirmed

// Calculate our stop distance & size for the current bar
stopSize = atr * stopMultiplier
longStopPrice = low < low[1] ? low - stopSize : low[1] - stopSize
longStopDistance = close - longStopPrice
longTargetPrice = close + longStopDistance * rr

// Save trade stop & target & position size if a valid setup is detected
var t_stop = 0.0
var t_target = 0.0

// // Detect valid long setups & trigger alert
if validLong
    t_stop := longStopPrice
    t_target := longTargetPrice
//     strategy.entry(id='Long', direction=strategy.long, when=validLong, comment='(SL=' + str.tostring(truncate(toWhole(longStopDistance), 2)) + ' pips)')

// Exit trades whenever our stop or target is hit
// strategy.exit(id='Long Exit', from_entry='Long', limit=t_target, stop=t_stop, when=strategy.position_size > 0)

// Draw trade data
// plot(strategy.position_size != 0 or validLong ? t_stop : na, title='Trade Stop Price', color=color.new(color.red, 0), style=plot.style_linebr)
// plot(strategy.position_size != 0 or validLong ? t_target : na, title='Trade Target Price', color=color.new(color.green, 0), style=plot.style_linebr)
// plot(strategy.position_size != 0 or validLong ? tradePositionSize : na, color=color.new(color.purple, 0), display=display.none, title='AutoView Position Size')

// // Draw EMA if it's enabled
// plot(emaFilter == 0 ? na : ema, color=emaFilterLong ? color.green : color.red, linewidth=2, title='EMA')

// Draw price action setup arrows
// plotshape(validLong ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), title='Bullish Setup')    

//===================================================================================================================================

//Rulls A B C E

E_A             = ma3   < close and hma > close and out1 < ma6 and close[1] < close and isWithinPeriod()        // A
E_BC            = ma3   < close and hma > close and out1 < ma6 and close[1] < close and dnl                      // B & C
E_C             = close > out1  and hma < out1  or close > hma and dnl                                           // C

C_A             = BBbasis > close and ( close > low[1])                                  
C_BC            = BBbasis > close and (  close > low[1]) and upl                           
C_ABC           = ma5     < close and close > out1 and close[1] > close and hma > close                          // and upl

D_CC            =  upl



//===================================================================================================================================

//===================================================================================================================================


if  E_BC
    strategy.entry("Long" , strategy.long                                                        ,comment= "E1")  

if  ema10 
    if takemtf == true and array.max(a, 1) > strategy.position_avg_price
        strategy.exit("TP1Mtf", "Long", qty_percent = qty1, limit = tpmtf1, stop = long_sl_lv    ,comment= "E1tp")     
        strategy.exit("TP2Mtf", "Long", qty_percent = qty2, limit = tpmtf2, stop = long_sl_lv    ,comment= "E1tp")     
        strategy.exit("TP3Mtf", "Long", qty_percent = qty3, limit = tpmtf3, stop = long_sl_lv    ,comment= "E1tp")     
        strategy.close_all(when =  C_ABC                                                         ,comment= "E1c")  
    strategy.close_all(when = C_BC                                                               ,comment= "E1cc")  

//=============================================================
//Strategy D
if     E_BC and dnl 
    if ema10 
        strategy.entry("D" , strategy.long                                               ,comment= "E2") 

    
if    D_CC 
    if takemtf == true and array.max(a, 1) > strategy.position_avg_price
        strategy.exit("TP1Mtf", "D", qty_percent = qty1, limit = tpmtf1, stop = long_sl_lv           ,comment= "E2tp") 
        strategy.exit("TP2Mtf", "D", qty_percent = qty2, limit = tpmtf2, stop = long_sl_lv           ,comment= "E2tp") 
        strategy.exit("TP3Mtf", "D", qty_percent = qty3, limit = tpmtf3, stop = long_sl_lv           ,comment= "E2tp") 
        strategy.exit  (id = "D Take Profit ", from_entry = "D", 
         limit = enableTrailing ? na : longTakeProfitPrice,trail_price = enableTrailing ? longTakeProfitPrice : na,
         trail_offset = enableTrailing ? longTrailingTakeProfitStepTicks : na,
         stop=t_stop                                                                                    ,comment= "E2c") 
0 Answers
Related