The Witcher [30MIN] - Alerts
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wielkieef

//@version=4


//study("The Witcher [30MIN]", overlay=true)

study("The Witcher [30MIN]", overlay=true)


//SOURCE =============================================================================================================================================================================================================================================================================================================

src                 =                   input(hl2)

// POSITION ==========================================================================================================================================================================================================================================================================================================

Position            =                   input("Both",                           title= "Longs / Shorts",                                    options = ["Both","Longs","Shorts"])

is_Long             =                   Position                                                    == "SHORT" ? na : true
is_Short            =                   Position                                                    == "LONG" ? na : true

// INPUTS ============================================================================================================================================================================================================================================================================================================

//ADX --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ADX_options         =                   input("CLASSIC",                        title= "Adx Type",                                       options = ["CLASSIC", "MASANAKAMURA"],                                             group = "ADX")
ADX_len             =                   input(18,                               title= "Adx lenght",                                       type = input.integer, minval = 1,                                                group = "ADX")
th                  =                   input(17,                               title= "Adx Treshold",                                    type = input.float, minval = 0, step = 0.5,                                       group = "ADX")

//RSI----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

len_3               =                   input(35,                               title="RSI lenght",                                                                                                                         group = "Relative Strenght Indeks")
src_3               =                   input(low,                              title="RSI Source",                                                                                                                         group = "Relative Strenght Indeks")

//TREND STRENGHT--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

n1                  =                   input(10,                               title="Channel Length",                                                                                                                     group="Trend Strenght")
n2                  =                   input(21,                               title="Average Length",                                                                                                                     group="Trend Strenght")

//JMA--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

inp                 =                   input(defval=hlc3,                      title="JMA Source",                                         type=input.source,                                                              group = "Jurik Moving Average")
reso                =                   input("",                               title="JMA Resolution",                                     type=input.resolution,                                                          group = "Jurik Moving Average")
rep                 =                   input(false,                            title="JMA Allow Repainting?",                              type=input.bool,                                                                group = "Jurik Moving Average")
src0                =                   security(syminfo.tickerid, reso, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1]
lengths             =                   input(22,                               title="JMA Length",                                         type=input.integer,                                                             group = "Jurik Moving Average")

//SAR-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

start               =                   input(0.007,                            title="SAR Start",                                          type=input.float, step=0.001 ,                                                  group="SAR")       
increment           =                   input(0.018,                            title="SAR Increment",                                      type=input.float, step=0.001 ,                                                  group="SAR")     
maximum             =                   input(0.05,                             title="SAR Maximum",                                        type=input.float, step=0.01 ,                                                   group="SAR")       
width               =                   input(1,                                title="SAR Point Width",                                    type=input.integer, minval=1,                                                   group="SAR")   

//Trend Indicator-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

timeframe           =                   input(13,                               title="Trend Timeframe",                                    minval=3,                                                                       group = "Trend Indicator")

//Momentum------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

srcType             =                   input("Price",                          title="Source Type",                                       options=["Price", "VWAP"],                                                       group = "MOMENTUM")
srcPrice            =                   input(close,                            title="Momentum Source",                                                                                                                    group = "MOMENTUM")
rsiLen              =                   input(56,                               title="Rsi Lenght",                                         minval=1,                                                                       group = "MOMENTUM")
sLen                =                   input(40,                               title="Smooth Length",                                                                                                                      group = "MOMENTUM")

//OBV------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

e1                  =       ema(obv,    input(30,                               title="OBV line 1",                                                                                                                         group = "OBV"))        
e2                  =       ema(obv,    input(12,                               title="OBV line 2",                                                                                                                         group = "OBV")) 

//MA----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

length              =                   input(72,                               title="MA Length",                                          minval=1,                                                                       group="Fast MA" )
matype              =                   input(5,                                title="AvgType",                                            minval=1, maxval=5,                                                             group="Fast MA")

//Range Filter--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

length0             =                   input(22,                               title="Range Filter lenght",                                                                                                                group = "Range Filter")
mult                =                   input(3,                                title="Range Filter mult" ,                                                                                                                 group = "Range Filter")

//TP PLOTS-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

tp_long0            =                   input(1.1,                              title="TP Long",                                          type = input.float,     minval = 0,     step = 0.1,                               group="TP") 
tp_short0           =                   input(1.1,                              title="TP Short",                                         type = input.float,     minval = 0,     step = 0.1,                               group="TP") 

