Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // © UAlgo
- //==x77x My Other Indicators @ https://pastebin.com/u/SavingFace
- //@version=5
- 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)
- // Variables from indicator
- var float lastHigh = na
- var float lastLow = na
- var float lastPriceLow = na
- var float lastPriceHigh = na
- var bool shortLiq = na
- var bool longLiq = na
- var color upColorLiquidation = color.new(#089981, 50)
- var color downColorLiquidation = color.new(#FF5252, 50)
- var color upCircleStyle = color.new(color.aqua, 30)
- var color downCircleStyle = color.new(color.orange, 30)
- // Inputs
- selectedSrc = input.string("Close", "Source", options=["Close", "Open", "High", "Low", "HL2", "HLC3", "OHLC4", "Volume", "VWAP"], group="Liquidation Calculations")
- maLength1 = input.int(20, "SMA Length 1", group="Liquidation Calculations")
- maLength2 = input.int(38, "EMA Length 2", group="Liquidation Calculations")
- // Assign the selected source to `src`
- src = (selectedSrc == "Close" ? close :
- selectedSrc == "Open" ? open :
- selectedSrc == "High" ? high :
- selectedSrc == "Low" ? low :
- selectedSrc == "HL2" ? (high + low) / 2 : // Average of High and Low
- selectedSrc == "HLC3" ? (high + low + close) / 3 : // Average of High, Low, and Close
- selectedSrc == "OHLC4" ? (open + high + low + close) / 4 : // Average of Open, High, Low, and Close
- selectedSrc == "Volume" ? volume :
- selectedSrc == "VWAP" ? ta.vwap : close) // Default to close if none match
- upColor = input.color(upColorLiquidation, title="Long Liquidation Color", group="Style Settings", inline="1")
- downColor = input.color(downColorLiquidation, title="Short Liquidation Color", group="Style Settings", inline="1")
- upCircle = input.color(upCircleStyle, title="Long Liquidation Shape Color", group="Style Settings", inline="2")
- downCircle = input.color(downCircleStyle, title="Short Liquidation Shape Color", group="Style Settings", inline="2")
- ma1 = ta.sma(src, maLength1)
- ma2 = ta.ema(src, maLength2)
- avgLine = ((ma1 + ma2) / 2)
- distVal = (((src - avgLine) / avgLine) * 100)
- // Independent lookback periods for `ph` and `pl`
- lookbackPeriodPH = input.int(60, "Lookback Period for PH", minval=1, group="Liquidation Calculations")
- lookbackPeriodPL = input.int(89, "Lookback Period for PL", minval=1, group="Liquidation Calculations")
- // Calculate `ph` and `pl` using their respective lookback periods
- ph = ta.highest(distVal, lookbackPeriodPH)
- pl = ta.lowest(distVal, lookbackPeriodPL)
- // Plot `ph` and `pl` as separate lines for visual reference
- plot(ph, color=color.new(color.green, 50), title="Highest Distance (ph)")
- plot(pl, color=color.new(color.red, 50), title="Lowest Distance (pl)")
- if ph == distVal and ph > 0
- lastHigh := distVal
- lastPriceHigh := high
- if pl == distVal and pl < 0
- lastLow := distVal
- lastPriceLow := low
- shortLiq := not na(lastHigh) and lastHigh == distVal and distVal > 0 ? true : false
- longLiq := not na(lastLow) and lastLow == distVal and distVal < 0 ? true : false
- // Bear Market Filter
- halvingYear = input(2011, title="Last Halving Year")
- yearDifference = year(time) - halvingYear
- isBearMarket = (yearDifference % 4 == 3)
- // Detect beginning and end of bear market
- var bool wasBearMarket = false
- bearMarketStart = not wasBearMarket and isBearMarket
- bearMarketEnd = wasBearMarket and not isBearMarket
- wasBearMarket := isBearMarket
- // Take Profit Settings
- takeProfits = input.int(2, "Number of Take Profits", minval=1, maxval=10)
- takeProfitPercent = 100 / takeProfits // Calculate the percentage for each take profit
- // Take Profit Counter
- var int takeProfitCount = 0
- // Backtest Period Inputs
- startYear = input.int(2020, title="Backtest Start Year", minval=2010)
- endYear = input.int(2024, title="Backtest End Year", minval=2010)
- inBacktestRange = year(time) >= startYear and year(time) <= endYear
- // Plot the bear market filter on the chart for reference
- bgcolor(isBearMarket ? color.red : na, transp=90, title="Bear Market", force_overlay=true)
- // Entry and Exit Signals
- drawCircleShortLiq = (shortLiq and distVal > 7.97) ? true : false
- drawCircleLongLiq = (longLiq and distVal < -4) ? true : false
- // On Chart Plot indicators
- plot(distVal, color=distVal > 0 ? downColor : upColor, style=plot.style_columns)
- plotshape(drawCircleShortLiq ? distVal : na, style=shape.circle, title='On chart Shorts Liquidation', color=downCircle, location=location.abovebar, size=size.tiny, force_overlay=true)
- plotshape(drawCircleLongLiq ? distVal : na, style=shape.circle, title='On chart Long Liquidation', color=upCircle, location=location.belowbar, size=size.tiny, force_overlay=true)
- // Oscillator Plots
- plotshape(drawCircleShortLiq ? distVal : na, title='Oscillator Shorts Liquidation', style=shape.circle, color=downCircle, location=location.absolute, size=size.tiny)
- plotshape(drawCircleLongLiq ? distVal : na, title='Oscillator Longs Liquidation', style=shape.circle, color=upCircle, location=location.absolute, size=size.tiny)
- // On Chart Plot indicators
- plot(distVal, color=distVal > 0 ? downColor : upColor, style=plot.style_columns)
- plotshape(drawCircleShortLiq ? distVal : na, style=shape.circle, title='On chart Shorts Liquidation', color=downCircle, location=location.abovebar, size=size.tiny, force_overlay=true)
- plotshape(drawCircleLongLiq ? distVal : na, style=shape.circle, title='On chart Long Liquidation', color=upCircle, location=location.belowbar, size=size.tiny, force_overlay=true)
- // Reset conditions
- if bearMarketStart
- strategy.close("Long") // Close any open long positions at bear market start
- takeProfitCount := 0 // Reset take profit count
- if bearMarketEnd
- strategy.close("Short") // Close any open short positions at bear market end
- // Strategy Logic with Adjustable Take Profits, respecting backtest range
- if inBacktestRange and isBearMarket
- if drawCircleShortLiq
- if strategy.position_size < 0 // Existing short position
- strategy.entry("Short", strategy.short) // Add to the short position
- else
- strategy.entry("Short", strategy.short) // New short position entry
- takeProfitCount := 0 // Reset take profit count on new entry
- if drawCircleLongLiq and strategy.position_size < 0 // Take profit on existing short
- if takeProfitCount < takeProfits - 1
- strategy.close("Short", qty_percent=takeProfitPercent) // Take a portion of profit
- takeProfitCount += 1
- else if takeProfitCount == takeProfits - 1
- strategy.close("Short") // Close the remaining position on last take profit
- takeProfitCount := 0 // Reset for next position
- else if inBacktestRange
- if drawCircleLongLiq
- if strategy.position_size > 0 // Existing long position
- strategy.entry("Long", strategy.long) // Add to the long position
- else
- strategy.entry("Long", strategy.long) // New long position entry
- takeProfitCount := 0 // Reset take profit count on new entry
- if drawCircleShortLiq and strategy.position_size > 0 // Take profit on existing long
- if takeProfitCount < takeProfits - 1
- strategy.close("Long", qty_percent=takeProfitPercent) // Take a portion of profit
- takeProfitCount += 1
- else if takeProfitCount == takeProfits - 1
- strategy.close("Long") // Close the remaining position on last take profit
- takeProfitCount := 0 // Reset for next position
- // Average Entry Line
- var float avgEntryPrice = na // Declare as a variable with explicit float type
- if strategy.position_size != 0
- avgEntryPrice := strategy.position_avg_price // Track the average entry price
- else
- avgEntryPrice := na // Reset when position is closed
- plot(avgEntryPrice, color=color.blue, style=plot.style_linebr, linewidth=1, title="Average Entry Price", force_overlay = true)
- // Variable to track if a label has already been created
- var label positionLabel = na
- // Calculate the dollar value of the position
- positionValueUSD = strategy.position_size * strategy.position_avg_price
- // Calculate the percentage change relative to the average entry price
- percentageChange = (close - strategy.position_avg_price) / strategy.position_avg_price * 100
- // Check if the position size has changed
- if strategy.position_size != 0
- // Update the label with the new position value and percentage change
- if na(positionLabel)
- // Create the label if it doesn't exist, positioned to the right side of the chart
- positionLabel := label.new(x=bar_index + 1, y=avgEntryPrice,
- text="Position Value: $" + str.tostring(positionValueUSD, "##0.00") + "\nChange: " + str.tostring(percentageChange, "##0.00") + "%",
- color=color.blue, style=label.style_label_left, textcolor=#131313, force_overlay=true)
- else
- // Update the existing label with the new position value, percentage change, and position at the end of the line
- label.set_text(positionLabel, "Position Value: $" + str.tostring(positionValueUSD, "##0.00") + "\nChange: " + str.tostring(percentageChange, "##0.00") + "%")
- label.set_y(positionLabel, avgEntryPrice) // Follow the average entry price line
- label.set_x(positionLabel, bar_index + 1) // Move label to the right edge
- // Remove the label when the position is closed
- if (strategy.opentrades == 0 and not na(positionLabel))
- label.delete(positionLabel)
- positionLabel := na
- // Additional code for table, performance summary, etc., remains unchanged
- ////////////////////////////////////////////////// Table
- closeLongCondition = false
- closeShortCondition = false
- //////////////////////////////////////////////////////////////////////////////////
- // Dashboard Table Text Size
- i_tableTextSize = input.string(title="Dashboard Size", defval="Small", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="Dashboards")
- table_text_size(s) =>
- switch s
- "Auto" => size.auto
- "Huge" => size.huge
- "Large" => size.large
- "Normal" => size.normal
- "Small" => size.small
- => size.tiny
- tableTextSize = table_text_size(i_tableTextSize)
- /// Performance Summary Dashboard
- i_showDashboard = input.bool(title="Performance Summary", defval=true, group="Dashboards", inline="Show Dashboards")
- f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
- _cellText = _title + "\n" + _value
- table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=tableTextSize)
- if i_showDashboard
- var bgcolor = color.new(color.black,0)
- // Track Wins/Losses streaks
- newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
- newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
- varip int winRow = 0
- varip int lossRow = 0
- varip int maxWinRow = 0
- varip int maxLossRow = 0
- if newWin
- lossRow := 0
- winRow := winRow + 1
- if winRow > maxWinRow
- maxWinRow := winRow
- if newLoss
- winRow := 0
- lossRow := lossRow + 1
- if lossRow > maxLossRow
- maxLossRow := lossRow
- var table dashTable = table.new(position.top_right, 1, 15, border_width=1,force_overlay = true)
- if barstate.islastconfirmedhistory
- lastTime = strategy.position_size == 0 ? strategy.closedtrades.exit_time(strategy.closedtrades-1) : time
- dollarReturn = strategy.netprofit
- _profit = (strategy.netprofit / strategy.initial_capital) * 100
- _numOfDaysInStrategy = (lastTime - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
- _numOfDaysInStrategy := _numOfDaysInStrategy != 0 ? _numOfDaysInStrategy : 1
- f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '##.###')+"%", _profit > 0 ? color.teal : color.maroon, color.white)
- _winRate = (strategy.wintrades / strategy.closedtrades) * 100
- f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.maroon : _winRate < 75 ? #999900 : color.teal, color.white)
- f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.teal : color.maroon, color.white)
- f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
- f_fillCell(dashTable, 0, 7, "Winning Trades:", str.tostring(strategy.wintrades, '######') , bgcolor, color.white)
- f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
- f_fillCell(dashTable, 0, 9, "Losing Trades:", str.tostring(strategy.losstrades, '######') , bgcolor, color.white)
- f_fillCell(dashTable, 0, 10, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
- ///////////////////////////////////////
Advertisement
Add Comment
Please, Sign In to add comment