Strategy LinReg ST@RL
// This Source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RegisL76
// strategy based on an original idea of @KivancOzbilgic (SuperTrend) and DevLucem (@LucemAnb) (Lin Reg ++)                                  //
// TradingView version : a special credit goes to - KivancOzbilgic and @LucemAnb which inspired me a lot to improve this indicator/Strategy. //

// ******************** //
// © RegisL76 //
// V 1780.0
// ******************** //

// V1.0 publiée 27/03/2022 (v845)
// V2.0 publiée 03/04/2022 (v921)
// V3.0 publiée 06/04/2022 (v927)
// V4.0 publiée 04/05/2022 (v938)
// V5.0 publiée 20/04/2023 (v1574)
// V6.0 publiée 28/06/2023 (v1780)

// TradingView Pine V5 //
//@version=5
// TradingView Pine V5 //

 
// *********************************************************************************************************************************************************************************************************** //
// ********************************************* Parametres Par Defaut Optimisés Pour BTC/USDT Perp Binance TF= 1m 3m 5m 15m 30m H1 H2 H3 H4 Daily Weekly  *************************************************** //
// *********************************************************************************************************************************************************************************************************** //
strategy('Strategy LinReg ST@RL',shorttitle='LinRegST@RL', overlay=true, margin_long=70,margin_short=70,commission_value=0.04,
 default_qty_value=80,initial_capital=1000,default_qty_type= strategy.percent_of_equity, currency=currency.USD,pyramiding=0,
 calc_on_order_fills=false,calc_on_every_tick=false,process_orders_on_close=false,max_labels_count=500,max_lines_count=500,max_bars_back=0)

// ****************************************************************************************************************************************** // 
//                                       Parametres par defaut pour BTC/USDT Perp Binance TF=H1                                               //
// *************************************************** LINEAR REGRESSION INPUTS ************************************************************* //
THANKS          = input.string('THANKS i -->>', tooltip=
 'If you use this strategy and you are satisfied with the trading results,\n you may donate to me via paypal to lebourg.regis@free.fr\n Thanks in advance !!!\n Have good winning trades and enjoy !'
 ,                                                                                                               confirm=true, group='CONFIRMATION NEEDED')

CONFIG = input.string('CONFIG-->>',tooltip='MEMO -->>'
 +'\nDef BTCUSDT Perp : Low -  ??  -  ?? - ?? -  ?? - REGULAR : ALL TF !'
 +'\n---------------------------------------------------------------'
 +'\n1m  BTCUSDT Perp : Low - 115 - 3 - 3.3  - 1 - REGULAR' 
 +'\n3m  BTCUSDT Perp : Low - 142 - 0 - 3.9  - 1 - REGULAR'
 +'\n5m  BTCUSDT Perp : Low - 169 - 1 - 2.3  - 1 - REGULAR'
 +'\n15m BTCUSDT Perp : Low - 167 - 0 - 0.6  - 6 - REGULAR'
 +'\n30m BTCUSDT Perp : Low - 115 - 2 - 0.9  - 7 - REGULAR'
 +'\nH1  BTCUSDT Perp : Low - 196 - 3 - 2.2  - 1 - REGULAR' 
 +'\nH2  BTCUSDT Perp : Low -  70 - 7 - 2.2  - 3 - REGULAR'
 +'\nH3  BTCUSDT Perp : Low -  75 - 2 - 2.0  - 3 - REGULAR'
 +'\nH4  BTCUSDT Perp : Low -  23 - 2 - 1.6  - 4 - REGULAR'
 +'\nD   BTCUSDT Perp : Low -  52 - 2 - 1.7  - 9 - REGULAR'
 +'\nW   BTCUSDT Perp : Low -  14 - 0 - 0.7  - 5 - REGULAR' 
 +'\nONLY FOR : '
 +'\n1m 3m 5m 15m 30m H2 H3 H4 DAILY WEEKLY'
 +'\nIF "CONF AUTO"',                                                                                             confirm=true, group='CONFIRMATION NEEDED')

NOTA            = input.string('READ i -->>',tooltip='Inputs Marked With * Influence The Result Of The Stategy !',confirm=true, group='CONFIRMATION NEEDED')

// *********************************************************************************************************************** //
buy_only        = input       (false, 'BUY ONLY*',                                                      tooltip ='[Buy only] & [Sell only] both checked or both unchecked = [BUY + SELL]'
 ,                                                                                                      group='For All TF',                                                   inline='ALLTF')
 
sell_only       = input       (false, 'SELL ONLY*',                                                     tooltip ='[Buy only] & [Sell only] both checked or both unchecked = [BUY + SELL]'
 ,                                                                                                      group='For All TF',                                                   inline='ALLTF')

// **************************************************** STOP LOSS Inputs ************************************************* //
sl1             = input.float (1.5, 'STOP LOSS*  % '               , minval=0.2,maxval=10,step=0.05,    tooltip='Stop Loss : 0 to 10 % of Position Size, 100% with X10 [Default Value For All TimeFrame]'
 ,                                                                                                      group='For All TF')
 
slX10           = input.bool  (true,'STOP LOSS*  X 10',                                                 tooltip='Stop Loss X10 Multiplier'
 ,                                                                                                      group='For All TF',                                                    inline='SL')
 
no_sl           = input.bool  (false,'DISABLE* STOP LOSS',                                              tooltip='Checked=Disable Exit by Stop Loss'
 ,                                                                                                      group='For All TF')

// **************************************************** TAKE PROFIT Inputs *********************************************** // 
tp1             = input.float (4.35, 'TAKE PROFIT*  % '             ,minval=0.2,maxval=10,step=0.05,    tooltip='Take Profit : 0 to 10 % of Position Size, 100% with X10 [Default Value For All TimeFrame]'
 ,                                                                                                      group='For All TF')
 
tpX10           = input.bool  (true,'TAKE PROFIT*  X 10',                                               tooltip='Take Profit X10 Multiplier'
 ,                                                                                                      group='For All TF',                                                     inline='TP')
 
no_tp           = input.bool  (false,'DISABLE* TAKE PROFIT',                                            tooltip='Checked=Disable Exit by Take Profit'
 ,                                                                                                      group='For All TF')
// **************************************************** DISPLAY Inputs *************************************************** //
line_thick      = input.int   (2,     'Line LR Thickness',                    minval=1, maxval=4,       group='COMMON INPUTS DISPLAY',                                          inline='LR')
signals         = input.string('All', 'Line LR Signals Display', options=['All','Last 500 Bars'],       group='COMMON INPUTS DISPLAY',                                          inline='LR')