//Inputs----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ACT_SCLP            =                   input(true,                             title="SCALPING",                                         type = input.bool,                                                                group="Scalping")
HiLoLen             =                   input(6,                                title="Scalping Lenght",                                    minval=2,                                                                       group="Scalping")
fastEMAlength       =                   input(10,                               title="Fast EMA lenght",                                    minval=2,                                                                       group="Scalping")
mediumEMAlength     =                   input(120,                              title="Medium EMA lenght",                                  minval=2,                                                                       group="Scalping")
slowEMAlength       =                   input(500,                              title="Slow EMA lenght",                                    minval=2,                                                                       group="Scalping")
filterBW            =                   input(false,                            title="Filter")
Lookback            =                   input(5,                                title="Pullback Lookback")
UseHAcandles        =                   input(true,                             title="Use H.A Calculations")

// Scalping Indicator  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

haClose             =                   UseHAcandles                        ?                                                               security(heikinashi(syminfo.tickerid), timeframe.period, close) : close
haOpen              =                   UseHAcandles                        ?                                                               security(heikinashi(syminfo.tickerid), timeframe.period, open) : open
haHigh              =                   UseHAcandles                        ?                                                               security(heikinashi(syminfo.tickerid), timeframe.period, high) : high
haLow               =                   UseHAcandles                        ?                                                               security(heikinashi(syminfo.tickerid), timeframe.period, low) : low
isRegularFractal(mode) =>
    ret = mode == 1 ? high[4] < high[3] and high[3] < high[2] and high[2] > high[1] and 
       high[1] > high[0] : mode == -1 ? 
       low[4] > low[3] and low[3] > low[2] and low[2] < low[1] and low[1] < low[0] : 
       false
    ret
isBWFractal(mode) =>
    ret = mode == 1 ? high[4] < high[2] and high[3] <= high[2] and high[2] >= high[1] and 
       high[2] > high[0] : mode == -1 ? 
       low[4] > low[2] and low[3] >= low[2] and low[2] <= low[1] and low[2] < low[0] : 
       false
    ret
fastEMA             =                                                                                                                       ema(haClose, fastEMAlength)
mediumEMA           =                                                                                                                       ema(haClose, mediumEMAlength)
slowEMA             =                                                                                                                       ema(haClose, slowEMAlength)
pacC                =                                                                                                                       ema(haClose, HiLoLen)
pacL                =                                                                                                                       ema(haLow, HiLoLen)
pacU                =                                                                                                                       ema(haHigh, HiLoLen)
TrendDirection      = fastEMA > mediumEMA and pacL > mediumEMA ? 1 : 
   fastEMA < mediumEMA and pacU < mediumEMA ? -1 : 0
filteredtopf        =                                                                                                                       filterBW ? isRegularFractal(1) : isBWFractal(1)
filteredbotf        =                                                                                                                       filterBW ? isRegularFractal(-1) : isBWFractal(-1)
valuewhen_H0        =                                                                                                                       valuewhen(filteredtopf == true, high[2], 0)
valuewhen_H1        =                                                                                                                       valuewhen(filteredtopf == true, high[2], 1)
valuewhen_H2        =                                                                                                                       valuewhen(filteredtopf == true, high[2], 2)
higherhigh          =                                                                                                                       filteredtopf == false ? false : 
   valuewhen_H1 < valuewhen_H0 and valuewhen_H2 < valuewhen_H0
lowerhigh = filteredtopf == false ? false : 
   valuewhen_H1 > valuewhen_H0 and valuewhen_H2 > valuewhen_H0
valuewhen_L0        =                                                                                                                       valuewhen(filteredbotf == true, low[2], 0)
valuewhen_L1        =                                                                                                                       valuewhen(filteredbotf == true, low[2], 1)
valuewhen_L2        =                                                                                                                       valuewhen(filteredbotf == true, low[2], 2)
higherlow = filteredbotf == false ? false : 
   valuewhen_L1 < valuewhen_L0 and valuewhen_L2 < valuewhen_L0
lowerlow = filteredbotf == false ? false : 
   valuewhen_L1 > valuewhen_L0 and valuewhen_L2 > valuewhen_L0
