SavingFace

Buy Low Sell High Strategy " If orders don't show up try contracts"

Nov 4th, 2024
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.30 KB | Cryptocurrency | 0 0
  1. // © UAlgo
  2. //==x77x My Other Indicators @ https://pastebin.com/u/SavingFace
  3. //@version=5
  4. strategy("Buy Low Sell High", overlay=false, default_qty_type=strategy.cash, default_qty_value=1000,initial_capital=5000, pyramiding=5, process_orders_on_close=true)
  5.  
  6.  
  7. // Variables from indicator
  8. var float lastHigh = na
  9. var float lastLow = na
  10. var float lastPriceLow = na
  11. var float lastPriceHigh = na
  12. var bool shortLiq = na
  13. var bool longLiq = na
  14. var color upColorLiquidation = color.new(#089981, 50)
  15. var color downColorLiquidation = color.new(#FF5252, 50)
  16. var color upCircleStyle = color.new(color.aqua, 30)
  17. var color downCircleStyle = color.new(color.orange, 30)
  18.  
  19. // Inputs
  20. selectedSrc = input.string("Close", "Source", options=["Close", "Open", "High", "Low", "HL2", "HLC3", "OHLC4", "Volume", "VWAP"], group="Liquidation Calculations")
  21. maLength1 = input.int(20, "SMA Length 1", group="Liquidation Calculations")
  22. maLength2 = input.int(38, "EMA Length 2", group="Liquidation Calculations")
  23.  
  24. // Assign the selected source to `src`
  25. src = (selectedSrc == "Close" ? close :
  26. selectedSrc == "Open" ? open :
  27. selectedSrc == "High" ? high :
  28. selectedSrc == "Low" ? low :
  29. selectedSrc == "HL2" ? (high + low) / 2 : // Average of High and Low
  30. selectedSrc == "HLC3" ? (high + low + close) / 3 : // Average of High, Low, and Close
  31. selectedSrc == "OHLC4" ? (open + high + low + close) / 4 : // Average of Open, High, Low, and Close
  32. selectedSrc == "Volume" ? volume :
  33. selectedSrc == "VWAP" ? ta.vwap : close) // Default to close if none match
  34.  
  35. upColor = input.color(upColorLiquidation, title="Long Liquidation Color", group="Style Settings", inline="1")
  36. downColor = input.color(downColorLiquidation, title="Short Liquidation Color", group="Style Settings", inline="1")
  37. upCircle = input.color(upCircleStyle, title="Long Liquidation Shape Color", group="Style Settings", inline="2")
  38. downCircle = input.color(downCircleStyle, title="Short Liquidation Shape Color", group="Style Settings", inline="2")
  39.  
  40. ma1 = ta.sma(src, maLength1)
  41. ma2 = ta.ema(src, maLength2)
  42. avgLine = ((ma1 + ma2) / 2)
  43. distVal = (((src - avgLine) / avgLine) * 100)
  44.  
  45. // Independent lookback periods for `ph` and `pl`
  46. lookbackPeriodPH = input.int(60, "Lookback Period for PH", minval=1, group="Liquidation Calculations")
  47. lookbackPeriodPL = input.int(89, "Lookback Period for PL", minval=1, group="Liquidation Calculations")
  48.  
  49. // Calculate `ph` and `pl` using their respective lookback periods
  50. ph = ta.highest(distVal, lookbackPeriodPH)
  51. pl = ta.lowest(distVal, lookbackPeriodPL)
  52.  
  53. // Plot `ph` and `pl` as separate lines for visual reference
  54. plot(ph, color=color.new(color.green, 50), title="Highest Distance (ph)")
  55. plot(pl, color=color.new(color.red, 50), title="Lowest Distance (pl)")
  56.  
  57. if ph == distVal and ph > 0
  58. lastHigh := distVal
  59. lastPriceHigh := high
  60.  
  61. if pl == distVal and pl < 0
  62. lastLow := distVal
  63. lastPriceLow := low
  64.  
  65. shortLiq := not na(lastHigh) and lastHigh == distVal and distVal > 0 ? true : false
  66. longLiq := not na(lastLow) and lastLow == distVal and distVal < 0 ? true : false
  67.  
  68. // Bear Market Filter
  69. halvingYear = input(2011, title="Last Halving Year")
  70. yearDifference = year(time) - halvingYear
  71. isBearMarket = (yearDifference % 4 == 3)
  72.  
  73. // Detect beginning and end of bear market
  74. var bool wasBearMarket = false
  75. bearMarketStart = not wasBearMarket and isBearMarket
  76. bearMarketEnd = wasBearMarket and not isBearMarket
  77. wasBearMarket := isBearMarket
  78.  
  79. // Take Profit Settings
  80. takeProfits = input.int(2, "Number of Take Profits", minval=1, maxval=10)
  81. takeProfitPercent = 100 / takeProfits // Calculate the percentage for each take profit
  82.  
  83. // Take Profit Counter
  84. var int takeProfitCount = 0
  85.  
  86. // Backtest Period Inputs
  87. startYear = input.int(2020, title="Backtest Start Year", minval=2010)
  88. endYear = input.int(2024, title="Backtest End Year", minval=2010)
  89. inBacktestRange = year(time) >= startYear and year(time) <= endYear
  90.  
  91. // Plot the bear market filter on the chart for reference
  92. bgcolor(isBearMarket ? color.red : na, transp=90, title="Bear Market", force_overlay=true)
  93.  
  94. // Entry and Exit Signals
  95. drawCircleShortLiq = (shortLiq and distVal > 7.97) ? true : false
  96. drawCircleLongLiq = (longLiq and distVal < -4) ? true : false
  97.  
  98. // On Chart Plot indicators
  99. plot(distVal, color=distVal > 0 ? downColor : upColor, style=plot.style_columns)
  100. plotshape(drawCircleShortLiq ? distVal : na, style=shape.circle, title='On chart Shorts Liquidation', color=downCircle, location=location.abovebar, size=size.tiny, force_overlay=true)
  101. plotshape(drawCircleLongLiq ? distVal : na, style=shape.circle, title='On chart Long Liquidation', color=upCircle, location=location.belowbar, size=size.tiny, force_overlay=true)
  102.  
  103. // Oscillator Plots
  104. plotshape(drawCircleShortLiq ? distVal : na, title='Oscillator Shorts Liquidation', style=shape.circle, color=downCircle, location=location.absolute, size=size.tiny)
  105. plotshape(drawCircleLongLiq ? distVal : na, title='Oscillator Longs Liquidation', style=shape.circle, color=upCircle, location=location.absolute, size=size.tiny)
  106.  
  107. // On Chart Plot indicators
  108. plot(distVal, color=distVal > 0 ? downColor : upColor, style=plot.style_columns)
  109. plotshape(drawCircleShortLiq ? distVal : na, style=shape.circle, title='On chart Shorts Liquidation', color=downCircle, location=location.abovebar, size=size.tiny, force_overlay=true)
  110. plotshape(drawCircleLongLiq ? distVal : na, style=shape.circle, title='On chart Long Liquidation', color=upCircle, location=location.belowbar, size=size.tiny, force_overlay=true)
  111.  
  112.  
  113.  
  114. // Reset conditions
  115. if bearMarketStart
  116. strategy.close("Long") // Close any open long positions at bear market start
  117. takeProfitCount := 0 // Reset take profit count
  118.  
  119. if bearMarketEnd
  120. strategy.close("Short") // Close any open short positions at bear market end
  121.  
  122. // Strategy Logic with Adjustable Take Profits, respecting backtest range
  123. if inBacktestRange and isBearMarket
  124. if drawCircleShortLiq
  125. if strategy.position_size < 0 // Existing short position
  126. strategy.entry("Short", strategy.short) // Add to the short position
  127. else
  128. strategy.entry("Short", strategy.short) // New short position entry
  129. takeProfitCount := 0 // Reset take profit count on new entry
  130. if drawCircleLongLiq and strategy.position_size < 0 // Take profit on existing short
  131. if takeProfitCount < takeProfits - 1
  132. strategy.close("Short", qty_percent=takeProfitPercent) // Take a portion of profit
  133. takeProfitCount += 1
  134. else if takeProfitCount == takeProfits - 1
  135. strategy.close("Short") // Close the remaining position on last take profit
  136. takeProfitCount := 0 // Reset for next position
  137. else if inBacktestRange
  138. if drawCircleLongLiq
  139. if strategy.position_size > 0 // Existing long position
  140. strategy.entry("Long", strategy.long) // Add to the long position
  141. else
  142. strategy.entry("Long", strategy.long) // New long position entry
  143. takeProfitCount := 0 // Reset take profit count on new entry
  144. if drawCircleShortLiq and strategy.position_size > 0 // Take profit on existing long
  145. if takeProfitCount < takeProfits - 1
  146. strategy.close("Long", qty_percent=takeProfitPercent) // Take a portion of profit
  147. takeProfitCount += 1
  148. else if takeProfitCount == takeProfits - 1
  149. strategy.close("Long") // Close the remaining position on last take profit
  150. takeProfitCount := 0 // Reset for next position
  151.  
  152. // Average Entry Line
  153. var float avgEntryPrice = na // Declare as a variable with explicit float type
  154. if strategy.position_size != 0
  155. avgEntryPrice := strategy.position_avg_price // Track the average entry price
  156. else
  157. avgEntryPrice := na // Reset when position is closed
  158.  
  159. plot(avgEntryPrice, color=color.blue, style=plot.style_linebr, linewidth=1, title="Average Entry Price", force_overlay = true)
  160.  
  161. // Variable to track if a label has already been created
  162. var label positionLabel = na
  163.  
  164. // Calculate the dollar value of the position
  165. positionValueUSD = strategy.position_size * strategy.position_avg_price
  166.  
  167. // Calculate the percentage change relative to the average entry price
  168. percentageChange = (close - strategy.position_avg_price) / strategy.position_avg_price * 100
  169.  
  170. // Check if the position size has changed
  171. if strategy.position_size != 0
  172. // Update the label with the new position value and percentage change
  173. if na(positionLabel)
  174. // Create the label if it doesn't exist, positioned to the right side of the chart
  175. positionLabel := label.new(x=bar_index + 1, y=avgEntryPrice,
  176. text="Position Value: $" + str.tostring(positionValueUSD, "##0.00") + "\nChange: " + str.tostring(percentageChange, "##0.00") + "%",
  177. color=color.blue, style=label.style_label_left, textcolor=#131313, force_overlay=true)
  178. else
  179. // Update the existing label with the new position value, percentage change, and position at the end of the line
  180. label.set_text(positionLabel, "Position Value: $" + str.tostring(positionValueUSD, "##0.00") + "\nChange: " + str.tostring(percentageChange, "##0.00") + "%")
  181. label.set_y(positionLabel, avgEntryPrice) // Follow the average entry price line
  182. label.set_x(positionLabel, bar_index + 1) // Move label to the right edge
  183.  
  184. // Remove the label when the position is closed
  185. if (strategy.opentrades == 0 and not na(positionLabel))
  186. label.delete(positionLabel)
  187. positionLabel := na
  188.  
  189.  
  190. // Additional code for table, performance summary, etc., remains unchanged
  191.  
  192. ////////////////////////////////////////////////// Table
  193.  
  194. closeLongCondition = false
  195. closeShortCondition = false
  196.  
  197. //////////////////////////////////////////////////////////////////////////////////
  198.  
  199. // Dashboard Table Text Size
  200. i_tableTextSize = input.string(title="Dashboard Size", defval="Small", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="Dashboards")
  201. table_text_size(s) =>
  202. switch s
  203. "Auto" => size.auto
  204. "Huge" => size.huge
  205. "Large" => size.large
  206. "Normal" => size.normal
  207. "Small" => size.small
  208. => size.tiny
  209. tableTextSize = table_text_size(i_tableTextSize)
  210.  
  211. /// Performance Summary Dashboard
  212. i_showDashboard = input.bool(title="Performance Summary", defval=true, group="Dashboards", inline="Show Dashboards")
  213.  
  214. f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
  215. _cellText = _title + "\n" + _value
  216. table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=tableTextSize)
  217.  
  218. if i_showDashboard
  219. var bgcolor = color.new(color.black,0)
  220.  
  221. // Track Wins/Losses streaks
  222. newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
  223. newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
  224.  
  225. varip int winRow = 0
  226. varip int lossRow = 0
  227. varip int maxWinRow = 0
  228. varip int maxLossRow = 0
  229.  
  230. if newWin
  231. lossRow := 0
  232. winRow := winRow + 1
  233. if winRow > maxWinRow
  234. maxWinRow := winRow
  235.  
  236. if newLoss
  237. winRow := 0
  238. lossRow := lossRow + 1
  239. if lossRow > maxLossRow
  240. maxLossRow := lossRow
  241.  
  242. var table dashTable = table.new(position.top_right, 1, 15, border_width=1,force_overlay = true)
  243.  
  244. if barstate.islastconfirmedhistory
  245. lastTime = strategy.position_size == 0 ? strategy.closedtrades.exit_time(strategy.closedtrades-1) : time
  246. dollarReturn = strategy.netprofit
  247. _profit = (strategy.netprofit / strategy.initial_capital) * 100
  248. _numOfDaysInStrategy = (lastTime - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
  249. _numOfDaysInStrategy := _numOfDaysInStrategy != 0 ? _numOfDaysInStrategy : 1
  250. f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '##.###')+"%", _profit > 0 ? color.teal : color.maroon, color.white)
  251. _winRate = (strategy.wintrades / strategy.closedtrades) * 100
  252. f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.maroon : _winRate < 75 ? #999900 : color.teal, color.white)
  253. f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.teal : color.maroon, color.white)
  254. f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
  255. f_fillCell(dashTable, 0, 7, "Winning Trades:", str.tostring(strategy.wintrades, '######') , bgcolor, color.white)
  256. f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
  257. f_fillCell(dashTable, 0, 9, "Losing Trades:", str.tostring(strategy.losstrades, '######') , bgcolor, color.white)
  258. f_fillCell(dashTable, 0, 10, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
  259.  
  260. ///////////////////////////////////////
Tags: btc Strategy
Advertisement
Add Comment
Please, Sign In to add comment