color_up        = input.color (color.new(#82fc00,0),'Up Color'  ,                                     group='COMMON INPUTS DISPLAY',                                          inline='COLOR')
color_down      = input.color (color.new(#ff0000,0),'Down Color',                                     group='COMMON INPUTS DISPLAY',                                          inline='COLOR')

y_Pos_factor    = input.float (3.0,   'Label Y Position Factor',      minval=0.0,maxval=20.0,step=0.25, group='COMMON INPUTS DISPLAY')

show_trade_info = input       (true,  'Show Trade Infos',                                           
 tooltip='Display Or Not The Trade Infos Label',                                                         group='COMMON INPUTS DISPLAY',                                          inline='INFO')

show_full_info = input        (false, 'Show Full Infos Label',                                           
 tooltip='Display Full Or Simple Trade Infos Label',                                                     group='COMMON INPUTS DISPLAY',                                          inline='INFO')
 
barscolors      = input       (true,  'Trend Bars Colors',                                            
 tooltip='Displays Or Not The Color Of The Candles According To The Trend Of The Strategy, Instead Of The Standard Colors'
 ,                                                                                                       group='COMMON INPUTS DISPLAY',                                          inline='INFO')
 
trans_Col_bg    = input.float (88,   'Trend Background Transparency',  minval=86,  maxval=90,  step=1,   group='COMMON INPUTS DISPLAY')
show_sl_line    = input.bool  (true, 'Show SL Line',                                                     group='COMMON INPUTS DISPLAY',                                          inline='SL-TP')
show_tp_line    = input.bool  (true, 'Show TP Line', tooltip='Show TP / SL Lines & Backgrounds',         group='COMMON INPUTS DISPLAY',                                          inline='SL-TP')

showIntermedSignal= input.bool(true, 'Show intermediate Signals', tooltip='Show intermediate Signals',   group='ALERT MESSAGES')
showBuySignal     = input.bool(true, 'Show Buy Signals',          tooltip='Show Buy Signals',            group='ALERT MESSAGES')
showSellSignal    = input.bool(true, 'Show Sell Signals',         tooltip='Show Sell Signals',           group='ALERT MESSAGES')
showTpSignal      = input.bool(true, 'Show Exit TP Signals',      tooltip='Show Exit TP Signals',        group='ALERT MESSAGES')
showSlSignal      = input.bool(true, 'Show Exit SL Signals',      tooltip='Show Exit SL Signals',        group='ALERT MESSAGES')
showExitSignal    = input.bool(true, 'Show Exit Signals',         tooltip='Show Exit Signals',           group='ALERT MESSAGES')

source          = input       (low,   'COMMON SOURCE*',tooltip='(Default is "LOW")',                     group='DEFAULT FOR ALL TF')
conf_auto       = input.bool  (true,'CONF AUTO 1m 3m 5m 15m 30m H1 H2 H3 H4 DAILY WEEKLY*',
 tooltip='CONF AUTO Only For Timeframe 1m 3m 5m 15m 30m H1 H2 H3 H4 DAILY WEEKLY, ELSE ALL OTHER TF = DEF CONF !', 
                                                                                           confirm=true, group='DEFAULT FOR ALL TF')

// ------------------------------------------------------------------------------------------------- //
// Parametres defaut pour ALL Time Frame = DEFAUT Futures BTC/USDT Perp : Low - ?? - ?? - ?? - ?? - REGULAR // Default //
// ------------------------------------------------------------------------------------------------- //
length_Def         = input.int      (75,    'DEFAULT LENGTH* --',        minval=1,                  group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF')
offset_Def         = input.int      (2,     'DEFAULT OFFSET* --',        minval=0,                  group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF')
dev_Def            = input.float    (2.0,   'DEFAULT DEVIATION*',        minval=0.1,      step=0.1, group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF') 
smoothing_Def      = input.int      (3,     'DEFAULT SMOOTHING*',        minval=1,                  group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF')
reversal_Def       = input          (false, 'DEFAULT REVERSAL* ',                                   group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF',                                                    
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// ------------------------------------------------------------------------------------------------- //


// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = 1m Futures BTC/USDT Perp : Low  - 115 - 3 - 3.3 - 1 - REGULAR - CONF AUTO 1m ! -    //
// *********************************************************************************************************************** //
length_1m       = input.int      (115,  'LENGTH 1m* --',                  minval=1,                  group='CONFIG ONLY FOR 1m, IF CONF AUTO',                         inline='1m')
offset_1m       = input.int      (3,    'OFFSET 1m* -----' ,              minval=0,                  group='CONFIG ONLY FOR 1m, IF CONF AUTO',                         inline='1m')
dev_1m          = input.float    (3.3,  'DEVIATION 1m*',                  minval=0.1,      step=0.1, group='CONFIG ONLY FOR 1m, IF CONF AUTO',                         inline='1m') 
smoothing_1m    = input.int      (1,    'SMOOTHING 1m*',                  minval=1,                  group='CONFIG ONLY FOR 1m, IF CONF AUTO',                         inline='1m')
reversal_1m     = input          (false,'REVERSAL 1m*',                                              group='CONFIG ONLY FOR 1m, IF CONF AUTO',                         inline='1m',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** // 
// Parametres de base pour Time Frame = 3m Futures BTC/USDT Perp : Low  - 142 - 0 - 3.9 - 1 - REGULAR - CONF AUTO 3m ! -    //
// *********************************************************************************************************************** //
length_3m       = input.int      (142,  'LENGTH 3m* --',                  minval=1,                  group='CONFIG ONLY FOR 3m, IF CONF AUTO',                         inline='3m')
offset_3m       = input.int      (0,    'OFFSET 3m* -----' ,              minval=0,                  group='CONFIG ONLY FOR 3m, IF CONF AUTO',                         inline='3m')
dev_3m          = input.float    (3.9,  'DEVIATION 3m*',                  minval=0.1,      step=0.1, group='CONFIG ONLY FOR 3m, IF CONF AUTO',                         inline='3m') 
smoothing_3m    = input.int      (1,    'SMOOTHING 3m*',                  minval=1,                  group='CONFIG ONLY FOR 3m, IF CONF AUTO',                         inline='3m')
reversal_3m     = input          (false,'REVERSAL 3m*',                                              group='CONFIG ONLY FOR 3m, IF CONF AUTO',                         inline='3m',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = 5m Futures BTC/USDT Perp : Low  - 169 - 1 - 2.3 - 1 - REGULAR - CONF AUTO 5m ! -    //
// *********************************************************************************************************************** //
length_5m       = input.int      (169,   'LENGTH 5m* --',               minval=1,                  group='CONFIG ONLY FOR 5m, IF CONF AUTO',                         inline='5m')
offset_5m       = input.int      (1,     'OFFSET 5m* -----' ,           minval=0,                  group='CONFIG ONLY FOR 5m, IF CONF AUTO',                         inline='5m')
dev_5m          = input.float    (2.3,   'DEVIATION 5m*',               minval=0.1,      step=0.1, group='CONFIG ONLY FOR 5m, IF CONF AUTO',                         inline='5m')
smoothing_5m    = input.int      (1,     'SMOOTHING 5m*',               minval=1,                  group='CONFIG ONLY FOR 5m, IF CONF AUTO',                         inline='5m')
reversal_5m     = input          (false, 'REVERSAL 5m*',                                           group='CONFIG ONLY FOR 5m, IF CONF AUTO',                         inline='5m',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = 15m Futures BTC/USDT Perp : Low  - 167 - 0 - 0.6 - 6 - REGULAR - CONF AUTO 15m ! -    //
// *********************************************************************************************************************** //
length_15m       = input.int      (167,   'LENGTH 15m* --',              minval=1,                  group='CONFIG ONLY FOR 15m, IF CONF AUTO',                        inline='15m')
offset_15m       = input.int      (0,     'OFFSET 15m* -----' ,          minval=0,                  group='CONFIG ONLY FOR 15m, IF CONF AUTO',                        inline='15m')
dev_15m          = input.float    (0.6,   'DEVIATION 15m*',              minval=0.1,      step=0.1, group='CONFIG ONLY FOR 15m, IF CONF AUTO',                        inline='15m')
smoothing_15m    = input.int      (6,     'SMOOTHING 15m*',              minval=1,                  group='CONFIG ONLY FOR 15m, IF CONF AUTO',                        inline='15m')
reversal_15m     = input          (false, 'REVERSAL 15m*',                                          group='CONFIG ONLY FOR 15m, IF CONF AUTO',                        inline='15m',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = 30m Futures BTC/USDT Perp : Low  - 115 - 2 - 0.9 - 7 - REGULAR - CONF AUTO 30m ! -    //
// *********************************************************************************************************************** //
length_30m       = input.int      (115,   'LENGTH 30m* --',              minval=1,                  group='CONFIG ONLY FOR 30m, IF CONF AUTO',                        inline='30m')
offset_30m       = input.int      (2,     'OFFSET 30m* -----' ,          minval=0,                  group='CONFIG ONLY FOR 30m, IF CONF AUTO',                        inline='30m')
dev_30m          = input.float    (0.9,   'DEVIATION 30m*',              minval=0.1,      step=0.1, group='CONFIG ONLY FOR 30m, IF CONF AUTO',                        inline='30m')
smoothing_30m    = input.int      (7,     'SMOOTHING 30m*',              minval=1,                  group='CONFIG ONLY FOR 30m, IF CONF AUTO',                        inline='30m')
reversal_30m     = input          (false, 'REVERSAL 30m*',                                          group='CONFIG ONLY FOR 30m, IF CONF AUTO',                        inline='30m',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
 // ------------------------------------------------------------------------------------------------- //
// Parametres de base pour Time Frame = H1 Futures BTC/USDT Perp : Low - 196 - 3 - 2.2 - 1 - REGULAR - CONF AUTO H1 ! -    //
// ------------------------------------------------------------------------------------------------- //
length_H1          = input.int      (196,   'LENGTH H1* --',              minval=1,                  group='CONFIG ONLY FOR H1, IF CONF AUTO',                        inline='H1')
offset_H1          = input.int      (3,     'OFFSET H1* -----',           minval=0,                  group='CONFIG ONLY FOR H1, IF CONF AUTO',                        inline='H1')
dev_H1             = input.float    (2.2,   'DEVIATION H1*',              minval=0.1,      step=0.1, group='CONFIG ONLY FOR H1, IF CONF AUTO',                        inline='H1')
smoothing_H1       = input.int      (1,     'SMOOTHING H1*',              minval=1,                  group='CONFIG ONLY FOR H1, IF CONF AUTO',                        inline='H1')
reversal_H1        = input          (false, 'REVERSAL H1*',                                          group='CONFIG ONLY FOR H1, IF CONF AUTO',                        inline='H1',
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = H2 Futures BTC/USDT Perp : Low - 70 - 7 - 2.2 - 3 - REGULAR - CONF AUTO H2 ! -    //
// *********************************************************************************************************************** //
length_H2       = input.int      (70,     'LENGTH H2* --',               minval=1,                  group='CONFIG ONLY FOR H2, IF CONF AUTO',                          inline='H2')
offset_H2       = input.int      (7,      'OFFSET H2* -----' ,           minval=0,                  group='CONFIG ONLY FOR H2, IF CONF AUTO',                          inline='H2')
dev_H2          = input.float    (2.2,    'DEVIATION H2*',               minval=0.1,      step=0.1, group='CONFIG ONLY FOR H2, IF CONF AUTO',                          inline='H2') 
smoothing_H2    = input.int      (3,      'SMOOTHING H2*',               minval=1,                  group='CONFIG ONLY FOR H2, IF CONF AUTO',                          inline='H2')
reversal_H2     = input          (false,  'REVERSAL _H2*',                                           group='CONFIG ONLY FOR H2, IF CONF AUTO',                         inline='H2',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = H3 Futures BTC/USDT Perp : Low - 75 - 2 - 2.0 - 3 - REGULAR - CONF AUTO H3 ! -    //
// *********************************************************************************************************************** //
length_H3       = input.int      (75,     'LENGTH H3* --',               minval=1,                  group='CONFIG ONLY FOR H3, IF CONF AUTO',                          inline='H3')
offset_H3       = input.int      (2,      'OFFSET H3* -----' ,           minval=0,                  group='CONFIG ONLY FOR H3, IF CONF AUTO',                          inline='H3')
dev_H3          = input.float    (2.0,    'DEVIATION H3*',               minval=0.1,      step=0.1, group='CONFIG ONLY FOR H3, IF CONF AUTO',                          inline='H3') 
smoothing_H3    = input.int      (3,      'SMOOTHING H3*',               minval=1,                  group='CONFIG ONLY FOR H3, IF CONF AUTO',                          inline='H3')
reversal_H3     = input          (false,  'REVERSAL H3*',                                           group='CONFIG ONLY FOR H3, IF CONF AUTO',                          inline='H2',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = H4 Futures BTC/USDT Perp : Low - 23 - 2 - 1.6 - 4 - REGULAR - CONF AUTO H4 ! -    //
// *********************************************************************************************************************** //
length_H4       = input.int      (23,     'LENGTH H4* --',               minval=1,                  group='CONFIG ONLY FOR H4, IF CONF AUTO',                          inline='H4')
offset_H4       = input.int      (2,      'OFFSET H4* -----' ,           minval=0,                  group='CONFIG ONLY FOR H4, IF CONF AUTO',                          inline='H4')
dev_H4          = input.float    (1.6,    'DEVIATION H4*',               minval=0.1,      step=0.1, group='CONFIG ONLY FOR H4, IF CONF AUTO',                          inline='H4') 
smoothing_H4    = input.int      (4,      'SMOOTHING H4*',               minval=1,                  group='CONFIG ONLY FOR H4, IF CONF AUTO',                          inline='H4')
reversal_H4     = input          (false,  'REVERSAL H4*',                                           group='CONFIG ONLY FOR H4, IF CONF AUTO',                          inline='H4',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = D  Futures BTC/USDT Perp : Low - 52 - 2 - 1.7 - 9 - REGULAR - CONF AUTO D  ! -    //
// *********************************************************************************************************************** //
length_D       = input.int      (52,      'LENGTH Daily* --',             minval=1,                 group='CONFIG ONLY FOR DAILY, IF CONF AUTO',                       inline='DAILY')
offset_D       = input.int      (2,       'OFFSET Daily* -----' ,         minval=0,                 group='CONFIG ONLY FOR DAILY, IF CONF AUTO',                       inline='DAILY')
dev_D          = input.float    (1.7,     'DEVIATION Daily*',             minval=0.1,      step=0.1,group='CONFIG ONLY FOR DAILY, IF CONF AUTO',                       inline='DAILY') 
smoothing_D    = input.int      (9,       'SMOOTHING Daily*',             minval=1,                 group='CONFIG ONLY FOR DAILY, IF CONF AUTO',                       inline='DAILY')
reversal_D     = input          (false,   'REVERSAL Daily*',                                        group='CONFIG ONLY FOR DAILY, IF CONF AUTO',                       inline='DAILY',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// *********************************************************************************************************************** //
// Parametres de base pour Time Frame = W  Futures BTC/USDT Perp : Low - 14 - 0 - 0.7 - 5 - REGULAR - CONF AUTO W  ! -    //
// *********************************************************************************************************************** //
length_W       = input.int      (14,      'LENGTH Weekly* --',            minval=1,                 group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO',                      inline='WEEKLY')
offset_W       = input.int      (0,       'OFFSET Weekly* -----' ,        minval=0,                 group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO',                      inline='WEEKLY')
dev_W          = input.float    (0.7,     'DEVIATION Weekly*',            minval=0.1,     step=0.1, group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO',                      inline='WEEKLY') 
smoothing_W    = input.int      (5,       'SMOOTHING Weekly*',            minval=1,                 group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO',                      inline='WEEKLY')
reversal_W     = input          (false,   'REVERSAL Weekly*',                                       group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO',                      inline='WEEKLY',                              
 tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !')
// ********************************************************************************************************************************************* //

// Default Conf //
smoothing=smoothing_Def
loop=length_Def
dev=dev_Def
conf='[CONF DEF]' // Default Conf //
reversal=reversal_Def

if (timeframe.period =='1') and conf_auto
    smoothing:=smoothing_1m
    loop:=length_1m
    dev:=dev_1m
    conf:='[CONF 1m]'
    reversal:=reversal_1m

if (timeframe.period =='3') and conf_auto
    smoothing:=smoothing_3m
    loop:=length_3m
    dev:=dev_3m
    conf:='[CONF 3m]'
    reversal:=reversal_3m

if (timeframe.period =='5') and conf_auto
    smoothing:=smoothing_5m
    loop:=length_5m
    dev:=dev_5m
    conf:='[CONF 5m]'
    reversal:=reversal_5m

if (timeframe.period =='15') and conf_auto
    smoothing:=smoothing_15m
    loop:=length_15m
    dev:=dev_15m
    conf:='[CONF 15m]'
    reversal:=reversal_15m

if (timeframe.period =='30') and conf_auto
    smoothing:=smoothing_30m
    loop:=length_30m
    dev:=dev_30m
    conf:='[CONF 30m]'
    reversal:=reversal_30m

if timeframe.period =='60' and conf_auto    
    smoothing:=smoothing_H1
    loop:=length_H1
    dev:=dev_H1
    conf:='[CONF H1]'
    reversal:=reversal_H1

if timeframe.period =='120' and conf_auto    
    smoothing:=smoothing_H2
    loop:=length_H2
    dev:=dev_H2
    conf:='[CONF H2]'
    reversal:=reversal_H2

if timeframe.period =='180' and conf_auto    
    smoothing:=smoothing_H3
    loop:=length_H3
    dev:=dev_H3
    conf:='[CONF H3]'
    reversal:=reversal_H3

if timeframe.period =='240' and conf_auto    
    smoothing:=smoothing_H4
    loop:=length_H4
    dev:=dev_H4
    conf:='[CONF H4]'
    reversal:=reversal_H4

if timeframe.period =='D' and conf_auto    
    smoothing:=smoothing_D
    loop:=length_D
    dev:=dev_D
    conf:='[CONF D]'
    reversal:=reversal_D

if timeframe.period =='W' and conf_auto    
    smoothing:=smoothing_W
    loop:=length_W
    dev:=dev_W
    conf:='[CONF W]'
    reversal:=reversal_W

data(x) =>
    ta.sma(request.security(syminfo.tickerid,timeframe.period, x), smoothing)
    
// ********************************************************************************************************************************************* //
// Default Conf //
linreg   = data(ta.linreg(source, length_Def, offset_Def))
linreg_p = data(ta.linreg(source, length_Def, offset_Def + 1))

if (timeframe.period =='1') and conf_auto
    linreg   := data(ta.linreg(source, length_1m, offset_1m))
    linreg_p := data(ta.linreg(source, length_1m, offset_1m + 1))

if (timeframe.period =='3') and conf_auto
    linreg   := data(ta.linreg(source, length_3m, offset_3m))
    linreg_p := data(ta.linreg(source, length_3m, offset_3m + 1))

if timeframe.period =='5' and conf_auto
    linreg   := data(ta.linreg(source, length_5m, offset_5m))
    linreg_p := data(ta.linreg(source, length_5m, offset_5m + 1))

if timeframe.period =='15' and conf_auto
    linreg   := data(ta.linreg(source, length_15m, offset_15m))
    linreg_p := data(ta.linreg(source, length_15m, offset_15m + 1))

if timeframe.period =='30' and conf_auto
    linreg   := data(ta.linreg(source, length_30m, offset_30m))
    linreg_p := data(ta.linreg(source, length_30m, offset_30m + 1))

if timeframe.period =='60' and conf_auto
    linreg   := data(ta.linreg(source, length_H1, offset_H1))
    linreg_p := data(ta.linreg(source, length_H1, offset_H1 + 1))

if timeframe.period =='120' and conf_auto
    linreg   := data(ta.linreg(source, length_H2, offset_H2))
    linreg_p := data(ta.linreg(source, length_H2, offset_H2 + 1))

if timeframe.period =='180' and conf_auto
    linreg   := data(ta.linreg(source, length_H3, offset_H3))
    linreg_p := data(ta.linreg(source, length_H3, offset_H3 + 1))

if timeframe.period =='240' and conf_auto
    linreg   := data(ta.linreg(source, length_H4, offset_H4))
    linreg_p := data(ta.linreg(source, length_H4, offset_H4 + 1))

if timeframe.period =='D' and conf_auto
    linreg   := data(ta.linreg(source, length_D, offset_D))
    linreg_p := data(ta.linreg(source, length_D, offset_D + 1))

if timeframe.period =='W' and conf_auto
    linreg   := data(ta.linreg(source, length_W, offset_W))
    linreg_p := data(ta.linreg(source, length_W, offset_W + 1))
    
// ********************************************************************************************************************************************* //
x = bar_index 
slope = linreg - linreg_p
intercept = linreg - x * slope
deviationSum = 0.0

for i = 0 to loop - 1 by 1
    deviationSum += math.pow(source[i] - (slope * (x - i) + intercept), 2)
    deviationSum

// Default Conf //
deviation = math.sqrt(deviationSum / length_Def)
x1 = x - length_Def
y1 = slope * (x - length_Def) + intercept
lengthHist=length_Def

if (timeframe.period =='1') and conf_auto
    deviation := math.sqrt(deviationSum / length_1m)
    x1 := x - length_1m
    y1 := slope * (x - length_1m) + intercept
    lengthHist:=length_1m

if (timeframe.period =='3') and conf_auto
    deviation := math.sqrt(deviationSum / length_3m)
    x1 := x - length_3m
    y1 := slope * (x - length_3m) + intercept
    lengthHist:=length_3m

if (timeframe.period =='5') and conf_auto
    deviation := math.sqrt(deviationSum / length_5m)
    x1 := x - length_5m
    y1 := slope * (x - length_5m) + intercept
    lengthHist:=length_5m

if (timeframe.period =='15') and conf_auto
    deviation := math.sqrt(deviationSum / length_15m)
    x1 := x - length_15m
    y1 := slope * (x - length_15m) + intercept
    lengthHist:=length_15m

if (timeframe.period =='30') and conf_auto
    deviation := math.sqrt(deviationSum / length_30m)
    x1 := x - length_30m
    y1 := slope * (x - length_30m) + intercept
    lengthHist:=length_30m

if timeframe.period =='60' and conf_auto
    deviation := math.sqrt(deviationSum / length_H1)
    x1 := x - length_H1
    y1 := slope * (x - length_H1) + intercept
    lengthHist:=length_H1

if timeframe.period =='120' and conf_auto
    deviation := math.sqrt(deviationSum / length_H2)
    x1 := x - length_H2
    y1 := slope * (x - length_H2) + intercept
    lengthHist:=length_H2

if timeframe.period =='180' and conf_auto
    deviation := math.sqrt(deviationSum / length_H3)
    x1 := x - length_H3
    y1 := slope * (x - length_H3) + intercept
    lengthHist:=length_H3

if timeframe.period =='240' and conf_auto
    deviation := math.sqrt(deviationSum / length_H4)
    x1 := x - length_H4
    y1 := slope * (x - length_H4) + intercept
    lengthHist:=length_H4

if timeframe.period =='D' and conf_auto
    deviation := math.sqrt(deviationSum / length_D)
    x1 := x - length_D
    y1 := slope * (x - length_D) + intercept
    lengthHist:=length_D

if timeframe.period =='W' and conf_auto
    deviation := math.sqrt(deviationSum / length_W)
    x1 := x - length_W
    y1 := slope * (x - length_W) + intercept
    lengthHist:=length_W

x2 = x
y2 = linreg

// ********************************************************************************************************************************************* //
b  = line(na) 
dp = line(na)
dm = line(na)

bHist  = line(na)
dpHist = line(na)
dmHist = line(na)

bHist1 = line(na)
dpHist1= line(na)
dmHist1= line(na)

b := line.new(x1, y1, x2, y2, xloc.bar_index, extend.right, color.white,style=line.style_dashed, width=line_thick)
line.delete(b[1])

bHist := line.new(x1[lengthHist], y1[lengthHist], x2[lengthHist], y2[lengthHist], xloc.bar_index, extend.none,
 color.white,style=line.style_dashed, width=line_thick)
line.delete(bHist[1])

bHist1 := line.new(x1[lengthHist*2], y1[lengthHist*2], x2[lengthHist*2], y2[lengthHist*2], xloc.bar_index, extend.none,
 color.white,style=line.style_dashed, width=line_thick)
line.delete(bHist1[1])

dp := line.new(x1, deviation * dev + y1, x2, deviation * dev + y2,   xloc.bar_index, extend.right,
 color_up,style=line.style_dashed, width=line_thick)
line.delete(dp[1])

dpHist := line.new(x1[lengthHist], deviation * dev + y1[lengthHist], x2[lengthHist], deviation * dev + y2[lengthHist],
 xloc.bar_index, extend.none, color_up,style=line.style_dashed, width=line_thick)
line.delete(dpHist[1])

dpHist1 := line.new(x1[lengthHist*2], deviation * dev + y1[lengthHist*2], x2[lengthHist*2], deviation * dev + y2[lengthHist*2],
 xloc.bar_index, extend.none, color_up,style=line.style_dashed, width=line_thick)
line.delete(dpHist1[1])

dm := line.new(x1, -deviation * dev + y1, x2, -deviation * dev + y2, xloc.bar_index, extend.right,
 color_down,style=line.style_dashed, width=line_thick)
line.delete(dm[1])

dmHist := line.new(x1[lengthHist], -deviation * dev + y1[lengthHist], x2[lengthHist], -deviation * dev + y2[lengthHist],
 xloc.bar_index, extend.none, color_down,style=line.style_dashed, width=line_thick)
line.delete(dmHist[1])

dmHist1 := line.new(x1[lengthHist*2], -deviation * dev + y1[lengthHist*2], x2[lengthHist*2], -deviation * dev + y2[lengthHist*2],
 xloc.bar_index, extend.none, color_down,style=line.style_dashed, width=line_thick)
line.delete(dmHist1[1])

// ********************************************************************************************************************************************* //
// Signaux 
dm_current = -deviation * dev + y2
dp_current = deviation  * dev + y2

// *** Linear Regression Buy & Sell Signal Regular Mode *** //
sell  = ta.crossunder (close, dm_current)
buy = ta.crossover    (close, dp_current)

// ********************************************************************************************************************************************* //
plotshape(not reversal ? buy :  na, title='BUY',     style=shape.triangleup,  location=location.top,color=color.new(#00ff00,0),size=size.tiny,
 text='Buy',     textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500)
if not reversal and buy
    line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#00ff00,0), style=line.style_solid, width=1)

plotshape(not reversal ? sell : na, title='SELL',    style=shape.triangledown,location=location.top,color=color.new(#ff0000,0) ,size=size.tiny,
 text='Sell',    textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500)
if not reversal and sell
    line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#ff0000,0), style=line.style_solid, width=1)

plotshape(reversal ?     buy :  na, title='SELL Rv', style=shape.triangledown,location=location.top,color=color.new(#ff0000,0),size=size.tiny,
 text='Sell\nRv',textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500)
if reversal and buy
    line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#ff0000,0), style=line.style_solid, width=1) 

plotshape(reversal ?     sell:  na, title='BUY Rv',  style=shape.triangleup,  location=location.top,color=color.new(#00ff00,0) ,size=size.tiny,
 text='Buy\nRv', textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500)
if reversal and sell
    line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#00ff00,0), style=line.style_solid, width=1)

// ******************************************************************************** // 
// *** Define F_print_last function For Current Trade Infos *** //
f_print_last(_offsetx, _offsety, _lab_styl, _bkg_color, _text, _color_text, _size) =>
    // *** Create label *** //.
    var _label = label(na)
    label.delete(_label)
    _label := label.new(bar_index+_offsetx, _offsety, _text, xloc.bar_index, yloc.price, _bkg_color, _lab_styl, _color_text, _size, text.align_center)
    _label

// ******************************************************************************** // 
// *** Define F_print2 function For Trades Infos *** //
f_print2(_offsetx, _offsety, _lab_styl, _bkg_color, _text, _color_text, _size) =>
    // *** Create label *** //.
    var _label = label(na)
    // label.delete(_label) // permanent label //
    _label := label.new(bar_index + _offsetx, _offsety, _text, xloc.bar_index, yloc.price, _bkg_color, _lab_styl, _color_text, _size, text.align_center)
    _label

// ******************************************************************************** //
// [Buy Only] & [Sell Only]' both checked or no checked = [BUY + SELL]              //
if (sell_only and buy_only) or (not sell_only and not buy_only)
    sell_only:=false
    buy_only:=false
    
// ******************************************************************************** // 
// Gestion Des Multiplicateurs Stop Loss  //
// Managing Stop Loss Multipliers         //
sl=sl1
if slX10 and sl>0
    sl:=sl1*10

if no_sl
    sl:=0

// *************************************** // 
stp_loss_enable=bool(na)
if sl==0
    stp_loss_enable:=false
else
    stp_loss_enable:=true

// *************************************** // 
// Gestion Des Multiplicateurs Take Profit //
// Managing Take Profit Multipliers        //
tp=tp1
if tpX10 and tp>0
    tp:=tp1*10

if no_tp
    tp:=0

// *************************************** // 
tp_enable=bool(na)
if tp==0
    tp_enable:=false
else
    tp_enable:=true  

// ******************************************************************************************************************** // 
trend = -1
trend := nz(trend[1], trend)

// ************************************************ LINEAR REGRESSION METHODE ***************************************** //
// Trend == 1 --> Long If Not Reverse //
if not reversal 
    trend := trend == -1 and buy ? 1 : trend == 1 and sell ? -1 : trend
else
    trend := trend == 1 and buy ? -1 : trend == -1 and sell ? 1 : trend

changeCond = trend != trend[1]

// ********************************************************************************************************************* // 
var no_bar=int(0)
varip int no_trend =0 // Varip //
var last_trend=int(na)
//-------------------------//
no_bar:=no_bar+1
last_trend:=no_bar-no_trend
varip trade = float(0)
//-------------------------//
if changeCond
    no_trend := no_bar
    
// ******************************************************************************** // 
var buySignal=bool(na) 

if not reversal
    buySignal:= changeCond and trend == 1
else
    buySignal:= changeCond and trend == -1

// ******************************************************************************** // 
var sellSignal = bool(na)

if not reversal
    sellSignal:= changeCond and trend == -1
else
    sellSignal:= changeCond and trend == 1

// ******************************************************************************** // 
var bool sl_lg       =na
var bool sl_sh       =na
var bool stop_loss   =na

var bool tp_lg       =na
var bool tp_sh       =na
var bool take_profit =na

// ********************************************************************************************************** // 
// Gestion des Numeros de Trade, En Accord Avec La Liste Des Transactions Du testeur De Strategie TradindView //
// Management of Trade Numbers, In Accordance With The TradindView Strategy tester's Transactions List        //
// ********************************************************************************************************** //
// ********************************************************************************************************** //
// ************************** modifying this section is not recommended ! *********************************** //
// ********************************************************************************************************** //
if (changeCond and not sell_only and not buy_only) and trade==0       // ************************************ //
    trade:=trade+1                                                    // ************************************ //  
else 
    if (changeCond and not sell_only and not buy_only)                // ************************************ //
        trade:=trade+1

if  trade==0 and not reversal and buySignal and buy_only              // ************************************ //
    trade:=trade+1

if  trade==0 and not reversal and sellSignal and sell_only            // ************************************ //
    trade:=trade+1
    
if  trade==0 and reversal and buySignal and sell_only                 // ************************************ //
    trade:=trade+1

if  trade==0 and reversal and sellSignal and buy_only                 // ************************************ //
    trade:=trade+1    
// ********************************************************************************************************** //

// ******************************************************************************** // 
// ******************************* STRATEGY *************************************** //
// ******************************************************************************** // 
var str_lg=bool(na)
var str_sh=bool(na)

// !!! Varip -> start_price!!! 
varip start_price=float(na) // varip //

//**************************************************************************//
// Trend == 1 --> Long Normal
if trend == 1 and changeCond and not reversal and not str_lg
    str_lg:=true
    str_sh:=false
    start_price:=close
    sl_lg:=false
    sl_sh:=false
    tp_lg:=false
    tp_sh:=false

// Trend == -1 --> Short Normal
if trend == -1 and changeCond and not reversal and not str_sh
    str_lg:=false
    str_sh:=true
    start_price:=close
    sl_lg:=false
    sl_sh:=false
    tp_lg:=false
    tp_sh:=false

//**************************************************************************//
// Trend == -1 -->Short Reversal
if trend == -1 and changeCond and reversal and not str_sh
    str_lg:=false
    str_sh:=true
    start_price:=close
    sl_lg:=false
    sl_sh:=false
    tp_lg:=false
    tp_sh:=false

// Trend == 1 --> Long Reversal
if trend == 1 and changeCond and reversal and not str_lg
    str_lg:=true
    str_sh:=false
    start_price:=close
    sl_lg:=false
    sl_sh:=false
    tp_lg:=false
    tp_sh:=false

// **************************************************************************************************************************************************** // 
// ************************************************ Strategy Entry LG - SH - LG Rev - SH Rev ********************************************************** //
// **************************************************************************************************************************************************** // 
if not reversal and str_lg and not sell_only and buySignal
    strategy.entry('Lg', strategy.long, comment = 'Lg '+str.format('{0,number,#}',trade))
    stop_loss:=false
    take_profit:=false

if not reversal and str_sh and not buy_only and sellSignal
    strategy.entry('Sh', strategy.short,comment = 'Sh '+str.format('{0,number,#}',trade))
    stop_loss:=false
    take_profit:=false

if     reversal and str_lg and not sell_only and sellSignal
    strategy.entry('Lg Rev', strategy.long,comment = 'Lg Rev '+str.format('{0,number,#}',trade))
    stop_loss:=false
    take_profit:=false

if     reversal and str_sh and not buy_only and buySignal
    strategy.entry('Sh Rev', strategy.short,comment = 'Sh Rev '+str.format('{0,number,#}',trade))
    stop_loss:=false
    take_profit:=false
    
//**************************************************************************//
// Difference De Prix % //
// Price difference %   //
d_per100=(close-close[last_trend])/math.max(close,close[last_trend])

var txt_end_trade=string(na)
total_days=string(na)

//**************************************************************************//
if str.tonumber(timeframe.period)<=240
    total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index*str.tonumber(timeframe.period)/1440)) +' DAYS'

if timeframe.period=='D'
    total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index)) +' DAYS'
    
if timeframe.period=='W'
    total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index*7)) +' DAYS'
 
if timeframe.period=='M'
    total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index*30.4375)) +' DAYS'

if timeframe.period!='M' and timeframe.period!='W' and timeframe.period!='D' and (str.tonumber(timeframe.period)>240 or str.tonumber(timeframe.period)<1)
    total_days:='\nHist ???' + ' DAYS'
    
//**************************************************************************//
since_days=string(na)
since=bar_index-bar_index[last_trend]

//  si le script s'exécute sur la barre précédant immédiatement la barre en temps réel
if barstate.islastconfirmedhistory
    since:=bar_index-bar_index[last_trend]

//**************************************************************************//
if str.tonumber(timeframe.period)<=240
    since_days:='\nSince '+str.format('{0,number,#.#} ', (since*str.tonumber(timeframe.period)/1440)) +' DAYS'

if timeframe.period=='D'
    since_days:='\nSince '+str.format('{0,number,#.#} ', (since)) +' DAYS'
    
if timeframe.period=='W'
    since_days:='\nSince '+str.format('{0,number,#.#} ', (since*7)) +' DAYS'
 
if timeframe.period=='M'
    since_days:='\nSince '+str.format('{0,number,#.#} ', (since*30.4375)) +' DAYS'

if timeframe.period!='M' and timeframe.period!='W' and timeframe.period!='D' and (str.tonumber(timeframe.period)>240 or str.tonumber(timeframe.period)<1)
    since_days:='\nSince ???' + ' DAYS'

//**************************************************************************//
SizePosUsd=string(na)
SizePosBtc   =float(na)

if trade>=1
    SizePosUsd:=strategy.account_currency+str.tostring(strategy.position_size*start_price,format =' #.##')
    SizePosBtc:=strategy.position_size

PnlFlag=string(na)
GreenCircle  =string('🟢')
RedCircle    =string('🔴')
WhiteCircle  =string('⚪')

if strategy.opentrades.profit(0)<0
    PnlFlag:=RedCircle
else if strategy.opentrades.profit(0)>0
    PnlFlag:=GreenCircle
else
    PnlFlag:=WhiteCircle

if show_full_info
    txt_end_trade:='# '+str.format('{0,number,#}',trade) +
     ' ' + PnlFlag  +
     '\n<last # '+str.format('{0,number,#}',trade[last_trend]) +
     '\n<'    + syminfo.basecurrency +str.format(' {0,number,#.########} ',strategy.position_size) +
     '\n<'    + SizePosUsd +
     '\nSL '  + str.format('{0,number,#.###}',sl)+'%'+ ' TP '   +str.format('{0,number,#.###}',tp)+'%' +
     '\n<E '  + str.format('{0,number,#.########} '     + strategy.account_currency,close[last_trend]) +
     '\n=C '  + str.format('{0,number,#.########} '     + strategy.account_currency,close) +
     '\nd '   + str.format('{0,number,#.########} '     + strategy.account_currency,close-close[last_trend]) +
     '\n%d '  + str.format('{0,number,#.##%}',d_per100) +
     '\n=PnL '+ str.format('{0,number,#.##} '           + strategy.account_currency ,strategy.opentrades.profit(0)) +
     '\nCom ' + str.format('{0,number,-#.## }'          + strategy.account_currency ,strategy.opentrades.commission(0)*2) +
     total_days + 
     since_days
else
    txt_end_trade:='# '+str.format('{0,number,#}',trade) +
     ' ' + PnlFlag  + 
     '\n<'    + syminfo.basecurrency +str.format(' {0,number,#.########} ',strategy.position_size) +
     '\n<'    + SizePosUsd +
     '\n%d '  + str.format('{0,number,#.##%}',d_per100) +
     '\nPnL ' + str.format('{0,number,#.##} '           + strategy.account_currency ,strategy.opentrades.profit(0)) +
     '\nCom ' + str.format('{0,number,-#.## }'          + strategy.account_currency ,strategy.opentrades.commission(0)*2) +
     since_days

// ************************************ //
// Label Horizontal Position Setting    //
atr = ta.sma(ta.tr, loop) 
high_pos=ohlc4 + (y_Pos_factor * atr)
low_pos=ohlc4  - (y_Pos_factor * atr)
// ************************************ //

var f2=label(na)
if trade==0
    label.delete(f2)
pnl_color=color(na)

if strategy.opentrades.profit(0)<0
    pnl_color:=color.new(#080808, 0)
else if strategy.opentrades.profit(0)>0
    pnl_color:=color.new(#ffffff,0)
else
    pnl_color:=color.new(#fbe78c, 0)
    
varip trade_dir=string(na)

// **************************************************************************************************************** //
// *** Ordre Des Parametres Pour F_Print2 : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size)    *** //
// *** Order Of Parameters For F_Print2: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) *** //
// **************************************************************************************************************** //
// ----------------------------------------------------------------------------
txt_end_trade:=txt_end_trade +'\n'+str.format_time(time, "yyyy-MM-dd", "UTC")+'\ntrig='+str.format_time(time, "HH:mm", "UTC")+'\nUTC '

// ----------------------------------------------------------------------------
// Alert Intermediat Buy / Sell
if ta.crossunder (close, dm_current) and not reversal and showIntermedSignal
    alert('\nIntermediate BUY Signal\n'+txt_end_trade, alert.freq_all)

if ta.crossover (close, dp_current) and not reversal and showIntermedSignal
    alert('\nIntermediate SELL Signal\n'+txt_end_trade, alert.freq_all)    

if ta.crossunder (close, dm_current) and reversal and showIntermedSignal
    alert('\nIntermediate SELL Signal Rev.\n'+txt_end_trade, alert.freq_all)

if ta.crossover (close, dp_current) and reversal and showIntermedSignal
    alert('\nIntermediate BUY Signal Rev.\n'+txt_end_trade, alert.freq_all)

// ----------------------------------------------------------------------------
if buySignal and show_trade_info and not reversal and not sell_only 
    f2:=f_print2( 1,high_pos,label.style_label_down, color.new(#65ff65, 40), 
     'Lg '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Lg '

if buySignal and not reversal and not sell_only
    if showBuySignal    
        alert('\nBUY Signal\n'+txt_end_trade, alert.freq_all)
    trade_dir:='Lg '
// ----------------------------------------------------------------------------
if buySignal and show_trade_info and     reversal and not buy_only 
    f2:=f_print2( 1,low_pos,label.style_label_up, color.new(#ff6565, 40), 
     'ShRv '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='ShRv '

if buySignal and     reversal and not buy_only
    if showSellSignal
        alert('\nSELL Rev. SIGNAL\n'+txt_end_trade, alert.freq_all)
    trade_dir:='ShRv '
// ----------------------------------------------------------------------------
if sellSignal and show_trade_info and not reversal and not buy_only 
    f2:=f_print2( 1,low_pos,label.style_label_up, color.new(#ff6565,40), 
     'Sh '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Sh '

if sellSignal and not reversal and not buy_only
    if showSellSignal
        alert('\nSELL SIGNAL\n'+txt_end_trade, alert.freq_all)
    trade_dir:='Sh '
// ----------------------------------------------------------------------------
if sellSignal and show_trade_info and     reversal and not sell_only 
    f2:=f_print2( 1,high_pos,label.style_label_down, color.new(#65ff65,40), 
     'LgRv '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='LgRv '

if sellSignal and     reversal and not sell_only
    if showBuySignal
        alert('\nBUY Rev. SIGNAL\n'+txt_end_trade, alert.freq_all)   
    trade_dir:='LgRv '
// ----------------------------------------------------------------------------
// ********************************************************************************************************************************************************** // 
//                                                        CALCUL des valeurs de Stop Loss et Take Profit                                                      //
// ********************************************************************************************************************************************************** //
// Stop Loss & Take Profit calculés en pourcentage de la taille de la Position 
// FORMULE De CALCUL du : TP_SL_usd = ((E_usd x SIZE_btc x TP_SL_% / 100) +- (E_usd x SIZE_btc)) / SIZE_btc
// Les Valeurs des Commissions d'Entrée & de Sortie sont prises en Compte !
SLLgValUsd= ( ( (start_price*SizePosBtc) - (start_price*SizePosBtc*sl/100) ) / SizePosBtc )+strategy.opentrades.commission(0)
SLShValUsd= ( ( (start_price*SizePosBtc) + (start_price*SizePosBtc*sl/100) ) / SizePosBtc )-strategy.opentrades.commission(0)

TPLgValUsd= ( ( (start_price*SizePosBtc) + (start_price*SizePosBtc*tp/100) ) / SizePosBtc )+strategy.opentrades.commission(0)
TPShValUsd= ( ( (start_price*SizePosBtc) - (start_price*SizePosBtc*tp/100) ) / SizePosBtc )-strategy.opentrades.commission(0)
// ********************************************************************************************************************************************************** //

// ********************************************************************************************************************************************************** // 
// ********************************************************************* STOP LOSS ************************************************************************** // 
// ********************************************************************************************************************************************************** // 
// SIGNAL SL
if close <= SLLgValUsd and stp_loss_enable and str_lg and not sell_only
    sl_lg := true
    stop_loss:=true

if close >= SLShValUsd and stp_loss_enable and str_sh and not buy_only
    sl_sh := true
    stop_loss:=true

// **************************************************************************************************************** //
// *** Ordre Des Parametres Pour F_Print2 : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size)    *** //
// *** Order Of Parameters For F_Print2: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) *** //
// **************************************************************************************************************** //
varip sl_price=float(na) // varip //

if sl_lg and stp_loss_enable and not reversal and show_trade_info and str_lg and not sell_only 
    f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00aaff,40), 
     'SL LG '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '    

if sl_lg and stp_loss_enable and not reversal and str_lg
    strategy.close('Lg', comment = 'STOP LOSS LG '+str.format('{0,number,#}',trade),immediately = true)
    if showSlSignal
        alert('\nSTOP LOSS LG\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    sl_price:=close
    trade_dir:='Null '   

// ******************************************************************************** // 
if sl_sh and stp_loss_enable and not reversal and show_trade_info and str_sh and not buy_only
    f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#fbea7f, 40), 
     'SL SH '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if sl_sh and stp_loss_enable and not reversal and str_sh
    strategy.close('Sh', comment = 'STOP LOSS SH '+str.format('{0,number,#}',trade),immediately = true)
    if showSlSignal
        alert('\nSTOP LOSS SH\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    sl_price:=close
    trade_dir:='Null '   

// ******************************************************************************** //
// ******************************************************************************** //
if sl_lg and stp_loss_enable and reversal and show_trade_info and str_lg and not sell_only
    f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00aaff,40), 
     'SL LGRv '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if sl_lg and stp_loss_enable and reversal and str_lg
    strategy.close('Lg Rev', comment = 'STOP LOSS LG Rev. '+str.format('{0,number,#}',trade),immediately = true)
    if showSlSignal
        alert('\nSTOP LOSS LG Rev.\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    sl_price:=close
    trade_dir:='Null '   

// ******************************************************************************** // 
if sl_sh and stp_loss_enable and reversal and show_trade_info and str_sh and not buy_only
    f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#fbea7f, 40), 
     'SL SHRv '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if sl_sh and stp_loss_enable and reversal and str_sh
    strategy.close('Sh Rev', comment = 'STOP LOSS SH Rev. '+str.format('{0,number,#}',trade),immediately = true)
    if showSlSignal
        alert('\nSTOP LOSS SH Rev.\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    sl_price:=close
    trade_dir:='Null '  

// ********************************************************************************************************************************************************** // 
// ********************************************************************* TAKE PROFIT ************************************************************************ // 
// ********************************************************************************************************************************************************** //
// SIGNAL TP
if close >= TPLgValUsd and tp_enable and str_lg and not sell_only
    tp_lg := true
    take_profit:=true

if close <= TPShValUsd and tp_enable and str_sh and not buy_only
    tp_sh := true
    take_profit:=true

// **************************************************************************************************************** //
// *** Ordre Des Parametres Pour F_Print2 : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size)    *** //
// *** Order Of Parameters For F_Print2: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) *** //
// **************************************************************************************************************** //
varip tp_price=float(na) //varip //

if tp_lg and tp_enable and not reversal and show_trade_info and str_lg and not sell_only 
    f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00ffdd, 40), 
     'TP LG '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if tp_lg and tp_enable and not reversal and str_lg
    strategy.close('Lg', comment = 'TAKE PROFIT LG '+str.format('{0,number,#}',trade),immediately = true)
    if showTpSignal
        alert('\nTAKE PROFIT LG\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    tp_price:=close
    trade_dir:='Null ' 

// ******************************************************************************** // 
if tp_sh and tp_enable and not reversal and show_trade_info and str_sh and not buy_only
    f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#ff5f00,40), 
     'TP SH '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if tp_sh and tp_enable and not reversal and str_sh
    strategy.close('Sh', comment = 'TAKE PROFIT SH '+str.format('{0,number,#}',trade),immediately = true)
    if showTpSignal
        alert('\nTAKE PROFIT SH\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    tp_price:=close
    trade_dir:='Null '  

// ******************************************************************************** //
// ******************************************************************************** //
if tp_lg and tp_enable and reversal and show_trade_info and str_lg and not sell_only
    f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00ffdd, 40), 
     'TP LGRv '+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if tp_lg and tp_enable and reversal and str_lg
    strategy.close('Lg Rev', comment = 'TAKE PROFIT LG Rev. '+str.format('{0,number,#}',trade),immediately = true)
    if showTpSignal
        alert('\nTAKE PROFIT LG Rev.\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    tp_price:=close
    trade_dir:='Null '   

// ******************************************************************************** // 
if tp_sh and tp_enable and reversal and show_trade_info and str_sh and not buy_only
    f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#ff5f00,40), 
     'TP SHRv'+txt_end_trade,
     pnl_color, size.normal)
    trade_dir:='Null '

if tp_sh and tp_enable and reversal and str_sh
    strategy.close('Sh Rev', comment = 'TAKE PROFIT SH Rev. '+str.format('{0,number,#}',trade),immediately = true)
    if showTpSignal
        alert('\nTAKE PROFIT SH Rev.\n'+txt_end_trade, alert.freq_all)
    str_lg:=false
    str_sh:=false
    tp_price:=close
    trade_dir:='Null '  

// ********************************************************************************************************************************************************** // 
//                                                                           EXIT                                                                             //
// ********************************************************************************************************************************************************** // 
if changeCond and sellSignal and not reversal and buy_only and show_trade_info and not stop_loss and not take_profit
    f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#f47ff2, 40),
     'ExLg '+txt_end_trade,
     pnl_color, size.normal)
    stop_loss:=false
    take_profit:=false
    trade_dir:='Null '

if changeCond and sellSignal and not reversal and buy_only 
    strategy.close('Lg',comment = 'Exit Lg '+str.format('{0,number,#}',trade), immediately=true)
    if showExitSignal
        alert('\nEXIT LG\n'+txt_end_trade, alert.freq_all) 
    stop_loss:=false
    take_profit:=false
    trade:=trade+1
    trade_dir:='Null '
    str_lg:=false
    str_sh:=false  

// ********************************************************************************************************************************************************** //
if changeCond and buySignal and not reversal and sell_only and show_trade_info and not stop_loss and not take_profit
    f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#8bfcc7, 40), 
     'ExSh '+txt_end_trade,
     pnl_color, size.normal)
    stop_loss:=false
    take_profit:=false
    trade_dir:='Null '

if changeCond and buySignal and not reversal and sell_only
    strategy.close('Sh', comment = 'Exit Sh '+str.format('{0,number,#}',trade), immediately=true)
    if showExitSignal
        alert('\nEXIT SH\n'+txt_end_trade, alert.freq_all)
    stop_loss:=false
    take_profit:=false
    trade:=trade+1
    trade_dir:='Null '    
    str_lg:=false
    str_sh:=false  

// ********************************************************************************************************************************************************** //
// ********************************************************************************************************************************************************** //
if changeCond and sellSignal and reversal and sell_only and show_trade_info and not stop_loss and not take_profit
    f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#8bfcc7,40), 
     'ExShRv '+txt_end_trade,
     pnl_color, size.normal)
    stop_loss:=false
    take_profit:=false
    trade_dir:='Null '

if changeCond and sellSignal and reversal and sell_only
    strategy.close('Sh Rev', comment = 'Exit Sh Rev '+str.format('{0,number,#}',trade), immediately=true)
    if showExitSignal
        alert('\nEXIT SH REV.\n'+txt_end_trade, alert.freq_all)
    stop_loss:=false
    take_profit:=false
    trade:=trade+1
    trade_dir:='Null '
    str_lg:=false
    str_sh:=false   

// ********************************************************************************************************************************************************** //
if changeCond and buySignal and reversal and buy_only and show_trade_info and not stop_loss and not take_profit
    f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#f47ff2,40), 
     'ExLgRv '+txt_end_trade,
     pnl_color, size.normal)
    stop_loss:=false
    take_profit:=false
    trade_dir:='Null '

if changeCond and buySignal and reversal and buy_only
    strategy.close('Lg Rev', comment = 'Exit Lg Rev '+str.format('{0,number,#}',trade), immediately=true)
    if showExitSignal
        alert('\n'+'EXIT LG REV.\n'+txt_end_trade, alert.freq_all)
    stop_loss:=false
    take_profit:=false
    trade:=trade+1
    trade_dir:='Null '     
    str_lg:=false
    str_sh:=false   

// ********************************************* Candle Colors According To Trend Direction ***************************************************************** //
barcolor (not reversal and trend == -1 and barscolors and not buy_only and not stop_loss and not take_profit ? color.new(#ff0000, 55) : 
 not reversal and trend == 1 and barscolors and not sell_only and not stop_loss and not take_profit ? color.new(#00ff00, 55) :
 reversal and trend == -1 and barscolors and not buy_only and not stop_loss and not take_profit ? color.new(#ff0000, 55) :
 reversal and trend == 1 and barscolors and not sell_only and not stop_loss and not take_profit ? color.new(#00ff00, 55) :
 barscolors ? color.new(#2a2a2c, 55) : na )

// ********************************************************************************************************************************************************** //
shp_color =color.new(na,100)

if not take_profit and not stop_loss
    if str_lg and (linreg >= linreg[1])
        shp_color:=not sell_only ? color.new(#00ff00,0) : color.new(#00ff00,80)

    if str_lg and (linreg < linreg[1])
        shp_color:=not sell_only ? color.new(#eaff00,0) : color.new(#eaff00,80)
        
    // ------------------------------------------------------------------------------------------------- //
    if str_sh and (linreg < linreg[1])
        shp_color:=not buy_only ? color.new(#ff0000,0) : color.new(#ff0000,80)

    if str_sh and (linreg >= linreg[1])
        shp_color:=not buy_only ? color.new(#ff9100,0) : color.new(#ff9100,80)

plot(linreg, 'Regression Line', color= shp_color,linewidth=2,style=plot.style_line)

plotshape(str_lg ? linreg : na, 'Lg PnL Line',style=shape.square,location=location.bottom,color=str_lg and (close>=start_price) ? color.new(#00ff00, 20) :
 str_lg and (close<start_price)  ? color.new(#ff0000, 20) : na,size=size.tiny)

plotshape(str_sh ? linreg : na, 'Sh PnL Line',style=shape.square,location=location.bottom,color=str_sh and (close<start_price)  ? color.new(#00ff00, 20) :
 str_sh and (close>=start_price) ? color.new(#ff0000, 20) : na,size=size.tiny)
// ********************************************************************* Stop Loss Indicator ************************************************************************************ //
sl_lg_price=SLLgValUsd

if show_sl_line and stp_loss_enable and not sell_only  and sl_lg
    sl_lg_price:=sl_price

sl_sh_price=SLShValUsd

if show_sl_line and stp_loss_enable and not buy_only and sl_sh
    sl_sh_price:=sl_price

sl_line_lg=plot(show_sl_line and stp_loss_enable and not sell_only  and (str_lg or sl_lg) and not stop_loss ? sl_lg_price : na,
 title='Stop loss Lg Line',  style=plot.style_linebr, linewidth=2, color=color.new(#ff0000,0),offset=1)
 
sl_line_sh=plot(show_sl_line and stp_loss_enable and not buy_only and (str_sh or sl_sh) and not stop_loss ? sl_sh_price : na,
 title='Stop loss Sh Line',  style=plot.style_linebr, linewidth=2, color=color.new(#ff0000,0),offset=1)

// ********************************************************************* Take Profit Indicator ************************************************************************************ //
tp_lg_price=TPLgValUsd

if show_tp_line and tp_enable and not sell_only  and tp_lg
    tp_lg_price:=tp_price

tp_sh_price=TPShValUsd

if show_tp_line and tp_enable and not buy_only and tp_sh
    tp_sh_price:=tp_price

tp_line_lg=plot(show_tp_line and tp_enable and not sell_only  and (str_lg or tp_lg) and not take_profit ? tp_lg_price : na,
 title='Take Profit Lg Line',  style=plot.style_linebr, linewidth=2, color=color.new(#00ff00,0),offset=1)
 
tp_line_sh=plot(show_tp_line and tp_enable and not buy_only and (str_sh or tp_sh) and not take_profit ? tp_sh_price : na,
 title='Take Profit Sh Line',  style=plot.style_linebr, linewidth=2, color=color.new(#00ff00,0),offset=1)

// ********************************************************************* Entry Price Indicator ********************************************************************************** //
start_price_lg=plot(start_price , title='Start Price Lg Line',  style=plot.style_stepline_diamond, linewidth=2,
 color=not changeCond and not sell_only  and (str_lg or sl_lg or tp_lg) and not stop_loss and not take_profit ? color.new(color.white,0) : na,trackprice=false,offset=1)
 
start_price_sh=plot(start_price , title='Start Price Sh Line',  style=plot.style_stepline_diamond, linewidth=2,
 color=not changeCond and not buy_only and (str_sh or sl_sh or tp_sh) and not stop_loss and not take_profit ? color.new(color.white,0) : na,trackprice=false,offset=1)

// ********************************************************************* Stop Loss Background *********************************************************************************** //
fill(start_price_lg, sl_line_lg , title='Stop Long Background',  color=show_sl_line and stp_loss_enable and not sell_only and not stop_loss ? color.new(#ff4fb3,90): na)
fill(start_price_sh, sl_line_sh , title='Stop Short Background', color=show_sl_line and stp_loss_enable and not buy_only and not stop_loss ? color.new(#ff4fb3,90): na)

// ******************************************************************* Take Profit Background *********************************************************************************** //
fill(start_price_lg, tp_line_lg , title='TP Long Background',  color=show_tp_line and tp_enable and not sell_only and not take_profit ? color.new(#00ff00,90): na)
fill(start_price_sh, tp_line_sh , title='TP Short Background', color=show_tp_line and tp_enable and not buy_only and not take_profit ? color.new(#00ff00,90): na)

// dmline & dpline
dmline=plot(dm_current,'dm_current',color=str_lg or str_sh ? color.new(#00ff00, 0) : color.new(#217d21, 0),style=plot.style_line,linewidth=1)
dpline=plot(dp_current,'dp_current',color=str_lg or str_sh ? color.new(#ff0000, 0) : color.new(#852727, 0),style=plot.style_line,linewidth=1)

// ******************************************************************* Take Profit Background *********************************************************************************** //
var f1=label(na)
if trade==0 or barstate.ishistory 
    label.delete(f1) 

// ******************************************************************* Label Current Position *************************************************************** //
// ***************************************************************************************************************** //
// *** Ordre Des Parametres Pour F_Print_last : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size) *** //
// *** Order Of Parameters For F_Print_last: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size)  //
// ***************************************************************************************************************** //
// 
f1:=f_print_last(8,close,label.style_label_left, strategy.openprofit>=0 ? color.new(#aaffaa,50) : strategy.openprofit<0 ? color.new(#ff7777,50) : color.new(#cccccc,80), 
     trade_dir+txt_end_trade+'\n'+conf, 
     pnl_color, size.normal)


// ********************************************************************************************************************************************************** // 


// ********************************************************************************************************************************************************** // 
// ************************************************************************ END CODE ************************************************************************ // 
// ********************************************************************************************************************************************************** //


// ********************************************************************************************************************************************************** //