TradeDirection = 0
TradeDirection := nz(TradeDirection[1])
pacExitU = haOpen < pacU and haClose > pacU and barssince(haClose<pacC)<=Lookback
pacExitL = haOpen > pacL and haClose < pacL and barssince(haClose>pacC)<=Lookback
Buy      = TrendDirection == 1        and pacExitU
Sell     = TrendDirection == -1       and pacExitL
TradeDirection := TradeDirection == 1 and haClose<pacC ? 0 : 
   TradeDirection == -1               and haClose>pacC ? 0 : 
   TradeDirection == 0                and Buy ? 1 : 
   TradeDirection == 0                and Sell ? -1 : TradeDirection
   
L_scalp             =                                                           nz(TradeDirection[1]) == 0 and TradeDirection == 1
S_scalp             =                                                           nz(TradeDirection[1]) == 0 and TradeDirection == -1


//INDICATORS =============================================================================================================================================================================================================================================================================================================



//ADX-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

calcADX(_len) =>
    up              =                                                                                                                       change(high)
	down            =                                                                                                                      -change(low)
	plusDM          =                                                                                                                       na(up)   ? na : (up > down and up > 0   ? up   : 0)
    minusDM         =                                                                                                                       na(down) ? na : (down > up and down > 0 ? down : 0)
	truerange       =                                                                                                                       rma(tr, _len)
	_plus           =                                                                                                                       fixnan(100 * rma(plusDM, _len)  / truerange)
	_minus          =                                                                                                                       fixnan(100 * rma(minusDM, _len) / truerange)
	sum             =                                                                                                                       _plus + _minus
	_adx            =                                                                                                                       100 * rma(abs(_plus - _minus) / (sum == 0 ? 1 : sum), _len)
    [_plus,_minus,_adx]
calcADX_Masanakamura(_len) =>
    SmoothedTrueRange                   =                                                                                                   0.0
    SmoothedDirectionalMovementPlus     =                                                                                                   0.0
    SmoothedDirectionalMovementMinus    =                                                                                                   0.0
    TrueRange                           =                                                                                                   max(max(high - low, abs(high - nz(close[1]))), abs(low - nz(close[1])))
    DirectionalMovementPlus             =                                                                                                   high - nz(high[1]) > nz(low[1]) - low ? max(high - nz(high[1]), 0) : 0
    DirectionalMovementMinus            =                                                                                                   nz(low[1]) - low > high - nz(high[1]) ? max(nz(low[1]) - low, 0)   : 0
    SmoothedTrueRange                   :=                                                                                                  nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1]) /_len) + TrueRange
    SmoothedDirectionalMovementPlus     :=                                                                                                  nz(SmoothedDirectionalMovementPlus[1])  - (nz(SmoothedDirectionalMovementPlus[1])  / _len) + DirectionalMovementPlus
    SmoothedDirectionalMovementMinus    :=                                                                                                  nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1]) / _len) + DirectionalMovementMinus
    DIP                                 =                                                                                                   SmoothedDirectionalMovementPlus  / SmoothedTrueRange * 100
    DIM                                 =                                                                                                   SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
    DX                                  =                                                                                                   abs(DIP-DIM) / (DIP+DIM)*100
    adx                                 =                                                                                                   sma(DX, _len)
    [DIP,DIM,adx]
[DIPlusC,DIMinusC,ADXC] =                                                                                                                   calcADX(ADX_len) 
[DIPlusM,DIMinusM,ADXM] =                                                                                                                   calcADX_Masanakamura(ADX_len)
DIPlus                  =                                                                                                                   ADX_options == "CLASSIC" ? DIPlusC    : DIPlusM
DIMinus                 =                                                                                                                   ADX_options == "CLASSIC" ? DIMinusC   : DIMinusM
ADX                     =                                                                                                                   ADX_options == "CLASSIC" ? ADXC       : ADXM





L_adx                   =                                                       DIPlus > DIMinus and ADX > th
S_adx                   =                                                       DIPlus < DIMinus and ADX > th

macol                   = L_adx ? color.lime : S_adx ? color.red : color.orange
barcolor(color = macol)

//RSI------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

up_3                    =                                                                                                                   rma(max(change(src_3), 0), len_3)
down_3                  =                                                                                                                   rma(-min(change(src_3), 0), len_3)
rsi_3                   =                                                                                                                   down_3 == 0 ? 100 : up_3 == 0 ? 0 : 100 - (100 / (1 + up_3 / down_3))
L_rsi                   =                                                       (rsi_3 < 70)
S_rsi                   =                                                       (rsi_3 > 30) 

