//-----------------------------------------------------------------------------}
//UDT
//-----------------------------------------------------------------------------{
type piv
float swing_prc // price
int swing_bix // bar_index
float oppos_prc // price
int oppos_bix // bar_index
bool active
bool confirmed
line swing_line
line oppos_line
line wicky_line
label wicky_label
if validate
if ltf_size > 0 and ltf_size[1] == 0
line.new(n, close, n, close + syminfo.mintick, color=color.silver, style=line.style_dotted, extend=extend.both)
//---------------------------------------------------------------------------------------------------------------------}
//Bearish Pattern
//---------------------------------------------------------------------------------------------------------------------{
if bear
code
if ph.n()
swingH.bix := n-1
swingH.prc := ph
sw = swingH.prc
bx = swingH.bix
if high > sw
and open < sw
and close < sw
valid = true
if validate
if ltf_close.size() > 0
outsideVolume = 0.
totalVolume = ltf_volume.sum()
for j = 0 to ltf_close.size() -1
if ltf_close.get(j) > sw
outsideVolume += ltf_volume.get(j)
if (valHigher ? 100 / totalVolume * outsideVolume < percent
: 100 / totalVolume * outsideVolume > percent
)
valid := false
//if valid
// label.new(n, high, text=str.format("Total Volume: {0}\nWick Volume: {1}", totalVolume, outsideVolume))
if valid
opposL = sw
opposB = n
for i = 1 to n - bx -1
if low [i] < opposL
opposL := low [i]
opposB := n - i
if not pivH.confirmed
pivH.swing_line .delete()
pivH.oppos_line .delete()
pivH.wicky_line .delete()
pivH.wicky_label.delete()
pivH := piv.new(sw, bx, opposL, opposB, true, false)
if dSwingLine
pivH.swing_line := line.new (bx , sw , n, sw , color=colBr)
if dOpposLine
pivH.oppos_line := line.new (opposB, opposL, n, opposL, color=colBr, style=line.style_dotted)
if dSFP_Line
pivH.wicky_line := line.new (n , high , n, sw , color=colBr2, width=3)
if dSFP_Label
pivH.wicky_label := label.new(n , high
, style=label.style_label_down
, text='SFP', textcolor=colBr
, color=INV, size=size.normal
)
if pivH.active and not pivH.confirmed
pivH.swing_line.set_x2(n)
pivH.oppos_line.set_x2(n)
if close < pivH.oppos_prc
pivH.confirmed := true
if pivH.wicky_label.get_x() == n
pivH.wicky_label.set_text('SFP\n▼')
else
label.new(n, high, style=label.style_label_down, text='▼', textcolor=colBr, color=INV, size=size.normal)
if n - pivH.swing_bix > 500
or close > pivH.swing_prc
pivH.active := false
if not pivH.confirmed
pivH.swing_line .delete()
pivH.oppos_line .delete()
pivH.wicky_line .delete()
pivH.wicky_label.delete()
//---------------------------------------------------------------------------------------------------------------------}
//Bullish Pattern
//---------------------------------------------------------------------------------------------------------------------{
if bull
code
if pl.n()
swingL.bix := n-1
swingL.prc := pl
sw = swingL.prc
bx = swingL.bix
if low < sw
and open > sw
and close > sw
valid = true
if validate
if ltf_close.size() > 0
outsideVolume = 0.
totalVolume = ltf_volume.sum()
for j = 0 to ltf_close.size() -1
if ltf_close.get(j) < sw
outsideVolume += ltf_volume.get(j)
if (valHigher ? 100 / totalVolume * outsideVolume < percent
: 100 / totalVolume * outsideVolume > percent
)
valid := false
if valid
opposH = sw
opposB = n
for i = 1 to n - bx -1
if high[i] > opposH
opposH := high[i]
opposB := n - i
if not pivL.confirmed
pivL.swing_line .delete()
pivL.oppos_line .delete()
pivL.wicky_line .delete()
pivL.wicky_label.delete()
pivL := piv.new(sw, bx, opposH, opposB, true, false)
if dSwingLine
pivL.swing_line := line.new (bx , sw , n, sw , color=colBl )
if dOpposLine
pivL.oppos_line := line.new (opposB, opposH, n, opposH, color=colBl , style=line.style_dotted)
if dSFP_Line
pivL.wicky_line := line.new (n , low , n, sw , color=colBl2, width=3)
if dSFP_Label
pivL.wicky_label := label.new(n , low
, style=label.style_label_up
, text='SFP', textcolor=colBl
, color=INV, size=size.normal
)
if pivL.active and not pivL.confirmed
pivL.swing_line.set_x2(n)
pivL.oppos_line.set_x2(n)
if close > pivL.oppos_prc
pivL.confirmed := true
if pivL.wicky_label.get_x() == n
pivL.wicky_label.set_text('▲\nSFP')
else
label.new(n, low, style=label.style_label_up, text='▲', textcolor=colBl, color=INV, size=size.normal)
if n - pivL.swing_bix > 500
or close < pivL.swing_prc
pivL.active := false
if not pivL.confirmed
pivL.swing_line .delete()
pivL.oppos_line .delete()
pivL.wicky_line .delete()
pivL.wicky_label.delete()
//---------------------------------------------------------------------------------------------------------------------}
//Dashboard
//---------------------------------------------------------------------------------------------------------------------{
if barstate.islast and validate and showDash
tb.cell(0, 0, str.format("LTF: {0}", res), text_color=color.white, text_size=table_size)
Certainly! Below is a TradingView Strategy based on the provided Swing Failure Pattern (SFP) indicator. This strategy incorporates your specified rules:
Time Filter: The SFP must occur between 13:00 and 22:00 UTC.
Single Entry: Enter only on the first signal when the SFP occurs within the specified time frame.
Validation Setting: The "Volume outside swing" must be less than the threshold.
Key Features of the Strategy:
Bullish and Bearish SFP Detection: The strategy identifies both bullish and bearish swing failure patterns based on the original indicator logic.
Volume Validation: Ensures that the volume outside the swing is below the specified threshold.
Time Filtering: Activates trades only within the defined UTC time window.
Single Entry per Signal: Prevents multiple entries for the same SFP signal by tracking active trades.
Basic Exit Rules: Includes simple exit conditions using Stop Loss and Take Profit. You can customize these as needed.
Strategy Script
pinescript
// This strategy is based on LuxAlgo's Swing Failure Pattern indicator
// It is customized to include specific trading rules as requested
//@version=5
strategy("Swing Failure Pattern Strategy [LuxAlgo]", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
//---------------------------------------------------------------------------------------------------------------------
// Settings
//---------------------------------------------------------------------------------------------------------------------
// Swings
len = input.int(5, "Swings", minval=1)
bull = input.bool(true, "Bullish SFP")
bear = input.bool(true, "Bearish SFP")
// Volume Validation
validation_options = ['Volume outside swing < Threshold', 'Volume outside swing > Threshold', 'None']
iVal = input.string('Volume outside swing < Threshold', 'Validation', options=validation_options)
percent = input.float(25, 'Volume Threshold %', group='Volume Validation', tooltip='% of Total Volume', minval=0, maxval=100)
auto = input.bool(true, '', group='Volume Validation')
mlt = input.int(50, 'Auto', group='Volume Validation')
res = input.timeframe('1', 'LTF', group='Volume Validation')
prem = input.bool(false, 'Premium', group='Volume Validation')
// Dashboard (Optional - can be omitted in strategy)
showDash = input.bool(false, "Show Dashboard")
dashLoc = input.string('Top Right', 'Dashboard Location', options=['Top Right', 'Bottom Right', 'Bottom Left'])
textSize = input.string('Normal', 'Dashboard Text Size', options=['Tiny', 'Small', 'Normal'])
// Style Settings
dSwingLine = input.bool(true, 'Show Swing Lines', group='Style')
dOpposLine = input.bool(true, 'Show Confirmation Lines', group='Style')
dSFP_Line = input.bool(true, 'Show SFP Wick Lines', group='Style')
dSFP_Label = input.bool(false, 'Show SFP Labels', group='Style') // Labels are optional for strategy
colBl = input.color(color.new(color.teal, 0), 'Bullish Colors', group='Style')
colBr = input.color(color.new(color.red, 0), 'Bearish Colors', group='Style')
colBl2 = input.color(color.new(color.teal, 50), 'Bullish Wick Color', group='Style')
colBr2 = input.color(color.new(color.red, 50), 'Bearish Wick Color', group='Style')
// Exit Settings (Customize as needed)
stopLossPerc = input.float(1.0, "Stop Loss %")
takeProfitPerc = input.float(2.0, "Take Profit %")
//---------------------------------------------------------------------------------------------------------------------
// Helper Types and Variables
//---------------------------------------------------------------------------------------------------------------------
type piv
float swing_prc // price
int swing_bix // bar_index
float oppos_prc // price
int oppos_bix // bar_index
bool active
bool confirmed
line swing_line
line oppos_line
line wicky_line
label wicky_label
type swing
int bix
float prc
n = bar_index
validate = iVal == 'Volume outside swing < Threshold'
valLower = true // Since we set validation to "Volume outside swing < Threshold"
// Time filter settings
startTimeUTC = timestamp("UTC", year, month, dayofmonth, 13, 0)
endTimeUTC = timestamp("UTC", year, month, dayofmonth, 22, 0)
isWithinTime = time >= startTimeUTC and time <= endTimeUTC
// Initialize swings and pivots
var swing swingH = swing.new()
var swing swingL = swing.new()
var piv pivH = piv.new()
var piv pivL = piv.new()
//---------------------------------------------------------------------------------------------------------------------
// Volume Validation
//---------------------------------------------------------------------------------------------------------------------
[ltf_close, ltf_volume] = request.security_lower_tf(syminfo.tickerid, res, [close, volume])
totalVolume = ta.sum(ltf_volume, len)
outsideVolume = 0.0
for j = 0 to len - 1
if (bear and high[j] > swingH.prc) or (bull and low[j] < swingL.prc)
outsideVolume += ltf_volume[j]
validVolume = (100 / totalVolume * outsideVolume) < percent and validate
//---------------------------------------------------------------------------------------------------------------------
// Bearish Pattern Detection
//---------------------------------------------------------------------------------------------------------------------
if bear and isWithinTime
ph = ta.pivothigh(high, len, len)
if not na(ph)
swingH.bix := bar_index - len
swingH.prc := ph
if high > swingH.prc and open < swingH.prc and close < swingH.prc
if validVolume
// Find opposite swing
opposL = swingH.prc
opposB = swingH.bix
for i = 1 to len
if low[i] < opposL
opposL := low[i]
opposB := bar_index - i
// Set pivot
pivH := piv.new(swingH.prc, swingH.bix, opposL, opposB, true, false)
// Optional: Draw lines and labels
if dSwingLine
pivH.swing_line := line.new(pivH.swing_bix, pivH.swing_prc, bar_index, pivH.swing_prc, color=colBr)
if dOpposLine
pivH.oppos_line := line.new(pivH.oppos_bix, pivH.oppos_prc, bar_index, pivH.oppos_prc, color=colBr, style=line.style_dotted)
if dSFP_Line
pivH.wicky_line := line.new(bar_index, high, bar_index, pivH.swing_prc, color=colBr2, width=3)
if dSFP_Label
pivH.wicky_label := label.new(bar_index, high, style=label.style_label_down, text='SFP', textcolor=colBr, color=color.new(color.red, 0), size=size.normal)
// Confirm pattern
if pivH.active and not pivH.confirmed
if close < pivH.oppos_prc
pivH.confirmed := true
// Entry Signal for Bearish SFP
if isWithinTime and validVolume
strategy.entry("Bearish SFP", strategy.short)
// Set exit orders
strategy.exit("Bearish TP/SL", from_entry="Bearish SFP",
stop=close * (1 + stopLossPerc / 100),
limit=close * (1 - takeProfitPerc / 100))
//---------------------------------------------------------------------------------------------------------------------
// Bullish Pattern Detection
//---------------------------------------------------------------------------------------------------------------------
if bull and isWithinTime
pl = ta.pivotlow(low, len, len)
if not na(pl)
swingL.bix := bar_index - len
swingL.prc := pl
if low < swingL.prc and open > swingL.prc and close > swingL.prc
if validVolume
// Find opposite swing
opposH = swingL.prc
opposB = swingL.bix
for i = 1 to len
if high[i] > opposH
opposH := high[i]
opposB := bar_index - i
// Set pivot
pivL := piv.new(swingL.prc, swingL.bix, opposH, opposB, true, false)
// Optional: Draw lines and labels
if dSwingLine
pivL.swing_line := line.new(pivL.swing_bix, pivL.swing_prc, bar_index, pivL.swing_prc, color=colBl)
if dOpposLine
pivL.oppos_line := line.new(pivL.oppos_bix, pivL.oppos_prc, bar_index, pivL.oppos_prc, color=colBl, style=line.style_dotted)
if dSFP_Line
pivL.wicky_line := line.new(bar_index, low, bar_index, pivL.swing_prc, color=colBl2, width=3)
if dSFP_Label
pivL.wicky_label := label.new(bar_index, low, style=label.style_label_up, text='SFP', textcolor=colBl, color=color.new(color.teal, 0), size=size.normal)
// Confirm pattern
if pivL.active and not pivL.confirmed
if close > pivL.oppos_prc
pivL.confirmed := true
// Entry Signal for Bullish SFP
if isWithinTime and validVolume
strategy.entry("Bullish SFP", strategy.long)
// Set exit orders
strategy.exit("Bullish TP/SL", from_entry="Bullish SFP",
stop=close * (1 - stopLossPerc / 100),
limit=close * (1 + takeProfitPerc / 100))
//---------------------------------------------------------------------------------------------------------------------
// Optional Dashboard (Can be omitted for strategy)
//---------------------------------------------------------------------------------------------------------------------
if barstate.islast and showDash
var table tb = table.new(position=location.top_right, columns=2, rows=3, bgcolor=color.new(color.black, 90))
table.cell(tb, 0, 0, "LTF:", text_color=color.white, text_size=size.normal)
table.cell(tb, 1, 0, res, text_color=color.white, text_size=size.normal)
table.cell(tb, 0, 1, "Validation:", text_color=color.white, text_size=size.normal)
table.cell(tb, 1, 1, iVal, text_color=color.white, text_size=size.normal)
table.cell(tb, 0, 2, "Threshold %:", text_color=color.white, text_size=size.normal)
table.cell(tb, 1, 2, str.tostring(percent), text_color=color.white, text_size=size.normal)
//---------------------------------------------------------------------------------------------------------------------
// End of Script
//---------------------------------------------------------------------------------------------------------------------
Explanation of the Strategy Components
Strategy Declaration:
strategy("Swing Failure Pattern Strategy [LuxAlgo]", ...) initializes the strategy with a name and sets it to overlay on the chart.
default_qty_type and default_qty_value define the position size (e.g., 10% of equity).
Input Parameters:
Swings: Determines the length for identifying pivot points.
Volume Validation: Sets the validation method to ensure volume outside the swing is below the threshold.
Dashboard Settings: Optional settings for displaying information on the chart.
Style Settings: Customize the appearance of lines and labels.
Exit Settings: Define Stop Loss and Take Profit percentages.
Time Filtering:
The strategy only activates trades between 13:00 and 22:00 UTC using isWithinTime.
Volume Validation:
Calculates the total volume over the swing length and the volume outside the swing to ensure it meets the "Volume outside swing < Threshold" condition.
Bearish and Bullish SFP Detection:
Bearish SFP: When a pivot high is broken, and validation criteria are met, the strategy enters a short position.
Bullish SFP: When a pivot low is broken, and validation criteria are met, the strategy enters a long position.
Entry signals are confirmed patterns where the price closes beyond the opposite swing point.
Entry and Exit Orders:
Entry: Uses strategy.entry to enter long or short positions based on SFP signals.
Exit: Uses strategy.exit to set Stop Loss and Take Profit levels relative to the entry price.
Optional Dashboard:
Displays selected settings on the chart for easy reference. This is optional and can be disabled by setting showDash to false.
Visual Aids:
Draws lines and labels on the chart to visualize swing points and SFP occurrences. These are optional and can be customized or removed as needed.
How to Use the Strategy
Copy the Script:
Copy the entire Pine Script code provided above.
Open TradingView:
Navigate to TradingView and log in to your account.
Access Pine Editor:
Open the chart of the instrument you want to trade.
Click on the Pine Editor tab at the bottom of the chart.
Paste the Script:
Delete any existing code in the Pine Editor.
Paste the copied script into the editor.
Add to Chart:
Click the Add to Chart button (usually a ”▶” icon) at the top of the Pine Editor.
The strategy will compile and apply to your current chart.
Configure Settings:
After adding the strategy, click on the strategy name in the chart's Strategy Tester panel.
Adjust input parameters such as Swings, Volume Threshold %, Stop Loss %, and Take Profit % as desired.
Backtest:
Use the Strategy Tester tab to review the performance, including metrics like Net Profit, Drawdown, and the number of trades.
Customization Tips
Adjusting Time Window: If you wish to change the trading hours, modify the startTimeUTC and endTimeUTC variables.
Entry Conditions: Currently, the strategy enters on confirmed SFP patterns. You can add additional conditions or filters as needed.
Exit Strategies: The current setup uses simple percentage-based Stop Loss and Take Profit. For more sophisticated exits, consider trailing stops or exiting on opposite signals.
Position Sizing: Adjust default_qty_type and default_qty_value to fit your risk management preferences.
Visual Elements: If you prefer not to have lines and labels on the chart, set dSwingLine, dOpposLine, dSFP_Line, and dSFP_Label to false.
Important Considerations
Market Conditions: SFP strategies can perform differently across various market conditions. Ensure thorough backtesting and consider forward testing with paper trading before committing real capital.
Slippage and Commissions: Real trading involves slippage and commissions which are not accounted for in backtesting. Adjust your strategy parameters accordingly.
Strategy Limitations: This strategy is based on the provided indicator and rules. It may require further optimization and risk management to suit specific trading styles.
Feel free to further customize the strategy to better fit your trading requirements. If you have any questions or need additional modifications, feel free to ask!