TEXT   78

Untitled

Guest on 13th July 2022 06:41:51 PM

  1. //@version=5
  2.  
  3. strategy(title='TxS Testing Cipher', overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=15)
  4.  
  5.  
  6. import              Bjorgum/BjCandlePatterns/2 as bj
  7.  
  8. // ================================== //
  9. // ------------> Tips <-------------- //
  10. // ================================== //
  11.  
  12.  
  13. leftTip         =   "Look left for swing high/low in x number of bars to form pivot. The higher the number, the higher the script looks to the left for the highest/lowest point before drawing pivot"        
  14. rightTip        =   "Look right for swing high/low in x number of bars to form pivot. The higher the number, the higher the script looks to the right for the highest/lowest point before drawing pivot"      
  15. nPivTip         =   "This sets the array size, or the number of pivots to track at a time (x highs, and x number of lows)"
  16. atrLenTip       =   "Number of bars to average. ATR is used to standardize zone width between assets and timeframes"    
  17. multTip         =   "ATR multiplier to set zone width. Default is half of one ATR from box bottom to box top"    
  18. perTip          =   "Max zone size as a percent of price. Some assets can be too volatile at low prices creating an unreasonably sized zone"
  19. maxTip          =   "Number of boxes for candlestick patterns to track historically. Note: the higher the number the less pivot zones will be tracked when looking back in time due to the limitation on the number of box elements allowed at once"
  20. futTip          =   "Number of bars to offset labels for price levels"
  21. srcTip          =   "Source input for pivots. Default tracks the highest and lowest bodies of HA candles to average price action, which can result in a level that sits in the overlap of support and resistance"    
  22. alignZonesTip   =   "Aligns recurring zones who's edges overlap an existing zone creating a zone that ages in time and intensifies visually"    
  23. extendTip       =   "Extends current zones right"
  24. lLabTip         =   "Show labels for price levels extended off Key Levels"
  25.  
  26. dhighsTip       =   "Disabling will prevent highs from being tracked"          
  27. dlowsTip        =   "Disabling will prevent lows from being tracked"        
  28. detectBOTip     =   "Show points that price action breaks above all pivots. An arrow from below is displayed"        
  29. detectBDTip     =   "Show points that price action breaks below all pivots. An arrow from above is displayed"        
  30. breakUpTip      =   "Show points that price action breaks above resistance. An arrow from below is displayed"        
  31. breakDnTip      =   "Show points that price action breaks below support. An arrow from above is displayed"          
  32. falseBullTip    =   "Show points that price action initially breaks below support before reversing. False moves can lead to fast moves in the opposite direction (bear trap). A large arrow from below is displayed"          
  33. falseBearTip    =   "Show points that price action initially breaks above resistance before reversing. False moves can lead to fast moves in the opposite direction (bull trap). A large arrow from above is displayed"          
  34. supPushTip      =   "Show up candles that are detected within a support zone. Can show points support is being respected. A triangle from below is displayed"          
  35. resPushTip      =   "Show down candles that are detected within a resistance zone. Can show points resistance is being respected. A triangle from above is displayed"          
  36. curlTip         =   "Show Bjorgum TSI 'curl' when candles are detected in the range of a key zone. Can show momentum shift at Key Levels. (Correlates to Bjorgum TSI indicator)"
  37.  
  38. repaintTip      =   "Wait for candles end before detecting patterns. False will show potential patterns forming before they are confirmed."
  39. labelsTip       =   "Show a label for detected candle patterns"
  40. sBoxTip         =   "Show a box around detected candle patterns"
  41. dTip            =   "Detect Doji candle patterns"      
  42. beTip           =   "Detect Engulfing patterns"    
  43. hsTip           =   "Detect Hammers and Shooting Star patterns"    
  44. dgTip           =   "Detect Dragonfly Doji and Gravestone Doji patterns"    
  45. twTip           =   "Detect Tweezer Top and Tweezer Bottom patterns"    
  46. stTip           =   "Detect Spinning Top patterns"    
  47. pcTip           =   "Detect Piercing and Dark Cloud Cover patterns"    
  48. bhTip           =   "Detect Harami candle patterns"    
  49. lsTip           =   "Detect Long Upper Shadow and Long Lower Shadow patterns"    
  50.  
  51. ecWickTip       =   "Determines if engulfing candles must engulf the wick or just the body of the preceding candle"    
  52. colorMatchTip   =   "Determines if hammers must be up candles and shooting stars must be down candles"    
  53. closeHalfTip    =   "Determines if Tweezer patterns must close beyond the half way point of the preceding candle"    
  54. atrMaxTip       =   "Maximum size of setup candles (as a multiplier of the current ATR)"    
  55. rejectWickTip   =   "The maximum wick size as a percentage of body size allowable for a rejection wick on the resolution candle of the pattern. 0 disables the filter"
  56. hammerFibTip    =   "The relationship of body to candle size for hammers and stars. (ie. body is 33% of total candle size)."    
  57. hsShadowPercTip =   "The maximum allowable opposing wick size as a percent of body size (ex. top wick for a hammer pattern etc.)"    
  58. hammerSizeTip   =   "The minimum size of hammers, stars, or long shadows as a multiplier of ATR. (To filter out tiny setups)"    
  59. dojiSizeTip     =   "The relationship of body to candle size (ie. body is 5% of total candle size)."    
  60. dojiWickSizeTip =   "Maximum wick size comparative to the opposite wick. (eg. 2 = bottom wick must be less than or equal to 2x the top wick)."    
  61. luRatioTip      =   "A relationship of the upper wick to the overall candle size expressed as a percent."    
  62.  
  63. lookbackTip     =   "Number of candles that can be included in a false break signal"        
  64. swingTip        =   "Swing detection is used to filter signals on breakout type signals. A higher number will mean more significant points, but less of them"        
  65. reflectTip      =   "Filter to ensure a setup is a significant swing point. Look back this far"
  66. offsetTip       =   "Candle pattern high/low distance from absolute swing high/low. Example: 0 would filter patterns that are only the highest/lowest, 1 filters second highest over the significant length, etc."
  67.  
  68. bullPivotTip    =   "Color of bullish Key Levels\n(border, background)"            
  69. bearPivotTip    =   "Color of bearish Key Levels\n(border, background)"            
  70. breakoutTip     =   "Color of breakout arrows\n(bull, bear,)"          
  71. SnRTip          =   "Color of triangles for broken support or resistance\n(bull, bear)"  
  72. falseBreakTip   =   "Color of arrows for false breaks\n(bull, bear, arrow max height in pixels)"            
  73. moveTip         =   "Color of triangles for candles that are detected within zones\n(bull, bear)"    
  74. patTip          =   "Color of boxes that wrap candestick patterns\nBackgrounds: (bull, neutral, bear)\nBorders: (bull, neutral, bear)"    
  75. labTip          =   "Color of labels that mark candestick patterns\nText: (bull, neutral, bear)\nLabels: (bull, neutral, bear)"    
  76. stratTip        =   "TSI speed control presets. Both speeds correlate to the Bjorgum TSI indicator"
  77.  
  78. // ================================== //
  79. // ---------> User Input <----------- //
  80. // ================================== //
  81. // useTrailingSL   =   input.bool      (true, "Use Trailing Stop Loss?")
  82.  
  83. //SuperTrend Inputs
  84. useSuperTrend = input.bool      (false   ,   "use SuperTrend"            ,   group= "Exit Conditions"                     )
  85. atrPeriod = input(10, "ATR Length", group= "SuperTrend")
  86. factor = input.float(3.0, "Factor", step = 0.01, group= "SuperTrend")
  87. entry_distance=input(5, title="Entry distance for stop orders", group= "SuperTrend")
  88.  
  89. //Trailing Stop Loss Inputs
  90. // Configure trail stop level with input options (optional)
  91. useTrailingStopLoss = input.bool      (false   ,   "use Trailing StopLoss"            ,   group= "Exit Conditions"                     )
  92. longTrailPerc = input.float(title="Trail Long Loss (%)", group= "Exit Conditions",
  93.       minval=0.0, step=0.1, defval=3) * 0.01
  94.  
  95. shortTrailPerc = input.float(title="Trail Short Loss (%)", group= "Exit Conditions",
  96.       minval=0.0, step=0.1, defval=3) * 0.01
  97.      
  98.  
  99.  
  100.  
  101. left            =   input.int       (20     ,   "Look Left"                     ,   group= "Zones"                , tooltip= leftTip            )    
  102. right           =   input.int       (15     ,   "Look Right"                    ,   group= "Zones"                , tooltip= rightTip           )    
  103. nPiv            =   input.int       (4      ,   "Number of Pivots"              ,   group= "Zones"                , tooltip= nPivTip            )
  104. atrLen          =   input.int       (30     ,   "ATR Length"                    ,   group= "Zones"                , tooltip= atrLenTip          )
  105. mult            =   input.float     (0.5    ,   "Zone Width (ATR)"              ,   group= "Zones"                , tooltip= multTip            ,   step   = 0.1)
  106. per             =   input.float     (5      ,   "Max Zone Percent"              ,   group= "Zones"                , tooltip= perTip             )
  107. max             =   input.float     (10     ,   "Max Boxes for Patterns"        ,   group= "Zones"                , tooltip= maxTip             )
  108. fut             =   input.int       (30     ,   "Offset For Labels"             ,   group= "Zones"                , tooltip= futTip             )
  109. src             =   input.string    ("HA"   ,   "Source For Pivots"             ,   group= "Zones"                , tooltip= srcTip             ,   options= ["HA", "High/Low Body", "High/Low"])
  110. alignZones      =   input.bool      (true   ,   "Align Zones"                   ,   group= "Zones"                , tooltip= alignZonesTip      )
  111. extend          =   input.bool      (false  ,   "Extend Right"                  ,   group= "Zones"                , tooltip= extendTip          )
  112. lLab            =   input.bool      (false  ,   "Show Level Labels"             ,   group= "Zones"                , tooltip= lLabTip            )
  113.  
  114. dhighs          =   input.bool      (true   ,   "Detect Pivot Highs"            ,   group= "Detection"            , tooltip= dhighsTip          )
  115. dlows           =   input.bool      (true   ,   "Detect Pivot Lows"             ,   group= "Detection"            , tooltip= dlowsTip           )
  116. detectBO        =   input.bool      (false  ,   "Detect Breakout"               ,   group= "Detection"            , tooltip= detectBOTip        )
  117. detectBD        =   input.bool      (false  ,   "Detect Breakdown"              ,   group= "Detection"            , tooltip= detectBDTip        )
  118. breakUp         =   input.bool      (false  ,   "Detect Resistance Break"       ,   group= "Detection"            , tooltip= breakUpTip         )
  119. breakDn         =   input.bool      (false  ,   "Detect Support Break"          ,   group= "Detection"            , tooltip= breakDnTip         )
  120. falseBull       =   input.bool      (false  ,   "Detect False Breakdown"        ,   group= "Detection"            , tooltip= falseBullTip       )
  121. falseBear       =   input.bool      (false  ,   "Detect False Breakup"          ,   group= "Detection"            , tooltip= falseBearTip       )
  122. supPush         =   input.bool      (false  ,   "Detect Moves Off Support"      ,   group= "Detection"            , tooltip= supPushTip         )
  123. resPush         =   input.bool      (false  ,   "Detect Moves Off Resistance"   ,   group= "Detection"            , tooltip= resPushTip         )
  124. curl            =   input.bool      (false  ,   "Detect TSI Curl"               ,   group= "Detection"            , tooltip= curlTip            )
  125.  
  126. repaint         =   input.bool      (true   ,   "Wait For Confirmed Bar"        ,   group= "Candle Patterns"      , tooltip= repaintTip         )
  127. labels          =   input.bool      (false  ,   "Show Label"                    ,   group= "Candle Patterns"      , tooltip= labelsTip          )
  128. sBox            =   input.bool      (false  ,   "Show Boxes Around Patterns"    ,   group= "Candle Patterns"      , tooltip= sBoxTip            )
  129. d_              =   input.bool      (false  ,   "Detect Doji"                   ,   group= "Candle Patterns"      , tooltip= dTip               )
  130. be_             =   input.bool      (false  ,   "Detect Engulfing"              ,   group= "Candle Patterns"      , tooltip= beTip              )
  131. hs_             =   input.bool      (false  ,   "Detect Hammers and Stars"      ,   group= "Candle Patterns"      , tooltip= hsTip              )
  132. dg_             =   input.bool      (false  ,   "Detect Dragons and Graves"     ,   group= "Candle Patterns"      , tooltip= dgTip              )
  133. tw_             =   input.bool      (false  ,   "Detect Tweezers"               ,   group= "Candle Patterns"      , tooltip= twTip              )
  134. st_             =   input.bool      (false  ,   "Detect Spinning Top"           ,   group= "Candle Patterns"      , tooltip= stTip              )
  135. pc_             =   input.bool      (false  ,   "Detect Piercing and Clouds"    ,   group= "Candle Patterns"      , tooltip= pcTip              )
  136. bh_             =   input.bool      (false  ,   "Detect Harami"                 ,   group= "Candle Patterns"      , tooltip= bhTip              )
  137. ls_             =   input.bool      (false  ,   "Detect Long Shadows"           ,   group= "Candle Patterns"      , tooltip= lsTip              )
  138.  
  139. alertMode       =   input.string    (alert.freq_once_per_bar_close              ,   "Alerts Mode"                 , group  = "Alert Frequency"  ,   options= [alert.freq_once_per_bar, alert.freq_once_per_bar_close])
  140.  
  141. ecWick          =   input.bool      (false  ,   "Engulfing Must Engulf Wick"    ,   group= "Candle Filters"       , tooltip= ecWickTip          )
  142. colorMatch      =   input.bool      (false  ,   "H&S Must Match Color"          ,   group= "Candle Filters"       , tooltip= colorMatchTip      )
  143. closeHalf       =   input.bool      (false  ,   "Tweezer Close Over Half"       ,   group= "Candle Filters"       , tooltip= closeHalfTip       )
  144. atrMax          =   input.float     (0.0    ,   "Max Candle Size (× ATR)"       ,   group= "Candle Filters"       , tooltip= atrMaxTip          ,   step= 0.1 )
  145. rejectWickMax   =   input.float     (0.0    ,   "[EC] Max Reject Wick Size"     ,   group= "Candle Filters"       , tooltip= rejectWickTip      ,   step= 1   )  
  146. hammerFib       =   input.float     (33     ,   "[HS] H&S Ratio (%)"            ,   group= "Candle Filters"       , tooltip= hammerFibTip       ,   step= 1   )
  147. hsShadowPerc    =   input.float     (5      ,   "[HS] H&S Opposing Shadow (%)"  ,   group= "Candle Filters"       , tooltip= hsShadowPercTip    ,   step= 1   )
  148. hammerSize      =   input.float     (0.1    ,   "[HS] H&S Min Size (× ATR)"     ,   group= "Candle Filters"       , tooltip= hammerSizeTip      ,   step= 0.1 )
  149. dojiSize        =   input.float     (5      ,   "[DJ] Doji Size (%)"            ,   group= "Candle Filters"       , tooltip= dojiSizeTip        ,   step= 1   )
  150. dojiWickSize    =   input.float     (2      ,   "[DJ] Max Doji Wick Size"       ,   group= "Candle Filters"       , tooltip= dojiWickSizeTip    ,   step= 1   )
  151. luRatio         =   input.float     (75     ,   "[LS] Long Shadow (%)"          ,   group= "Candle Filters"       , tooltip= luRatioTip         ,   step= 1   )
  152.  
  153. lookback        =   input.int       (2      ,   "Lookback For Breaks"           ,   group= "Lookback"             , tooltip= lookbackTip        )
  154. swing           =   input.int       (5      ,   "swing High/Low"                ,   group= "Lookback"             , tooltip= swingTip           )
  155. reflect         =   input.int       (10     ,   "Significant High/Low"          ,   group= "Lookback"             , tooltip= reflectTip         )
  156. offset          =   input.int       (1      ,   "Consider Bar From High/Low"    ,   group= "Lookback"             , tooltip= offsetTip          )
  157.  
  158. bullBorder      =   input.color     (color.new  (#64b5f6, 60), "", inline= "0"  ,   group= "Pivot Color"                                        )
  159. bullBgCol       =   input.color     (color.new  (#64b5f6, 95), "", inline= "0"  ,   group= "Pivot Color"          , tooltip= bullPivotTip       )
  160. bearBorder      =   input.color     (color.new  (#ffeb3b, 60), "", inline= "1"  ,   group= "Pivot Color"                                        )  
  161. bearBgCol       =   input.color     (color.new  (#ffeb3b, 95), "", inline= "1"  ,   group= "Pivot Color"          , tooltip= bearPivotTip       )
  162.  
  163. upCol           =   input.color     (color.new  (#ff6d00, 25), "", inline= "2"  ,   group= "Breakout Color"                                     )
  164. dnCol           =   input.color     (color.new  (#ff00ff, 25), "", inline= "2"  ,   group= "Breakout Color"       , tooltip= breakoutTip        )
  165.  
  166. supCol          =   input.color     (color.new  (#17ff00, 25), "", inline= "3"  ,   group= "S&R Break Color"                                    )
  167. resCol          =   input.color     (color.new  (#ff0000, 25), "", inline= "3"  ,   group= "S&R Break Color"      , tooltip= SnRTip             )
  168.  
  169. fBull           =   input.color     (color.new  (#17ff00, 25), "", inline= "4"  ,   group= "False Break Color"                                  )
  170. fBear           =   input.color     (color.new  (#ff0000, 25), "", inline= "4"  ,   group= "False Break Color"                                  )
  171. arrowMax        =   input.int       (75                      , "", inline= "4"  ,   group= "False Break Color"    , tooltip= falseBreakTip      )
  172.  
  173. moveBullCol     =   input.color     (color.new  (#64b5f6, 25), "", inline= "5"  ,   group= "Moves From S&R Color"                               )
  174. moveBearCol     =   input.color     (color.new  (#ffeb3b, 25), "", inline= "5"  ,   group= "Moves From S&R Color" , tooltip= moveTip            )
  175.  
  176. curlBullCol     =   input.color     (color.new  (#17ff00, 40), "", inline= "6"  ,   group= "Momentum Curl Color"                                )
  177. curlBearCol     =   input.color     (color.new  (#f3ff00, 40), "", inline= "6"  ,   group= "Momentum Curl Color"  , tooltip= curlTip            )
  178.  
  179. patBullBg       =   input.color     (color.new  (#17ff00, 90), "", inline= "7"  ,   group= "Pattern Box Color"                                  )
  180. patNeutBg       =   input.color     (color.new  (#b2b5be, 90), "", inline= "7"  ,   group= "Pattern Box Color"                                  )
  181. patBearBg       =   input.color     (color.new  (#ff0000, 90), "", inline= "7"  ,   group= "Pattern Box Color"                                  )
  182. patBullBo       =   input.color     (color.new  (#17ff00, 80), "", inline= "8"  ,   group= "Pattern Box Color"                                  )
  183. patNeutBo       =   input.color     (color.new  (#b2b5be, 80), "", inline= "8"  ,   group= "Pattern Box Color"                                  )
  184. patBearBo       =   input.color     (color.new  (#ff0000, 80), "", inline= "8"  ,   group= "Pattern Box Color"    , tooltip= patTip             )
  185.  
  186. textBullCol     =   input.color     (color.new  (#17ff00,  0), "", inline= "9"  ,   group= "Label Color (Text/Bg)"                              )
  187. textNeutCol     =   input.color     (color.new  (#b2b5be,  0), "", inline= "9"  ,   group= "Label Color (Text/Bg)"                              )
  188. textBearCol     =   input.color     (color.new  (#ff0000,  0), "", inline= "9"  ,   group= "Label Color (Text/Bg)"                              )
  189. labBullCol      =   input.color     (color.new  (#17ff00, 80), "", inline= "10" ,   group= "Label Color (Text/Bg)"                              )
  190. labNeutCol      =   input.color     (color.new  (#b2b5be, 80), "", inline= "10" ,   group= "Label Color (Text/Bg)"                              )
  191. labBearCol      =   input.color     (color.new  (#ff0000, 80), "", inline= "10" ,   group= "Label Color (Text/Bg)", tooltip= labTip             )
  192.  
  193. strat           =   input.string    ("Fast" ,   "Select a Speed"                ,   group= "TSI Speed Control"    , tooltip= stratTip           ,   options= ["Fast", "Slow"])
  194.    
  195. longf           =   input.int       (25     ,   "Long Length"                   ,   group= "TSI Fast Settings"                                  )
  196. shortf          =   input.int       (5      ,   "Short Length"                  ,   group= "TSI Fast Settings"                                  )
  197. signalf         =   input.int       (14     ,   "Signal Length"                 ,   group= "TSI Fast Settings"                                  )
  198.  
  199. longs           =   input.int       (25     ,   "Long Length"                   ,   group= "TSI Slow Settings"                                  )
  200. shorts          =   input.int       (13     ,   "Short Length"                  ,   group= "TSI Slow Settings"                                  )
  201. signals         =   input.int       (13     ,   "Signal Length"                 ,   group= "TSI Slow Settings"                                  )
  202.  
  203. // ================================== //
  204. // -----> Immutable Constants <------ //
  205. // ================================== //    
  206.  
  207. sync            =   bar_index
  208. labUp           =   label.style_label_up
  209. labDn           =   label.style_label_down
  210. confirmed       =   barstate.isconfirmed
  211. extrap          =   extend ?        extend.right  : extend.none
  212.  
  213. var pivotHigh   =   array.new_box   (nPiv)
  214. var pivotLows   =   array.new_box   (nPiv)  
  215. var highBull    =   array.new_bool  (nPiv)
  216. var lowsBull    =   array.new_bool  (nPiv)
  217. var boxes       =   array.new_box   ()
  218.  
  219. haSrc           =   src    ==       "HA"    
  220. hiLoSrc         =   src    ==       "High/Low"
  221. tsifast         =   strat  ==       "Fast"
  222. tsislow         =   strat  ==       "Slow"
  223.  
  224. // ================================== //
  225. // ---> Functional Declarations <---- //
  226. // ================================== //
  227.  
  228. atr             =   ta.atr          (atrLen)
  229. perMax          =   close*          0.02
  230. min             =   math.min        (perMax, atr*0.3)
  231.  
  232. _haBody()       =>
  233.     haClose     =   (open + high  +  low  + close)    / 4
  234.     haOpen      =   float(na)
  235.     haOpen      :=  na(haOpen[1]) ? (open + close)    / 2 :
  236.                    (nz(haOpen[1]) + nz(haClose[1]))   / 2
  237.    
  238.     [haOpen, haClose]
  239.    
  240. _extend(_x) =>
  241.     for i = 0 to               array.size       (_x)-1
  242.         box.set_right          (array.get       (_x, i), sync)
  243.        
  244. _arrayLoad(_x, _max, _val) =>  
  245.     array.unshift                               (_x,   _val)  
  246.     if  array.size                              (_x) > _max
  247.         array.pop                               (_x)
  248.  
  249. _arrayBox(_x, _max, _val) =>  
  250.     array.unshift                               (_x,   _val)  
  251.     if       array.size                         (_x) > _max
  252.         _b = array.pop                          (_x)
  253.         if extend
  254.             box.set_extend                      (_b, extend.none)
  255.  
  256. _arrayWrap(_x, _max, _val) =>  
  257.     array.unshift                               (_x,   _val)  
  258.     if  array.size                              (_x) > _max
  259.         box.delete(array.pop                    (_x))
  260.  
  261. _delLab(_x)     =>
  262.     if array.size(_x) > 0
  263.         label.delete           (array.pop       (_x))
  264.  
  265. _delLine(_x)    =>
  266.     if array.size(_x) > 0
  267.         line.delete            (array.pop       (_x))
  268.  
  269. _delLevels(_x, _y)  =>
  270.     for i = 0 to array.size                     (_x)-1
  271.         _delLab                                 (_x)
  272.         _delLine                                (_y)
  273.  
  274. _box(_x1, _t, _r, _b, _boCol, _bgCol, _e) =>
  275.     box.new(                   _x1, _t, _r, _b  ,
  276.      xloc        =             xloc.bar_index   ,
  277.      extend      =             _e               ,
  278.      border_color=             _boCol           ,  
  279.      bgcolor     =             _bgCol           )
  280.  
  281. _wrap(_cond, _x, _bb, _bc, _bgc) =>
  282.     _t           =             ta.highest       (high, _bb) + min
  283.     _b           =             ta.lowest        (low , _bb) - min
  284.     _l           =             bar_index -      _bb
  285.     _r           =             bar_index +      1
  286.     if  _cond
  287.         _arrayWrap            (_x, max, _box    (_l, _t, _r, _b, _bc, _bgc, extend.none))
  288.  
  289. _getBox(_x,_i)   =>
  290.     _box         =             array.get        (_x,_i)
  291.     _t           =             box.get_top      (_box)
  292.     _b           =             box.get_bottom   (_box)
  293.     [_t, _b]
  294.    
  295. _align(_x,_y)    =>
  296.     for i = 0 to               array.size       (_x) -1
  297.         [_T, _B] =             _getBox          (_y, 0)
  298.         [_t, _b] =             _getBox          (_x, i)
  299.         if _T > _b and         _T < _t or
  300.            _B < _t and         _B > _b or
  301.            _T > _t and         _B < _b or
  302.            _B > _b and         _T < _t
  303.             box.set_top        (array.get       (_y, 0), _t)
  304.             box.set_bottom     (array.get       (_y, 0), _b)
  305.  
  306. _color(_x, _y)     =>
  307.     var int _track = nPiv
  308.     for i = 0 to               array.size       (_x) -1
  309.         [t_, b_] =             _getBox          (_x, i)
  310.         _isBull  =             array.get        (_y, i)
  311.         if close > t_ and not  _isBull
  312.             box.set_extend(    array.get        (_x, i), extend.none)
  313.             array.set(_x, i,   _box             (sync  , t_, sync, b_, bullBorder, bullBgCol, extrap))
  314.             array.set(_y, i,   true)
  315.             _track += 1
  316.         if close < b_ and _isBull
  317.             box.set_extend(    array.get        (_x, i), extend.none)
  318.             array.set(_x, i,   _box             (sync  , t_, sync, b_, bearBorder, bearBgCol, extrap))
  319.             array.set(_y, i,   false)
  320.             _track -= 1
  321.     _track
  322.  
  323. _detect(_x,_y)      =>
  324.     int  _i         = 0
  325.     bool _found     = false
  326.     bool _isBull    = na
  327.     while (not _found and _i < array.size       (_x)  )
  328.         [t_, b_] =             _getBox          (_x,_i)
  329.         if low < t_ and high > b_
  330.             _isBull :=         array.get        (_y,_i)
  331.             _found  :=         true
  332.         _i          +=         1
  333.     [_found, _isBull]
  334.  
  335. _falseBreak(_l)     =>      
  336.     bool _d         = false
  337.     bool _u         = false
  338.     for i = 1 to lookback
  339.         if _l[i] < _l and _l[i+1] >= _l and _l[1] < _l
  340.             _d      := true
  341.         if _l[i] > _l and _l[i+1] <= _l and _l[1] > _l
  342.             _u      := true
  343.     [_d, _u]
  344.  
  345. _numLevel(_x,_y)    =>
  346.     int _above      = 0
  347.     int _fill       = 0
  348.     for i = 0 to               array.size       (_x)-1
  349.         _isBull     =          array.get        (_x,i)
  350.         if  _isBull
  351.             _above += 1
  352.         if  not na(_isBull)
  353.             _fill  += 1
  354.     for i = 0 to               array.size       (_y)-1
  355.         _isBull     =          array.get        (_y,i)
  356.         if  _isBull
  357.             _above += 1
  358.         if  not na(_isBull)
  359.             _fill  += 1
  360.     [_above, _fill]  
  361.  
  362. _check(_src,_l)     =>
  363.     bool _check     = false
  364.     for i = 0 to _l
  365.         if _src[i]
  366.             _check := true
  367.     _check
  368.  
  369. _count(_src, _l)    =>
  370.     int _result     = 0
  371.     for i = 0 to _l
  372.         if _src > _src[i]
  373.             _result += 1
  374.     _result
  375.  
  376. _label(_x, _y, y, _s, _col1, _col2) =>
  377.     transp = math.min   (color.t(_col1),  color.t(_col2))
  378.     array.unshift       (_x,   label.new (sync+fut,   y                                        ,
  379.                                           text      = str.tostring(math.round_to_mintick(y)   ),
  380.                                           color     = color.new(_col1, transp)                 ,
  381.                                           style     = _s                                       ,
  382.                                           textcolor = color.white                             ))
  383.     if not extend and fut > 0
  384.         array.unshift   (_y,   line.new  (sync, y, sync+fut, y, color= color.new(_col1, transp)))
  385.  
  386. _level(_x, _y)          =>
  387.     var label [] lab    =      array.new_label  (nPiv)
  388.     var line  [] lines  =      array.new_line   (nPiv)
  389.     if barstate.islast and lLab
  390.         _delLevels             (lab, lines)
  391.         for i = 0 to           array.size       (_x)-1
  392.             [_t, _b]    =      _getBox          (_x,i)
  393.             _isBull     =      array.get        (_y,i)
  394.             _col1        =     _isBull ?        bullBgCol  : bearBgCol
  395.             _col2        =     _isBull ?        bullBorder : bearBorder
  396.             if close >  _t
  397.                 _label  (lab, lines, _t, labUp, _col1, _col2)
  398.             if close <  _b
  399.                 _label  (lab, lines, _b, labDn, _col1, _col2)
  400.             if close <  _t and close >   _b
  401.                 _label  (lab, lines, _t, labDn, _col1, _col2)
  402.                 _label  (lab, lines, _b, labUp, _col1, _col2)
  403.  
  404. _alert(_x, _y) =>
  405.     if _x
  406.         alert   (_y + timeframe.period + ' chart. Price is ' + str.tostring(close), alertMode)
  407.        
  408. // ================================== //
  409. // ----> Variable Calculations <----- //
  410. // ================================== //
  411.  
  412. shortvar        =   tsifast ?           shortf  :       shorts  
  413. longvar         =   tsifast ?           longf   :       longs    
  414. signalvar       =   tsifast ?           signalf :       signals
  415.  
  416. tsi             =   ta.tsi              (close,         shortvar,   longvar)
  417. tsl             =   ta.ema              (tsi,           signalvar)
  418.  
  419. highest         =   close ==            ta.highest      (close,     right)
  420. lowest          =   close ==            ta.lowest       (close,     right)
  421.  
  422. closeLows       =   ta.lowest           (close,         swing)
  423. closeHigh       =   ta.highest          (close,         swing)
  424.  
  425. numLows         =   _count              (low,           reflect)
  426. numHigh         =   _count              (high,          reflect)
  427.  
  428. [open_, close_] =   _haBody             ()
  429.  
  430. hiHaBod         =   math.max            (close_,        open_)
  431. loHaBod         =   math.min            (close_,        open_)
  432.  
  433. hiBod           =   math.max            (close,         open)
  434. loBod           =   math.min            (close,         open)
  435.  
  436. srcHigh         =   haSrc ?             hiHaBod :       hiLoSrc ?   high :      hiBod
  437. srcLow          =   haSrc ?             loHaBod :       hiLoSrc ?   low  :      loBod
  438.  
  439. pivot_high      =   ta.pivothigh        (srcHigh,       left,       right)
  440. pivot_low       =   ta.pivotlow         (srcLow,        left,       right)
  441.  
  442. perc            =   close*              (per/100)
  443.  
  444. band            =   math.min            (atr*mult,      perc)       [right]     /2
  445.  
  446. HH              =   pivot_high+         band
  447. HL              =   pivot_high-         band
  448.  
  449. LH              =   pivot_low+          band
  450. LL              =   pivot_low-          band
  451.  
  452. coDiff          =   close -             open
  453.  
  454. // ================================== //
  455. // --------> Logical Order <--------- //
  456. // ================================== //
  457.  
  458. if pivot_high and   dhighs and  confirmed
  459.     _arrayLoad      (highBull , nPiv,   false)      
  460.     _arrayBox       (pivotHigh, nPiv,   _box(sync[right], HH, sync, HL, bearBorder, bearBgCol, extrap))
  461.  
  462. if pivot_low  and   dlows and   confirmed
  463.     _arrayLoad      (lowsBull , nPiv,   true)      
  464.     _arrayBox       (pivotLows, nPiv,   _box(sync[right], LH, sync, LL, bullBorder, bullBgCol, extrap))
  465.  
  466. if alignZones
  467.     _align          (pivotHigh,         pivotHigh)
  468.     _align          (pivotHigh,         pivotLows)    
  469.     _align          (pivotLows,         pivotLows)
  470.     _align          (pivotLows,         pivotHigh)
  471.  
  472. _extend             (pivotHigh)
  473. _extend             (pivotLows)
  474.  
  475. trackHigh       =   _color              (pivotHigh,     highBull)
  476. trackLows       =   _color              (pivotLows,     lowsBull)
  477.  
  478. // ================================== //
  479. // ----> Conditional Parameters <---- //
  480. // ================================== //
  481.  
  482. isLows          =   closeLows      ==   close
  483. isHigh          =   closeHigh      ==   close
  484.  
  485. wasLows         =   _check              (isLows,        lookback)
  486. wasHigh         =   _check              (isHigh,        lookback)
  487.  
  488. [above, total]  =   _numLevel           (highBull,      lowsBull)
  489.  
  490. moveAbove       =   trackHigh       >   trackHigh[1]
  491. moveBelow       =   trackLows       <   trackLows[1]
  492.  
  493. resBreak        =   (trackLows      >   trackLows[1]    or  moveAbove)
  494. supBreak        =   (trackHigh      <   trackHigh[1]    or  moveBelow)
  495.  
  496. breakOut        =   moveAbove     and   highest and     above == total            
  497. breakDwn        =   moveBelow     and   lowest  and     above == 0        
  498.  
  499. [dh, uh]        =   _falseBreak         (trackHigh)
  500. [dl, ul]        =   _falseBreak         (trackLows)
  501.  
  502. falseBreakBull  =   wasLows       and   (dh or dl)
  503. falseBreakBear  =   wasHigh       and   (uh or ul)
  504.  
  505. [fh,hb]         =   _detect             (pivotHigh,     highBull)
  506. [fl,lb]         =   _detect             (pivotLows,     lowsBull)
  507.  
  508. bull            =   (fh or fl) and      (hb or lb)
  509. bear            =   (fh or fl) and not  (hb or lb)
  510.  
  511. bullCheck       =   not resBreak  and   not resBreak[1] and (fh or fl) and  close > open and     (hb or lb)
  512. bearCheck       =   not supBreak  and   not supBreak[1] and (fh or fl) and  close < open and not (hb or lb)
  513.  
  514. highrange       =   reflect-offset
  515. lowsrange       =   offset
  516.  
  517. sigLows         =   numLows        <=   lowsrange  
  518. sigHigh         =   numHigh        >=   highrange
  519.  
  520. isBull1         =   sigLows       and   bull
  521. isBear1         =   sigHigh       and   bear
  522.  
  523. isBull2         =   (sigLows       or   sigLows[1]) and         (bull or bull[1])
  524. isBear2         =   (sigHigh       or   sigHigh[1]) and         (bear or bear[1])
  525.  
  526. data            =   tsi > tsi[1]  and   tsi < tsl
  527. dtat            =   tsi < tsi[1]  and   tsi > tsl
  528.  
  529. hMatch          =   not colorMatch or   close > open
  530. sMatch          =   not colorMatch or   close < open
  531.  
  532. hsFilter        =   bj.barRange()  >=   hammerSize * atr
  533. atrMaxSize      =   bj.barRange()  <=   atrMax     * atr or     atrMax == 0.0
  534.  
  535. rp              =   confirmed  or not   repaint
  536.  
  537. // ================================== //
  538. // -----> Pattern Recognition <------ //
  539. // ================================== //
  540.  
  541. dw              =   isBull1 and rp and d_  and atrMaxSize and bj.doji              (dojiSize           = dojiSize,         dojiWickSize    = dojiWickSize)
  542. db              =   isBear1 and rp and d_  and atrMaxSize and bj.doji              (dojiSize           = dojiSize,         dojiWickSize    = dojiWickSize)
  543. bew             =   isBull2 and rp and be_ and atrMaxSize and bj.bullEngulf        (maxRejectWick      = rejectWickMax,    mustEngulfWick  = ecWick)
  544. beb             =   isBear2 and rp and be_ and atrMaxSize and bj.bearEngulf        (maxRejectWick      = rejectWickMax,    mustEngulfWick  = ecWick)
  545. h               =   isBull1 and rp and hs_ and atrMaxSize and bj.hammer            (ratio              = hammerFib,        shadowPercent   = hsShadowPerc) and hsFilter and hMatch
  546. ss              =   isBear1 and rp and hs_ and atrMaxSize and bj.star              (ratio              = hammerFib,        shadowPercent   = hsShadowPerc) and hsFilter and sMatch
  547. dd              =   isBull1 and rp and dg_ and atrMaxSize and bj.dragonflyDoji     ()
  548. gd              =   isBear1 and rp and dg_ and atrMaxSize and bj.gravestoneDoji    ()
  549. tb              =   isBull2 and rp and tw_ and atrMaxSize and bj.tweezerBottom     (closeUpperHalf     = closeHalf)
  550. tt              =   isBear2 and rp and tw_ and atrMaxSize and bj.tweezerTop        (closeLowerHalf     = closeHalf)
  551. stw             =   isBull1 and rp and st_ and atrMaxSize and bj.spinningTop       ()
  552. stb             =   isBear1 and rp and st_ and atrMaxSize and bj.spinningTop       ()
  553. p               =   isBull1 and rp and pc_ and atrMaxSize and bj.piercing          ()
  554. dcc             =   isBear1 and rp and pc_ and atrMaxSize and bj.darkCloudCover    ()
  555. bhw             =   isBull1 and rp and bh_ and atrMaxSize and bj.haramiBull        ()  
  556. bhb             =   isBear1 and rp and bh_ and atrMaxSize and bj.haramiBear        ()
  557. ll              =   isBull1 and rp and ls_ and atrMaxSize and bj.lls               (ratio              = luRatio)          and hsFilter
  558. lu              =   isBear1 and rp and ls_ and atrMaxSize and bj.lus               (ratio              = luRatio)          and hsFilter
  559.  
  560. // ================================== //
  561. // ------> Graphical Display <------- //
  562. // ================================== //
  563.  
  564. plotFalseDn     =   falseBull     and   falseBreakBull
  565. plotFalseUp     =   falseBear     and   falseBreakBear
  566.  
  567. falseUpCol      =   plotFalseUp     ?   upCol       :   na
  568. falseDnCol      =   plotFalseDn     ?   dnCol       :   na
  569.  
  570. plotBreakOut    =   breakOut      and   detectBO    and not     plotFalseDn
  571. plotBreakDn     =   breakDwn      and   detectBD    and not     plotFalseUp
  572.  
  573. plotResBreak    =   resBreak      and   breakUp     and not     (plotBreakOut or plotFalseDn)
  574. plotSupBreak    =   supBreak      and   breakDn     and not     (plotBreakDn  or plotFalseUp)
  575.  
  576. plotBullCheck   =   bullCheck     and   supPush
  577. plotBearCheck   =   bearCheck     and   resPush
  578.  
  579. plotCurlBull    =   curl and data and   bull
  580. plotCurlBear    =   curl and dtat and   bear
  581.  
  582. plotarrow           (plotFalseUp    ?   coDiff      :   na      ,   colorup  = fBull          ,     colordown=      fBear ,         maxheight=      arrowMax)
  583. plotarrow           (plotFalseDn    ?   coDiff      :   na      ,   colorup  = fBull          ,     colordown=      fBear ,         maxheight=      arrowMax)
  584.  
  585. plotshape           (plotBreakOut   ,   style=shape.arrowup     ,   location=location.belowbar,     color=          upCol ,         size=           size.small)
  586. plotshape           (plotBreakDn    ,   style=shape.arrowdown   ,   location=location.abovebar,     color=          dnCol ,         size=           size.small)
  587.  
  588. plotshape           (plotResBreak   ,   style=shape.arrowup     ,   location=location.belowbar,     color=          supCol,         size=           size.small)
  589. plotshape           (plotSupBreak   ,   style=shape.arrowdown   ,   location=location.abovebar,     color=          resCol,         size=           size.small)
  590.  
  591. plotshape           (plotBullCheck  ,   style=shape.triangleup  ,   location=location.belowbar,     color=          moveBullCol)
  592. plotshape           (plotBearCheck  ,   style=shape.triangledown,   location=location.abovebar,     color=          moveBearCol)
  593.  
  594. plotshape           (plotCurlBull   ,   style=shape.triangleup  ,   location=location.belowbar,     color=          curlBullCol)
  595. plotshape           (plotCurlBear   ,   style=shape.triangledown,   location=location.abovebar,     color=          curlBearCol)
  596.  
  597. bj.dLab             (dw  and labels, labNeutCol, textNeutCol), _wrap (dw  and sBox, boxes, 1, patNeutBo, patNeutBg)
  598. bj.bewLab           (bew and labels, labBullCol, textBullCol), _wrap (bew and sBox, boxes, 2, patBullBo, patBullBg)
  599. bj.hLab             (h   and labels, labBullCol, textBullCol), _wrap (h   and sBox, boxes, 1, patBullBo, patBullBg)
  600. bj.ddLab            (dd  and labels, labBullCol, textBullCol), _wrap (dd  and sBox, boxes, 1, patBullBo, patBullBg)
  601. bj.tbLab            (tb  and labels, labBullCol, textBullCol), _wrap (tb  and sBox, boxes, 2, patBullBo, patBullBg)
  602. bj.stwLab           (stw and labels, labNeutCol, textNeutCol), _wrap (stw and sBox, boxes, 1, patBullBo, patNeutBg)
  603. bj.pLab             (p   and labels, labBullCol, textBullCol), _wrap (p   and sBox, boxes, 2, patBullBo, patBullBg)
  604. bj.hwLab            (bhw and labels, labBullCol, textBullCol), _wrap (bhw and sBox, boxes, 2, patBullBo, patBullBg)
  605. bj.llsLab           (ll  and labels, labBullCol, textBullCol), _wrap (ll  and sBox, boxes, 1, patBullBo, patBullBg)
  606.  
  607. bj.dLab             (db  and labels, labNeutCol, textNeutCol), _wrap (db  and sBox, boxes, 1, patNeutBo, patNeutBg)
  608. bj.bebLab           (beb and labels, labBearCol, textBearCol), _wrap (beb and sBox, boxes, 2, patBearBo, patBearBg)
  609. bj.ssLab            (ss  and labels, labBearCol, textBearCol), _wrap (ss  and sBox, boxes, 1, patBearBo, patBearBg)
  610. bj.gdLab            (gd  and labels, labBearCol, textBearCol), _wrap (gd  and sBox, boxes, 1, patBearBo, patBearBg)
  611. bj.ttLab            (tt  and labels, labBearCol, textBearCol), _wrap (tt  and sBox, boxes, 2, patBearBo, patBearBg)
  612. bj.stbLab           (stb and labels, labNeutCol, textNeutCol), _wrap (stb and sBox, boxes, 1, patBearBo, patBearBg)
  613. bj.dccLab           (dcc and labels, labBearCol, textBearCol), _wrap (dcc and sBox, boxes, 2, patBearBo, patBearBg)
  614. bj.hbLab            (bhb and labels, labBearCol, textBearCol), _wrap (bhb and sBox, boxes, 2, patBearBo, patBearBg)
  615. bj.lusLab           (lu  and labels, labBearCol, textBearCol), _wrap (lu  and sBox, boxes, 1, patBearBo, patBearBg)
  616.  
  617. _level              (pivotHigh, highBull)
  618. _level              (pivotLows, lowsBull)
  619.  
  620.  
  621. if useSuperTrend
  622.     [supertrend, direction] = ta.supertrend(factor, atrPeriod)
  623.     // bodyMiddle = plot((open + close) / 2, display=display.none)
  624.     // upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
  625.     // downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
  626.     isUpTrend = direction < 0 ? true : false
  627.     isDownTrend = direction < 0 ? false : true
  628.    
  629. // fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
  630. // fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
  631. // ================================== //
  632. // -----> Alert Functionality <------ //
  633. // ================================== //
  634.  
  635. alertcondition      (resBreak       ,   'Resistance break'                      ,   'Resistance broke on {{interval}} chart. Price is {{close}}'                    )
  636. alertcondition      (supBreak       ,   'Support break'                         ,   'Support broke on {{interval}} chart. Price is {{close}}'                       )
  637. alertcondition      (bullCheck      ,   'Found support'                         ,   'Pushing Off Key Level Support on {{interval}} chart. Price is {{close}}'       )
  638. alertcondition      (bearCheck      ,   'Found resistance'                      ,   'Pushing Off Key Level Resistance on {{interval}} chart. Price is {{close}}'    )
  639. alertcondition      (falseBreakBull ,   'False break down'                      ,   'False Break Down on {{interval}} chart. Price is {{close}}'                    )
  640. alertcondition      (falseBreakBear ,   'False break up'                        ,   'False Break Up on {{interval}} chart. Price is {{close}}'                      )
  641. alertcondition      (breakOut       ,   'Breakout'                              ,   'Breakout on {{interval}} chart. Price is {{close}}'                            )
  642. alertcondition      (breakDwn       ,   'Breakdown'                             ,   'Breakdown on {{interval}} chart. Price is {{close}}'                           )
  643.  
  644. _alert              (plotResBreak   ,   'Resistance broke on '                  )
  645. _alert              (plotSupBreak   ,   'Support break '                        )
  646. _alert              (plotBullCheck  ,   'Pushing off key level support on '     )
  647. _alert              (plotBearCheck  ,   'Pushing off key level resistance on '  )
  648. _alert              (plotFalseDn    ,   'False break down on '                  )
  649. _alert              (plotFalseUp    ,   'False break up on '                    )
  650. _alert              (plotBreakOut   ,   'Breakout on '                          )
  651. _alert              (plotBreakDn    ,   'Breakdown on '                         )
  652.  
  653. _alert              (dw             ,   'Doji at support on '                   )
  654. _alert              (db             ,   'Doji at resistance on '                )
  655. _alert              (bew            ,   'Bullish Engulfing on '                 )
  656. _alert              (beb            ,   'Bearish Engulfing on '                 )
  657. _alert              (h              ,   'Hammer candle on '                     )
  658. _alert              (ss             ,   'Shooting star on '                     )
  659. _alert              (dd             ,   'Dragonfly Doji on '                    )
  660. _alert              (gd             ,   'Gravestone Doji on '                   )
  661. _alert              (tb             ,   'Tweezer Bottom on '                    )
  662. _alert              (tt             ,   'Tweezer Top on '                       )
  663. _alert              (stw            ,   'White Spinning Top on '                )
  664. _alert              (stb            ,   'Black Spinning Top on '                )
  665. _alert              (p              ,   'Piercing on '                          )
  666. _alert              (dcc            ,   'Dark Cloud Cover on '                  )
  667. _alert              (bhw            ,   'Bullish Harami on '                    )
  668. _alert              (bhb            ,   'Bearish Harami on '                    )
  669. _alert              (ll             ,   'Long Lower Shadow on '                 )
  670. _alert              (lu             ,   'Long Upper Shadow on '                 )
  671.  
  672. //  ____  __ _  ____
  673. // (  __)(  ( \(    \
  674. //  ) _) /    / ) D (
  675. // (____)\_)__)(____/
  676.  
  677.  
  678.  
  679. //END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
  680. ////////////////////////////////////////////////////////////////////////////////
  681. //STRATEGY TESTER▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
  682.  
  683. // piv_high = ta.p(high,1,1)
  684. // piv_low = ta.pivotlow(low,1,1)
  685. // var float stoploss_long=low
  686. // var float stoploss_short=high
  687.  
  688. // pl=valuewhen(piv_low,piv_low,0)
  689. // ph=valuewhen(piv_high,piv_high,0)
  690.  
  691. // if GoLong
  692. //     stoploss_long := low<pl ? low : pl
  693. // if GoShort
  694. //     stoploss_short := high>ph ? high : ph
  695. // plot(stoploss_long, color=color.lime, title="stoploss_long")
  696. // plot(stoploss_short, color=color.red, title="stoploss_short")
  697.  
  698. //BACKTEST DATE RANGE
  699. // === BACKTEST RANGE ===
  700.  
  701. dummy0 = input.bool(true, title = "=Backtest Inputs=")
  702. FromDay    = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)
  703. FromMonth  = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)
  704. FromYear   = input.int(defval = 2022, title = "From Year", minval = 2005)
  705. ToDay      = input.int(defval = 31, title = "To Day", minval = 1, maxval = 31)
  706. ToMonth    = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12)
  707. ToYear     = input.int(defval = 2022, title = "To Year", minval = 2006)
  708. Start     = timestamp(FromYear, FromMonth, FromDay, 00, 00)
  709. Finish    = timestamp(ToYear, ToMonth, ToDay, 23, 59)
  710. date_range = time >= Start and time <= Finish ? true : false  
  711.  
  712. ////////////////STOP LOSS and TAKE PROFIT////////////////////////////
  713.  
  714. longStopPrice = 0.0
  715.  
  716. longStopPrice := if (strategy.position_size > 0)
  717.     stopValue = close * (1 - longTrailPerc)
  718.     math.max(stopValue, longStopPrice[1])
  719. else
  720.     0
  721.    
  722. shortStopPrice = 0.0
  723.  
  724. shortStopPrice := if (strategy.position_size < 0)
  725.     stopValue = close * (1 + shortTrailPerc)
  726.     math.min(stopValue, shortStopPrice[1])
  727. else
  728.     999999
  729.  
  730.  
  731.  
  732.  
  733.  
  734.  
  735.  
  736.  
  737. ////////////////
  738.  
  739. resistanceTouch = plotBreakDn or plotSupBreak or plotCurlBear
  740. supportTouch = plotBreakOut or plotResBreak or plotCurlBull
  741.  
  742. longCondition = supportTouch and date_range
  743. shortCondition = resistanceTouch and date_range
  744.  
  745. exitLong = resistanceTouch or plotBearCheck
  746. exitShort = supportTouch or plotBullCheck
  747.        
  748.        
  749. strategy.entry("long", strategy.long, 1, when = longCondition)
  750. // strategy.exit("exit", "long", profit = takePer, loss = stopPer)
  751. // strategy.exit("Exit Long", from_entry="long", when = isDownTrend )
  752. strategy.close("long", when =  exitLong or shortCondition)
  753.  
  754. strategy.entry("short", strategy.short, 1, when = shortCondition)
  755. // strategy.exit("exit", "short", profit = takePer, when = isUpTrend)
  756. // strategy.exit("Exit Short", from_entry="short", stop=3)
  757. strategy.close("short", when = exitShort or longCondition)
  758.  
  759.  
  760. if (strategy.position_size > 0 and useTrailingStopLoss)
  761.     strategy.exit(id="XL TRL STP", stop=longStopPrice)
  762.  
  763. if (strategy.position_size < 0 and useTrailingStopLoss)
  764.     strategy.exit(id="XS TRL STP", stop=shortStopPrice)
  765.  
  766. // if GoLong
  767. //     alertsyntax_golong='long offset=' + tostring(entry_distance) + ' slprice=' + tostring(stoploss_long) + ' tp=' + tostring(TakeProfitLevel)
  768. //     alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close)
  769. // if GoShort
  770. //     alertsyntax_goshort='short offset=' + tostring(-entry_distance) + ' slprice=' + tostring(stoploss_short) + ' tp=' + tostring(TakeProfitLevel)
  771. //     alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close)
  772. // if CancelLong
  773. //     alertsyntax_cancellong='cancel long'
  774. //     alert(message=alertsyntax_cancellong, freq=alert.freq_once_per_bar_close)
  775. // if CancelShort
  776. //     alertsyntax_cancelshort='cancel short'
  777. //     alert(message=alertsyntax_cancelshort, freq=alert.freq_once_per_bar_close)
  778. //Entry Alerts
  779. if longCondition
  780.     alert('Long Position Entry', alert.freq_once_per_bar)
  781. if shortCondition
  782.     alert('Short Position Entry', alert.freq_once_per_bar)
  783.  
  784. //Exit Alerts
  785. if exitLong
  786.     alert('Long Position Exit', alert.freq_once_per_bar)
  787. if exitShort
  788.     alert('Short Position Exit', alert.freq_once_per_bar)
  789.    
  790.  
  791. // //Take Profit Alerts
  792. // if (((direction_strategy == "Long Only" or direction_strategy == "Long and Short")) and use_take_profit and exit_function_long) and OPTION_TP_ALERT
  793. //     alert(tpAlertMessage, alert.freq_once_per_bar)
  794. // if ((direction_strategy == "Short Only" or direction_strategy == "Long and Short") and use_take_profit and exit_function_short) and OPTION_TP_ALERT
  795. //     alert(tpAlertMessage, alert.freq_once_per_bar)
  796.    
  797. // //Stop Loss Alerts
  798. // if (((direction_strategy == "Long Only" or direction_strategy == "Long and Short")) and use_stop_loss and (stop_function_long or stop_function_long_2)) and OPTION_SL_ALERT
  799. //  

Raw Paste


Login or Register to edit or fork this paste. It's free.