//TREND STRENGHT---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ap                      =                                                                                                                   hlc3 
esa                     =                                                                                                                   ema(ap, n1)
d                       =                                                                                                                   ema(abs(ap - esa), n1)
ci                      =                                                                                                                   (ap - esa) / (0.015 * d)
tci                     =                                                                                                                   ema(ci, n2)
wt1                     =                                                                                                                   tci
wt2                     =                                                                                                                   sma(wt1,4)
mfi_upper               =                                                                                                                   sum(volume * (change(hlc3) <= 0 ? 0 : hlc3), 58)
mfi_lower               =                                                                                                                   sum(volume * (change(hlc3) >= 0 ? 0 : hlc3), 58)
_mfi_rsi(mfi_upper, mfi_lower) =>
    if mfi_lower == 0
        100
    if mfi_upper == 0
        0
	100.0 - (100.0 / (1.0 + mfi_upper / mfi_lower))
mf                      = _mfi_rsi(mfi_upper, mfi_lower)
mfi                     = (mf - 50) * 3
L_mfi                   =                                                       mfi > 10
S_mfi                   =                                                       mfi < -10

//JMA------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

jsa                     =                                                                                                                               (src0 + src0[lengths]) / 2
sig                     =                                                                                                                               src0 > jsa ? 1 : src0 < jsa ? -1 : 0
L_jma                   =                                                       sig > 0 
S_jma                   =                                                       sig < 0 

//SAR------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

psar                                    =                                                                                                   sar(start, increment, maximum)
dir                                     =                                                                                                   psar < close ? 1 : -1

psarColor                               =                                                                                                   dir == 1 ? color.green : color.red
psarPlot                                =                                                                                                   plot(psar, title="PSAR", style=plot.style_circles, linewidth=width, color=macol, transp=0)
var color longColor = color.green
var color shortColor = color.red

L_sar                                   =                                       dir ==1
S_sar                                   =                                       dir ==-1

//Trend Indicator------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

lower                                   =                                                                                                   lowest(timeframe)
upper                                   =                                                                                                   highest(timeframe)
basis                                   =                                                                                                   avg(upper, lower)
orange_data                             =                                                                                                   offset(basis, (timeframe -1))
purple_data                             =                                                                                                   offset(basis, 1)
purple                                  =                                                                                                   plot(basis, offset = 1, title = "Current", color = color.black)
orange                                  =                                                                                                   plot(basis, offset = (timeframe -1), title = "Prev", color= color.black)
fill(purple, orange, color=macol, title="Trend Indicator RED/Green")

L_indicator                             =                                       purple_data > orange_data
S_indicator                             =                                       purple_data < orange_data

//Momentum---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

src_m                                   =  srcType=="Price"?srcPrice:security(syminfo.tickerid, timeframe.period, vwap[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
f_dema(_src, _length) =>
	_ema0 	                            =                                                                                                   ema( _src, _length)
	_ema1 	                            =                                                                                                   ema(_ema0, _length)
	_dema 	                            =                                                                                                   2 * _ema0 - _ema1	
rsi1                                    =                                                                                                   hma(rsi(src_m, rsiLen), sLen)
        
rsi2                                    =                                                                                                   rsi1-50
dema1                                   =                                                                                                   f_dema(rsi2, 9)
dema2                                   =                                                                                                   f_dema(rsi2, 21)
M_l1_cond                               =                                                                                                   e1 > e1[1] or e2 > e2[1]
M_s1_cond                               =                                                                                                   e1 < e1[1] or e2 < e2[1]
M_l2_cond                               =                                                                                                   dema1>0
M_s2_cond                               =                                                                                                   dema1<0
L_momentum                              =                                       M_l1_cond and M_l2_cond
S_momentum                              =                                       M_s1_cond and M_s2_cond

//MA------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

simplema                =                                                                                                                   sma(src,length)
exponentialma           =                                                                                                                   ema(src,length)
hullma                  =                                                                                                                   wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length)))
weightedma              =                                                                                                                   wma(src, length)
volweightedma           =                                                                                                                   vwma(src, length)
avgval                  =                                                                                                                   matype==1 ? simplema : matype==2 ? exponentialma : matype==3 ? hullma : matype==4 ? weightedma : matype==5 ? volweightedma : na
MA_speed                =                                                                                                                   (avgval / avgval[1] -1 ) *100
L_s_ma                  =                                                       MA_speed > 0 
S_s_ma                  =                                                       MA_speed < 0 

//Range Filter---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

