Advertisement
PineCoders

New GD-ADXDI

Dec 18th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.62 KB | None | 0 0
  1. //@version=4
  2.  
  3. //====================================================================
  4. // ADX DI AutoTrader
  5. // Version 1.4
  6. // Created by GreenDragon
  7. //====================================================================
  8. // 2019-08-29 - Beta V0.1 created
  9. // 2019-08-30 - remove green trigger when di crossing up on a pos adx
  10. // 2019-09-02 - modify exit to not fire when ADX < 25 but DI still pos
  11. // 2019-09-03 - added TP, TTP and TSL
  12. // 2019-09-09 - add slope filter
  13. // 2019-09-19 - add RSI filter - only allow buy when RSI last 2 are rising.
  14. // 2019-09-23 - remove slope filter and code as no use in filtering
  15. // 2019-10-02 - Fix bug in Trailing Stop Loss
  16. // 2019-10-15 - change both sell to be both down (removed)
  17. // 2019-10-30 - more work on TP, TTP & TSL
  18. // 2019-11-06 - V1.0 Official Release
  19. // 2019-11-10 - more work on TP, TTP, TSL
  20. // 2019-11-26 - total re-write of but sell control logic.
  21. // 2019-11-27 - limit vars with max_bars_back to stop compiler error
  22. // 2019-11-28 - more max_bars_back issues fixed in highest_ func
  23. // 2019-11-28 - fix volume filter, make volumecode global
  24. // 2019-12-06 - Add Dirty 30 marker and trade option.
  25. // 2019-12-16 - V1.4 - add fixed SL or Trailing
  26. //=====================================================================
  27. //
  28. // Description
  29. // -----------
  30. // This is a main window indicator that can be used to trade based on ADX DI or Both
  31. // it also has various filters that can be set to stop buy signals if the filter
  32. // conditions are not met. When filters are enabled the "Buy" will be DELAYED until
  33. // All set filters are true e.g. if adx fires below 200ma trade will not buy until over
  34. // 200ma provided that the adx di condition is still true.
  35. //
  36. // Filters
  37. // -------
  38. // 1. All filters and other variables can be set in the settings and then saved as
  39. // default or can be changed in the code.
  40. // 2. Background colours can be enabled so Green when trade is open and red when
  41. // trade closed.
  42. // 3. NQ's common simple MA lines can be enabled or disabled in settings, 8ma,
  43. // 21ma, 50ma, 200ma & 314ma
  44. // 4. Trading price labels can also be enabled in settings.
  45. // 5. Trade below 200ma is generally not a good idea and against the NQ methedology
  46. // but can be enabled in settings if needed.
  47. // 6. sell by ADX, DI or Both can be disabled to allow the TP, TTP, SL or TSL to continue
  48. // to run the trade
  49. // 7. Trade sell can be by TP or Trailing TP, choose in settings
  50. // 8. Stop Loss or Trailing Stop Loss can also be enabled.
  51. // 9. ADX Filter allows for the setting of DI Length (default 14) and ADX Threshold
  52. // (Default 25)
  53. // 10. RSI Filter can be enabled and you can chose 2 or 3 candle back, will stop buy
  54. // if RSI is declining over the set number of candles.
  55. // 11. Volume filter can be enabled and will stop buy if "Daily or Hourly" rolling
  56. // volume of the "Base Coin" is below the set threshold, e.g BATBTC trade BTC is
  57. // the Base Coin, ETHUSDT USDT is the Base Coin.
  58. // 12. Value Filter, this can be set to stop buy under a sertain coin price, this is
  59. // the coin being purchased NOT the base coin. Default coin threshold for trading
  60. // is 100 satoshis.
  61. //
  62. // Markers
  63. // -------
  64. // 1. Buy Marker is Green Up Triangle at bottom of chart
  65. // 2. Sell Marker is Red Down Triangle at bottom of chart
  66. // 3. TP Sell indicator is Blue Square at bottom of Chart and TP Value line is blue
  67. // line on chart from buy point to sell or TP point.
  68. // 4. TTP Sell indicator is Green Square at bottom of Chart and TTP Value line is Dark Green
  69. // line on chart from TP point to sell or TTP point.
  70. // 5. TSL Sell indicator is Orange Square at bottom of Chart and TSL Value line is Red
  71. // line on chart from buy point to sell or TSL point.
  72. // 6. Dirty 30 is purple triangle below candle.
  73. //
  74. // For backtesting you can uncomment the strategy entries and comment out study() and
  75. // alertcondition() entries.
  76. //=====================================================================
  77.  
  78.  
  79. //strategy(title="GD ADXDI AutoTrader VB 1.4", shorttitle="GD-ADXDI-Auto-V1.4", overlay = true, pyramiding = 0, calc_on_order_fills = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 10000, commission_type=strategy.commission.percent, commission_value=0.2)
  80. study("GD ADXDI AutoTrader V1.4", shorttitle="GD-ADXDI-Auto-V1.4", overlay=true, max_bars_back=4998)
  81.  
  82. // create options for inputs
  83. TradeADX = "ADX", TradeDI = "DI Line", TradeBoth = "ADX + DI+", TradeDirty30 = "Dirty 30", TradeNone = "Disabled"
  84. tpon = "TP", ttpon = "TTP"
  85. RSIOpen = "Open", RSIClose="Close", RSIHigh="High", RSILow="Low", RSIhl2="hl2", RSIhlc3="hlc3", RSIohlc4="ohlc4"
  86. two = "two candles", three = "three candles"
  87. vH = "Hours", vD = "Days"
  88.  
  89. // set main inputs
  90. b1 = input(false, title="╔══════════════════════════════════════════╗")
  91. c1 = input(false, title="       ADX DI Autotrader")
  92. c2 = input(false, title="       Version 1.4")
  93. c3 = input(false, title="       Created by GreenDragon")
  94. c4 = input(false, title="       --------------------------------------")
  95. c9 = input(false, title="╠══════════════════════════════════════════╣")
  96. enableBackground = input(true, title="       Enable Background colours")
  97. enableMAs = input(true, title="       Enable MA's lines")
  98. startOn = input(TradeBoth, title="              Trade based on ", options=[TradeADX, TradeDI, TradeBoth, TradeDirty30, TradeNone])
  99. b2 = input(false, title="╠══════════════════════════════════════════╣")
  100. b3 = input(false, title=" ******************************** Trade Settings ******************************** ")
  101. showTradeLbl = input(true, title="       Show Trade Price Labels")
  102. ebl200ma = input(false, title="       Enable Trade below 200ma")
  103. disableS = input( true, title="       Allow SELL by TP, TTP or SL ONLY. Not adx or di")
  104. enableTP = input( true, title="       Enable Take Profit or Trailing Take Profit")
  105. enableTPOn = input(ttpon, title="              Take Profit or Trailing Take Profit", options=[tpon,ttpon])
  106. tpLevel = input(2.2, title="              Take Profit Percentage",type=input.float, minval=0.001, maxval=100.0, step=0.001)
  107. ttpLevel = input(6, title="              Trailing Take Profit by Percentage",type=input.float, minval=0.001, maxval=100.0, step=0.001)
  108. enableTSL = input(false, title="       Enable Trailing Stop Loss, False = Fixed SL")
  109. tslLevel = input(-0.2, title="              Trailing Stop Loss Percentage",type=input.float, maxval=100.0, step=0.001)
  110. b4 = input(false, title="╠══════════════════════════════════════════╣")
  111. b5 = input(false, title=" ****************************** D30 Filter Settings ***************************** ")
  112. barcount = input(3, title="              Bar count since ma cross or adx")
  113. b6 = input(false, title="╠══════════════════════════════════════════╣")
  114. b7 = input(false, title=" ******************************** ADX Filter ************************************ ")
  115. len = input(14, title="              DI Length", type=input.integer)
  116. th = input(25, title="              Trend Threshold", type=input.integer)
  117. b8 = input(false, title="╠══════════════════════════════════════════╣")
  118. b9 = input(false, title=" ********************************* RSI Filter ********************************** ")
  119. enableRSI = input(false, title="       Enable RSI Filter")
  120. RSILength = input(14, title="              RSI Length", type=input.integer)
  121. RSIBasedOn = input(RSIohlc4, title="              RSI Source", options=[RSIOpen, RSIClose, RSIHigh, RSILow, RSIhl2, RSIhlc3, RSIohlc4])
  122. RSITwoThree = input(two, title="              RSI candles", options=[two, three])
  123. b10 = input(false, title="╠══════════════════════════════════════════╣")
  124. b11 = input(false, title=" ********************************* Volume Filter ******************************** ")
  125. eblVolume = input(true, title="       Enable Volume Filter")
  126. volThreshold = input( 30, title="               Volume Threshold in Base Coin ",type=input.integer, minval=1, step=1)
  127. measureOn = input( vD, title="               Measure Volume Range in ", options=[vH, vD])
  128. volTime = input( 1, title="               Volume Range in Days/Hours" ,type=input.integer, minval=1, maxval=100, step=1)
  129. b12 = input(false, title="╠══════════════════════════════════════════╣")
  130. b13 = input(false, title=" ********************************* Value Filter ******************************** ")
  131. eblValFilter = input( true, title="       Enable min Coin value to trade Filter (def 100 Satoshis)")
  132. valThreshold = input(0.00000100,title="               Min Value of Coin", type=input.float, minval=0.00000001, step=0.00000001)
  133. b16 = input(false, title="╚══════════════════════════════════════════╝")
  134.  
  135. // choose src for indicator from
  136. // open, close, high, low, hl2, hlc3, ohlc4
  137. src = close
  138.  
  139. // Trade Flags
  140. buyFlag = false
  141. sellFlag = false
  142. BuyCondition = false
  143. SellCondition = false
  144. tpAlert = false
  145. ttpAlert = false
  146. slAlert = false
  147. tslAlert = false
  148.  
  149. // var to hold last valid buy or sell condition.
  150. var LastCondWasBuy = false
  151.  
  152. ////////////////////////
  153. // NQ's Rules and Indies
  154. // Use Simple MA for NQ's 8, 200 & 314
  155. ma8 = sma(src, 8)
  156. ma21 = sma(src, 21)
  157. ema30 = ema(src, 30)
  158. ma50 = sma(src, 50)
  159. ma200 = sma(src,200)
  160. ma314 = sma(src,314)
  161. plot( ma8, color=color.red, style=plot.style_line, title="Ma 8", linewidth=1, transp= enableMAs ? 0 : 100)
  162. plot( ma21, color=color.purple, style=plot.style_line, title="Ma 21", linewidth=1, transp= enableMAs ? 0 : 100)
  163. plot( ema30, color=#880F4F, style=plot.style_line, title="ema 30", linewidth=2, transp= enableMAs ? 0 : 100)
  164. plot( ma50, color=color.orange, style=plot.style_line, title="Ma 50", linewidth=1, transp= enableMAs ? 0 : 100)
  165. plot( ma200, color=color.blue, style=plot.style_line, title="Ma 200",linewidth=2, transp= enableMAs ? 0 : 100)
  166. plot( ma314, color=color.green, style=plot.style_line, title="Ma 314",linewidth=2, transp= enableMAs ? 0 : 100)
  167.  
  168.  
  169. ////////////////////
  170. // Custom Functions
  171. ////////////////////
  172.  
  173. // sumSeries() function
  174. // vol*close to get sum of Base Volume
  175. sumSeries(insrc, length) =>
  176. l = min(length, 4990)
  177. max_bars_back(insrc, 4996)
  178. total = 0.0
  179. if (l > 1)
  180. for i = 1 to l-1
  181. total := total + (insrc[i]*src[i])
  182. else
  183. total = (insrc[1]*src[1])
  184. total
  185.  
  186. highest_(values, length) =>
  187. l = min(length, 4990)
  188. max_bars_back(values, 4997)
  189. max_bars_back(l, 1)
  190. h_val = values[0]
  191. if l >= 1
  192. for i = 0 to l-1
  193. if ( not na(values[i]) and values[i] > h_val )
  194. h_val := values[i]
  195. h_val
  196.  
  197. // when and price
  198. whenandprice(event) =>
  199. when = nz(barssince(event))
  200. price = valuewhen(event,src,0)
  201. // left shift result by 1 candle
  202. [when + 1, price]
  203.  
  204. // percentage() function
  205. percentage(source,per) =>
  206. percent = (source * (per/100))
  207. percent
  208.  
  209. // ADX and DI function
  210. getADX() =>
  211. // hard code close not src for this function
  212. TRange = max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1])))
  213. DirMovePlus = high-nz(high[1]) > nz(low[1])-low ? max(high-nz(high[1]), 0): 0
  214. DirMoveMinus = nz(low[1])-low > high-nz(high[1]) ? max(nz(low[1])-low, 0): 0
  215. SmoothedTRange = 0.0
  216. SmoothedDirMovePlus = 0.0
  217. SmoothedDirMoveMinus = 0.0
  218. SmoothedTRange := nz(SmoothedTRange[1]) - (nz(SmoothedTRange[1])/len) + TRange
  219. SmoothedDirMovePlus := nz(SmoothedDirMovePlus[1]) - (nz(SmoothedDirMovePlus[1])/len) + DirMovePlus
  220. SmoothedDirMoveMinus := nz(SmoothedDirMoveMinus[1]) - (nz(SmoothedDirMoveMinus[1])/len) + DirMoveMinus
  221. DIPlus = SmoothedDirMovePlus / SmoothedTRange * 100
  222. DIMinus = SmoothedDirMoveMinus / SmoothedTRange * 100
  223. _di = th + (DIPlus-DIMinus)
  224. _DX = abs(DIPlus-DIMinus) / (DIPlus+DIMinus)*100
  225. _ADX = sum(_DX,14)/14
  226. _ADX := ((nz(_ADX[1])*13)+_DX)/14
  227. _ADX
  228. [_di, _ADX]
  229.  
  230. // get ADX and di values
  231. [di, ADX] = getADX()
  232.  
  233. cr = color.gray
  234. cg = color.gray
  235. cr := ADX <= 22 ? color.new(color.green, 80) :
  236. ADX <= 34 ? color.new(color.green, 60) :
  237. ADX <= 46 ? color.new(color.green, 35) :
  238. ADX <= 58 ? color.new(color.green, 5) :
  239. ADX <= 70 ? color.new(color.green, 0) :
  240. color.new(color.green, 0)
  241. cg := ADX <= 22 ? color.new(color.red, 80) :
  242. ADX <= 34 ? color.new(color.red, 60) :
  243. ADX <= 46 ? color.new(color.red, 35) :
  244. ADX <= 58 ? color.new(color.red, 5) :
  245. ADX <= 70 ? color.new(color.red, 0) :
  246. color.new(color.red, 0)
  247.  
  248. ///////////////////////
  249. // inline volume code - moved out from function to stop
  250. // max_bars_back problem.
  251. // check on number of milliseconds needed
  252. milliseconds = 0
  253. if (measureOn == vD)
  254. milliseconds := 1000 * 60 * 60 * 24 * volTime
  255. if (measureOn == vH)
  256. milliseconds := 1000 * 60 * 60 * volTime
  257. NoOfCandles = 0
  258. volumeSum = 0.0
  259. if (timeframe.isseconds) // new second resolution
  260. NoOfCandles := ((milliseconds/1000) / timeframe.multiplier)
  261. volumeSum := sumSeries(volume, NoOfCandles)
  262. if (timeframe.isintraday)
  263. NoOfCandles := ((milliseconds/1000/60) / timeframe.multiplier)
  264. volumeSum := sumSeries(volume, NoOfCandles)
  265. if (timeframe.isdaily)
  266. if (measureOn == vD)
  267. volumeSum := volTime * (nz(volume[1])*nz(close[1]))
  268. if (measureOn == vH)
  269. volumeSum := 24 * volTime * (nz(volume[1])*nz(close[1]))
  270. if (timeframe.isweekly)
  271. if (measureOn == vD)
  272. volumeSum := 7 * volTime * (nz(volume[1])*nz(close[1]))
  273. if (measureOn == vH)
  274. volumeSum := 7 * 24 * volTime * (nz(volume[1])*nz(close[1]))
  275. if (timeframe.ismonthly)
  276. if (measureOn == vD)
  277. volumeSum := 30 * 7 * volTime * (nz(volume[1])*nz(close[1]))
  278. if (measureOn == vH)
  279. volumeSum := 30 * 7 * 24 * volTime * (nz(volume[1])*nz(close[1]))
  280.  
  281. //////////
  282. // Filters
  283. //////////
  284.  
  285. // RSI Filter
  286. // indi uses RSISource not src
  287. rsiOK() =>
  288. rsisrc = close
  289. ok = false
  290. if (RSIBasedOn == RSIOpen)
  291. rsisrc := open
  292. if (RSIBasedOn == RSIClose)
  293. rsisrc := close
  294. if (RSIBasedOn == RSIHigh)
  295. rsisrc := high
  296. if (RSIBasedOn == RSILow)
  297. rsisrc := low
  298. if (RSIBasedOn == RSIhl2)
  299. rsisrc := hl2
  300. if (RSIBasedOn == RSIhlc3)
  301. rsisrc := hlc3
  302. if (RSIBasedOn == RSIohlc4)
  303. rsisrc := ohlc4
  304. rsiValue = rsi(rsisrc, RSILength)
  305. if (RSITwoThree == two and (rsiValue > nz(rsiValue[1])))
  306. ok := true
  307. if (RSITwoThree == three and (rsiValue > nz(rsiValue[1])) and (nz(rsiValue[1]) > nz(rsiValue[2])))
  308. ok := true
  309. ok
  310.  
  311. // 200ma Filter
  312. ma200OK() =>
  313. max_bars_back(src, 4899)
  314. max_bars_back(ma200, 4898)
  315. result = true
  316. closeBelow200 = (src < ma200)
  317. if ((ebl200ma == false) and closeBelow200)
  318. result := false
  319. result
  320.  
  321. // Volume Filter
  322. volumeOK() =>
  323. ok = false
  324. if (volumeSum >= volThreshold)
  325. ok := true
  326. ok
  327.  
  328. // Coin Value Filter
  329. valueOK() =>
  330. ok = false
  331. if (src >= valThreshold)
  332. ok := true
  333.  
  334. ////////////////
  335. // Filter Checks
  336. ////////////////
  337.  
  338. // main function to check all filters
  339. filtersOK() =>
  340. ok = true
  341. // // test RSIfilter
  342. if (enableRSI and not rsiOK())
  343. ok := false
  344. // test ms200 filter
  345. if (not ma200OK())
  346. ok := false
  347. // test Volume filter
  348. if (eblVolume and not volumeOK())
  349. ok := false
  350. // test Value filter
  351. if (eblValFilter and not valueOK())
  352. ok := false
  353. ok
  354.  
  355. filterFired() =>
  356. ok = false
  357. if (filtersOK() and not filtersOK()[1])
  358. ok := true
  359. ok
  360. ///////////////////////
  361. // End of Filter Checks
  362. ///////////////////////
  363.  
  364.  
  365. /////////////////////
  366. // Main Trading Block
  367. /////////////////////
  368.  
  369. // Common
  370. adxup = crossover(ADX, th)
  371. diup = crossover(di, th)
  372. adxdiup = adxup and di >= th
  373. diadxup = diup and ADX >= th and (ADX > ADX[1])
  374. bothup = ((ADX >= th) and (di >= th))
  375.  
  376. // Preset d30 triggers
  377. D30True = false
  378. // Dirty 30 logic
  379. d30cross = crossover(ema30, ma200)
  380. firenow = (d30cross and bothup) // d30 cross after adx and di both up
  381. firenow2 = (adxdiup and barssince(d30cross) < barcount and barssince(diadxup) < barcount) // adx cross when d30 and di both up
  382. firenow3 = (diadxup and barssince(d30cross) < barcount and barssince(adxdiup) < barcount) // di cross when d30 and adx both up
  383. D30True := (firenow or firenow2 or firenow3)
  384.  
  385. // for TP, TTP & TSL
  386. tadxFlag = ((adxdiup and filtersOK()) or (ADX > th and di >= th and filterFired())) and not LastCondWasBuy
  387. tadxSell = crossunder(ADX, th) and LastCondWasBuy
  388. diFlag = ((crossover(di, th) and filtersOK()) or (di > th and filterFired())) and not LastCondWasBuy
  389. disell = crossunder(di, th) and LastCondWasBuy
  390. bothFlag = (((adxdiup or diadxup) and filtersOK()) or (bothup and filterFired())) and not LastCondWasBuy
  391. bothsell = (crossunder(di, th)) and LastCondWasBuy
  392.  
  393. ////////////////////
  394. // Trade on ADX ONLY
  395. if (startOn == TradeADX)
  396. buyFlag := tadxFlag
  397. if (disableS == false)
  398. sellFlag := tadxSell
  399. else
  400. // Trade on DI ONLY
  401. if (startOn == TradeDI)
  402. buyFlag := diFlag
  403. if (disableS == false)
  404. sellFlag := disell
  405. else
  406. // Trade Both
  407. if (startOn == TradeBoth)
  408. buyFlag := bothFlag
  409. if (disableS == false)
  410. sellFlag := bothsell
  411. else
  412. // Trade Dirty 30 - buy only allow TP logic to sell
  413. if (startOn == TradeDirty30)
  414. buyFlag := D30True
  415.  
  416. // buy logic complete so get when and price
  417. [lastBuyCount, lastBuyPrice] = whenandprice(buyFlag)
  418.  
  419.  
  420. ////////////////////////
  421. // TP, TTP and TSL Block
  422. ////////////////////////
  423.  
  424. // 1. Take Profit
  425. tpValue = (lastBuyPrice + percentage(lastBuyPrice, tpLevel))
  426. tpTrigger = (src > tpValue) and (nz(src[1]) <= tpValue)
  427. tpTriggeredCount = barssince(tpTrigger)
  428. allowTP = enableTP
  429. and (tpTrigger)
  430. and (nz(src[1]) <= tpValue)
  431. and (tpTriggeredCount < lastBuyCount)
  432. and LastCondWasBuy
  433. if (enableTPOn == tpon and allowTP)
  434. tpAlert := true
  435.  
  436. // 2. Trailing Take Profit
  437. ttp = (src - percentage(src, ttpLevel))
  438. ttpValue = highest_(ttp, lastBuyCount[0])
  439. tpRunningCount = barssince(allowTP)
  440. ttpTrigger = (barssince(src < ttpValue) < tpRunningCount)
  441. allowTTP = enableTP
  442. and (tpRunningCount < lastBuyCount)
  443. and ttpTrigger
  444. and LastCondWasBuy
  445. if (enableTPOn == ttpon and allowTTP)
  446. ttpAlert := true
  447.  
  448. // 3. Fixed Stop Loss
  449. slValue = (lastBuyPrice - percentage(lastBuyPrice, tslLevel))
  450. slTrigger = (src > slValue) and (nz(src[1]) <= slValue)
  451. slTriggeredCount = barssince(slTrigger)
  452. allowSL = (enableTSL == false)
  453. and (slTrigger)
  454. and (nz(src[1]) <= slValue)
  455. and (slTriggeredCount < lastBuyCount)
  456. and LastCondWasBuy
  457. if (enableTSL == false and allowSL)
  458. slAlert := true
  459.  
  460. // 4. Trailing Stop Loss
  461. tslStart = src - percentage(src, tslLevel)
  462. tslValue = highest_(tslStart, lastBuyCount[0])
  463. tslTriggeredCount = barssince(src < tslValue)
  464. allowTSL = enableTSL
  465. and (src < tslValue)
  466. and (nz(src[1]) >= nz(tslValue[1]))
  467. and (tslTriggeredCount < lastBuyCount)
  468. and LastCondWasBuy
  469. if (allowTSL)
  470. tslAlert := true
  471.  
  472. //update sellFlag for TP, TTP, SL or TSP
  473. sellFlag := (
  474. sellFlag or
  475. tpAlert or
  476. ttpAlert or
  477. slAlert or
  478. tslAlert )
  479.  
  480. ///////////////////////////
  481. // End TP TTP and TSL Logic
  482. ///////////////////////////
  483.  
  484.  
  485.  
  486.  
  487. /////////////////////////////////////////////////////////////////////////////////////
  488. // PineCoders, this is where the issue happens.
  489. // If you comment out this if block the max_bars_back error goes away...
  490. // but then the code does not work.. Leaving this if block in will cause max_bars_back
  491. // error on short timeframes, FETBTC on Binance @45min causes the issue... 2H does not
  492. //////////////////////////////////////////////////////////////////////////////////////
  493.  
  494. // New buy/sell allow logic
  495. if buyFlag and not LastCondWasBuy
  496. BuyCondition := true
  497. LastCondWasBuy := true
  498.  
  499. ///////////////////////////////////
  500. // PineCoders, End of problem area.
  501. ///////////////////////////////////
  502.  
  503.  
  504.  
  505.  
  506.  
  507. if sellFlag and LastCondWasBuy
  508. SellCondition := true
  509. LastCondWasBuy := false
  510.  
  511. // New calculate last buy/sell as sell prices and position
  512. [lastBuy2Count, lastBuy2Price] = whenandprice(BuyCondition)
  513. [lastSell2Count, lastSell2Price] = whenandprice(SellCondition)
  514.  
  515. // recalc tp values if changed ??? not sure
  516. tpValue := (lastBuy2Price + percentage(lastBuy2Price, tpLevel))
  517. slValue := (lastBuy2Price - percentage(lastBuy2Price, tslLevel))
  518.  
  519. // GL - Next lines cause issue
  520. ttpValue := highest_(ttp, lastBuy2Count[0])
  521. tslValue := highest_(tslStart, lastBuy2Count[0])
  522.  
  523. ///////////////////////////
  524. // Set Red Green Background
  525. // colour based on buy/sell
  526. setColour = color.red
  527. buyTrigger = (barssince(BuyCondition) <= barssince(SellCondition))
  528. if (buyTrigger)
  529. setColour := color.green
  530. bgcolor(setColour, transp = enableBackground ? 85 : 100)
  531.  
  532. ///////////////////////////
  533. // plot TP, TTP & TSL Lines
  534. ///////////////////////////
  535. enablePlotTP = enableTP
  536. and ((enableTPOn == tpon) or (enableTPOn == ttpon))
  537. and (lastBuy2Count < lastSell2Count)
  538. and (lastBuy2Count > 1)
  539. enablePlotTTP = enableTP
  540. and (enableTPOn == ttpon)
  541. and (lastBuy2Count < lastSell2Count)
  542. and ((tpRunningCount) < lastBuy2Count)
  543. and (lastBuy2Count > 1)
  544. enablePlotTSL = (lastBuy2Count < lastSell2Count)
  545. and (lastBuy2Count > 1) //and enableTSL
  546. // extend the lines by 1 candle to line up with tp markers
  547. PlotTP = (enablePlotTP) and (enablePlotTTP == false)
  548. PlotTTP = (enablePlotTTP or enablePlotTTP[1] == true) and barssince(ttpTrigger) > 1
  549. PlotTSL = (enablePlotTSL or enablePlotTSL[1] == true)
  550. // now plot the lines
  551. plot(tpValue, color=PlotTP ? color.blue : na, style=plot.style_line, title="TP Line", linewidth=2, transp=0)
  552. plot(ttpValue, color=PlotTTP ? #1d6303 : na, style=plot.style_line, title="TTP Line", linewidth=2, transp=0)
  553. plot(enableTSL ? tslValue : slValue, color=PlotTSL ? color.red : na, style=plot.style_line, title="SL Line", linewidth=2, transp=0)
  554. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
  555.  
  556. /////////////////////////////
  557. // Calc when to TP, TTP & TSL
  558. // done in 2 steps so all can be calculated
  559. // BEFORE final flag setting
  560. // 1. TP
  561. tpAlertFlag = tpAlert
  562. and (barssince(tpAlert) < lastBuy2Count)
  563. and (barssince(tpAlert[1]) > lastBuy2Count)
  564. // 2. TTP
  565. ttpAlertFlag = ttpAlert
  566. and (barssince(ttpAlert) < lastBuy2Count)
  567. and (barssince(ttpAlert[1]) > lastBuy2Count)
  568. // 3. TSL
  569. tslAlertFlag = tslAlert
  570. and (barssince(tslAlert) < lastBuy2Count)
  571. and (barssince(tslAlert[1]) > lastBuy2Count)
  572.  
  573. // set the plot flags for TP, TTP & TSL
  574. plotTPFlag = tpAlertFlag
  575. and not (
  576. (lastBuy2Count >= barssince(ttpAlertFlag)) or
  577. (lastBuy2Count >= barssince(tslAlertFlag))
  578. )
  579. plotTTPFlag = ttpAlertFlag
  580. and not (
  581. (lastBuy2Count >= barssince(tpAlertFlag)) or
  582. (lastBuy2Count >= barssince(tslAlertFlag))
  583. )
  584. plotTSLFlag = tslAlertFlag
  585. and not (
  586. (lastBuy2Count >= barssince(tpAlertFlag)) or
  587. (lastBuy2Count >= barssince(ttpAlertFlag))
  588. )
  589.  
  590. adxTrade = (startOn == TradeADX) and BuyCondition
  591. diTrade = (startOn == TradeDI) and BuyCondition
  592. bothTrade = (startOn == TradeBoth) and BuyCondition
  593. d30Trade = (startOn == TradeDirty30) and BuyCondition
  594. // Plot the TP, TTP & TSL Markers
  595. plotshape(plotTPFlag, color=color.blue, style=shape.square, location=location.bottom, title="TP Marker", size=size.tiny, editable=true, transp=10)
  596. plotshape(plotTTPFlag, color=#1d6303, style=shape.square, location=location.bottom, title="TTP Marker", size=size.tiny, editable=true, transp=10)
  597. plotshape(plotTSLFlag, color=color.orange, style=shape.square, location=location.bottom, title="TSL Marker", size=size.tiny, editable=true, transp=10)
  598. // Plot buy sell markers
  599. plotshape(BuyCondition, color=color.green, style=shape.triangleup, location=location.bottom, title="Buy", size=size.tiny, editable=true, transp=0)
  600. plotshape(SellCondition, color=color.red, style=shape.triangledown, location=location.bottom, title="Sell", size=size.tiny, editable=true, transp=0)
  601. // Plot Dirty 30 marker
  602. plotshape(D30True, color=#880F4F, style=shape.triangleup, location=location.belowbar, title="d30", size=size.tiny, editable=true, transp=0)
  603.  
  604. // Show price labels if enabled
  605. if (showTradeLbl)
  606. if (plotTPFlag)
  607. ltp = label.new(bar_index, na, text = "TP " + tostring(lastSell2Price), color=color.blue, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  608. if (plotTTPFlag)
  609. lttp = label.new(bar_index, na, text = "TTP " + tostring(lastSell2Price), color=#1d6303, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  610. if (plotTSLFlag)
  611. ltsl = label.new(bar_index, na, text = "TSL " + tostring(lastSell2Price), color=color.red, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  612. if (BuyCondition)
  613. lb = label.new(bar_index, na, text = "buy " + tostring(lastBuy2Price), color=color.green, textcolor=color.white, style=label.style_labelup, yloc=yloc.belowbar)
  614. if (adxTrade)
  615. lb = label.new(bar_index, na, text = "adx-buy", color=color.purple, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  616. if (diTrade)
  617. lb = label.new(bar_index, na, text = "di-buy", color=color.purple, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  618. if (bothTrade)
  619. lb = label.new(bar_index, na, text = "adxdi-buy", color=color.purple, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  620. if (d30Trade)
  621. lb = label.new(bar_index, na, text = "d30-buy", color=color.purple, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  622. // Debug Lable
  623. // lbv = label.new(bar_index, na, text = "Vol " + tostring(volumeSum), color=color.blue, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
  624. if (SellCondition and not (plotTPFlag or plotTTPFlag or plotTSLFlag))
  625. ls = label.new(bar_index, na, text = "sell " + tostring(lastSell2Price), color=color.red, textcolor=color.white, style=label.style_labelup, yloc=yloc.belowbar)
  626.  
  627. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  628. // setup the alerts for autoview to trade (multiples of 99% as 100% does not work for market buy/sell on binance)
  629. alertcondition(BuyCondition, title='_BUY', message='AUTO - Buy - {{ticker}}\ne={{exchange}} s={{ticker}} b=buy q=20% t=market')
  630. alertcondition(SellCondition, title='_SELL', message='AUTO - Sell - {{ticker}}\ne={{exchange}} s={{ticker}} b=sell q=99% t=market | delay=2 b=sell q=99% t=market | delay=2 b=sell q=99% t=market')
  631.  
  632. ////////////////////////////////////////////////////////////////////////////////////
  633. // Enter and close long orders for the Strategy Tester, no shorting in this version
  634. //strategy.entry(id="Enter Long", long=true, when = (BuyCondition == true ))
  635. //strategy.close(id="Enter Long", when = (SellCondition == true))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement