xmd79

Limit Order + ATR Stop-Loss

May 18th, 2023
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 50.41 KB | None | 0 0
  1. //████████╗ █████╗ ███╗ ██╗██╗ ██╗███████╗███████╗
  2. //╚══██╔══╝██╔══██╗████╗ ██║██║ ██║██╔════╝██╔════╝
  3. // ██║ ███████║██╔██╗██║███████║█████╗ █████╗
  4. // ██║ ██╔══██║██║╚████║██╔══██║██╔══╝ ██╔══╝
  5. // ██║ ██║ ██║██║ ╚███║██║ ██║███████╗██║
  6. // ╚═╝ ╚═╝ ╚═╝╚═╝ ╚══╝╚═╝ ╚═╝╚══════╝╚═╝
  7. //@version=5
  8. indicator(title='Limit Order + ATR Stop-Loss', shorttitle='Limit + ATR Stop-Loss', overlay=true)
  9.  
  10. //TOOLTIPS
  11. var string tt_Hide = "If selected, this indicator will only be visible on the enterred ticker.\n\nAn error ❗ will display beside indicator title when when hidden."
  12. var string tt_Interact = "Click location for ATR Trailing Stoploss entry on next price cross (Long by default). Drag 🟢 to modify afterwards."
  13. var string tt_entryType = "Entry Type Long or Short.\n\nLong Limit: Buy after cross down.\nLong Stop-Limit: Buy after cross above.\nShort Limit: Sell after cross up.\nShort Stop-Limit: Sell after cross below."
  14. var string tt_PriceTarget = "Profit target can be set on the opposite side of price in compared to the trailing stoploss.\n\nR:R = Risk/Reward Target\nPrice = Price Target\n\nStop At Target = If Target hit, Trailing Stoploss stops."
  15. var string tt_updateStop = "Select frequency of Stoploss updates.\n\n\nAlways = update continuously.\n\nBar Open = update bar from prior bar close.\n\nEntry Bar Open, then Always = update bar from prior bar close for entry bar, then every bar after updates continuously."
  16. var string tt_settingsATR = "The Average True Range (ATR) is a volatility indicator that measures price fluctuations. Higher calculated ATR values mean more volatility. This ATR result is aplied to the stoploss."
  17. var string tt_src = "Source of ATR Stoploss placement. Note that using a different source may result in unexpected results due to limitations of how this indicator was created.\n\nSources: \n Entry = 'non-trailing' from entry price (start point) \n Open = open \n High = high \n Low = low \n Close = close \n OC2 = (open + close)/2 \n HL2 = (high + low)/2 \n HLC3 = (high + low + close)/3 \n OHLC4 = (open + high + low + close)/4 \n HLCC4 = (high + low + close + close)/4"
  18. var string tt_srcEntry = "Only applies to the first bar of an entry for the ATR Stoploss placement."
  19. var string tt_Trigger = "Criteria used to determine if entry, stop-loss, or target has been hit.\n\nWick: low/high wicks outside. \nClose: close outside."
  20. var string tt_estimate = "Smooth the estimated stoploss prior to the active entry begins. This will affect the estimated target to be smoothed."
  21. var string tt_Interactive = "Display ATR Trailing Position"
  22. var string tt_Label = "Label including Positions Levels and Status\n\nCurrent = Label location is at current price bar \nTrailing = Label location is at trailing stoploss"
  23. var string tt_Table = "Table including Position Levels, Stoploss Settings, Target Settings, and Trigger Settings"
  24. var string tt_TargetFill = 'Display Target Fill, Target Fill Color, Target Line Color'
  25. var string tt_StopFill = 'Display Stoploss Fill, Stoploss Fill Color, Stoploss Line Color'
  26. var string tt_UpperBand = "Display Normal ATR Upper Band\nUses all settings from 'ATR Settings'"
  27. var string tt_LowerBand = "Display Normal ATR Lower Band\nUses all settings from 'ATR Settings'"
  28. var string tt_alert = "\n\nCheck alerts to use. Go to 'Create Alert' and set the condition to 'Limit Order + ATR Stoploss', select create. \n\nDetails can be added using words in Curly Brackets:\n {{trail}} = ATR trailing stop-loss (price) \n {{target}} = Profit Target (price) \n {{type}} = Long or Short stop-loss (word) \n {{traildistance}} = Trailing Distance (%) \n {{targetdistance}} = Target Distance (%) \n {{starttime}} = Start time of position (day:hr:min) \n {{target}} = Price target (price) \n {{maxdrawdown}} = max loss \n {{maxprofit}} = max profit \n {{update}} = stoploss update frequency (input) \n {{entrysource}} = entry as 1st bar source (yes/no) \n {{triggerentry}} = Wick/Close Trigger entry input\n {{triggerexit}} = Wick/Close Trigger exit input\n {{triggertarget}} = Wick/Close Trigger target input\n {{atrlength}} = ATR length input \n {{atrmultiplier}} = ATR multiplier input \n {{atrtype}} = ATR type input \n {{ticker}} = Ticker of chart (word) \n {{exchange}} = Exchange of chart (word) \n {{description}} = Description of ticker (words) \n {{close}} = Bar close (price) \n {{open}} = Bar open (price) \n {{high}} = Bar high (price) \n {{low}} = Bar low (price) \n {{hl2}} = Bar HL2 (price) \n {{volume}} = Bar volume (value) \n {{time}} = Current time (day:hr:min) \n {{interval}} = Chart timeframe \n {{newline}} = New line for text"
  29. var string tt_alertEntry = "Entry: alert when new entry begins."
  30. var string tt_alertEntryEx = "\n\nExample Alert Message Input: \n New {{type}} Entry with ATR Trailing Stoploss {{newline}}{{interval}} {{ticker}}\n\nExample Alert Message Output: \n New Long Entry with ATR Trailing Stoploss\n 4h BTCUSD"
  31. var string tt_alertTrailHit= "Trailing Hit: alert trailing ATR Stoploss hit."
  32. var string tt_alertTrailEx = "\n\nExample Alert Message Input: \n {{band}} ATR Trailing Stop Hit at {{trail}} ({{type}}){{newline}}{{interval}} {{ticker}}\n\nExample Alert Message Output: \n Lower ATR Trailing Stop Hit at 25 (Long)\n 4h BTCUSD"
  33. var string tt_alertTarget = "Target Hit: alert target hit (while trailing not hit)."
  34. var string tt_alertTargetEx= "\n\nExample Alert Message Input: \n Price crossing target of {{target}} ({{type}}){{newline}}{{interval}} {{ticker}} ATR Trailing Stop Not Hit\n\nExample Alert Message Output: \n Price crossing target of 100 (Long)\n 4h BTCUSD ATR Trailing Stop Not Hit"
  35. var string tt_alertInvalid = "Overlapping ATR Failed Entry, which only occurs on entry bar if the ATR settings cause the ATR Stoploss to be hit on the open bar."
  36.  
  37. //OPTIONS
  38. var string o_Long = '🟢Long' //Entry Type
  39. var string o_Short = '🔴Short' //Entry Type
  40. var string o_RR = 'R:R' //Target Type
  41. var string o_Price = 'Price' //Target Type
  42. var string o_Every = 'Always' //Stoploss Update Frequency
  43. var string o_BarOpen = 'Bar Open' //Stoploss Update Frequency
  44. var string o_EntryBarOpen = 'Entry Bar Open, then Always' //Stoploss Update Frequency
  45. var string o_entry = "New {{type}} Entry with ATR Trailing Stoploss {{newline}}{{interval}} {{ticker}}" //Alert Message
  46. var string o_trailing = "{{band}} ATR Trailing Stop Hit at {{trail}} ({{type}}){{newline}}{{interval}} {{ticker}}" //Alert Message
  47. var string o_target = "Price crossing target of {{target}} ({{type}}){{newline}}{{interval}} {{ticker}} ATR Trailing Stop Not Hit" //Alert Message
  48. var string o_inavlidEntry = "Overlapping ATR and Bar" //Alert Message
  49.  
  50.  
  51. //COLORS
  52. var color c_colStoploss = color.new(color.blue,0) //Line - Stoploss
  53. var color c_colTarget = color.new(color.blue,0) //Line - Target
  54. var color c_colLossFill = color.new(color.red,20) //Fill - Stoploss
  55. var color c_colProfitFill = color.new(color.lime,20) //Fill - Target
  56. var color c_colBandUpper = color.new(color.purple,20) //Line - Normal Upper ATR Band
  57. var color c_colBandLower = color.new(color.teal,20) //Line - Normal Upper ATR Band
  58. var color colClear = color.new(color.blue,100) //Transparent
  59.  
  60. //VARIABLES
  61. var timeLabel = time(na) //Time saved for placement of label
  62. var bool startNow = false //Start Plotting TrailingStop Loss
  63. var bool waitFirstTargetHit= true //Prevents multiple hits of profit target
  64. var bool overlappingATR = false //Check if ATR is overlapping price bar on entry
  65. var bool waitingTrailing = true //Waiting to enter Position
  66. var bool currentlyTrailing = false //Active Position
  67. var bool limitOrder = true //Limit Order or Stop-Limit Order
  68. var float upperTrailing = 0.0 //Set during active short
  69. var float lowerTrailing = 0.0 //Set during active long
  70. var float targetPrice = float(na) //For price target value (from either R:R or Price input)
  71. var float exitPrice = float(na) //For exit price value
  72. var float estimatedStoploss= float(na) //Estimated Stoploss (smoothed)
  73. var string limitTypeText = '' //Limit or Stop-Limit
  74. var int startMinute = int(na) //Start minute (for alerts)
  75. var int startHour = int(na) //Start hour (for alerts)
  76. var int startDay = int(na) //Start day (for alerts)
  77.  
  78. //INPUTS - Show only on certain ticker
  79. hideUnlessSelected = input(false, title='Show only on ticker', inline='sec', tooltip=tt_Hide)
  80. hideUnlessSelectedVAL = input.symbol("", title="", inline='sec')
  81. if hideUnlessSelected
  82. if syminfo.ticker(hideUnlessSelectedVAL) != syminfo.ticker and hideUnlessSelectedVAL != '' //Checks symbol (exludes exchange check)
  83. runtime.error('Selected to show only on ' + syminfo.ticker(hideUnlessSelectedVAL))
  84.  
  85. //INPUTS - Interactive
  86. entryType = input.string(o_Long, title="Entry Type", inline='Entry', group='Interactive Position', tooltip=tt_entryType, options=[o_Long,o_Short])
  87. yBarPrice = input.price(0.0, title='Start Point', inline='Start', group='Interactive Position', confirm=true)
  88. xBarTime = input.time(0, title='', inline='Start', group='Interactive Position', tooltip=tt_Interact, confirm=true)
  89. var isLong = entryType == o_Long ? true : false //Position Direction
  90. var col_isLong = isLong ? color.lime : color.red //Position Direction (Color)
  91. var entryPrice = yBarPrice //For entry price value
  92. var invalidStart= xBarTime == 0 or yBarPrice == 0 ? true : false
  93.  
  94. //Check Starting Bar to Search for Entry
  95. xBarTime_Now = xBarTime == time ? true : false //First valid bar
  96. xBarTime_Valid = xBarTime <= time ? true : false //All valid bars
  97.  
  98. //Limit or Stoplimit order
  99. if xBarTime == time
  100. if isLong //Long
  101. limitOrder := yBarPrice < hl2 ? true : false
  102. else //Short
  103. limitOrder := yBarPrice > hl2 ? true : false
  104. limitTypeText := limitOrder ? 'Limit' : 'Stop-Limit'
  105.  
  106. //DESCRIPTIONS - Stop-limit orders and limit orders
  107. var string descLongStopLimit = "Long stop limit order: A buy order that is triggered only after the price reaches a specific level, and is executed at a set price or better."
  108. var string descShortStopLimit = "Short stop limit order: A sell order that is triggered only after the price reaches a specific level, and is executed at a set price or better."
  109. var string descLongLimit = "Long limit order: A buy order that is executed at a set price or better, without any trigger condition."
  110. var string descShortLimit = "Short limit order: A sell order that is executed at a set price or better, without any trigger condition."
  111. var string selectedDesc = isLong and limitOrder ? descLongLimit :
  112. isLong and limitOrder == false ? descLongStopLimit :
  113. isLong == false and limitOrder ? descShortLimit :
  114. descShortStopLimit
  115.  
  116. //INPUTS - Stoploss Update
  117. updateStopVAL = input.string(o_Every, title="Update Frequency", inline="ATR", group="Interactive Position", options=[o_Every,o_BarOpen,o_EntryBarOpen], tooltip=tt_updateStop)
  118. updateOnce = updateStopVAL == o_BarOpen ? true : false
  119. updateEntryOnce = updateStopVAL == o_EntryBarOpen ? true : false
  120.  
  121. //INPUTS - Price Target
  122. useDisplayTarget= input(false, title="Profit Target", inline="Target", group="Interactive Position", tooltip=tt_PriceTarget)
  123. targetType = input.string(o_RR, title="", inline='Target', group="Interactive Position", options=[o_RR,o_Price])
  124. targetMult = input.float(1.5, title="", inline="Target", group="Interactive Position", step=0.1)
  125. stopAtTarget = input(true, title="Stop at Target", inline="Target", group="Interactive Position")
  126. var targetTypeRR= targetType == o_RR ? true : false
  127. var entryTypeText= isLong ? 'Long ' : 'Short '
  128.  
  129. //INPUTS - ATR Settings
  130. length = input.int(14, minval=1, title='Length', inline="ATR", group="ATR Settings")
  131. multiplier = input.float(3.0,step=0.5,title='Multiplier', inline="ATR", group="ATR Settings")
  132. maTypeInput = input.string("RMA", title="Type", inline="ATR", group="ATR Settings", options=["SMA", "EMA", "RMA", "WMA", "VWMA"])
  133.  
  134. //OPTIONS - Sources
  135. var string o_src_entry = 'Entry'
  136. var string o_src_open = 'Open'
  137. var string o_src_high = 'High'
  138. var string o_src_low = 'Low'
  139. var string o_src_close = 'Close'
  140. var string o_src_oc2 = 'OC2'
  141. var string o_src_hl2 = 'HL2'
  142. var string o_src_hlc3 = 'HLC3'
  143. var string o_src_ohlc4 = 'OHLC4'
  144. var string o_src_hlcc4 = 'HLCC4'
  145.  
  146. //INPUTS - ATR Sources
  147. srcUpperVAL = input.string(o_src_high, title='Source Upper', inline="ATR1", group="ATR Settings", options=[o_src_entry,o_src_open,o_src_high,o_src_low,o_src_close,o_src_oc2,o_src_hl2,o_src_hlc3,o_src_ohlc4,o_src_hlcc4],tooltip=tt_src)
  148. srcLowerVAL = input.string(o_src_low, title='Source Lower', inline="ATR2", group="ATR Settings", options=[o_src_entry,o_src_open,o_src_high,o_src_low,o_src_close,o_src_oc2,o_src_hl2,o_src_hlc3,o_src_ohlc4,o_src_hlcc4])
  149. srcUseEntry = input(false, title='Entry as Entry Bar Source (1st bar)', inline="ATR3", group="ATR Settings", tooltip=tt_srcEntry)
  150.  
  151. //INPUTS - Triggers
  152. entryTrigger = input.string("Wick", title="Entry", inline='Trigger',group="Trigger Settings", options=["Wick","Close"])
  153. stopTrigger = input.string("Wick", title="Stoploss", inline='Trigger',group="Trigger Settings", options=["Wick","Close"])
  154. targetTrigger = input.string("Wick", title="Target", inline='Trigger',group="Trigger Settings", options=["Wick","Close"], tooltip=tt_Trigger)
  155. var entry_Wick = entryTrigger == "Wick" ? true : false
  156. var stop_Wick = stopTrigger == "Wick" ? true : false
  157. var target_Wick = targetTrigger == "Wick" ? true : false
  158.  
  159. //INPUTS - MA Settings for Estimate
  160. useSmoother = input(true, title='Smooth Estimate', inline="EST", group="Estimate Smoothing", tooltip=tt_estimate)
  161. maTypeInputEST = input.string("RMA", title=" - Type", inline="EST", group="Estimate Smoothing", options=["SMA", "EMA", "RMA", "WMA", "VWMA"])
  162. lengthEST = input.int(5, minval=1, title='Length', inline="EST", group="Estimate Smoothing")
  163.  
  164. //INPUTS - Display Settings
  165. displayTrailATR = input(true, title="Display ATR Trailing (Position)", inline='Trail', group="Display", tooltip=tt_Interactive)
  166. fillProfitArea = input(true, title="Fill Target (Position)   ", inline='Stop', group="Display")
  167. colLossFill = input(c_colLossFill, title='', inline='Stop', group="Display")
  168. colStoploss = input(c_colStoploss, title='Line', inline='Stop', group="Display", tooltip=tt_TargetFill)
  169. fillLossArea = input(true, title="Fill Stoploss (Position)", inline='Target', group="Display")
  170. colProfitFill = input(c_colProfitFill, title='', inline='Target', group="Display")
  171. colTarget = input(c_colTarget, title='Line', inline='Target', group="Display", tooltip=tt_TargetFill)
  172. displayUpperATR = input(false, title="Display Normal ATR Upper Band", inline='Band1', group="Display")
  173. colBandUpper = input(c_colBandUpper, title='', inline='Band1', group="Display", tooltip=tt_UpperBand)
  174. displayLowerATR = input(false, title="Display Normal ATR Lower Band", inline='Band2', group="Display")
  175. colBandLower = input(c_colBandLower, title='', inline='Band2', group="Display", tooltip=tt_LowerBand)
  176. displayLabel = input(true, title='Label', inline='Label', group="Display", tooltip=tt_Label)
  177. labelSize = input.string(size.normal,title="", inline="Label", group="Display", options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge])
  178. labelPos = input.string('Trailing', title="Position", inline="Label", group="Display", options=['Current','Trailing'])
  179. displayTable = input(true, title='Table', inline='Table', group="Display", tooltip=tt_Table)
  180. tableSize = input.string(size.small, title="", inline="Table", group="Display", options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge])
  181. tablePos1 = input.string("bottom", title="Position", inline="Table", group="Display", options=["top","middle","bottom"])
  182. tablePos2 = input.string("right", title="", inline="Table", group="Display", options=["left","center","right"])
  183.  
  184. //CALCULATE - Source
  185. getSource(_val) =>
  186. srcUpper = _val == o_src_entry ? entryPrice :
  187. _val == o_src_open ? open :
  188. _val == o_src_high ? high :
  189. _val == o_src_low ? low :
  190. _val == o_src_close ? close :
  191. _val == o_src_oc2 ? (open+close)/2 :
  192. _val == o_src_hl2 ? hl2 :
  193. _val == o_src_hlc3 ? hlc3 :
  194. _val == o_src_ohlc4 ? ohlc4 :
  195. _val == o_src_hlcc4 ? hlcc4 :
  196. close
  197. srcUpper = getSource(srcUpperVAL)
  198. srcLower = getSource(srcLowerVAL)
  199.  
  200. //CALCULATE - MA
  201. calcMA(source, length, type) =>
  202. switch type
  203. "RMA" => ta.rma(source, length)
  204. "SMA" => ta.sma(source, length)
  205. "EMA" => ta.ema(source, length)
  206. "WMA" => ta.wma(source, length)
  207. "VWMA"=> ta.vwma(source, length)
  208. atr = calcMA(ta.tr(true), length, maTypeInput) * multiplier
  209. upper = atr + srcUpper
  210. lower = srcLower - atr
  211.  
  212. //CALCULATE - Trailing ATR
  213.  
  214. //Check first bar of trailing stoploss, also if short or long stoploss
  215. if xBarTime_Valid
  216. if entry_Wick //entryTrigger == "Wick"
  217. if limitOrder //Limit Order
  218. if (low < yBarPrice and isLong) or (high > yBarPrice and isLong == false) //New Limit Order (Wick Trigger)
  219. startNow := true
  220. startMinute := minute, startHour := hour, startDay := dayofmonth
  221. else //Stop-Limit Order
  222. if (high > yBarPrice and isLong) or (low < yBarPrice and isLong == false) //New Stop-Limit Order (Wick Trigger)
  223. startNow := true
  224. startMinute := minute, startHour := hour, startDay := dayofmonth
  225. else
  226. if ta.cross(yBarPrice,close) //New Limit or Stop-Limit Order (Close Trigger)
  227. startNow := true
  228. startMinute := minute, startHour := hour, startDay := dayofmonth
  229.  
  230. //Start stoploss and set trailing value
  231. if startNow and startNow[1] == false
  232.  
  233. //Stoploss
  234. if srcUseEntry
  235. upperTrailing := atr + entryPrice //Stoploss (Short)
  236. lowerTrailing := entryPrice - atr //Stoploss (Long)
  237. else if updateEntryOnce or updateOnce
  238. upperTrailing := upper[1] //Stoploss (Short)
  239. lowerTrailing := lower[1] //Stoploss (Long)
  240. else
  241. upperTrailing := upper //Stoploss (Short)
  242. lowerTrailing := lower //Stoploss (Long)
  243.  
  244. //Entry Price
  245. entryPrice := entry_Wick ? math.round_to_mintick(yBarPrice) : close //entryTrigger == "Wick"
  246.  
  247. //Price Target
  248. targetPrice := targetTypeRR == false ? targetMult : ( isLong ? entryPrice+((entryPrice-lowerTrailing)*targetMult) : entryPrice-((upperTrailing-entryPrice)*targetMult) ) //targetType == o_Price
  249.  
  250. //Warning that an entry did not occur due ATR being within the price bar on the opening bar (this only occurs if the ATR Stoploss settings are to tight to the price bar)
  251. if isLong
  252. if lowerTrailing > low
  253. labelATR = label.new(bar_index, isLong ? low : high, text='🚨\nOverlapping\nATR and Bar', textalign = text.align_center, color=color.new(color.red,90), textcolor=color.blue, xloc=xloc.bar_index, yloc=yloc.price,size=labelSize, tooltip='Either place on another bar or modify ATR Settings')
  254. label.set_style(labelATR, isLong ? label.style_label_up : label.style_label_down)
  255. overlappingATR := true
  256. else
  257. if upperTrailing < high
  258. labelATR = label.new(bar_index, isLong ? low : high, text='🚨\nOverlapping\nATR and Bar', textalign = text.align_center, color=color.new(color.red,90), textcolor=color.blue, xloc=xloc.bar_index, yloc=yloc.price,size=labelSize, tooltip='Either place on another bar or modify ATR Settings')
  259. label.set_style(labelATR, isLong ? label.style_label_up : label.style_label_down)
  260. overlappingATR := true
  261.  
  262. //Overlapping - Prevent position from starting if price bar overlapping with ATR
  263. if overlappingATR == false
  264. currentlyTrailing := true //True during active position
  265. waitingTrailing := false //True if no position occurred yet
  266.  
  267. //Update ATR Trailing Stop Value
  268. if updateOnce == false or (updateEntryOnce and startNow and startNow[1] == false) //Updates Continuously
  269. if currentlyTrailing and currentlyTrailing[1]
  270. if isLong
  271. lowerTrailing := lowerTrailing < lower ? lower : lowerTrailing
  272. else
  273. upperTrailing := upperTrailing > upper ? upper : upperTrailing
  274. else //Updates on bar open
  275. if currentlyTrailing and currentlyTrailing[1]
  276. if isLong
  277. lowerTrailing := lowerTrailing < lower[1] ? lower[1] : lowerTrailing
  278. else
  279. upperTrailing := upperTrailing > upper[1] ? upper[1] : upperTrailing
  280.  
  281. //PLOT - Draggable Start Point
  282. plot(xBarTime_Now ? yBarPrice : na,style=plot.style_circles, color=col_isLong, linewidth=5, title="🟢/🔴 Start Point (Draggable Circle)")
  283.  
  284. //CALCULATE - Estimated Stoploss
  285. estimatedStoploss := isLong ? entryPrice-atr : entryPrice+atr //Calculate Estimated Stoploss
  286. estimatedStoplossSmooth = calcMA(estimatedStoploss, lengthEST, maTypeInputEST) //Calculate Estimated Stoploss (Smoothed)
  287. estimatedStoploss := useSmoother ? estimatedStoplossSmooth : estimatedStoploss //Choose normal estimate or smoothed
  288.  
  289. //CALCULATE - Estimated Profit Target & Check if Profit Target Valid
  290. var displayTarget = useDisplayTarget //Hide target if invalid
  291. var estimatedProfitTarget = targetMult //Profit Target
  292. if useDisplayTarget
  293. if targetTypeRR //targetType == o_RR
  294. estimatedProfitTarget := isLong ? yBarPrice+((yBarPrice-estimatedStoploss)*targetMult) : yBarPrice-((estimatedStoploss-yBarPrice)*targetMult)
  295. else if useDisplayTarget
  296. if isLong
  297. displayTarget := targetMult > yBarPrice ? true : false
  298. else
  299. displayTarget := targetMult < yBarPrice ? true : false
  300.  
  301. //Label - Price of for entry trigger
  302. if xBarTime_Now
  303. tt_TargetType = targetTypeRR ? 'Calculated from current ATR to price difference' : 'Profit Target' //targetType == o_RR
  304. entryText = entryTypeText+limitTypeText+' '+str.tostring(math.round_to_mintick(yBarPrice)) + '➔'
  305. label.new(bar_index, yBarPrice, style=label.style_label_right, text=entryText, textalign = text.align_center, color=colClear, textcolor=color.blue, xloc=xloc.bar_index, yloc=yloc.price,size=labelSize, tooltip=entryTypeText+limitTypeText)
  306. label.new(bar_index, estimatedStoploss, style=label.style_label_right, text='⚠️➔', textalign = text.align_center, color=colClear, textcolor=color.new(color.blue,50), xloc=xloc.bar_index, yloc=yloc.price,size=labelSize, tooltip='Estimated ATR Stoploss')
  307. label.new(displayTarget ? bar_index : na, estimatedProfitTarget, style=label.style_label_right, text='🎯➔', textalign = text.align_center, color=colClear, textcolor=color.new(color.blue,50), xloc=xloc.bar_index, yloc=yloc.price,size=labelSize, tooltip=tt_TargetType)
  308.  
  309. //Common requirement for plotting
  310. checkPlot = xBarTime_Valid and startNow[1] == false and invalidStart == false ? true : false
  311.  
  312. //PLOT - Entry price line
  313. plot(checkPlot ? yBarPrice : na, linewidth=1, title="Entry Price Line", color=col_isLong)
  314.  
  315. //PLOT - Estimated Stoploss
  316. plot(checkPlot ? estimatedStoploss : na, linewidth=1, title="Estimated Stoploss", color=color.new(color.blue,50), style= plot.style_circles)
  317.  
  318. //PLOT - Estimated Profit Target
  319. plot(checkPlot and displayTarget ? estimatedProfitTarget : na, linewidth=1, title="Estimated Profit Target", color=color.new(color.blue,50), style= plot.style_circles)
  320.  
  321. //PLOT - Trailing Stop-loss
  322. plotUpperTrailing = plot(displayTrailATR and currentlyTrailing and isLong == false ? upperTrailing : na, title="Upper Trailing Stoploss (Short)", color=colStoploss) //Upper Trail (Short)
  323. plotLowerTrailing = plot(displayTrailATR and currentlyTrailing and isLong ? lowerTrailing : na, title="Lower Trailing Stoploss (Long)", color=colStoploss) //Lower Trail (Long)
  324. placeholder = plot(currentlyTrailing ? hlc3 : na, title="Placeholder", editable=false, color=colClear) //Placeholder
  325.  
  326. profitHit = false //Profit Target Hit
  327. stopHit = false //Stoploss Hit
  328.  
  329. //CHECK - Stoploss Hit
  330. if currentlyTrailing
  331. if stop_Wick //stopTrigger == "Wick"
  332. if high > upperTrailing and isLong == false //Wick Stoploss (Short)
  333. currentlyTrailing := false
  334. exitPrice := upperTrailing
  335. stopHit := true
  336. if low < lowerTrailing and isLong //Wick Stoploss (Long)
  337. currentlyTrailing := false
  338. exitPrice := lowerTrailing
  339. stopHit := true
  340. else //stopTrigger == "Close"
  341. if close[1] > upperTrailing and isLong == false //Close Stoploss (Short)
  342. currentlyTrailing := false
  343. exitPrice := close[1]
  344. stopHit := true
  345. if close[1] < lowerTrailing and isLong //Close Stoploss (Long)
  346. currentlyTrailing := false
  347. exitPrice := close[1]
  348. stopHit := true
  349.  
  350. //CHECK - Profit Target Hit
  351. if displayTarget //Require profit target to be displayed
  352. if currentlyTrailing
  353. if target_Wick //targetTrigger == "Wick"
  354. if (ta.cross(high,targetPrice) or ta.cross(low,targetPrice)) //Wick Target
  355. waitFirstTargetHit := false
  356. profitHit := true
  357. exitPrice := targetPrice
  358. currentlyTrailing := stopAtTarget ? false : true
  359. else //targetTrigger == "Close"
  360. if (ta.cross(close,targetPrice)) //Close Target
  361. waitFirstTargetHit := false
  362. profitHit := true
  363. exitPrice := close
  364. currentlyTrailing := stopAtTarget ? false : true
  365.  
  366. //PLOT - Stoploss Fill (only while active, removes after exit)
  367. fill(plotUpperTrailing,placeholder,color=close < upperTrailing ? color.new(colLossFill,80) : na,display=fillLossArea ? display.all : display.none)
  368. fill(plotLowerTrailing,placeholder,color=close > lowerTrailing ? color.new(colLossFill,80) : na,display=fillLossArea ? display.all : display.none)
  369.  
  370. //PLOT - Price Target and Fill Target
  371. plotTarget = plot(displayTarget and (currentlyTrailing or currentlyTrailing[1]) and waitFirstTargetHit[1] ? targetPrice : na, title="Profit Target", color=colTarget)
  372. fill(placeholder, plotTarget, color=waitFirstTargetHit[1] ? color.new(colProfitFill,80) : na,display=fillProfitArea ? display.all : display.none)
  373.  
  374. //PLOT - Shape (Stoploss Hit)
  375. plotchar(displayTrailATR and isLong and stopHit, title="Symbol - Long Stop", char='⚠️', location=location.belowbar, size=size.small)
  376. plotchar(displayTrailATR and isLong == false and stopHit, title="Symbol - Short Stop", char='⚠️', location=location.abovebar, size=size.small)
  377.  
  378. //PLOT - Shape (Target Hit)
  379. plotchar(displayTrailATR and isLong and displayTarget and profitHit and waitFirstTargetHit[1], title="Symbol - Long Profit", char='🎯', location=location.abovebar, size=size.small)
  380. plotchar(displayTrailATR and isLong == false and displayTarget and profitHit and waitFirstTargetHit[1], title="Symbol - Short Profit", char='🎯', location=location.belowbar, size=size.small)
  381.  
  382. //PLOT - Normal ATR Bands
  383. plotUpper = plot(displayUpperATR ? atr + srcUpper : na, title='ATR Normal Band - Upper', color=colBandUpper)
  384. plotLower = plot(displayLowerATR ? srcLower - atr : na, title='ATR Normal Band - Lower', color=colBandLower)
  385.  
  386. //CALCULATE - Percent Distance
  387. getLongPercentText(_entry,_exit) => ((_exit-_entry)/_entry)*100
  388. getShortPercentText(_entry,_exit) => ((_entry-_exit)/_entry)*100
  389.  
  390. //CALCULATE - Percentage Distance (Text)
  391. percentFromEntry() => isLong ? str.tostring(getLongPercentText(entryPrice,close),'#.##') : str.tostring(getShortPercentText(entryPrice,close),'#.##')
  392. percentPositionResult() => isLong ? str.tostring(getLongPercentText(entryPrice,exitPrice),'#.##') : str.tostring(getShortPercentText(entryPrice,close),'#.##')
  393. percentMaxDrawdownEST() => isLong ? str.tostring(getLongPercentText(yBarPrice,estimatedStoploss),'#.##') : str.tostring(getShortPercentText(yBarPrice,estimatedStoploss),'#.##')
  394. percentMaxProfitEST() => isLong ? str.tostring(getLongPercentText(yBarPrice,estimatedProfitTarget),'#.##') : str.tostring(getShortPercentText(yBarPrice,estimatedProfitTarget),'#.##')
  395. percentMaxDrawdown() => isLong ? str.tostring(getLongPercentText(entryPrice,lowerTrailing),'#.##') : str.tostring(getShortPercentText(entryPrice,upperTrailing),'#.##')
  396. percentMaxProfit() => isLong ? str.tostring(getLongPercentText(entryPrice,targetPrice),'#.##') : str.tostring(getShortPercentText(entryPrice,targetPrice),'#.##')
  397.  
  398. //CALCULATE - Timeframe text for alert ('fixes' letter consistancy between different timeframes)
  399. calcTimeframeText(_src) =>
  400. result = _src
  401. if str.contains(_src,'S')
  402. result := str.replace(_src,'S','s',0)
  403. else if str.contains(_src,'D') or str.contains(_src,'W') or str.contains(_src,'M')
  404. result := _src
  405. else
  406. result := str.tonumber(_src) < 60 ? _src + 'm' : str.tostring(str.tonumber(_src)/60) + 'h'
  407.  
  408. //CALCULATE - Curly brackets text into current data
  409. //One reason this code was added due to the preference of using alert() instead of alertcondition() which requires additional selection when setting up alerts.
  410. //This function allows for alert() to return messages with retreived values via curly brackets, that alertcondition() can do by default.
  411. //Additional indicator specific values can also be retreived, such as {{trail}} , {{band}} , {{type}} , {{target}} , {{newline}} , and more.
  412. checkAlertText(_text) =>
  413. result = _text
  414. result := str.replace(result, '{{trail}}', str.tostring(math.round_to_mintick(isLong ? lowerTrailing : upperTrailing)))
  415. result := str.replace(result, '{{target}}', str.tostring(math.round_to_mintick(targetPrice)))
  416. result := str.replace(result, '{{type}}', isLong ? 'Long' : 'Short')
  417. result := str.replace(result, '{{traildistance}}', isLong ? str.tostring(((lowerTrailing/close)-1)*100,'#.###') + '%' : str.tostring(((upperTrailing/close)-1)*100,'#.###') + '%')
  418. result := str.replace(result, '{{targetdistance}}', isLong ? str.tostring(((targetPrice/close)-1)*100,'#.###') + '%' : str.tostring(((targetPrice/close)-1)*100,'#.###') + '%')
  419. result := str.replace(result, '{{starttime}}', str.tostring(startDay,'#') + ':' + str.tostring(startHour,'#') + ':' + str.tostring(startMinute,'#'))
  420. result := str.replace(result, '{{maxdrawdown}}', percentMaxDrawdown())
  421. result := str.replace(result, '{{maxprofit}}', percentMaxProfit())
  422. result := str.replace(result, '{{update}}', updateStopVAL)
  423. result := str.replace(result, '{{entrysource}}', srcUseEntry ? 'Yes' : 'No')
  424. result := str.replace(result, '{{triggerentry}}', entryTrigger)
  425. result := str.replace(result, '{{triggerstop}}', stopTrigger)
  426. result := str.replace(result, '{{triggertarget}}', targetTrigger)
  427. result := str.replace(result, '{{atrlength}}', str.tostring(length,'#'))
  428. result := str.replace(result, '{{atrmultiplier}}', str.tostring(multiplier,'#'))
  429. result := str.replace(result, '{{atrtype}}', maTypeInput)
  430. result := str.replace(result, '{{ticker}}', syminfo.ticker)
  431. result := str.replace(result, '{{exchange}}', syminfo.prefix(syminfo.tickerid))
  432. result := str.replace(result, '{{description}}', syminfo.description)
  433. result := str.replace(result, '{{close}}', str.tostring(math.round_to_mintick(close)))
  434. result := str.replace(result, '{{open}}', str.tostring(math.round_to_mintick(open)))
  435. result := str.replace(result, '{{high}}', str.tostring(math.round_to_mintick(high)))
  436. result := str.replace(result, '{{low}}', str.tostring(math.round_to_mintick(low)))
  437. result := str.replace(result, '{{hl2}}', str.tostring(math.round_to_mintick(hl2)))
  438. result := str.replace(result, '{{volume}}', str.tostring(math.round_to_mintick(volume)))
  439. result := str.replace(result, '{{time}}', str.tostring(dayofmonth,'#') + ':' + str.tostring(hour,'#') + ':' + str.tostring(minute,'#'))
  440. result := str.replace(result, '{{interval}}', calcTimeframeText(timeframe.period))
  441. result := str.replace(result, '{{newline}}', '\n')
  442.  
  443. //INPUTS - Alerts 
  444. Alert_Entry = input(true, title="Alert Entry", inline='AlertEntry', group="Alert", tooltip=tt_alertEntry + tt_alert + tt_alertEntryEx)
  445. Alert_EntryText = input.string(o_entry, title='', inline='AlertEntry', group="Alert")
  446. Alert_TrailingHit = input(true, title="Alert Trailing Stop Hit", inline='AlertTrailingHit', group="Alert", tooltip=tt_alertTrailHit + tt_alert + tt_alertTrailEx)
  447. Alert_TrailingHitText = input.string(o_trailing, title='', inline='AlertTrailingHit', group="Alert")
  448. Alert_PriceTarget = input(true, title="Alert Profit Target Hit", inline='AlertProfitHit', group="Alert", tooltip=tt_alertTarget + tt_alert + tt_alertTargetEx)
  449. Alert_PriceTargetText = input.string(o_target, title='', inline='AlertProfitHit', group="Alert")
  450. Alert_InvalidEntry = input(true, title="Alert Failed Entry (ATR Overlap)", inline='AlertInvalidEntry', group="Alert", tooltip=tt_alertInvalid + tt_alert)
  451. Alert_InvalidEntryText= input.string(o_inavlidEntry,title='', inline='AlertInvalidEntry', group="Alert")
  452.  
  453. //CALCULATE - ALERTS
  454. if Alert_Entry
  455. if startNow
  456. alert(checkAlertText(Alert_EntryText),alert.freq_once_per_bar)
  457. if Alert_TrailingHit
  458. if stopHit
  459. alert(checkAlertText(Alert_TrailingHitText),alert.freq_once_per_bar)
  460. if Alert_PriceTarget
  461. if profitHit
  462. alert(checkAlertText(Alert_PriceTargetText),alert.freq_once_per_bar)
  463. if Alert_InvalidEntry
  464. if overlappingATR
  465. alert(checkAlertText(Alert_InvalidEntryText),alert.freq_once_per_bar)
  466.  
  467. //Label checks
  468. var resultSymbol = ''
  469. if stopHit
  470. resultSymbol := '⚠️'
  471. if profitHit
  472. resultSymbol := '🎯'
  473. var labelText = ""
  474. var labelATR = label.new(na, na, '', textalign = text.align_left, xloc=xloc.bar_time, yloc=yloc.price,size=labelSize)
  475.  
  476. //Set time location for displaying label
  477. if currentlyTrailing[1] or (waitingTrailing and xBarTime_Valid)
  478. timeLabel := time
  479.  
  480. if barstate.islast //Compile script faster
  481.  
  482. //Exit Entry
  483. if resultSymbol != '' and overlappingATR == false //resultSymbol != resultSymbol[1] //waitFirstTargetHit == false
  484. labelText := ''
  485. if isLong
  486. labelText := resultSymbol + (exitPrice > entryPrice ? 'Win: ' : (exitPrice < entryPrice ? 'Loss: ' : 'Draw: ')) //Win or Loss (Long)
  487. else
  488. labelText := resultSymbol + (exitPrice < entryPrice ? 'Win: ' : (exitPrice > entryPrice ? 'Loss: ' : 'Draw: ')) //Win or Loss (Short)
  489. labelText := labelText + percentPositionResult() + '%\nEntry: ' + str.tostring(math.round_to_mintick(entryPrice)) + //Entry Price
  490. '\nExit: ' + str.tostring(math.round_to_mintick(exitPrice)) //Exit Price
  491. labelText := (useDisplayTarget and displayTarget == false ? labelText + '\n\n🚨Target Invalid🚨' : labelText) //Target Invalid
  492.  
  493. //Waiting Entry
  494. if xBarTime_Valid and waitingTrailing and overlappingATR == false //xBarTime_Valid (xBarTime <= time , each bar after initial click) //waitingTrailing (prior to entry)
  495. labelText := ''
  496. labelText := labelText + 'Waiting ' + entryTypeText + 'Entry...\n\n' +
  497. (displayTarget ? ('🎯Profit Target: ' + str.tostring(math.round_to_mintick(estimatedProfitTarget)) + //Target Price
  498. (targetTypeRR ? ' (Estimate)\n' : '\n')) : '') + //Target Estimate ?
  499. '⏳' + entryTypeText + limitTypeText + ': ' + str.tostring(math.round_to_mintick(yBarPrice)) + //Entry Price
  500. '\n⚠️Stoploss: ' + str.tostring(math.round_to_mintick(estimatedStoploss)) + ' (Estimate)' + //Stoploss Price
  501. '\n\nMax Drawdown: ' + percentMaxDrawdownEST() + '% (Estimate)' + //Max Drawdown Percent
  502. (displayTarget ? '\nMax Profit: ' + percentMaxProfitEST() + '% (Estimate)' : '') + //Max Profit Percent
  503. (useDisplayTarget and displayTarget == false ? '\n\n🚨Target Invalid🚨' : '') //Target Invalid
  504.  
  505. //Active Entry
  506. if waitingTrailing == false and currentlyTrailing
  507. labelText := ''
  508. labelText := labelText + 'Active Position: ' + percentFromEntry() + //Active Position Percent
  509. '%\n\n' + (displayTarget ? '🎯Profit Target: ' + str.tostring(math.round_to_mintick(targetPrice)) + '\n' : '') + //Profit Target Price
  510. '✔️Entry: ' + str.tostring(math.round_to_mintick(entryPrice)) + //Entry Price
  511. '\n⚠️Stoploss: ' + str.tostring(math.round_to_mintick(isLong ? lowerTrailing : upperTrailing)) + //Stoploss Price
  512. (displayTarget ? '\n\nMax Profit: ' + percentMaxProfit() + '%' : '\n') + //Max Profit Percent
  513. '\nMax Drawdown: ' + percentMaxDrawdown() + '%' //Max Drawdown Percent
  514.  
  515. //LABEL - Check Label
  516. labelTextcolor = color.blue
  517. labelColor = isLong ? colProfitFill : colLossFill
  518. labelTooltip = selectedDesc
  519. if invalidStart //xBarTime == 0 or yBarPrice == 0
  520. labelText := '🚨Modify Start Point or Re-add to chart🚨'
  521. labelTooltip := "Start Point is currently zero or date is invalid. Modify the start point within settings or re-add this indicator to the chart."
  522. labelTextcolor := color.yellow
  523. labelColor := color.blue
  524.  
  525. //LABEL - Display
  526. if labelText != ''
  527. label.set_textcolor(labelATR, overlappingATR ? color.yellow : labelTextcolor)
  528. label.set_color(labelATR, overlappingATR ? color.blue : labelColor)
  529. label.set_text(labelATR, labelText)
  530. label.set_tooltip(labelATR, labelTooltip)
  531. if labelPos == 'Trailing'
  532. label.set_xy(labelATR, displayTrailATR and displayLabel ? timeLabel+1 : na, isLong ? (lowerTrailing == 0 ? close[1] : lowerTrailing) : (upperTrailing == 0 ? close[1] : upperTrailing))
  533. label.set_style(labelATR, isLong ? label.style_label_upper_left : label.style_label_lower_left)
  534. else
  535. label.set_xy(labelATR, displayTrailATR and displayLabel ? time+1 : na, close[1])
  536. label.set_style(labelATR, label.style_label_left)
  537.  
  538. //TABLE - Settings of this indicator
  539. if displayTable
  540. col_T = color.white //Text Color
  541. col_H = color.rgb(25, 0, 255) //Heading Color
  542. col_W = color.rgb(189, 0, 0) //Warning Color
  543. infobox = table.new(tablePos1 + "_" + tablePos2, 2, 20, bgcolor=color.rgb(0, 0, 0), frame_color=col_H, frame_width=1)
  544. //Warning
  545. if invalidStart //xBarTime == 0 or yBarPrice == 0
  546. warningTT = "Start Point is currently zero or date is invalid. Modify the start point within settings or re-add this indicator to the chart."
  547. warningText = '🚨Modify Start Point🚨\nOr\n🚨Re-add to chart🚨'
  548. table.cell(infobox, 0, 1, warningText, text_color=col_T, text_halign=text.align_center, text_size=tableSize, tooltip=warningTT, bgcolor=col_W)
  549. table.merge_cells(infobox, 0, 1, 1, 1)
  550. else if useDisplayTarget and displayTarget == false
  551. warningTT = 'Target entered is invalid'
  552. table.cell(infobox, 0, 1, '\n🚨Target Invalid🚨\n', text_color=col_T, text_halign=text.align_center, text_size=tableSize, tooltip=warningTT, bgcolor=col_W)
  553. table.merge_cells(infobox, 0, 1, 1, 1)
  554. //Gap
  555. table.cell(infobox, 0, 2, 'Position', text_color=col_T, text_halign=text.align_center, text_size=size.tiny, tooltip='Position', bgcolor=col_H)
  556. table.merge_cells(infobox, 0, 2, 1, 2)
  557. //Entry
  558. directionLimitText = (isLong ? '🟢' : '🔴') + limitTypeText + ':'
  559. priceText = str.tostring(math.round_to_mintick(yBarPrice))
  560. table.cell(infobox, 0, 3, directionLimitText, text_color=col_T, text_halign=text.align_left, text_size=tableSize, tooltip=selectedDesc)
  561. table.cell(infobox, 1, 3, priceText, text_color=col_T, text_halign=text.align_center, text_size=tableSize, tooltip=selectedDesc)
  562. //Entry Stoploss
  563. if invalidStart == false
  564. stopText = waitingTrailing ? '⚠️Estimated Stoploss:':'⚠️Stoploss:'
  565. table.cell(infobox, 0, 4, stopText, text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  566. stoplossText = waitingTrailing ? str.tostring(math.round_to_mintick(estimatedStoploss)) : str.tostring(math.round_to_mintick( isLong ? lowerTrailing : upperTrailing ))
  567. table.cell(infobox, 1, 4, stoplossText, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  568. //Entry Target
  569. if displayTarget and invalidStart == false
  570. targetText = waitingTrailing ? '🎯Estimated Target:':'🎯Target'
  571. profitText = waitingTrailing ? str.tostring(math.round_to_mintick(estimatedProfitTarget)) : str.tostring(math.round_to_mintick(targetPrice))
  572. table.cell(infobox, 0, 5, targetText, text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  573. table.cell(infobox, 1, 5, profitText, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  574. //Gap
  575. table.cell(infobox, 0, 6, 'ATR Settings', text_color=col_T, text_halign=text.align_center, text_size=size.tiny, tooltip="ATR Settings", bgcolor=col_H)
  576. table.merge_cells(infobox, 0, 6, 1, 6)
  577. //ATR Settings
  578. table.cell(infobox, 0, 7, 'Length:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  579. table.cell(infobox, 1, 7, str.tostring(length), text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  580. table.cell(infobox, 0, 8, 'Multiplier:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  581. table.cell(infobox, 1, 8, str.tostring(multiplier), text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  582. table.cell(infobox, 0, 9, 'Type:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  583. table.cell(infobox, 1, 9, str.tostring(maTypeInput), text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  584. table.cell(infobox, 0,10, 'Source:', text_color=col_T, text_halign=text.align_left, text_size=tableSize, tooltip='Source for ATR Stoploss placement')
  585. table.cell(infobox, 1,10, isLong ? srcLowerVAL : srcUpperVAL, text_color=col_T, text_halign=text.align_center, text_size=tableSize, tooltip='Source for ATR Stoploss placement')
  586. if srcUseEntry
  587. table.cell(infobox, 0,11, '(1st bar = Entry)', text_color=col_T, text_halign=text.align_right, text_size=tableSize)
  588. table.merge_cells(infobox, 0, 11, 1, 11)
  589. updateText = updateOnce ? 'Bar Open' :
  590. updateEntryOnce ? 'Entry Open, Always' :
  591. 'Always'
  592. updateTT = updateOnce ? "Update Trailing Stoploss only once per bar on open, referencing prior bar's close." :
  593. updateEntryOnce ? "Update Trailing Stoploss only once on open bar, referencing prior bar's close. After, update Trailing Stoploss continuously." :
  594. "Update Trailing Stoploss continuously."
  595. table.cell(infobox, 0,12, 'Update:', text_color=col_T, text_halign=text.align_left, text_size=tableSize, tooltip='Frequency of updating ATR Trailing Stoploss')
  596. table.cell(infobox, 1,12, updateText, text_color=col_T, text_halign=text.align_center, text_size=tableSize, tooltip=updateTT)
  597. //Target
  598. if displayTarget
  599. //Gap
  600. table.cell(infobox, 0,13, 'Target Setting', text_color=col_T, text_halign=text.align_center, text_size=size.tiny, tooltip="Target Setting", bgcolor=col_H)
  601. table.merge_cells(infobox, 0, 13, 1, 13)
  602. //Target
  603. targetText = targetTypeRR ? '1 : ' + str.tostring(targetMult) : str.tostring(targetMult)
  604. targetTitleText = targetTypeRR ? 'Target (R:R):' : 'Target (Price):'
  605. table.cell(infobox, 0,14, targetTitleText, text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  606. table.cell(infobox, 1,14, targetText, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  607. if targetTypeRR
  608. percentBreakEvenEST = str.tostring( 100 - (( 1 / ( 1 + (1/targetMult)) ) * 100) ,'#.#')
  609. table.cell(infobox, 0,15, 'Break Even:', text_color=col_T, text_halign=text.align_left, text_size=tableSize, tooltip='Break Even Winrate Percent')
  610. table.cell(infobox, 1,15, percentBreakEvenEST + '%', text_color=col_T, text_halign=text.align_center, text_size=tableSize, tooltip='Break Even Winrate Percent')
  611. //Gap
  612. table.cell(infobox, 0,16, 'Trigger Settings', text_color=col_T, text_halign=text.align_center, text_size=size.tiny, tooltip="Trigger Settings", bgcolor=col_H)
  613. table.merge_cells(infobox, 0, 16, 1, 16)
  614. //Triggers - Add this way to have the table take up less space on chart
  615. if displayTarget
  616. if entryTrigger == stopTrigger and stopTrigger == targetTrigger
  617. triggerText = 'Entry,Stop,Target: ' + entryTrigger
  618. table.cell(infobox, 0,17, triggerText, text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  619. table.merge_cells(infobox, 0, 17, 1, 17)
  620. else
  621. table.cell(infobox, 0,17, 'Entry:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  622. table.cell(infobox, 1,17, entryTrigger, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  623. table.cell(infobox, 0,18, 'Stop:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  624. table.cell(infobox, 1,18, stopTrigger, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  625. table.cell(infobox, 0,19, 'Target:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  626. table.cell(infobox, 1,19, targetTrigger, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  627. else
  628. if entryTrigger == stopTrigger
  629. table.cell(infobox, 0,17, 'Entry, Stop: ', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  630. table.cell(infobox, 1,17, entryTrigger, text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  631. else
  632. table.cell(infobox, 0,17, 'Entry:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  633. table.cell(infobox, 1,17, entryTrigger, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  634. table.cell(infobox, 0,18, 'Stop:', text_color=col_T, text_halign=text.align_left, text_size=tableSize)
  635. table.cell(infobox, 1,18, stopTrigger, text_color=col_T, text_halign=text.align_center, text_size=tableSize)
  636.  
  637.  
Advertisement
Add Comment
Please, Sign In to add comment