out                     =                                                                                                                   0., cma = 0., cts = 0.
Var                     =                                                                                                                   variance(src,length0)*mult
sma                     =                                                                                                                   sma(src,length0)
secma                   =                                                                                                                   pow(nz(sma - cma[1]),2) 
sects                   =                                                                                                                   pow(nz(src - cts[1]),2) 
ka                      =                                                                                                                   Var < secma ? 1 - Var/secma : 0
kb                      =                                                                                                                   Var < sects ? 1 - Var/sects : 0
cma                     :=                                                                                                                  ka*sma+(1-ka)*nz(cma[1],src)
cts                     :=                                                                                                                  kb*src+(1-kb)*nz(cts[1],src)
css                     =                                                                                                                   cts > cma ? color.green : color.red
a                       =                                                                                                                   plot(cts,"CTS",color=macol,linewidth=1,transp=0)
b                       =                                                                                                                   plot(cma,"CMA",color=macol,linewidth=1,transp=0)
fill(a,b,color=macol,transp=80)
L_range                 =                                                       cts > cma
S_range                 =                                                       cts < cma

//STRATEGY ==========================================================================================================================================================================================================================================================================================================

var bool longCond = na, var bool shortCond = na
var int CondIni_long = 0, var int CondIni_short = 0
var bool _Final_longCondition = na, var bool _Final_shortCondition = na
var float last_open_longCondition = na, var float last_open_shortCondition = na
var int last_longCondition = na, var int last_shortCondition = na
var int last_Final_longCondition = na, var int last_Final_shortCondition = na
var int nLongs = na, var int nShorts = na

L_scalp_condt           =                                                       L_scalp and ACT_SCLP
S_scalp_condt           =                                                       S_scalp and ACT_SCLP

L_basic_condt           =                                                       L_adx and L_rsi and L_mfi  and L_jma and L_sar and L_indicator and L_momentum and L_s_ma and L_range
S_basic_condt           =                                                       S_adx and S_rsi and S_mfi  and S_jma and S_sar and S_indicator and S_momentum and S_s_ma and S_range

L_second_condt          =                                                       L_basic_condt or L_scalp_condt and L_adx
S_second_condt          =                                                       S_basic_condt or S_scalp_condt and S_adx

longCond := L_second_condt
shortCond:= S_second_condt

CondIni_long        := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_long[1])
CondIni_short       := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_short[1])
longCondition       = (longCond[1]  and nz(CondIni_long[1])  == -1)
shortCondition      = (shortCond[1] and nz(CondIni_short[1]) == 1)

//POSITION PRICE--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

var float sum_long = 0.0, var float sum_short = 0.0
var float Position_Price = 0.0
var bool Final_long_BB = na, var bool Final_short_BB = na
var int last_long_BB = na, var int last_short_BB = na

last_open_longCondition     := longCondition  or Final_long_BB[1]  ? close[1] : nz(last_open_longCondition[1])
last_open_shortCondition    := shortCondition or Final_short_BB[1] ? close[1] : nz(last_open_shortCondition[1])
last_longCondition          := longCondition  or Final_long_BB[1]  ? time : nz(last_longCondition[1])
last_shortCondition         := shortCondition or Final_short_BB[1] ? time : nz(last_shortCondition[1])
in_longCondition            = last_longCondition  > last_shortCondition
in_shortCondition           = last_shortCondition > last_longCondition
last_Final_longCondition    := longCondition  ? time : nz(last_Final_longCondition[1])
last_Final_shortCondition   := shortCondition ? time : nz(last_Final_shortCondition[1])
nLongs                      := nz(nLongs[1])
nShorts                     := nz(nShorts[1])
if longCondition or Final_long_BB
    nLongs                  := nLongs + 1
    nShorts                 := 0
    sum_long                := nz(last_open_longCondition) + nz(sum_long[1])
    sum_short               := 0.0
if shortCondition or Final_short_BB
    nLongs                  := 0
    nShorts                 := nShorts + 1
    sum_short               := nz(last_open_shortCondition) + nz(sum_short[1])
    sum_long                := 0.0
Position_Price              := nz(Position_Price[1])
Position_Price              := longCondition or Final_long_BB ? sum_long/nLongs : shortCondition or Final_short_BB ? sum_short/nShorts : na

//TP-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

var bool long_tp = na, var bool short_tp = na
var int last_long_tp = na, var int last_short_tp = na
var bool Final_Long_tp = na, var bool Final_Short_tp = na
var bool Final_Long_sl0 = na, var bool Final_Short_sl0 = na
var bool Final_Long_sl = na, var bool Final_Short_sl = na
var int last_long_sl = na, var int last_short_sl = na

tp_long             =  ((nLongs  > 1) ? tp_long0  / nLongs  : tp_long0)  / 100
tp_short            =  ((nShorts > 1) ? tp_short0 / nShorts : tp_short0) / 100
long_tp             := high > (fixnan(Position_Price) * (1 + tp_long))  and in_longCondition
short_tp            := low  < (fixnan(Position_Price) * (1 - tp_short)) and in_shortCondition
last_long_tp        := long_tp  ? time : nz(last_long_tp[1])
last_short_tp       := short_tp ? time : nz(last_short_tp[1])
Final_Long_tp       := (long_tp  and last_longCondition  > nz(last_long_tp[1])  and last_longCondition  > nz(last_long_sl[1]))
Final_Short_tp      := (short_tp and last_shortCondition > nz(last_short_tp[1]) and last_shortCondition > nz(last_short_sl[1]))

//TP SIGNALS--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

tplLevel            = (in_longCondition and 
                      (last_longCondition > nz(last_long_tp[1])) and 
                      (last_longCondition > nz(last_long_sl[1])) and not Final_Long_sl[1]) ? 
                      (nLongs > 1) ? 
                      (fixnan(Position_Price) * (1 + tp_long)) : (last_open_longCondition * (1 + tp_long)) : na

tpsLevel            = (in_shortCondition and 
                      (last_shortCondition > nz(last_short_tp[1])) and 
                      (last_shortCondition > nz(last_short_sl[1])) and not Final_Short_sl[1]) ? 
                      (nShorts > 1) ? 
                      (fixnan(Position_Price) * (1 - tp_short)) : (last_open_shortCondition * (1 - tp_short)) : na

//RE-ENTRY ON TP-HIT-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

if Final_Long_tp 
    CondIni_long    := -1
    sum_long        := 0.0
    nLongs          := na
if Final_Short_tp 
    CondIni_short   := 1
    sum_short       := 0.0
    nShorts         := na
    
//PLOTS-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

plot((nLongs > 1) or (nShorts > 1) ? Position_Price : na, title = "Price", color = in_longCondition ? color.aqua : color.orange, linewidth = 2, style = plot.style_cross)

plot(tplLevel,            title = "Long TP ",               style = plot.style_cross,                                   color = color.green,                linewidth = 1)
plot(tpsLevel,            title = "Short TP ",              style = plot.style_cross,                                   color = color.red,                  linewidth = 1)

//PLOTSHAPES----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

plotshape(Final_Long_tp,  title = "TP Long Signal",         style = shape.flag,                 location = location.abovebar,           color = color.red,          size=size.small ,           transp = 0) 
plotshape(Final_Short_tp, title = "TP Short Signal",        style = shape.flag,                 location = location.belowbar,           color = color.green,        size=size.small ,           transp = 0) 

plotshape(longCondition,  title = "Long x1",                style=shape.triangleup,             location=location.belowbar,             color=color.blue,           size=size.small ,           transp=0)
plotshape(shortCondition, title = "Short x1",               style=shape.triangledown,           location=location.abovebar,             color=color.red,            size=size.small ,           transp=0)

//ALERTS FOR AUTOVIEW --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//LONG 
alertcondition(longCondition,  title="LONG", 
   message = "L | e=BINANCEFUTURES a=* s=BTCUSDT c=order | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT c=position b=short t=market ro=1 | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT b=long q=99% t=market l=1 | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT c=position b=long sl=-8.2% p=-8.2% t=limit")
   
//SHORT
alertcondition(shortCondition, title="Short x1", 
   message = "S  | e=BINANCEFUTURES a=* s=BTCUSDT c=order | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT c=position b=long t=market ro=1 | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT b=short q=99% t=market l=1 | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT c=position b=short sl=7.8% p=7.9% t=limit")
   
//LONG TP
alertcondition(Final_Long_tp, title="Long TP", 
   message = "LONG TP | e=BINANCEFUTURES a=* s=BTCUSDT c=position b=long q=100% t=market ro=1 | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT c=order")
 
alertcondition(Final_Short_tp, title="Short TP", 
   message = "SHORT TP | e=BINANCEFUTURES a=* s=BTCUSDT c=position b=short q=100% t=market ro=1 | delay=1 | e=BINANCEFUTURES a=* s=BTCUSDT c=order")


// By wielkieef