本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// =============================================================================
// Intraday Pullback Sniper (BB, Stoch RSI, Liquidity, HTF, Structure, Sessions)
// SIGNAL ONLY — marks entries, leaves target and stop to the trader
//
// WHAT IT DOES
// Marks the candles where a complete setup exists and where all enabled entry
// conditions are met. It does not manage trades: no stop, no targets, no
// simulated position. Position sizing and exits stay with the trader.
//
// READING THE TWO MARKERS - the one thing to understand before using this
// The small dot is the starting gun, the large dot is the complete signal, and
// the large one always needs a SECOND band touch on a LATER candle.
//
// Small dot - a setup is armed. Four conditions, all on the same candle:
// 1. the wick touches the band
// 2. the candle closes back inside, and in the half that faces that band
// 3. the Stoch RSI was at its extreme within the last few candles
// 4. the bias allows that direction
//
// Large dot - the signal. Seven conditions:
// 1. a setup from an earlier candle is running and has not expired
// 2. the structure of the entry timeframe is confirmed - depending on the
// mode a Higher Low followed by a Higher High, a break of the last swing,
// or both
// 3. there is a fresh band touch with a rejection on this very candle
// 4. the bias fits
// 5. the liquidity sweep is present, if it is required at all
// 6. the session is open
// 7. the cooldown after the last signal has passed
//
// The decisive part is the time gap. The band has to be touched twice: once for
// the setup, once for the signal, and in between the lower-timeframe structure
// has to confirm the turn. A large dot can therefore never appear on the same
// candle as its own small dot - the following one at the earliest.
//
// What does happen: a new small dot on a signal candle. That candle meets the
// setup conditions too, so it arms the next setup while it fires the current
// signal.
//
// In plain words: a small dot says "price bounced off the band, I am watching".
// A large dot says "it did so a second time, and the structure turned in
// between".
//
// WHERE IT DRAWS
// The script runs in its own pane below the chart, where the Stoch RSI that the
// setup logic uses is plotted together with its levels, the bias as a background
// tint and a strip showing how long a setup is still waiting for its entry.
// Everything belonging to price - bands, EMA, markers, structure, liquidity and
// the status table - is drawn onto the price chart from there.
//
// HOW SWINGS ARE FOUND
// Everything structural in this script - swing labels, market structure and
// liquidity - comes from one single swing engine using the classical definition
// of a turning point:
// * a swing high is a SYMMETRIC pivot: the highest candle of a window with
// "lookback" candles on its left and the same number on its right, so it is
// a local extreme in the literal sense, confirmed and never repainted
// * highs and lows strictly alternate; a second point of the same kind before
// the opposite one only replaces the current one if it is more extreme
// * a minimum number of candles between two points (backstep), and optionally
// a minimum leg size, which is off by default
// Two degrees are calculated: a short one with a lookback of 2 - the classic
// fractal - for the detail, and a long one with the standard pivot value of 10
// for the larger move. Reading a chart in more than one degree of movement is
// the oldest principle in technical analysis.
// Structure breaks are judged on the CLOSE, not on wicks. A break in the
// direction of the prevailing structure is a BOS, one against it a CHOCH; both
// are MSB events.
//
// HOW TO USE
// * Put the chart on the setup timeframe (5 minutes by default).
// * The entry timeframe must be lower than the chart. Its candles are read with
// request.security_lower_tf(), which does not repaint but is limited to a few
// months of intrabar history depending on your TradingView plan.
// * All higher-timeframe data is taken from CLOSED candles only.
// * Signals are evaluated at the close of a chart candle.
//
// DEVIATION FROM THE ORIGINAL SPECIFICATION
// §52 sets the setup expiration to 5 x 1m bars, which on a 5m chart is a single
// candle - the entry is only checked from the following bar, so nothing could
// ever trigger. Default here is 30 (6 chart bars, 5 of them usable).
// =============================================================================
indicator("Intraday Pullback Sniper (BB, Stoch RSI, Liquidity, HTF, Structure, Sessions)", "Pullback Sniper", overlay = false, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 100)
// =============================================================================
// 1 · INPUTS
// =============================================================================
g0 = "0 · Read me first"
note1 = input.string("Put the chart on 5 minutes", "Chart timeframe", options = ["Put the chart on 5 minutes"], group = g0, tooltip = "The chart MUST run on the Setup Timeframe set below, which is 5 minutes by default.\n\nBollinger Bands, Stoch RSI and the setup detection are calculated on the chart timeframe. The entry structure is pulled from real lower-timeframe candles inside each chart candle, and the bias is pulled from above, so you see all three levels at once without switching charts.\n\nOther combinations are fine as long as you keep the rule: chart = setup timeframe, entry timeframe below it. For example a 15m chart with a 1H bias and 5m entry structure.")
note2 = input.string("Signal only, no trade management", "Scope", options = ["Signal only, no trade management"], group = g0, tooltip = "This indicator marks setups and entry signals. It deliberately does not draw stops, targets or risk-reward levels, and it does not simulate a position.\n\nSignals appear at the close of a chart candle, never intrabar. That is what keeps them free of repainting.\n\nThe script itself sits in its own pane below the chart, which is where the Stoch RSI is plotted. Everything that belongs to price is drawn onto the chart from there. One consequence is worth knowing: TradingView ties a table to the pane its script runs in, so the status table appears in the lower pane, not on the chart. Drag the divider between the two panes if it needs more room.")
note3 = input.string("What the labels on the chart mean", "Glossary", options = ["What the labels on the chart mean"], group = g0, tooltip = "SWING LABELS\nHH Higher High - a high above the previous high.\nHL Higher Low - a low above the previous low. HH plus HL is a rising structure.\nLH Lower High, LL Lower Low - the mirror image, a falling structure.\n\nSTRUCTURE BREAKS\nA break is a close beyond the last confirmed swing point.\nBOS Break of Structure - the break continues the direction that was already in place.\nCHOCH Change of Character - the break goes against it and is the first hint of a turn.\nMSB Market Structure Break - the umbrella term; every BOS and every CHOCH is one.\nThe timeframe is always appended, for example 'MSB BOS 1H'.\n\nLIQUIDITY LEVELS\nThe name has three parts: source, side, rank.\nPDH and PDL are yesterday's high and low.\nOtherwise the timeframe comes first, then the side, then the rank counted outwards from price.\nBSL, buy-side liquidity, sits above old highs: the buy orders of everyone who is short, plus the stops above.\nSSL, sell-side liquidity, sits below old lows.\n'15m BSL2' is therefore the second-nearest untaken buy-side pool of the 15-minute chart above the current price.\nThe short form H2 and L2 can be chosen instead in the liquidity settings.\nRanking is by distance, not by age, so a level can move from H2 to H1 when the one in front of it is cleared.\n'swept' behind the name means price ran through the level and closed back on the old side - the orders resting there have been taken.\n\nMARKERS\nA small dot below or above a candle marks an armed setup. A larger dot marks a candle where every enabled condition was met. Below the candle means a long context, above it a short one.\nThere is deliberately no written buy or sell instruction: the dot tells you a condition is complete, not that this is the moment to enter.")
note4 = input.string("How to set up alerts", "Alerts", options = ["How to set up alerts"], group = g0, tooltip = "HOW TO SET AN ALERT\nRight-click the chart, Add alert, and under Condition pick this indicator by name. The second dropdown then lists everything it can fire on.\n\nFOR THE SIGNAL - the large dot\nPick 'Any alert() function call' and set the trigger to 'Once Per Bar Close'. One alert covers long and short, and the message is written by the indicator: symbol, direction, price, bias, setup direction, state of the entry structure, whether a sweep was present, and the session.\n\nIf you would rather have them apart, pick 'SNIPER LONG' or 'SNIPER SHORT' instead and create two alerts. The text is then fixed and short, but you can route each direction differently.\n\nEVERYTHING ELSE ON THE LIST\nLong Setup and Short Setup fire on the small dot. They come far more often than signals - set them separately or not at all, otherwise the one that matters drowns in the noise.\nBullish and Bearish Liquidity Sweep fire when a level is taken.\nBullish and Bearish BOS, CHOCH and MSB fire on structure breaks of the chart timeframe.\n\nALWAYS USE 'ONCE PER BAR CLOSE'\nThe indicator only evaluates at the close of a candle, so any other trigger cannot make an alert arrive earlier - it would only check more often for nothing. This is also what keeps the alert consistent with what you see on the chart.")
g1 = "1 · Timeframes"
biasTF = input.timeframe("15", "Bias Timeframe", group = g1, tooltip = "Higher timeframe used only to decide the overall market direction. Nothing here triggers a signal by itself; it decides which direction is allowed when Strict Bias is on.\n\nRule of thumb: about three times the setup timeframe. On a 5m chart that is 15m.")
setupTF = input.timeframe("5", "Setup Timeframe (must equal chart TF)", group = g1, tooltip = "The timeframe the Bollinger Bands and the Stoch RSI are calculated on. Put your chart on this timeframe; the status table tells you if it does not match.")
entryTF = input.timeframe("1", "Entry Timeframe (structure)", group = g1, tooltip = "The lower timeframe whose swing structure times the entry. Its candles are read from inside each chart candle, so you get the finer structure without leaving the chart.\n\nIt must be lower than the chart timeframe. On a 5m chart 1m is the natural choice.")
g2 = "2 · Market Bias"
emaLen = input.int(200, "EMA Length", minval = 1, group = g2, tooltip = "Number of candles the average is built from, calculated on the bias timeframe. Price above it counts as bullish, below it as bearish.\n\n200 is the classic long-term setting and reacts slowly. Shorter values such as 50 flip more often and give the bias a shorter memory.")
biasSrc = input.string("Both", "Bias source", options = ["Both", "Structure", "EMA"], group = g2, tooltip = "What decides whether the market counts as bullish or bearish.\n\nEMA: price above or below the moving average of the bias timeframe. Calm and slow, but an average is not a trend definition - after a sharp sell-off price needs a long time to climb back above it, so the turn is long over while this still says bearish.\n\nStructure: the trend state of the market structure on the bias timeframe - higher highs and higher lows against lower highs and lower lows. It flips at the CHOCH, which is what a change of character means. Turns early, but changes its mind more often in sideways phases.\n\nBoth: the two are combined and a third state appears when they disagree - the structure has already turned while price is still on the wrong side of the average. That state is shown separately instead of being hidden behind one of the two colours, so you do not go hunting for shorts in a market that has already turned up.")
transMode = input.string("Offensive", "While the sources disagree", options = ["Offensive", "Conservative"], group = g2, tooltip = "What may be traded while the two sources disagree.\n\nOffensive: the direction the structure has turned to is allowed, the old one is blocked. This is where the early trades of a reversal sit, often the best ones of a move.\n\nConservative: both directions are blocked until the two agree again. Fewer signals, and you miss the turn itself.\n\nOnly has an effect with Strict HTF Bias switched on and the source set to Both.")
strictBias = input.bool(true, "Strict HTF Bias (trade with bias only)", group = g2, tooltip = "ON: long signals only in a bullish bias, short signals only in a bearish one. This is the safer setting and the default.\n\nOFF: the bias becomes information only and counter-trend signals are allowed.")
showEma = input.bool(true, "Plot EMA", group = g2, inline = "ema", tooltip = "Draws the bias EMA on your chart.\n\nThis row: the checkbox switches the line on, the colour field sets its colour, the number its thickness in pixels.")
emaCol = input.color(color.yellow, "", group = g2, inline = "ema", tooltip = "Draws the bias EMA on your chart.\n\nThis row: the checkbox switches the line on, the colour field sets its colour, the number its thickness in pixels.")
emaWidth = input.int(2, "Width", minval = 1, maxval = 5, group = g2, inline = "ema", tooltip = "Draws the bias EMA on your chart.\n\nThis row: the checkbox switches the line on, the colour field sets its colour, the number its thickness in pixels.")
g3 = "3 · Bollinger Bands (setup TF)"
bbLen = input.int(20, "Length", minval = 2, group = g3, tooltip = "Number of candles the middle line of the bands is averaged over.\n\nShorter values make the bands hug price and react quickly, longer ones make them smoother and slower. 20 is the standard setting.")
bbMult = input.float(2.0, "Deviation", step = 0.1, group = g3, tooltip = "How far the outer bands sit from the middle line, measured in standard deviations of price.\n\nHigher values widen the bands, so price touches them less often and you get fewer but more extreme setups. 2.0 is the standard and covers roughly 95 percent of all candles.")
bbSrc = input.source(close, "Source", group = g3, tooltip = "Which price of each candle the bands are calculated from. Close is the standard and what almost every chart uses; the other options are for special cases.")
rejZone = input.float(50, "Entry zone (% of band width)", minval = 5, maxval = 100, step = 5, group = g3, tooltip = "How far into the bands the candle may close and still count as a rejection, measured from the band it touched as a percentage of the full band width.\n\n50 means a long may only close in the lower half. Without this, one large candle that wicks the lower band and closes at the upper band would qualify as a long - entering at the top of the move.\n\n100 switches the limit off and restores the plain rule from the specification.")
bbShow = input.bool(true, "Draw the bands", group = g3, tooltip = "Switches the three band lines and the shading off without touching the logic.\n\nSetups, signals and the entry zone keep working exactly as before - the bands are simply not drawn. Useful once you rely on the markers and want the chart free of lines.")
bbColBand = input.color(color.new(color.teal, 20), "Bands", group = g3, inline = "bb1", tooltip = "Appearance of the bands.\n\nThis row: colour of the outer bands, colour of the middle band, and line thickness in pixels.")
bbColMid = input.color(color.new(color.orange, 20), "Middle", group = g3, inline = "bb1", tooltip = "Appearance of the bands.\n\nThis row: colour of the outer bands, colour of the middle band, and line thickness in pixels.")
bbWidth = input.int(1, "Width", minval = 1, maxval = 5, group = g3, inline = "bb1", tooltip = "Appearance of the bands.\n\nThis row: colour of the outer bands, colour of the middle band, and line thickness in pixels.")
bbShowFill= input.bool(true, "Fill", group = g3, inline = "bb2", tooltip = "Shades the area between the outer bands.\n\nThis row: the checkbox switches the shading on, the colour field sets its colour and transparency.")
bbColFill = input.color(color.new(color.teal, 94), "", group = g3, inline = "bb2", tooltip = "Shades the area between the outer bands.\n\nThis row: the checkbox switches the shading on, the colour field sets its colour and transparency.")
g4 = "4 · Stoch RSI (setup TF)"
rsiLen = input.int(14, "RSI Length", minval = 1, group = g4, tooltip = "Number of candles the RSI is calculated over. The Stochastic is then applied on top of that RSI.\n\n14 is the standard. Shorter reacts faster and reaches the extremes more often, longer is calmer.")
stoLen = input.int(14, "Stoch Length", minval = 1, group = g4, tooltip = "How far back the Stochastic looks to place the current RSI value on a scale from 0 to 100.\n\n0 means the RSI is at the lowest point of that window, 100 at the highest. This is what turns the RSI into an oscillator with clear extremes.")
kSm = input.int(3, "K Smoothing", minval = 1, group = g4, tooltip = "Smoothing of the fast K line, in candles. K is the line the setup logic actually works with.\n\nHigher values give a calmer line and later signals, 1 switches the smoothing off and makes it jumpy.")
dSm = input.int(3, "D Smoothing", minval = 1, group = g4, tooltip = "Smoothing of the slow D line, in candles. D is K smoothed once more and lags behind it.\n\nIt is not used by the setup logic. It only serves the eye: the pane shades the area between the two, so you can see the momentum direction at a glance.")
osLvl = input.float(20, "Oversold", group = g4, tooltip = "Below this level the market counts as oversold, which is one of the conditions for a long setup.\n\nLower values mean a deeper drop is required, so fewer but more extreme setups. 20 is the standard.")
obLvl = input.float(80, "Overbought", group = g4, tooltip = "Above this level the market counts as overbought, which is one of the conditions for a short setup.\n\nKeep it symmetrical to the oversold level unless you want one direction to be harder to reach than the other. 80 is the standard.")
stochLB = input.int(5, "Extreme Lookback (bars)", minval = 1, group = g4, tooltip = "How many candles back the Stoch RSI may have reached its extreme. With 5 the oversold reading may be up to five candles old and the long setup still counts.\n\nHigher values give more setups because the rejection no longer has to happen right at the extreme.")
g5 = "5 · Swing Engine (feeds structure, labels and liquidity)"
swInt = input.int(2, "Internal lookback", minval = 1, maxval = 49, group = g5, tooltip = "Lookback for the SHORT-term swing points, in candles to each side. This is the fast structure used for entry timing and for the internal structure labels.\n\n2 is the classic fractal: a high with two lower highs to its left and two to its right. It is the finest reading of a swing that still deserves the name, and it is the standard value for the short degree.")
swMain = input.int(10, "Swing lookback", minval = 2, maxval = 100, group = g5, tooltip = "Lookback for the LONG-term swing points, in candles to each side. This is the structure that drives the HH/HL/LH/LL labels and the main BOS/CHOCH labels.\n\n10 is the standard value for pivot detection and marks the turning points that shape the larger move, while the short degree above catches the detail inside it. Two degrees of movement is the oldest idea in chart analysis and predates every modern indicator.\n\nA swing is only confirmed this many candles after it formed, so the last 10 candles can never carry a label yet. That delay is the price of never repainting.")
swDevMode= input.string("Off", "Deviation filter", options = ["Off", "ATR", "Percent"], group = g5, tooltip = "Optional extra filter: a minimum size a new leg must have before a swing point is accepted.\n\nOff by default, and deliberately so. The lookback and the backstep already define what counts as a swing, and there is no established value for this threshold - whatever number were put here would be invented rather than derived. Leave it off unless the chart tells you otherwise.\n\nATR: the minimum move measured in average true range, so it scales with the instrument and with volatility. Use this if a quiet sideways phase still produces more turning points than you want.\n\nPercent: the same idea measured in percent of price.")
swDevVal = input.float(0.5, "Deviation value", minval = 0.0, step = 0.1, group = g5, tooltip = "Only used when the deviation filter above is switched on: multiples of ATR in ATR mode, percent of price in Percent mode. 0.5 ATR keeps swings worth roughly half an average candle range.\n\nThis is a tuning knob for your own chart, not a standard value.")
swBack = input.int(2, "Backstep (bars)", minval = 0, maxval = 50, group = g5, tooltip = "Minimum number of candles between two accepted swing points.\n\nWithout it, two turning points can sit right next to each other and the structure becomes a zigzag of tiny steps. 2 is the classic value.")
swAtrLen = input.int(14, "ATR Length", minval = 1, group = g5, tooltip = "Number of candles the Average True Range is measured over. The ATR is the average distance a candle travels, and it is used here as a yardstick that adapts to the instrument.\n\nIt feeds the optional deviation filter above and the spacing that keeps labels off the markers.")
g6 = "6 · Entry timing"
use1M = input.bool(true, "Use entry-timeframe structure", group = g6, tooltip = "ON: the structure of the entry timeframe must confirm before a signal is given.\n\nOFF: only the Bollinger rejection on the setup timeframe is required, which gives many more but weaker signals.")
entryMode = input.string("HH/HL + BB Rejection", "Entry Mode", options = ["Structure Break", "HH/HL + BB Rejection", "Both"], group = g6, tooltip = "Structure Break: signal as soon as price closes beyond the last confirmed swing high (long) or swing low (short) of the entry timeframe.\n\nHH/HL + BB Rejection: signal after a Higher Low plus Higher High (long) or Lower High plus Lower Low (short), followed by a fresh band touch that closes back inside. This is the main variant.\n\nBoth: demands the sequence AND the break AND the rejection. Very few signals, for testing only.")
strLead = input.int(0, "Structure lead time (entry-TF bars)", minval = 0, maxval = 120, group = g6, tooltip = "0 = strictly as specified: the HH/HL or LH/LL sequence must form AFTER the setup appears.\n\nAbove 0: a sequence that completed up to this many entry-timeframe candles before the setup is accepted as well. In practice the structure often forms while price is still approaching the band.\n\nThe order is preserved either way: a signal never comes before its structure is confirmed.")
g7 = "7 · HTF Liquidity"
reqSweep = input.bool(false, "Require HTF liquidity sweep", group = g7, tooltip = "OFF: sweeps are drawn and alerted but are not required for a signal. This is the default so the effect of the filter can be measured separately.\n\nON: a signal additionally requires price to have run through a higher-timeframe level and closed back on the other side.")
liqDepth = input.string("Only main liquidities", "Liquidity detail", options = ["Only main liquidities", "Also fine liquidities"], group = g7, tooltip = "Quick setting for how much liquidity is drawn - no numbers needed.\n\nOnly main liquidities: a wick becomes a level only if it is the extreme of the whole window set below. Where several spikes sit close together, the deepest of them swallows its neighbours. Few, heavy levels.\n\nAlso fine liquidities: every wick that reaches past the one candle either side of it gets its own level. Nothing is swallowed any more, so the smaller wicks appear as well - stops rest at those too, not only at the deepest one. Busier chart, more complete picture.\n\nBoth modes show untaken levels only, and only the nearest few per timeframe, so the chart cannot flood.\n\nThe numeric lookback below stays available for anyone who wants to sit between the two.")
liqLen = input.int(10, "Liquidity lookback", minval = 2, maxval = 100, group = g7, tooltip = "Lookback for the swing points that become liquidity levels, in candles to each side of the pivot. Same symmetric pivot rule as the structure, kept as its own setting so the two can be tuned apart: structure may stay coarse to keep the chart readable, while liquidity is allowed to be finer, because stop orders rest at every swing a trader can see - not only at the largest ones.\n\nApplied to every enabled timeframe, so 10 on the 15m chart means two and a half hours to each side there.\n\nOnly used while Liquidity detail above is set to 'Only main liquidities'. The 'Also fine liquidities' mode ignores this value and uses the finest possible setting.")
useChart = input.bool(true, "Chart TF Swings", group = g7, tooltip = "Swing highs and lows of the timeframe you are looking at. Labelled with the chart timeframe as prefix, for example '5m BSL1' above price and '5m SSL1' below it.\n\nWithout this source the nearest levels are always at least one timeframe away, and the significant highs and lows of your own chart carry no marking at all.\n\nBSL means buy-side liquidity and sits ABOVE old highs - the buy orders of everyone who is short, plus the stops above. SSL means sell-side liquidity and sits BELOW old lows. The short form H and L can be chosen instead under Level naming.")
usePD = input.bool(true, "Previous Day High/Low", group = g7, tooltip = "Yesterday's high and low as liquidity levels. Among the most watched levels in the market, and unlike the swing levels they are kept even after price trades beyond them, because they stay a daily reference.\n\nEach line starts at the candle that actually made that high or low, not at the start of the day.")
use15m = input.bool(true, "15m Swings", group = g7, tooltip = "Swing highs and lows of the 15-minute chart. This is the range that matters for a trade running over a handful of chart candles: close enough to be reached inside a session, far enough to hold real stop orders.\n\nLabelled with the prefix 15m, so '15m BSL1' is the nearest untaken buy-side pool of the 15-minute chart above price.\n\nBSL means buy-side liquidity and sits ABOVE old highs - the buy orders of everyone who is short, plus the stops above. SSL means sell-side liquidity and sits BELOW old lows. The short form H and L can be chosen instead under Level naming.")
use30m = input.bool(false, "30m Swings", group = g7, tooltip = "Swing highs and lows of the 30-minute chart. A step coarser than 15m, reached less often but with more weight behind it.\n\nLabelled with the prefix 30m, so '30m BSL1' is the nearest untaken buy-side pool of the 30-minute chart above price.\n\nBSL means buy-side liquidity and sits ABOVE old highs - the buy orders of everyone who is short, plus the stops above. SSL means sell-side liquidity and sits BELOW old lows. The short form H and L can be chosen instead under Level naming.")
use1H = input.bool(true, "1H Swings", group = g7, tooltip = "Swing highs and lows of the 1-hour chart.\n\nLabelled with the prefix 1H, so '1H BSL1' is the nearest untaken buy-side pool of the 1-hour chart above price.\n\nBSL means buy-side liquidity and sits ABOVE old highs - the buy orders of everyone who is short, plus the stops above. SSL means sell-side liquidity and sits BELOW old lows. The short form H and L can be chosen instead under Level naming.")
use4H = input.bool(false, "4H Swings", group = g7, tooltip = "Swing highs and lows of the 4-hour chart. Big targets that are hit rarely, mostly useful as context.\n\nLabelled with the prefix 4H, so '4H BSL1' is the nearest untaken buy-side pool of the 4-hour chart above price.\n\nBSL means buy-side liquidity and sits ABOVE old highs - the buy orders of everyone who is short, plus the stops above. SSL means sell-side liquidity and sits BELOW old lows. The short form H and L can be chosen instead under Level naming.")
lvlNaming = input.string("Buy-side / Sell-side", "Level naming", options = ["Buy-side / Sell-side", "High / Low"], group = g7, tooltip = "How the levels are named on the chart.\n\nBuy-side / Sell-side: the established terms. Liquidity resting above highs is buy-side liquidity, because it is the buy orders of everyone who is short plus the stops above. Below lows it is sell-side liquidity. '15m BSL2' is therefore the second-nearest untaken buy-side pool of the 15-minute chart.\n\nHigh / Low: the shorter form, '15m H2' and '15m L2'. Compact, but an H alone reads as 'high' and does not say that liquidity is sitting there.\n\nPDH and PDL keep their names either way, they are the standard abbreviations for yesterday's high and low.")
nLvl = input.int(3, "Levels per direction and TF (1-10)", minval = 1, maxval = 10, group = g7, tooltip = "How many levels above and below price are kept per timeframe. This is the number in the label: BSL1 is the nearest untaken pool above price, BSL2 the next one behind it, and so on up to 10. SSL1 upwards is the same downwards.\n\nThe rank goes by distance from price, not by age, so a level can move up from BSL2 to BSL1 once the one in front of it is cleared.\n\nOnly levels price has not closed beyond are listed - a level the timeframe has closed through is dropped, because the orders resting there have been filled.\n\nMind the multiplication: with five sources enabled, 10 per direction can mean a hundred lines. Start at 3 and raise it while the chart stays readable.")
sweepLB = input.int(10, "Sweep validity (chart bars)", minval = 1, group = g7, tooltip = "A sweep is price running through a level and closing back on the side it came from - a stop hunt rather than a real break.\n\nThis setting is how long a sweep counts as RECENT for the entry condition: with 10, price may have pierced the level up to ten candles ago and the sweep still counts towards a signal. A stop hunt from two hours ago says nothing about the current candle.\n\nIt does not affect the display. Once a level has been swept it keeps the word 'swept' in its label for as long as the level exists, because the orders resting there have been taken and that does not undo itself when price walks away again.")
liqPrice = input.string("Swept only", "Price in the label", options = ["Off", "Swept only", "All levels"], group = g7, tooltip = "Adds the price of the level behind its name.\n\nSwept only: just the levels that have already been swept. Those are the ones you tend to look up afterwards - where exactly was the stop hunt - while the untested levels stay short and readable.\n\nAll levels: every line carries its price. Useful when you are working the numbers, but it makes the labels noticeably wider, so they will step aside from each other more often.\n\nOff: names only.")
liqLblGap = input.float(0.3, "Min. label spacing (x ATR)", minval = 0.0, maxval = 3.0, step = 0.1, group = g7, tooltip = "Two levels can sit so close together that their names would be printed on top of each other. When the vertical gap between them is smaller than this, the second name is moved to the left along its own line instead, so both stay readable.\n\nMeasured in ATR so it scales with the instrument. Raise it if names still collide, lower it if they are pushed apart too eagerly.")
showLiq = input.bool(true, "Draw liquidity levels", group = g7, tooltip = "Draws the levels as horizontal lines, each labelled with source, direction and rank - for example '1H SSL1' for the nearest untaken sell-side pool of the 1-hour chart, or 'PDH' for yesterday's high.\n\nEach line starts at the candle whose high or low created the level and runs to the current candle, so you see where it came from and how long it has been holding.")
sweptShow = input.bool(true, "Show swept levels", group = g7, inline = "lqsw1", tooltip = "What happens to a level after price has swept it - each part is set on its own, so any combination is possible.\n\nShow: the swept level stays on the chart. Off hides it entirely.\n\nColour: Dimmed uses the muted colour next to it, Side colour keeps the pink or turquoise of its side. Dimmed together with a dotted style is the quiet variant - still there, no longer competing for attention.")
sweptCol = input.string("Side colour", "Colour", options = ["Side colour", "Dimmed"], group = g7, inline = "lqsw1", tooltip = "What happens to a level after price has swept it - each part is set on its own, so any combination is possible.\n\nShow: the swept level stays on the chart. Off hides it entirely.\n\nColour: Dimmed uses the muted colour next to it, Side colour keeps the pink or turquoise of its side. Dimmed together with a dotted style is the quiet variant - still there, no longer competing for attention.")
sweptEnd = input.string("Stop at the sweep", "Line ends", options = ["Stop at the sweep", "Extend to now"], group = g7, tooltip = "Where the line of a swept level stops.\n\nStop at the sweep: the line ends on the candle that took the level. It documents what happened without running on through the rest of the chart.\n\nExtend to now: the line keeps running to the current candle like an untaken level.")
liqColHigh = input.color(#EF5350, "High", group = g7, inline = "lq1", tooltip = "Colours of the liquidity levels.\n\nThis row: an untested pool ABOVE price, an untested pool BELOW price, and the colour a level takes once it has been swept.\n\nAbove price the pool is buy-side liquidity, labelled BSL: the buy orders of everyone who is short, plus the stops above old highs. Below price it is sell-side liquidity, labelled SSL. Under Level naming you can switch to the short form H and L instead.\n\nPine only accepts whole pixels for line thickness, so if the untested lines are still too heavy, reduce them through the transparency slider in these colour pickers rather than the width.")
liqColLow = input.color(#26A69A, "Low", group = g7, inline = "lq1", tooltip = "Colours of the liquidity levels.\n\nThis row: an untested pool ABOVE price, an untested pool BELOW price, and the colour a level takes once it has been swept.\n\nAbove price the pool is buy-side liquidity, labelled BSL: the buy orders of everyone who is short, plus the stops above old highs. Below price it is sell-side liquidity, labelled SSL. Under Level naming you can switch to the short form H and L instead.\n\nPine only accepts whole pixels for line thickness, so if the untested lines are still too heavy, reduce them through the transparency slider in these colour pickers rather than the width.")
liqColSwept = input.color(color.new(color.gray, 35), "Swept", group = g7, inline = "lq1", tooltip = "Colours of the liquidity levels.\n\nThis row: an untested pool ABOVE price, an untested pool BELOW price, and the colour a level takes once it has been swept.\n\nAbove price the pool is buy-side liquidity, labelled BSL: the buy orders of everyone who is short, plus the stops above old highs. Below price it is sell-side liquidity, labelled SSL. Under Level naming you can switch to the short form H and L instead.\n\nPine only accepts whole pixels for line thickness, so if the untested lines are still too heavy, reduce them through the transparency slider in these colour pickers rather than the width.")
liqStyleOpen= input.string("Solid", "Style untested", options = ["Solid", "Dashed", "Dotted"], group = g7, inline = "lq2", tooltip = "Line style of a level that has not been swept yet. Solid stands out most, dotted stays quiet.\n\nThe style of a swept level is set separately below, so the two states can be told apart at a glance.")
liqStyleSw = input.string("Dotted", "Style swept", options = ["Solid", "Dashed", "Dotted"], group = g7, inline = "lqsw2", tooltip = "Appearance of a swept level.\n\nThis row: line style and line thickness. Dotted at one pixel with the dimmed colour is the most discreet combination; solid and thicker turns it into a marker you cannot miss.")
sweptWidth = input.int(1, "Width swept", minval = 1, maxval = 5, group = g7, inline = "lqsw2", tooltip = "Appearance of a swept level.\n\nThis row: line style and line thickness. Dotted at one pixel with the dimmed colour is the most discreet combination; solid and thicker turns it into a marker you cannot miss.")
liqWidth = input.int(1, "Width", minval = 1, maxval = 5, group = g7, inline = "lq3", tooltip = "Size of the liquidity display.\n\nThis row: line thickness in whole pixels - Pine has no half steps - and the font size of the level names.")
liqTextSize = input.string("Normal", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = g7, inline = "lq3", tooltip = "Size of the liquidity display.\n\nThis row: line thickness in whole pixels - Pine has no half steps - and the font size of the level names.")
g8 = "8 · Market Structure (display only)"
msOn = input.bool(true, "Show market structure", group = g8, tooltip = "Master switch for the structure display. Each break is drawn as a horizontal line at the swing level that was broken, starting at the candle that formed it, with the text at the far end.\n\nThis is information only: it never triggers or blocks a signal.\n\nOnly timeframes equal to or higher than the chart are drawn. A smaller one would produce several breaks inside a single chart candle and they would stack into an unreadable pile.")
msInternal= input.bool(false, "Show internal structure", group = g8, tooltip = "Draws the breaks of the SHORT-term structure as well, using the internal lookback from the swing engine. Dashed by convention, so the fast rhythm inside the larger moves stays distinguishable.\n\nOff by default: on a choppy chart it roughly doubles the number of labels and they start overlapping. Switch it on when you are zoomed into a single move.")
ms1On = input.bool(false, "Entry TF", group = g8, inline = "tf1", tooltip = "Structure breaks of the entry timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.\n\nOnly drawn while this timeframe is equal to or higher than the chart timeframe.")
ms1ColB = input.color(#80CBC4, "", group = g8, inline = "tf1", tooltip = "Structure breaks of the entry timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.\n\nOnly drawn while this timeframe is equal to or higher than the chart timeframe.")
ms1ColS = input.color(#EF9A9A, "", group = g8, inline = "tf1", tooltip = "Structure breaks of the entry timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.\n\nOnly drawn while this timeframe is equal to or higher than the chart timeframe.")
ms5On = input.bool(true, "Chart TF", group = g8, inline = "tf5", tooltip = "Structure breaks of the chart timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms5ColB = input.color(#26A69A, "", group = g8, inline = "tf5", tooltip = "Structure breaks of the chart timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms5ColS = input.color(#EF5350, "", group = g8, inline = "tf5", tooltip = "Structure breaks of the chart timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms15On = input.bool(false, "15m", group = g8, inline = "tf15", tooltip = "Structure breaks of the 15-minute timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.\n\nOnly drawn while this timeframe is equal to or higher than the chart timeframe.")
ms15ColB = input.color(#00BFA5, "", group = g8, inline = "tf15", tooltip = "Structure breaks of the 15-minute timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.\n\nOnly drawn while this timeframe is equal to or higher than the chart timeframe.")
ms15ColS = input.color(#E53935, "", group = g8, inline = "tf15", tooltip = "Structure breaks of the 15-minute timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.\n\nOnly drawn while this timeframe is equal to or higher than the chart timeframe.")
ms60On = input.bool(true, "1H", group = g8, inline = "tf60", tooltip = "Structure breaks of the 1-hour timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms60ColB = input.color(#00E676, "", group = g8, inline = "tf60", tooltip = "Structure breaks of the 1-hour timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms60ColS = input.color(#FF1744, "", group = g8, inline = "tf60", tooltip = "Structure breaks of the 1-hour timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms240On = input.bool(true, "4H", group = g8, inline = "tf240", tooltip = "Structure breaks of the 4-hour timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms240ColB = input.color(#00C853, "", group = g8, inline = "tf240", tooltip = "Structure breaks of the 4-hour timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
ms240ColS = input.color(#D50000, "", group = g8, inline = "tf240", tooltip = "Structure breaks of the 4-hour timeframe.\n\nThis row: the checkbox switches them on, then the colour of a bullish and of a bearish break.")
msShowIdle= input.bool(false, "Show structure while still neutral", group = g8, tooltip = "ON: a break appears immediately in the neutral colour and switches to its timeframe colour once it supports an active setup.\n\nOFF: nothing is drawn while a break is still neutral; it only becomes visible when a setup in the same direction appears.")
msColIdle = input.color(color.gray, "Colour while not relevant", group = g8, tooltip = "Every structure break starts in this colour and only takes its timeframe colour once it supports the direction of an active setup.")
msLblMode = input.string("MSB + type", "Label text", options = ["MSB only", "BOS / CHOCH", "MSB + type"], group = g8, tooltip = "What the text next to each structure line says.\n\nMSB stands for Market Structure Break and is the umbrella term: price closed beyond the last confirmed swing point.\n\nBOS, Break of Structure, means the break continued the direction that was already in place - a trend confirming itself.\n\nCHOCH, Change of Character, means it went the other way and is the first hint that control may be changing hands.\n\nMSB only: everything is labelled MSB.\nBOS / CHOCH: only the type.\nMSB + type: both, for example 'MSB CHOCH'.\n\nThe timeframe is always appended, so you can tell a 1H break from a 5m one at a glance.")
msWidth = input.int(1, "Width", minval = 1, maxval = 5, group = g8, inline = "ms2", tooltip = "Appearance of the structure lines.\n\nThis row: line thickness, line style of the main structure, and font size of the text. The text sits on the chart background without a label box.")
msStyle = input.string("Solid", "Style", options = ["Solid", "Dashed", "Dotted"], group = g8, inline = "ms2", tooltip = "Appearance of the structure lines.\n\nThis row: line thickness, line style of the main structure, and font size of the text. The text sits on the chart background without a label box.")
msTextSize= input.string("Normal", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = g8, inline = "ms2", tooltip = "Appearance of the structure lines.\n\nThis row: line thickness, line style of the main structure, and font size of the text. The text sits on the chart background without a label box.")
msExtend = input.int(5, "Extend line (bars)", minval = 0, maxval = 100, group = g8, tooltip = "How many candles the structure line runs on past the candle that caused the break. The text sits at that end.\n\nLonger means the line stays visible while price moves on, but it also reaches further into recent candles.")
msMax = input.int(60, "Max. structure drawings", minval = 5, maxval = 250, group = g8, tooltip = "How many structure lines stay on the chart at once. When the limit is reached, the oldest one is removed.\n\nLower values keep the chart clean, higher ones let you scroll back through the history of breaks.")
msPending = input.int(20, "Remove unused structure after (bars)", minval = 0, maxval = 500, group = g8, tooltip = "A break that never became relevant to a setup is deleted after this many candles, because price has moved past it and it can no longer matter.\n\n0 keeps everything, including breaks that were never used - the chart fills up accordingly.")
swDegree = input.string("Internal", "Label degree", options = ["Internal", "Swing"], group = g8, tooltip = "Which of the two degrees the HH/HL/LH/LL labels are taken from.\n\nInternal: the short lookback from group 5, 2 by default. Every turning point that stands out against the one candle either side of it gets a label, so you see the fine zigzag inside the larger move.\n\nSwing: the long lookback, 10 by default. Only the turning points that shape the bigger picture are labelled, the same ones the main structure lines are built on.\n\nThe structure lines are unaffected either way - this only changes which swings carry a text. Reading a chart in two degrees of movement is the point of having both.")
swOn = input.bool(true, "Label swings (HH/HL/LH/LL)", group = g8, tooltip = "Marks the confirmed swing points of the chart timeframe.\n\nHH, Higher High: a high above the previous high.\nHL, Higher Low: a low above the previous low. HH together with HL is a rising structure.\nLH, Lower High and LL, Lower Low: the mirror image, a falling structure.\n\nEach point is compared with the previous point of the same kind, so a high is measured against the last high and a low against the last low. Rising structure takes the up colour, falling structure the down colour.\n\nHighs and lows strictly alternate. A second high before the next low does not become its own point - it replaces the current one if it is more extreme, otherwise it is dropped. That is why not every visible turning point carries a label; which ones do depends on the degree set above.")
swColUp = input.color(color.lime, "Higher", group = g8, inline = "sw1", tooltip = "Colours of the swing labels.\n\nThis row: Higher High and Higher Low, then Lower High and Lower Low. The colour follows the structure itself.")
swColDn = input.color(color.red, "Lower", group = g8, inline = "sw1", tooltip = "Colours of the swing labels.\n\nThis row: Higher High and Higher Low, then Lower High and Lower Low. The colour follows the structure itself.")
swTextSize= input.string("Normal", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = g8, inline = "sw2", tooltip = "Size and amount of the swing labels.\n\nThis row: font size of the HH/HL/LH/LL text, and how many of these labels stay on the chart before the oldest are removed.")
maxSwLbl = input.int(40, "Max. swing labels", minval = 5, maxval = 200, group = g8, inline = "sw2", tooltip = "Size and amount of the swing labels.\n\nThis row: font size of the HH/HL/LH/LL text, and how many of these labels stay on the chart before the oldest are removed.")
g9 = "9 · Sessions"
useLDN = input.bool(true, "London", group = g9, inline = "s1", tooltip = "London session.\n\nThis row: the checkbox allows signals inside the window, the field defines it in Europe/London local time. The default is the real exchange session, 08:00 to 16:30, with the day mask 23456 limiting it to Monday through Friday.\n\nThat is a long stretch to trade. Rather than shortening it here, use Max. trading hours below - it cuts every session down to its opening hours at once.")
sLDN = input.session("0800-1630:23456", "", group = g9, inline = "s1", tooltip = "London session.\n\nThis row: the checkbox allows signals inside the window, the field defines it in Europe/London local time. The default is the real exchange session, 08:00 to 16:30, with the day mask 23456 limiting it to Monday through Friday.\n\nThat is a long stretch to trade. Rather than shortening it here, use Max. trading hours below - it cuts every session down to its opening hours at once.")
useNY = input.bool(true, "New York", group = g9, inline = "s2", tooltip = "New York session.\n\nThis row: the checkbox allows signals inside the window, the field defines it in America/New_York local time. The default is the real exchange session, 09:30 to 16:00, with the day mask 23456 limiting it to Monday through Friday.\n\nThat is a long stretch to trade. Rather than shortening it here, use Max. trading hours below - it cuts every session down to its opening hours at once.")
sNY = input.session("0930-1600:23456", "", group = g9, inline = "s2", tooltip = "New York session.\n\nThis row: the checkbox allows signals inside the window, the field defines it in America/New_York local time. The default is the real exchange session, 09:30 to 16:00, with the day mask 23456 limiting it to Monday through Friday.\n\nThat is a long stretch to trade. Rather than shortening it here, use Max. trading hours below - it cuts every session down to its opening hours at once.")
useAsia= input.bool(false, "Tokyo", group = g9, inline = "s3", tooltip = "Tokyo session.\n\nThis row: the checkbox allows signals inside the window, the field defines it in Asia/Tokyo local time. The default is the real exchange session, 09:00 to 15:00, with the day mask 23456 limiting it to Monday through Friday.\n\nThat is a long stretch to trade. Rather than shortening it here, use Max. trading hours below - it cuts every session down to its opening hours at once.")
sAsia = input.session("0900-1500:23456", "", group = g9, inline = "s3", tooltip = "Tokyo session.\n\nThis row: the checkbox allows signals inside the window, the field defines it in Asia/Tokyo local time. The default is the real exchange session, 09:00 to 15:00, with the day mask 23456 limiting it to Monday through Friday.\n\nThat is a long stretch to trade. Rather than shortening it here, use Max. trading hours below - it cuts every session down to its opening hours at once.")
maxHoursOn= input.bool(false, "Max. trading hours", group = g9, inline = "mh", tooltip = "Cuts every enabled session down to its first hours instead of you editing each window by hand.\n\nThe session fields below now hold the real exchange hours, which run far longer than most people want to trade. With this on, only the opening stretch counts - the part with the volume and the moves, before the midday lull.\n\nThis row: the checkbox, and how many hours from each session start are allowed. 2 keeps roughly the first two hours after the open. Fractions work, 1.5 gives ninety minutes.\n\nIt applies to the signal filter and to the session boxes alike, so what you see is what is allowed.")
maxHours = input.float(2.0, "", minval = 0.25, maxval = 24.0, step = 0.25, group = g9, inline = "mh", tooltip = "Cuts every enabled session down to its first hours instead of you editing each window by hand.\n\nThe session fields below now hold the real exchange hours, which run far longer than most people want to trade. With this on, only the opening stretch counts - the part with the volume and the moves, before the midday lull.\n\nThis row: the checkbox, and how many hours from each session start are allowed. 2 keeps roughly the first two hours after the open. Fractions work, 1.5 gives ninety minutes.\n\nIt applies to the signal filter and to the session boxes alike, so what you see is what is allowed.")
sessBoxSpan= input.string("Tradeable window", "Boxes span", options = ["Tradeable window", "Full session"], group = g9, tooltip = "What the session boxes are drawn around.\n\nTradeable window: only the part that Max. trading hours leaves open. The frame then shows exactly where a signal may appear.\n\nFull session: the complete exchange hours from the fields above, regardless of the limiter. The frame becomes pure context - you see the whole session and its high and low, while signals are still restricted to the opening hours.\n\nThe signal filter itself is not affected by this setting, only the drawing.")
sessShow = input.bool(true, "Show sessions in chart", group = g9, tooltip = "Draws each enabled session as a box on the price chart, from its first candle to its last, sized to the high and low the session made.\n\nThat frame is worth having on its own: the high and low of a session are among the most watched levels of the day, and you can see at a glance whether the current move is still inside the range of its session or has already left it.")
sessColL = input.color(#2962FF, "London", group = g9, inline = "sb1", tooltip = "Colour of each session box.\n\nThis row: London, New York, Tokyo. The transparency of the fill and of the border is set separately below, so the same hue can be used quietly in the background and clearly on the frame.")
sessColN = input.color(#FF9800, "New York", group = g9, inline = "sb1", tooltip = "Colour of each session box.\n\nThis row: London, New York, Tokyo. The transparency of the fill and of the border is set separately below, so the same hue can be used quietly in the background and clearly on the frame.")
sessColA = input.color(#AB47BC, "Tokyo", group = g9, inline = "sb1", tooltip = "Colour of each session box.\n\nThis row: London, New York, Tokyo. The transparency of the fill and of the border is set separately below, so the same hue can be used quietly in the background and clearly on the frame.")
sessFillTr= input.int(93, "Fill transp.", minval = 0, maxval = 100, group = g9, inline = "sb2", tooltip = "How present the boxes are.\n\nThis row: transparency of the fill and transparency of the border, each from 0 for solid to 100 for invisible. The defaults keep both faint - the box is meant to sit behind the candles, not compete with them.")
sessLineTr= input.int(70, "Border transp.", minval = 0, maxval = 100, group = g9, inline = "sb2", tooltip = "How present the boxes are.\n\nThis row: transparency of the fill and transparency of the border, each from 0 for solid to 100 for invisible. The defaults keep both faint - the box is meant to sit behind the candles, not compete with them.")
sessBordW = input.int(1, "Border width", minval = 1, maxval = 5, group = g9, inline = "sb3", tooltip = "Appearance and amount of the boxes.\n\nThis row: thickness of the border in pixels, and how many past sessions stay on the chart per session. Older boxes are removed automatically.")
sessKeep = input.int(5, "Keep sessions", minval = 1, maxval = 20, group = g9, inline = "sb3", tooltip = "Appearance and amount of the boxes.\n\nThis row: thickness of the border in pixels, and how many past sessions stay on the chart per session. Older boxes are removed automatically.")
g10 = "10 · Timing"
setupExp = input.int(30, "Setup expiration (entry-TF bars)", minval = 1, group = g10, tooltip = "How long a setup stays valid while waiting for its signal. Converted into chart bars: 30 / 5 = 6 chart bars, and since the signal is only checked from the bar after the setup, 5 of them are usable.\n\nThe specification says 5, which is a single chart bar and expires before anything can be evaluated.")
cooldown = input.int(3, "Cooldown after a signal (entry-TF bars)", minval = 0, group = g10, tooltip = "Pause after a signal before the next one may be given, counted in candles of the entry timeframe.\n\nWithout it, a single move can produce several signals in a row, because the conditions often stay true for a few candles. 0 switches the pause off.")
g11 = "11 · Signal markers"
markerWhen = input.string("At candle close", "Markers appear", options = ["At candle close", "While the candle forms"], group = g11, tooltip = "When a marker is allowed to appear.\n\nAt candle close: the marker is drawn once the candle is finished, which is the only moment the condition can actually be judged - the setup needs a CLOSE back inside the band, and there is no close before the candle ends. This is also the moment the alert fires, so chart and alert agree.\n\nWhile the candle forms: the marker already appears as soon as the current price would satisfy the condition. That gives you up to a full candle of warning, but it is provisional - if price moves back to the band before the close, the marker disappears again and there was no signal. Nothing is faster this way, only earlier and less certain.\n\nOn historical candles both settings look identical. The difference only exists on the candle that is still running.")
showSetup = input.bool(true, "Draw setup markers", group = g11, inline = "st1", tooltip = "Circles marking every candle where a setup was armed, even if no signal followed.\n\nThis row: the checkbox switches them on, then the colour of the long marker below the candle and of the short marker above it.")
setupColL = input.color(color.new(color.green, 40), "", group = g11, inline = "st1", tooltip = "Circles marking every candle where a setup was armed, even if no signal followed.\n\nThis row: the checkbox switches them on, then the colour of the long marker below the candle and of the short marker above it.")
setupColS = input.color(color.new(color.red, 40), "", group = g11, inline = "st1", tooltip = "Circles marking every candle where a setup was armed, even if no signal followed.\n\nThis row: the checkbox switches them on, then the colour of the long marker below the candle and of the short marker above it.")
showSniper = input.bool(true, "Draw signal markers", group = g11, inline = "sn1", tooltip = "The dot that appears once every enabled condition is met. It sits below the candle for a long context and above it for a short one, and it is drawn slightly larger than the setup dot.\n\nDeliberately a dot and not the word LONG or SHORT: a written instruction invites an immediate market order, while price may well keep running the other way first. The dot says a condition is complete, not that you should press the button.\n\nThis row: the checkbox switches the dots on, then the colour of each.")
sniperColL = input.color(color.lime, "", group = g11, inline = "sn1", tooltip = "The dot that appears once every enabled condition is met. It sits below the candle for a long context and above it for a short one, and it is drawn slightly larger than the setup dot.\n\nDeliberately a dot and not the word LONG or SHORT: a written instruction invites an immediate market order, while price may well keep running the other way first. The dot says a condition is complete, not that you should press the button.\n\nThis row: the checkbox switches the dots on, then the colour of each.")
sniperColS = input.color(color.red, "", group = g11, inline = "sn1", tooltip = "The dot that appears once every enabled condition is met. It sits below the candle for a long context and above it for a short one, and it is drawn slightly larger than the setup dot.\n\nDeliberately a dot and not the word LONG or SHORT: a written instruction invites an immediate market order, while price may well keep running the other way first. The dot says a condition is complete, not that you should press the button.\n\nThis row: the checkbox switches the dots on, then the colour of each.")
priceMode = input.string("Signals only", "Price next to the markers", options = ["Off", "Signals only", "Setups and signals"], group = g11, inline = "px1", tooltip = "Writes the price next to a marker: the close of the candle on which the conditions were complete. That is the level the marker refers to, and it saves reading it off the axis afterwards.\n\nSignals only: just the larger dots. This is the default, because setups appear far more often and a price on every one of them fills the chart quickly.\n\nSetups and signals: every dot gets its price.\n\nOff: no prices at all.\n\nThe number is the close of that candle, not a suggested entry - price can and often does move on before you act.")
priceSize = input.string("Small", "Size", options = ["Tiny", "Small", "Normal", "Large"], group = g11, inline = "px1", tooltip = "Writes the price next to a marker: the close of the candle on which the conditions were complete. That is the level the marker refers to, and it saves reading it off the axis afterwards.\n\nSignals only: just the larger dots. This is the default, because setups appear far more often and a price on every one of them fills the chart quickly.\n\nSetups and signals: every dot gets its price.\n\nOff: no prices at all.\n\nThe number is the close of that candle, not a suggested entry - price can and often does move on before you act.")
lblGap = input.bool(true, "Keep text clear of the markers", group = g11, tooltip = "When a candle carries a marker, any text on that same candle is lifted above or below it instead of overlapping. Several texts stack in a fixed order: marker, signal text, swing label.")
lblGapAtr = input.float(0.4, "Spacing (x ATR)", minval = 0.1, maxval = 3.0, step = 0.1, group = g11, tooltip = "Size of the gap between a marker and the text next to it, measured in ATR so it scales with the instrument and with volatility.\n\nRaise it if text still sits on top of a marker, lower it if the text drifts too far from the candle.")
g12 = "12 · Status Table"
tblMode = input.string("Compact", "Detail", options = ["Compact", "Full"], group = g12, tooltip = "How much the table shows.\n\nCompact: five rows. Bias, setup including its band rejection, entry structure together with the liquidity requirement, session with the current Stoch RSI reading, and the signal state. This is the default because the table lives in the oscillator pane, and a pane at its usual height cuts a nine-row table off at the top.\n\nFull: every condition on its own row, and the chart timeframe check as well. Use it while you are learning which condition blocks a signal - and drag the divider between the panes upwards, otherwise the first rows are cut off. Pine cannot set the pane height itself.")
showTable = input.bool(true, "Show status table", group = g12, tooltip = "A small table with the current state of every condition, so you can see at a glance what is still missing for a signal.\n\nIt appears in this lower pane, not on the price chart - TradingView ties a table to the pane of its script.")
tblPos = input.string("Bottom Right", "Position", options = ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left"], group = g12, inline = "tb1", tooltip = "Placement of the table.\n\nThis row: which corner it sits in, and the font size inside it.\n\nThe table belongs to the pane the script runs in, so it appears in the lower pane next to the oscillator, not on the price chart - TradingView offers no way to move a table across panes. On the right it sits clear of the level names along the left edge. If it crowds the oscillator, drag the divider between the two panes.")
tblSize = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = g12, inline = "tb1", tooltip = "Placement of the table.\n\nThis row: which corner it sits in, and the font size inside it.\n\nThe table belongs to the pane the script runs in, so it appears in the lower pane next to the oscillator, not on the price chart - TradingView offers no way to move a table across panes. On the right it sits clear of the level names along the left edge. If it crowds the oscillator, drag the divider between the two panes.")
tblBg = input.color(color.new(color.black, 80), "Background", group = g12, inline = "tb2", tooltip = "Basic colours of the table.\n\nThis row: background colour and transparency of the cells, and the colour of the left column.")
tblLabel = input.color(color.silver, "Labels", group = g12, inline = "tb2", tooltip = "Basic colours of the table.\n\nThis row: background colour and transparency of the cells, and the colour of the left column.")
tblColB = input.color(color.lime, "Bullish", group = g12, inline = "tb3", tooltip = "Colours for the values inside the table.\n\nThis row: anything currently bullish, anything currently bearish, and conditions switched off or not met yet.")
tblColS = input.color(color.red, "Bearish", group = g12, inline = "tb3", tooltip = "Colours for the values inside the table.\n\nThis row: anything currently bullish, anything currently bearish, and conditions switched off or not met yet.")
tblColIdle= input.color(color.gray, "Neutral", group = g12, inline = "tb3", tooltip = "Colours for the values inside the table.\n\nThis row: anything currently bullish, anything currently bearish, and conditions switched off or not met yet.")
g13 = "13 · Oscillator Pane"
oscK = input.bool(true, "K line", group = g13, inline = "os1", tooltip = "The two Stoch RSI lines, drawn with the settings from group 4.\n\nThis row: K is the fast line the setup logic actually works on, D is its smoothing. Their colours follow.")
oscColK = input.color(#2962FF, "", group = g13, inline = "os1", tooltip = "The two Stoch RSI lines, drawn with the settings from group 4.\n\nThis row: K is the fast line the setup logic actually works on, D is its smoothing. Their colours follow.")
oscD = input.bool(true, "D line", group = g13, inline = "os1", tooltip = "The two Stoch RSI lines, drawn with the settings from group 4.\n\nThis row: K is the fast line the setup logic actually works on, D is its smoothing. Their colours follow.")
oscColD = input.color(#FF6D00, "", group = g13, inline = "os1", tooltip = "The two Stoch RSI lines, drawn with the settings from group 4.\n\nThis row: K is the fast line the setup logic actually works on, D is its smoothing. Their colours follow.")
oscFill = input.bool(true, "Fill between K and D", group = g13, inline = "os2", tooltip = "Shades the area between the two lines: one colour while K is above D, the other while it is below.\n\nThat is the momentum direction at a glance - the same idea the well-known all-in-one oscillators use for their stochastic section, but built from the lines we already calculate rather than from an extra formula.\n\nThis row: the checkbox, then the colour for K above D and for K below D.")
oscFillUp = input.color(color.new(#26A69A, 65), "", group = g13, inline = "os2", tooltip = "Shades the area between the two lines: one colour while K is above D, the other while it is below.\n\nThat is the momentum direction at a glance - the same idea the well-known all-in-one oscillators use for their stochastic section, but built from the lines we already calculate rather than from an extra formula.\n\nThis row: the checkbox, then the colour for K above D and for K below D.")
oscFillDn = input.color(color.new(#EF5350, 65), "", group = g13, inline = "os2", tooltip = "Shades the area between the two lines: one colour while K is above D, the other while it is below.\n\nThat is the momentum direction at a glance - the same idea the well-known all-in-one oscillators use for their stochastic section, but built from the lines we already calculate rather than from an extra formula.\n\nThis row: the checkbox, then the colour for K above D and for K below D.")
oscLines = input.bool(true, "Show levels", group = g13, tooltip = "Draws your oversold and overbought levels from group 4 as horizontal lines, plus the 50 line in the middle.\n\nUseful for judging whether the thresholds fit the instrument: if the oscillator barely ever reaches them, they are too extreme for this market.")
oscDots = input.bool(true, "Extreme dots", group = g13, inline = "os3", tooltip = "A dot at the top of the pane while K is at or above the overbought level, and one at the bottom while it is at or below the oversold level.\n\nThese mark the condition itself, not a signal. A setup additionally needs the band touch and the rejection candle.\n\nThis row: the checkbox, then the colour of the overbought and of the oversold dot.")
oscDotOb = input.color(color.red, "", group = g13, inline = "os3", tooltip = "A dot at the top of the pane while K is at or above the overbought level, and one at the bottom while it is at or below the oversold level.\n\nThese mark the condition itself, not a signal. A setup additionally needs the band touch and the rejection candle.\n\nThis row: the checkbox, then the colour of the overbought and of the oversold dot.")
oscDotOs = input.color(color.lime, "", group = g13, inline = "os3", tooltip = "A dot at the top of the pane while K is at or above the overbought level, and one at the bottom while it is at or below the oversold level.\n\nThese mark the condition itself, not a signal. A setup additionally needs the band touch and the rejection candle.\n\nThis row: the checkbox, then the colour of the overbought and of the oversold dot.")
oscBias = input.bool(true, "Bias as background", group = g13, inline = "os4", tooltip = "Tints the whole pane with the bias, using the source chosen in group 2.\n\nThis answers the same question a money-flow background answers in the all-in-one oscillators - who is in control of the bigger picture - but from data we already have rather than from volume, which is unreliable on CFD and forex feeds anyway.\n\nThe third colour marks the state where structure and average disagree: the structure has already turned while price is still on the wrong side of the average. With Strict Bias on, that is when the old direction stops producing signals.\n\nThis row: the checkbox, then the bullish tint, the bearish tint and the tint while they disagree.")
oscBiasUp = input.color(color.new(#26A69A, 65), "", group = g13, inline = "os4", tooltip = "Tints the whole pane with the bias, using the source chosen in group 2.\n\nThis answers the same question a money-flow background answers in the all-in-one oscillators - who is in control of the bigger picture - but from data we already have rather than from volume, which is unreliable on CFD and forex feeds anyway.\n\nThe third colour marks the state where structure and average disagree: the structure has already turned while price is still on the wrong side of the average. With Strict Bias on, that is when the old direction stops producing signals.\n\nThis row: the checkbox, then the bullish tint, the bearish tint and the tint while they disagree.")
oscBiasTr = input.color(color.new(#FFA726, 65), "", group = g13, inline = "os4", tooltip = "Tints the whole pane with the bias, using the source chosen in group 2.\n\nThis answers the same question a money-flow background answers in the all-in-one oscillators - who is in control of the bigger picture - but from data we already have rather than from volume, which is unreliable on CFD and forex feeds anyway.\n\nThe third colour marks the state where structure and average disagree: the structure has already turned while price is still on the wrong side of the average. With Strict Bias on, that is when the old direction stops producing signals.\n\nThis row: the checkbox, then the bullish tint, the bearish tint and the tint while they disagree.")
oscBiasDn = input.color(color.new(#EF5350, 65), "", group = g13, inline = "os4", tooltip = "Tints the whole pane with the bias, using the source chosen in group 2.\n\nThis answers the same question a money-flow background answers in the all-in-one oscillators - who is in control of the bigger picture - but from data we already have rather than from volume, which is unreliable on CFD and forex feeds anyway.\n\nThe third colour marks the state where structure and average disagree: the structure has already turned while price is still on the wrong side of the average. With Strict Bias on, that is when the old direction stops producing signals.\n\nThis row: the checkbox, then the bullish tint, the bearish tint and the tint while they disagree.")
oscSignal = input.bool(true, "Repeat signal markers here", group = g13, tooltip = "Repeats the signal marker from the price chart inside this pane, drawn on the K line at the moment every enabled condition is met.\n\nWhile you are trading you often watch the oscillator rather than the candles, and a signal that only appears up on the chart is easy to miss. It is deliberately larger than the extreme dots at the edges - those mark a condition, this one marks a complete signal.")
oscStrip = input.bool(true, "Setup strip at the bottom", group = g13, tooltip = "A coloured strip along the bottom edge of the pane for as long as a setup is armed and waiting for its entry, green for long and red for short.\n\nIt starts on the same candle as the small dot on the chart, so the beginning tells you nothing new. The value is in the length and the end: the strip is the countdown of the setup.\n\nEnds together with a large dot - the setup converted into a signal. Ends without one - it expired unused, and the conditions have to build up again from scratch. Runs unusually long - price keeps rejecting at the band and re-arming the setup.")
// =============================================================================
// 2 · HELPERS
// =============================================================================
f_size(string s) => s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Normal" ? size.normal : size.large
f_lstyle(string s) => s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
// 15 -> 15m, 60 -> 1H, 240 -> 4H
f_tfLabel(string tf) =>
float v = str.tonumber(tf)
string r = tf
if not na(v)
if v >= 1440
r := str.tostring(v / 1440, "#.##") + "D"
else if v >= 60
r := str.tostring(v / 60, "#.##") + "H"
else
r := str.tostring(v, "#") + "m"
r
biasLbl = f_tfLabel(biasTF)
entryLbl = f_tfLabel(entryTF)
setupLbl = f_tfLabel(setupTF)
chartSec = timeframe.in_seconds(timeframe.period)
chartMin = math.max(1.0, chartSec / 60.0)
expBars = math.max(1, int(math.ceil(setupExp / chartMin)))
cdBars = int(math.ceil(cooldown / chartMin))
tfMatch = timeframe.period == setupTF
// =============================================================================
// 3 · SWING ENGINE
// -----------------------------------------------------------------------------
// One implementation for everything structural, using the classical definition of
// a turning point:
// * symmetric pivot: the extreme of a window of "len" candles on either side,
// so the point is a local extreme in the literal sense - confirmed and never
// repainted, at the cost of a delay of "len" candles
// * strict alternation of highs and lows; a same-kind pivot before the opposite
// one only replaces the current point if it is more extreme
// * backstep: a minimum number of candles between two accepted points
// * deviation: an optional minimum leg size, off by default, since no derived
// value exists for it and any figure here would be arbitrary
// Emits, per bar, whether a point was created or updated and everything needed to
// classify and draw it.
// =============================================================================
f_swings(simple int len, simple string devMode, simple float devVal, simple int backstep, simple int atrLen) =>
float ph = ta.pivothigh(high, len, len)
float pl = ta.pivotlow(low, len, len)
float atr = ta.atr(atrLen)
var int zt = 0 // 1 = last accepted point is a high, -1 = a low
var float zp = na // its price
var int zb = na // its bar index
var float pHi = na // previous high, reference for HH / LH
var float pLo = na
var float cHi = na // current high of the zigzag
var float cLo = na
bool evt = false
bool isHi = false
bool repl = false
float px = na
int tm = na
float ref = na
float minMove = devMode == "ATR" ? devVal * atr : devMode == "Percent" ? close * devVal / 100.0 : 0.0
int pbar = bar_index - len
if not na(ph)
if zt == 1
if ph > zp
zp := ph
zb := pbar
cHi := ph
evt := true
isHi := true
repl := true
px := ph
tm := time[len]
ref := pHi
else if zt == 0 or (ph - zp >= minMove and pbar - nz(zb, pbar) >= backstep)
zt := 1
zp := ph
zb := pbar
pHi := cHi
cHi := ph
evt := true
isHi := true
px := ph
tm := time[len]
ref := pHi
if not na(pl)
if zt == -1
if pl < zp
zp := pl
zb := pbar
cLo := pl
evt := true
repl := true
px := pl
tm := time[len]
ref := pLo
else if zt == 0 or (zp - pl >= minMove and pbar - nz(zb, pbar) >= backstep)
zt := -1
zp := pl
zb := pbar
pLo := cLo
cLo := pl
evt := true
px := pl
tm := time[len]
ref := pLo
[evt, isHi, px, tm, repl, ref]
// Market structure on top of the swing engine. A break is a CLOSE beyond the last
// accepted swing point. With the prevailing direction it is a BOS, against it a
// CHOCH; both are market structure breaks. The level is consumed so one swing
// cannot fire twice.
f_structure(simple int len, simple string devMode, simple float devVal, simple int backstep, simple int atrLen) =>
[evt, isHi, px, tm, repl, ref] = f_swings(len, devMode, devVal, backstep, atrLen)
var float lastHi = na
var int lastHiT = na
var float lastLo = na
var int lastLoT = na
var int tr = 0
bool bos = false
bool choch = false
int dir = 0
float lvl = na
int lvlT = na
if evt
if isHi
lastHi := px
lastHiT := tm
else
lastLo := px
lastLoT := tm
if not na(lastHi) and close > lastHi
lvl := lastHi
lvlT := lastHiT
dir := 1
if tr >= 0
bos := true
else
choch := true
tr := 1
lastHi := na
else if not na(lastLo) and close < lastLo
lvl := lastLo
lvlT := lastLoT
dir := -1
if tr <= 0
bos := true
else
choch := true
tr := -1
lastLo := na
[bos, choch, dir, lvl, lvlT, tr]
// Liquidity levels: swing points of the long degree that price has not closed
// beyond, nearest first, together with the candle each of them was made on.
//
// The result is bundled in a user-defined type on purpose. All request.*() calls
// of a script together may return at most 127 tuple elements; ten levels per
// direction with their timestamps would be forty elements per timeframe and blow
// that budget instantly. An object counts as one element no matter how much it
// carries.
type LiqSet
array<float> hi
array<int> hiT
array<float> lo
array<int> loT
f_liquidity(simple int len, simple string devMode, simple float devVal, simple int backstep, simple int atrLen) =>
[evt, isHi, px, tm, repl, ref] = f_swings(len, devMode, devVal, backstep, atrLen)
var array<float> ah = array.new<float>()
var array<int> aht = array.new<int>()
var array<float> al = array.new<float>()
var array<int> alt = array.new<int>()
if evt
if isHi
if repl and array.size(ah) > 0
array.pop(ah)
array.pop(aht)
array.push(ah, px)
array.push(aht, tm)
else
if repl and array.size(al) > 0
array.pop(al)
array.pop(alt)
array.push(al, px)
array.push(alt, tm)
// levels price has closed beyond are taken and drop out
if array.size(ah) > 0
for i = array.size(ah) - 1 to 0
if close > array.get(ah, i)
array.remove(ah, i)
array.remove(aht, i)
if array.size(al) > 0
for i = array.size(al) - 1 to 0
if close < array.get(al, i)
array.remove(al, i)
array.remove(alt, i)
if array.size(ah) > 60
array.shift(ah)
array.shift(aht)
if array.size(al) > 60
array.shift(al)
array.shift(alt)
// nearest first: lowest surviving high above price, highest low below it
array<float> sh = array.copy(ah)
array<float> sl = array.copy(al)
array.sort(sh, order.ascending)
array.sort(sl, order.descending)
LiqSet r = LiqSet.new(array.new<float>(), array.new<int>(), array.new<float>(), array.new<int>())
int nh = math.min(array.size(sh), 10)
if nh > 0
for i = 0 to nh - 1
float v = array.get(sh, i)
int ix = array.indexof(ah, v)
array.push(r.hi, v)
array.push(r.hiT, ix >= 0 ? array.get(aht, ix) : na)
int nl = math.min(array.size(sl), 10)
if nl > 0
for i = 0 to nl - 1
float v2 = array.get(sl, i)
int iy = array.indexof(al, v2)
array.push(r.lo, v2)
array.push(r.loT, iy >= 0 ? array.get(alt, iy) : na)
r
// =============================================================================
// 4 · BASIC CALCULATIONS
// =============================================================================
biasClose = request.security(syminfo.tickerid, biasTF, close[1], lookahead = barmerge.lookahead_off)
biasEmaV = request.security(syminfo.tickerid, biasTF, ta.ema(close, emaLen)[1], lookahead = barmerge.lookahead_off)
emaBull = not na(biasEmaV) and biasClose > biasEmaV
emaBear = not na(biasEmaV) and biasClose < biasEmaV
// Trend state of the market structure on the bias timeframe. An average says
// where price stands relative to its own history; the structure says whether the
// sequence of highs and lows is still intact. The second is the actual definition
// of a trend and it turns at the CHOCH, long before price climbs back over the
// average. Frozen on the close of each bias candle so it cannot repaint.
[bosB, chB, dirB, lvlB, lvlTB, trBraw] = request.security(syminfo.tickerid, biasTF, f_structure(swMain, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
tBias = request.security(syminfo.tickerid, biasTF, time, lookahead = barmerge.lookahead_off)
newBiasBar = tBias != tBias[1]
var int trBias = 0
if newBiasBar
trBias := trBraw
strBull = trBias == 1
strBear = trBias == -1
// The third state: the structure has already turned while price is still on the
// wrong side of the average. Shown as its own state instead of being forced into
// one of the two colours.
bool biasBull = false
bool biasBear = false
bool biasTrans = false
if biasSrc == "EMA"
biasBull := emaBull
biasBear := emaBear
else if biasSrc == "Structure"
biasBull := strBull
biasBear := strBear
else
if (emaBull and strBear) or (emaBear and strBull)
biasTrans := true
else
biasBull := emaBull and not strBear
biasBear := emaBear and not strBull
transBull = biasTrans and strBull // the direction the structure has turned to
transBear = biasTrans and strBear
bbBasis = ta.sma(bbSrc, bbLen)
bbDevV = bbMult * ta.stdev(bbSrc, bbLen)
bbUpper = bbBasis + bbDevV
bbLower = bbBasis - bbDevV
rsiV = ta.rsi(close, rsiLen)
stoV = ta.stoch(rsiV, rsiV, rsiV, stoLen)
kV = ta.sma(stoV, kSm)
dV = ta.sma(kV, dSm)
stochWasOS = ta.lowest(kV, stochLB) <= osLvl
stochWasOB = ta.highest(kV, stochLB) >= obLvl
// The session fields hold the real exchange hours. The limiter below keeps only
// the first hours of each of them, which is the usual way to trade a session
// without having to rewrite every window by hand.
f_sessLimit(bool raw) =>
var int startT = na
if raw and not raw[1]
startT := time
bool ok = raw
if raw and maxHoursOn and not na(startT)
ok := time - startT <= int(maxHours * 3600000)
ok
rawLDN = useLDN and not na(time(timeframe.period, sLDN, "Europe/London"))
rawNY = useNY and not na(time(timeframe.period, sNY, "America/New_York"))
rawAsia = useAsia and not na(time(timeframe.period, sAsia, "Asia/Tokyo"))
inLDN = f_sessLimit(rawLDN)
inNY = f_sessLimit(rawNY)
inAsia = f_sessLimit(rawAsia)
anySess = useLDN or useNY or useAsia
inSession = anySess ? (inLDN or inNY or inAsia) : true
sessName = inLDN ? "London" : inNY ? "New York" : inAsia ? "Tokyo" : "-"
atrV = ta.atr(swAtrLen)
// =============================================================================
// 5 · HTF LIQUIDITY
// =============================================================================
// Previous day high and low, tracked on the chart timeframe so we also know the
// exact candle each of them was made on. Reading them from a daily request would
// only give the day's opening time, and the line would start hours too early.
newDay = time("D") != time("D")[1]
var float curDH = na
var float curDL = na
var int curDHt = na
var int curDLt = na
var float pdH = na
var float pdL = na
var int pdHt = na
var int pdLt = na
if newDay
pdH := curDH
pdL := curDL
pdHt := curDHt
pdLt := curDLt
curDH := high
curDL := low
curDHt := time
curDLt := time
else
if na(curDH) or high > curDH
curDH := high
curDHt := time
if na(curDL) or low < curDL
curDL := low
curDLt := time
// "Only main liquidities" keeps the configured window; "Also fine liquidities"
// drops to the finest pivot there is - a wick reaching past the one candle either
// side of it.
liqLenEff = liqDepth == "Also fine liquidities" ? 1 : liqLen
LiqSet lq15 = request.security(syminfo.tickerid, "15", f_liquidity(liqLenEff, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
LiqSet lq30 = request.security(syminfo.tickerid, "30", f_liquidity(liqLenEff, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
LiqSet lq60 = request.security(syminfo.tickerid, "60", f_liquidity(liqLenEff, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
LiqSet lq240 = request.security(syminfo.tickerid, "240", f_liquidity(liqLenEff, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
LiqSet lqC = f_liquidity(liqLenEff, swDevMode, swDevVal, swBack, swAtrLen)
// A level from a higher timeframe carries the OPENING time of its own candle, not
// the moment the wick was made - on a 5m chart a 15m level would start up to ten
// minutes too far left. The rolling buffer below holds the recent chart candles
// so the exact one that produced the extreme can be looked up.
var array<float> hLow = array.new<float>()
var array<float> hHigh = array.new<float>()
var array<int> hTime = array.new<int>()
if barstate.isconfirmed
array.push(hLow, low)
array.push(hHigh, high)
array.push(hTime, time)
if array.size(hLow) > 500
array.shift(hLow)
array.shift(hHigh)
array.shift(hTime)
// First chart candle at or after the level's own timestamp whose wick matches it.
// Falls back to the original stamp if the level is older than the buffer.
f_exactLow(float lv, int fb) =>
int r = fb
if array.size(hLow) > 0 and not na(fb)
for i = 0 to array.size(hLow) - 1
if array.get(hTime, i) >= fb and math.abs(array.get(hLow, i) - lv) <= syminfo.mintick * 0.5
r := array.get(hTime, i)
break
r
f_exactHigh(float lv, int fb) =>
int r = fb
if array.size(hHigh) > 0 and not na(fb)
for i = 0 to array.size(hHigh) - 1
if array.get(hTime, i) >= fb and math.abs(array.get(hHigh, i) - lv) <= syminfo.mintick * 0.5
r := array.get(hTime, i)
break
r
lowestN = ta.lowest(low, sweepLB)
highestN = ta.highest(high, sweepLB)
f_sweptLow(float lv) => not na(lv) and lowestN < lv and close > lv
f_sweptHigh(float lv) => not na(lv) and highestN > lv and close < lv
highLv = array.new<float>()
highNm = array.new<string>()
highTm = array.new<int>()
lowLv = array.new<float>()
lowNm = array.new<string>()
lowTm = array.new<int>()
hTok = lvlNaming == "High / Low" ? " H" : " BSL"
lTok = lvlNaming == "High / Low" ? " L" : " SSL"
f_addLv(LiqSet L, string nm) =>
if not na(L)
int nh = math.min(nLvl, array.size(L.hi))
if nh > 0
for i = 0 to nh - 1
array.push(highLv, array.get(L.hi, i))
array.push(highNm, nm + hTok + str.tostring(i + 1))
array.push(highTm, array.get(L.hiT, i))
int nl = math.min(nLvl, array.size(L.lo))
if nl > 0
for i = 0 to nl - 1
array.push(lowLv, array.get(L.lo, i))
array.push(lowNm, nm + lTok + str.tostring(i + 1))
array.push(lowTm, array.get(L.loT, i))
if useChart
f_addLv(lqC, setupLbl)
if usePD
array.push(highLv, pdH)
array.push(highNm, "PDH")
array.push(highTm, pdHt)
array.push(lowLv, pdL)
array.push(lowNm, "PDL")
array.push(lowTm, pdLt)
if use15m
f_addLv(lq15, "15m")
if use30m
f_addLv(lq30, "30m")
if use1H
f_addLv(lq60, "1H")
if use4H
f_addLv(lq240, "4H")
// Two different questions are asked about the same event, and they need two
// different answers.
// For the ENTRY the sweep has to be RECENT - a stop hunt from two hours ago
// says nothing about this candle. That is the windowed check above.
// For the DISPLAY it is a property of the level: once it has been swept it
// stays swept until the level is removed, because the orders that were sitting
// there have been taken and that does not undo itself when price walks away.
// The lists below remember which levels have been through it.
var array<float> sweptHiMem = array.new<float>()
var array<int> sweptHiTm = array.new<int>()
var array<float> sweptLoMem = array.new<float>()
var array<int> sweptLoTm = array.new<int>()
f_wasSweptLow(float lv) =>
if f_sweptLow(lv) and array.indexof(sweptLoMem, lv) < 0
array.push(sweptLoMem, lv)
array.push(sweptLoTm, time)
if array.size(sweptLoMem) > 60
array.shift(sweptLoMem)
array.shift(sweptLoTm)
array.indexof(sweptLoMem, lv) >= 0
f_wasSweptHigh(float lv) =>
if f_sweptHigh(lv) and array.indexof(sweptHiMem, lv) < 0
array.push(sweptHiMem, lv)
array.push(sweptHiTm, time)
if array.size(sweptHiMem) > 60
array.shift(sweptHiMem)
array.shift(sweptHiTm)
array.indexof(sweptHiMem, lv) >= 0
// when the level was taken, so its line can stop there instead of running on
f_sweepTimeLow(float lv) =>
int ix = array.indexof(sweptLoMem, lv)
ix >= 0 ? array.get(sweptLoTm, ix) : na
f_sweepTimeHigh(float lv) =>
int ix = array.indexof(sweptHiMem, lv)
ix >= 0 ? array.get(sweptHiTm, ix) : na
bool bullSweep = false
bool bearSweep = false
string bullSweepNm = ""
string bearSweepNm = ""
if array.size(lowLv) > 0
for i = 0 to array.size(lowLv) - 1
float lvl = array.get(lowLv, i)
bool mem = f_wasSweptLow(lvl) // records the event, evaluated every bar
if f_sweptLow(lvl)
bullSweep := true
bullSweepNm := bullSweepNm == "" ? array.get(lowNm, i) : bullSweepNm
if array.size(highLv) > 0
for i = 0 to array.size(highLv) - 1
float lvh = array.get(highLv, i)
bool memh = f_wasSweptHigh(lvh)
if f_sweptHigh(lvh)
bearSweep := true
bearSweepNm := bearSweepNm == "" ? array.get(highNm, i) : bearSweepNm
// =============================================================================
// 6 · ENTRY-TIMEFRAME STRUCTURE
// -----------------------------------------------------------------------------
// The candles of the entry timeframe are read out of the current chart candle and
// pushed into a rolling buffer, then run through the same swing rules as the rest
// of the script: symmetric pivot, alternation, deviation, backstep.
// =============================================================================
useLTF = timeframe.in_seconds(entryTF) < chartSec
aH = request.security_lower_tf(syminfo.tickerid, entryTF, high)
aL = request.security_lower_tf(syminfo.tickerid, entryTF, low)
aC = request.security_lower_tf(syminfo.tickerid, entryTF, close)
aT = request.security_lower_tf(syminfo.tickerid, entryTF, time)
var array<float> bufH = array.new<float>()
var array<float> bufL = array.new<float>()
var array<float> bufC = array.new<float>()
var array<int> bufT = array.new<int>()
f_isPH(array<float> a, int idx, int l, int r) =>
float v = array.get(a, idx)
bool ok = true
for i = 1 to l
if array.get(a, idx - i) >= v
ok := false
break
if ok
for j = 1 to r
if array.get(a, idx + j) >= v
ok := false
break
ok
f_isPL(array<float> a, int idx, int l, int r) =>
float v = array.get(a, idx)
bool ok = true
for i = 1 to l
if array.get(a, idx - i) <= v
ok := false
break
if ok
for j = 1 to r
if array.get(a, idx + j) <= v
ok := false
break
ok
// zigzag state of the entry timeframe
var float lastPH1 = na
var float lastPL1 = na
var float ms1H = na
var float ms1L = na
var int ms1Ht = na
var int ms1Lt = na
var int ms1Tr = 0
var int z1t = 0
var float z1p = na
var int z1b = na
var float cHi1 = na
var float pHi1 = na
var float cLo1 = na
var float pLo1 = na
var int oneCount = 0
// sequence tracking, independent of the setup so the lead time can work
var bool pendHL = false
var float pendHLpx = na
var bool pendLH = false
var float pendLHpx = na
var bool seqBull = false
var int seqBullCnt = na
var bool seqBear = false
var int seqBearCnt = na
var bool hlOK = false
var bool hhOK = false
var bool lhOK = false
var bool llOK = false
var bool longSetup = false
var bool shortSetup = false
var int longSetupBar = na
var int shortSetupBar = na
var int longSetupCnt = na
var int shortSetupCnt = na
var int lastSigBar = na
// state as it stood BEFORE this bar is processed, which guarantees §14: the
// structure has to exist before the signal, never the other way round
float phBefore = lastPH1
float plBefore = lastPL1
bool hlBefore = hlOK
bool hhBefore = hhOK
bool lhBefore = lhOK
bool llBefore = llOK
// =============================================================================
// 7 · SETUP LIFECYCLE AND SIGNAL
// =============================================================================
if longSetup and not na(longSetupBar) and bar_index - longSetupBar >= expBars
longSetup := false
if shortSetup and not na(shortSetupBar) and bar_index - shortSetupBar >= expBars
shortSetup := false
if not longSetup
hlOK := false
hhOK := false
if not shortSetup
lhOK := false
llOK := false
// A rejection means the candle touched the band AND closed back into the half
// that faces it. Without the second half, one large candle wicking the lower band
// and closing at the upper one would count as a long.
bbZone = (bbUpper - bbLower) * rejZone / 100.0
bbTouchLong = low <= bbLower
bbRejLong = close > bbLower and close <= bbLower + bbZone
bbTouchShort = high >= bbUpper
bbRejShort = close < bbUpper and close >= bbUpper - bbZone
// A structure break on the entry timeframe, judged on the close of its candles
brkLong = not na(phBefore) and close > phBefore
brkShort = not na(plBefore) and close < plBefore
structLong = not use1M ? true : entryMode == "Structure Break" ? brkLong : entryMode == "HH/HL + BB Rejection" ? (hlBefore and hhBefore) : (hlBefore and hhBefore and brkLong)
structShort = not use1M ? true : entryMode == "Structure Break" ? brkShort : entryMode == "HH/HL + BB Rejection" ? (lhBefore and llBefore) : (lhBefore and llBefore and brkShort)
needBBRej = not (use1M and entryMode == "Structure Break")
rejLongOK = needBBRej ? (bbTouchLong and bbRejLong) : true
rejShortOK = needBBRej ? (bbTouchShort and bbRejShort) : true
// While the sources disagree, Offensive allows the direction the structure has
// turned to and blocks the old one; Conservative blocks both.
biasOKLong = not strictBias or biasBull or (transBull and transMode == "Offensive")
biasOKShort = not strictBias or biasBear or (transBear and transMode == "Offensive")
sweepOKLong = not reqSweep or bullSweep
sweepOKShort = not reqSweep or bearSweep
cooldownOK = na(lastSigBar) or (bar_index - lastSigBar) > cdBars
// §65: every ENABLED condition combined with AND
sniperLong = longSetup and structLong and rejLongOK and biasOKLong and sweepOKLong and inSession and cooldownOK
sniperShort = shortSetup and structShort and rejShortOK and biasOKShort and sweepOKShort and inSession and cooldownOK
if sniperLong and sniperShort
sniperShort := false
if sniperLong or sniperShort
lastSigBar := bar_index
longSetup := false
shortSetup := false
// new setups are armed only after the signal check, so §14 stays intact
newLongSetup = bbTouchLong and bbRejLong and stochWasOS and biasOKLong
newShortSetup = bbTouchShort and bbRejShort and stochWasOB and biasOKShort
if newLongSetup
if not longSetup
hlOK := false
hhOK := false
longSetup := true
longSetupBar := bar_index
longSetupCnt := oneCount
if newShortSetup
if not shortSetup
lhOK := false
llOK := false
shortSetup := true
shortSetupBar := bar_index
shortSetupCnt := oneCount
// =============================================================================
// 8 · PROCESS THE ENTRY-TIMEFRAME CANDLES
// =============================================================================
bool ev1mBOSup = false
bool ev1mBOSdn = false
bool ev1mCHup = false
bool ev1mCHdn = false
float ev1mUpLvl = na
int ev1mUpT = na
float ev1mDnLvl = na
int ev1mDnT = na
if barstate.isconfirmed
int n = 0
if useLTF
if not na(aH)
n := array.size(aH)
else
n := 1
if n > 0
for bi = 0 to n - 1
float h1 = useLTF ? array.get(aH, bi) : high
float l1 = useLTF ? array.get(aL, bi) : low
float c1 = useLTF ? array.get(aC, bi) : close
int t1 = useLTF ? array.get(aT, bi) : time
oneCount := oneCount + 1
array.push(bufH, h1)
array.push(bufL, l1)
array.push(bufC, c1)
array.push(bufT, t1)
if array.size(bufH) > 400
array.shift(bufH)
array.shift(bufL)
array.shift(bufC)
array.shift(bufT)
int sz = array.size(bufH)
// average range of this timeframe, the yardstick for the deviation
float min1 = 0.0
if swDevMode == "ATR" and sz >= 14
float rsum = 0.0
for k = 0 to 13
rsum += array.get(bufH, sz - 1 - k) - array.get(bufL, sz - 1 - k)
min1 := swDevVal * rsum / 14.0
else if swDevMode == "Percent"
min1 := c1 * swDevVal / 100.0
int p = sz - 1 - swInt
if p >= swInt
if f_isPH(bufH, p, swInt, swInt)
float pv = array.get(bufH, p)
int pt = array.get(bufT, p)
int pb = oneCount - 1 - swInt
bool repl = z1t == 1
bool take = repl ? pv > z1p : (z1t == 0 or (pv - z1p >= min1 and pb - nz(z1b, pb) >= swBack))
if take
if not repl
pHi1 := cHi1
cHi1 := pv
z1t := 1
z1p := pv
z1b := pb
lastPH1 := pv
ms1H := pv
ms1Ht := pt
bool isHH = take and not na(pHi1) and pv > pHi1
bool isLH = take and not na(pHi1) and pv <= pHi1
if isHH
if pendHL
seqBull := true
seqBullCnt := oneCount
pendLH := false
seqBear := false
if isLH
pendLH := true
pendLHpx := pv
if f_isPL(bufL, p, swInt, swInt)
float pv2 = array.get(bufL, p)
int pt2 = array.get(bufT, p)
int pb2 = oneCount - 1 - swInt
bool repl2 = z1t == -1
bool take2 = repl2 ? pv2 < z1p : (z1t == 0 or (z1p - pv2 >= min1 and pb2 - nz(z1b, pb2) >= swBack))
if take2
if not repl2
pLo1 := cLo1
cLo1 := pv2
z1t := -1
z1p := pv2
z1b := pb2
lastPL1 := pv2
ms1L := pv2
ms1Lt := pt2
bool isHL = take2 and not na(pLo1) and pv2 > pLo1
bool isLL = take2 and not na(pLo1) and pv2 <= pLo1
if isHL
pendHL := true
pendHLpx := pv2
if isLL
if pendLH
seqBear := true
seqBearCnt := oneCount
pendHL := false
seqBull := false
if not na(ms1H) and c1 > ms1H
if ms1Tr >= 0
ev1mBOSup := true
else
ev1mCHup := true
ev1mUpLvl := ms1H
ev1mUpT := ms1Ht
ms1Tr := 1
ms1H := na
else if not na(ms1L) and c1 < ms1L
if ms1Tr <= 0
ev1mBOSdn := true
else
ev1mCHdn := true
ev1mDnLvl := ms1L
ev1mDnT := ms1Lt
ms1Tr := -1
ms1L := na
// A sequence completed AFTER the setup always counts; one completed before it
// only inside the configured lead time. Runs after the signal check, so the
// result is used by the next bar and the required order is preserved.
if longSetup and seqBull and not (hlOK and hhOK) and not na(longSetupCnt)
if seqBullCnt >= longSetupCnt - strLead
hlOK := true
hhOK := true
if shortSetup and seqBear and not (lhOK and llOK) and not na(shortSetupCnt)
if seqBearCnt >= shortSetupCnt - strLead
lhOK := true
llOK := true
// =============================================================================
// 9 · SWING LABELS AND MARKET STRUCTURE
// =============================================================================
f_stackUp(int off) =>
float g = 0.0
if lblGap
if showSetup and newShortSetup[off]
g += lblGapAtr * atrV[off]
if showSniper and sniperShort[off]
g += lblGapAtr * atrV[off]
g
f_stackDn(int off) =>
float g = 0.0
if lblGap
if showSetup and newLongSetup[off]
g += lblGapAtr * atrV[off]
if showSniper and sniperLong[off]
g += lblGapAtr * atrV[off]
g
// --- swing labels of the chart timeframe, from the long degree ---------------
// Labels are taken from their own call of the same engine, so the degree can be
// chosen without touching the structure lines. Both degrees are already being
// calculated; this only decides which of them carries the text.
swLblLen = swDegree == "Swing" ? swMain : swInt
[swEvt, swIsHi, swPx, swTm, swRepl, swRef] = f_swings(swLblLen, swDevMode, swDevVal, swBack, swAtrLen)
var array<label> swLbls = array.new<label>()
var label swLast = na
if swEvt and swOn
if swRepl and not na(swLast)
label.delete(swLast)
if array.size(swLbls) > 0
array.pop(swLbls)
label lb = na
if not na(swRef)
bool higher = swPx > swRef
string txt = swIsHi ? (higher ? "HH" : "LH") : (higher ? "HL" : "LL")
float y = swIsHi ? swPx + f_stackUp(swLblLen) : swPx - f_stackDn(swLblLen)
lb := label.new(bar_index - swLblLen, y, txt, style = swIsHi ? label.style_label_down : label.style_label_up, color = color.new(color.white, 100), textcolor = higher ? swColUp : swColDn, size = f_size(swTextSize), force_overlay = true)
array.push(swLbls, lb)
if array.size(swLbls) > maxSwLbl
label.delete(array.shift(swLbls))
swLast := lb
// --- market structure, both degrees, per timeframe ---------------------------
[bosM5, chM5, dirM5, lvlM5, lvlTM5, trM5] = f_structure(swMain, swDevMode, swDevVal, swBack, swAtrLen)
[bosI5, chI5, dirI5, lvlI5, lvlTI5, trI5] = f_structure(swInt, swDevMode, swDevVal, swBack, swAtrLen)
[bosM15, chM15, dirM15, lvlM15, lvlTM15, trM15] = request.security(syminfo.tickerid, "15", f_structure(swMain, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
[bosM60, chM60, dirM60, lvlM60, lvlTM60, trM60] = request.security(syminfo.tickerid, "60", f_structure(swMain, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
[bosM240, chM240, dirM240, lvlM240, lvlTM240, trM240] = request.security(syminfo.tickerid, "240", f_structure(swMain, swDevMode, swDevVal, swBack, swAtrLen), lookahead = barmerge.lookahead_off)
t15 = request.security(syminfo.tickerid, "15", time, lookahead = barmerge.lookahead_off)
t60 = request.security(syminfo.tickerid, "60", time, lookahead = barmerge.lookahead_off)
t240 = request.security(syminfo.tickerid, "240", time, lookahead = barmerge.lookahead_off)
new15 = t15 != t15[1]
new60 = t60 != t60[1]
new240 = t240 != t240[1]
msAllow1 = timeframe.in_seconds(entryTF) >= chartSec
msAllow15 = timeframe.in_seconds("15") >= chartSec
msAllow60 = timeframe.in_seconds("60") >= chartSec
msAllow240 = timeframe.in_seconds("240") >= chartSec
var array<line> msLines = array.new<line>()
var array<label> msLbls = array.new<label>()
var array<int> msDir = array.new<int>()
var array<int> msAct = array.new<int>()
var array<int> msBar = array.new<int>()
var array<color> msCol = array.new<color>()
// geometry and text, kept so a line can be redrawn on top of a longer one later
var array<int> msX1 = array.new<int>()
var array<int> msX2 = array.new<int>()
var array<float> msY = array.new<float>()
var array<string> msTxt = array.new<string>()
var array<int> msInt = array.new<int>()
f_msDrop(int i) =>
line.delete(array.get(msLines, i))
label.delete(array.get(msLbls, i))
array.remove(msLines, i)
array.remove(msLbls, i)
array.remove(msDir, i)
array.remove(msAct, i)
array.remove(msBar, i)
array.remove(msCol, i)
array.remove(msX1, i)
array.remove(msX2, i)
array.remove(msY, i)
array.remove(msTxt, i)
array.remove(msInt, i)
// Horizontal line at the broken level with plain text at its end, no label box.
drawMS(bool ev, int dr, float lvl, int lvlT, string tf, bool isChoch, bool on, color colBull, color colBear, bool internal) =>
if ev and on and msOn and barstate.isconfirmed and not na(lvl) and not na(lvlT)
bool active = (dr == 1 and longSetup) or (dr == -1 and shortSetup)
color colOn = dr == 1 ? colBull : colBear
color col = active ? colOn : (msShowIdle ? msColIdle : color.new(color.gray, 100))
string kind = isChoch ? "CHOCH" : "BOS"
string txt = msLblMode == "MSB only" ? "MSB" : msLblMode == "BOS / CHOCH" ? kind : "MSB " + kind
txt := txt + " " + tf
int xEnd = time + msExtend * chartSec * 1000
line ln = line.new(lvlT, lvl, xEnd, lvl, xloc = xloc.bar_time, color = col, width = internal ? 1 : msWidth, style = internal ? line.style_dashed : f_lstyle(msStyle), force_overlay = true)
label lb = label.new(xEnd, lvl, txt, xloc = xloc.bar_time, style = label.style_none, textcolor = col, size = internal ? size.tiny : f_size(msTextSize), force_overlay = true)
array.push(msLines, ln)
array.push(msLbls, lb)
array.push(msDir, dr)
array.push(msAct, active ? 1 : 0)
array.push(msBar, bar_index)
array.push(msCol, colOn)
array.push(msX1, lvlT)
array.push(msX2, xEnd)
array.push(msY, lvl)
array.push(msTxt, txt)
array.push(msInt, internal ? 1 : 0)
if array.size(msLines) > msMax
f_msDrop(0)
drawMS(bosM5, dirM5, lvlM5, lvlTM5, setupLbl, false, ms5On, ms5ColB, ms5ColS, false)
drawMS(chM5, dirM5, lvlM5, lvlTM5, setupLbl, true, ms5On, ms5ColB, ms5ColS, false)
drawMS(bosI5, dirI5, lvlI5, lvlTI5, setupLbl, false, ms5On and msInternal, ms5ColB, ms5ColS, true)
drawMS(chI5, dirI5, lvlI5, lvlTI5, setupLbl, true, ms5On and msInternal, ms5ColB, ms5ColS, true)
drawMS(bosM15 and new15, dirM15, lvlM15, lvlTM15, "15m", false, ms15On and msAllow15, ms15ColB, ms15ColS, false)
drawMS(chM15 and new15, dirM15, lvlM15, lvlTM15, "15m", true, ms15On and msAllow15, ms15ColB, ms15ColS, false)
drawMS(bosM60 and new60, dirM60, lvlM60, lvlTM60, "1H", false, ms60On and msAllow60, ms60ColB, ms60ColS, false)
drawMS(chM60 and new60, dirM60, lvlM60, lvlTM60, "1H", true, ms60On and msAllow60, ms60ColB, ms60ColS, false)
drawMS(bosM240 and new240, dirM240, lvlM240, lvlTM240, "4H", false, ms240On and msAllow240, ms240ColB, ms240ColS, false)
drawMS(chM240 and new240, dirM240, lvlM240, lvlTM240, "4H", true, ms240On and msAllow240, ms240ColB, ms240ColS, false)
drawMS(ev1mBOSup, 1, ev1mUpLvl, ev1mUpT, entryLbl, false, ms1On and msAllow1, ms1ColB, ms1ColS, true)
drawMS(ev1mCHup, 1, ev1mUpLvl, ev1mUpT, entryLbl, true, ms1On and msAllow1, ms1ColB, ms1ColS, true)
drawMS(ev1mBOSdn, -1, ev1mDnLvl, ev1mDnT, entryLbl, false, ms1On and msAllow1, ms1ColB, ms1ColS, true)
drawMS(ev1mCHdn, -1, ev1mDnLvl, ev1mDnT, entryLbl, true, ms1On and msAllow1, ms1ColB, ms1ColS, true)
// neutral structures either become active or disappear
if array.size(msLines) > 0
for i = array.size(msLines) - 1 to 0
if array.get(msAct, i) == 0
int dr = array.get(msDir, i)
if (dr == 1 and longSetup) or (dr == -1 and shortSetup)
array.set(msAct, i, 1)
line.set_color(array.get(msLines, i), array.get(msCol, i))
label.set_textcolor(array.get(msLbls, i), array.get(msCol, i))
else if msPending > 0 and bar_index - array.get(msBar, i) > msPending
f_msDrop(i)
// =============================================================================
// 10 · PLOTS
// =============================================================================
pU = plot(bbShow ? bbUpper : na, "BB Upper", color = bbColBand, linewidth = bbWidth, force_overlay = true)
pB = plot(bbShow ? bbBasis : na, "BB Basis", color = bbColMid, linewidth = bbWidth, force_overlay = true)
pL = plot(bbShow ? bbLower : na, "BB Lower", color = bbColBand, linewidth = bbWidth, force_overlay = true)
// fill() has no force_overlay argument - it follows the two plots it is given,
// and those are already forced onto the price chart
fill(pU, pL, color = bbShow and bbShowFill ? bbColFill : color.new(color.white, 100), title = "BB Fill")
plot(showEma ? biasEmaV : na, "HTF EMA", color = emaCol, linewidth = emaWidth, force_overlay = true)
// A marker may only be judged once the candle has closed - before that there is
// no close to compare against the band. "While the candle forms" lifts that
// restriction knowingly and accepts that a marker can vanish again.
markerOK = markerWhen == "While the candle forms" or barstate.isconfirmed
plotshape(showSetup and markerOK and newLongSetup, "Long Setup", location = location.belowbar, style = shape.circle, size = size.tiny, color = setupColL, force_overlay = true)
plotshape(showSetup and markerOK and newShortSetup, "Short Setup", location = location.abovebar, style = shape.circle, size = size.tiny, color = setupColS, force_overlay = true)
plotshape(showSniper and markerOK and sniperLong, "Signal Long", location = location.belowbar, style = shape.circle, size = size.small, color = sniperColL, force_overlay = true)
plotshape(showSniper and markerOK and sniperShort, "Signal Short", location = location.abovebar, style = shape.circle, size = size.small, color = sniperColS, force_overlay = true)
// Price of the candle on which the conditions were complete, written next to its
// marker. Plain text, no box, and offset by the same stacking rule as the rest so
// it never lands on top of the dot.
var array<label> pxLbls = array.new<label>()
f_pxLabel(bool cond, bool up, color col) =>
if cond
float y = up ? high + f_stackUp(0) : low - f_stackDn(0)
label lb = label.new(bar_index, y, str.tostring(close, format.mintick), style = up ? label.style_label_down : label.style_label_up, color = color.new(color.white, 100), textcolor = col, size = f_size(priceSize), force_overlay = true)
array.push(pxLbls, lb)
if array.size(pxLbls) > 60
label.delete(array.shift(pxLbls))
pxSignals = priceMode != "Off"
pxSetups = priceMode == "Setups and signals"
f_pxLabel(showSniper and markerOK and pxSignals and sniperLong, false, sniperColL)
f_pxLabel(showSniper and markerOK and pxSignals and sniperShort, true, sniperColS)
f_pxLabel(showSetup and markerOK and pxSetups and newLongSetup and not sniperLong, false, setupColL)
f_pxLabel(showSetup and markerOK and pxSetups and newShortSetup and not sniperShort, true, setupColS)
// =============================================================================
// 10b · SESSION BOXES
// -----------------------------------------------------------------------------
// One box per session run, opened on its first candle and grown with the high and
// low the session makes. Each call site of the function keeps its own state, so
// the three sessions cannot interfere with each other.
// =============================================================================
f_sessBox(bool active, color colHue) =>
var box b = na
var array<box> hist = array.new<box>()
if sessShow and active and not active[1]
b := box.new(bar_index, high, bar_index, low, border_color = color.new(colHue, sessLineTr), border_width = sessBordW, bgcolor = color.new(colHue, sessFillTr), force_overlay = true)
array.push(hist, b)
if array.size(hist) > sessKeep
box.delete(array.shift(hist))
else if sessShow and active and not na(b)
box.set_right(b, bar_index)
box.set_top(b, math.max(box.get_top(b), high))
box.set_bottom(b, math.min(box.get_bottom(b), low))
if not sessShow and array.size(hist) > 0
for i = array.size(hist) - 1 to 0
box.delete(array.get(hist, i))
array.remove(hist, i)
boxFull = sessBoxSpan == "Full session"
f_sessBox(boxFull ? rawLDN : inLDN, sessColL)
f_sessBox(boxFull ? rawNY : inNY, sessColN)
f_sessBox(boxFull ? rawAsia : inAsia, sessColA)
// =============================================================================
// 11 · DRAW LIQUIDITY LEVELS
// =============================================================================
var array<line> liqLines = array.new<line>()
var array<label> liqLbls = array.new<label>()
// price and span of every liquidity line, needed to find structure lines hiding
// behind them
var array<float> liqPx = array.new<float>()
var array<int> liqA = array.new<int>()
var array<int> liqB = array.new<int>()
if barstate.islast
if array.size(liqLines) > 0
for i = 0 to array.size(liqLines) - 1
line.delete(array.get(liqLines, i))
array.clear(liqLines)
if array.size(liqLbls) > 0
for i = 0 to array.size(liqLbls) - 1
label.delete(array.get(liqLbls, i))
array.clear(liqLbls)
array.clear(liqPx)
array.clear(liqA)
array.clear(liqB)
if showLiq
int xR = time + 12 * chartSec * 1000
// The lines are drawn straight away; the names are collected first and
// placed afterwards, because only then is it known which of them would
// land on top of each other.
array<float> nmPx = array.new<float>()
array<int> nmTm = array.new<int>()
array<int> nmEd = array.new<int>()
array<string> nmTx = array.new<string>()
array<color> nmCo = array.new<color>()
if array.size(highLv) > 0
for i = 0 to array.size(highLv) - 1
float lv = array.get(highLv, i)
int tm = f_exactHigh(lv, array.get(highTm, i))
if not na(lv) and not na(tm)
bool sw = f_wasSweptHigh(lv)
if not sw or sweptShow
color col = sw ? (sweptCol == "Side colour" ? liqColHigh : liqColSwept) : liqColHigh
int wd = sw ? sweptWidth : liqWidth
int xe = xR
if sw and sweptEnd == "Stop at the sweep"
int st = f_sweepTimeHigh(lv)
xe := na(st) ? xR : math.max(st, tm)
line ln = line.new(tm, lv, xe, lv, xloc = xloc.bar_time, color = col, style = sw ? f_lstyle(liqStyleSw) : f_lstyle(liqStyleOpen), width = wd, force_overlay = true)
array.push(liqLines, ln)
array.push(liqPx, lv)
array.push(liqA, tm)
array.push(liqB, xR)
array.push(nmPx, lv)
array.push(nmTm, tm)
array.push(nmEd, xe)
array.push(nmTx, array.get(highNm, i) + (sw ? " swept" : "") + (liqPrice == "All levels" or (liqPrice == "Swept only" and sw) ? " " + str.tostring(lv, format.mintick) : ""))
array.push(nmCo, col)
if array.size(lowLv) > 0
for i = 0 to array.size(lowLv) - 1
float lv2 = array.get(lowLv, i)
int tm2 = f_exactLow(lv2, array.get(lowTm, i))
if not na(lv2) and not na(tm2)
bool sw2 = f_wasSweptLow(lv2)
if not sw2 or sweptShow
color col2 = sw2 ? (sweptCol == "Side colour" ? liqColLow : liqColSwept) : liqColLow
int wd2 = sw2 ? sweptWidth : liqWidth
int xe2 = xR
if sw2 and sweptEnd == "Stop at the sweep"
int st2 = f_sweepTimeLow(lv2)
xe2 := na(st2) ? xR : math.max(st2, tm2)
line ln2 = line.new(tm2, lv2, xe2, lv2, xloc = xloc.bar_time, color = col2, style = sw2 ? f_lstyle(liqStyleSw) : f_lstyle(liqStyleOpen), width = wd2, force_overlay = true)
array.push(liqLines, ln2)
array.push(liqPx, lv2)
array.push(liqA, tm2)
array.push(liqB, xR)
array.push(nmPx, lv2)
array.push(nmTm, tm2)
array.push(nmEd, xe2)
array.push(nmTx, array.get(lowNm, i) + (sw2 ? " swept" : "") + (liqPrice == "All levels" or (liqPrice == "Swept only" and sw2) ? " " + str.tostring(lv2, format.mintick) : ""))
array.push(nmCo, col2)
// Walk the names from the lowest price upwards. Whenever one sits closer
// to the one below it than the minimum gap, it is stepped further left
// along its own line - never past the candle the level came from.
int cnt = array.size(nmPx)
if cnt > 0
array<bool> done = array.new<bool>(cnt, false)
float minGap = liqLblGap * atrV
float prevPx = na
int slot = 0
for k = 0 to cnt - 1
int best = -1
float bestPx = na
for j = 0 to cnt - 1
if not array.get(done, j)
float pj = array.get(nmPx, j)
if na(bestPx) or pj < bestPx
bestPx := pj
best := j
if best >= 0
array.set(done, best, true)
slot := (not na(prevPx) and bestPx - prevPx < minGap) ? slot + 1 : 0
prevPx := bestPx
int x = array.get(nmEd, best) - slot * 9 * chartSec * 1000
int xMin = array.get(nmTm, best)
label lb = label.new(math.max(x, xMin), bestPx, array.get(nmTx, best), xloc = xloc.bar_time, style = label.style_none, textcolor = array.get(nmCo, best), size = f_size(liqTextSize), force_overlay = true)
array.push(liqLbls, lb)
// =============================================================================
// 11b · BRING SHORT LINES TO THE FRONT
// -----------------------------------------------------------------------------
// Pine has no z-index: whatever is created last is drawn on top. The liquidity
// lines are rebuilt on every tick of the last candle, so they are always the
// youngest objects and would bury any structure line sitting at the same price.
// Where a structure line is SHORTER than the liquidity line it overlaps, it is
// deleted and drawn again here - after the liquidity block - which puts it back
// in front. The longer line stays visible on both sides of it.
// =============================================================================
if barstate.islast and msOn and array.size(msLines) > 0 and array.size(liqPx) > 0
float tol = atrV * 0.05
for i = 0 to array.size(msLines) - 1
float y = array.get(msY, i)
int xa = array.get(msX1, i)
int xb = array.get(msX2, i)
bool buried = false
for j = 0 to array.size(liqPx) - 1
if math.abs(array.get(liqPx, j) - y) <= tol and (array.get(liqB, j) - array.get(liqA, j)) > (xb - xa)
buried := true
if buried
bool intern = array.get(msInt, i) == 1
bool active = array.get(msAct, i) == 1
color col = active ? array.get(msCol, i) : (msShowIdle ? msColIdle : color.new(color.gray, 100))
line.delete(array.get(msLines, i))
label.delete(array.get(msLbls, i))
line ln = line.new(xa, y, xb, y, xloc = xloc.bar_time, color = col, width = intern ? 1 : msWidth, style = intern ? line.style_dashed : f_lstyle(msStyle), force_overlay = true)
label lb = label.new(xb, y, array.get(msTxt, i), xloc = xloc.bar_time, style = label.style_none, textcolor = col, size = intern ? size.tiny : f_size(msTextSize), force_overlay = true)
array.set(msLines, i, ln)
array.set(msLbls, i, lb)
// =============================================================================
// 12 · STATUS TABLE
// =============================================================================
var table st = table.new(tblPos == "Top Right" ? position.top_right : tblPos == "Middle Right" ? position.middle_right : tblPos == "Bottom Right" ? position.bottom_right : tblPos == "Top Left" ? position.top_left : tblPos == "Middle Left" ? position.middle_left : position.bottom_left, 2, 9, border_width = 1)
f_cell(int col, int row, string txt, color tc) =>
table.cell(st, col, row, txt, text_color = tc, text_size = f_size(tblSize), bgcolor = tblBg, text_halign = text.align_left)
if showTable and barstate.islast
string sBias = biasBull ? "BULLISH" : biasBear ? "BEARISH" : transBull ? "TURNING UP" : transBear ? "TURNING DOWN" : "-"
color cBias = biasBull ? tblColB : biasBear ? tblColS : biasTrans ? color.orange : tblColIdle
string sSetup = longSetup ? "LONG" : shortSetup ? "SHORT" : "-"
color cSetup = longSetup ? tblColB : shortSetup ? tblColS : tblColIdle
string sStruct = longSetup ? ((hlOK ? "HL" : "-") + " + " + (hhOK ? "HH" : "-")) : shortSetup ? ((lhOK ? "LH" : "-") + " + " + (llOK ? "LL" : "-")) : "-"
color cStruct = (hlOK and hhOK) ? tblColB : (lhOK and llOK) ? tblColS : tblColIdle
string sLiq = not reqSweep ? "not chosen" : bullSweep ? ("SWEPT " + bullSweepNm) : bearSweep ? ("SWEPT " + bearSweepNm) : "WAITING"
color cLiq = not reqSweep ? tblColIdle : (bullSweep or bearSweep) ? tblColB : color.orange
bool readyL = longSetup and structLong and biasOKLong and sweepOKLong and inSession and cooldownOK
bool readyS = shortSetup and structShort and biasOKShort and sweepOKShort and inSession and cooldownOK
string sReady = readyL ? "READY LONG" : readyS ? "READY SHORT" : (longSetup or shortSetup) ? "WAITING" : "-"
color cReady = readyL ? tblColB : readyS ? tblColS : color.orange
if tblMode == "Full"
f_cell(0, 0, "Chart TF", tblLabel)
f_cell(1, 0, tfMatch ? timeframe.period + " OK" : "set Setup TF to " + timeframe.period, tfMatch ? color.silver : color.orange)
f_cell(0, 1, biasLbl + " Bias", tblLabel)
f_cell(1, 1, sBias, cBias)
f_cell(0, 2, setupLbl + " Setup", tblLabel)
f_cell(1, 2, sSetup, cSetup)
f_cell(0, 3, setupLbl + " BB", tblLabel)
f_cell(1, 3, (bbTouchLong and bbRejLong) ? "REJECTED (long)" : (bbTouchShort and bbRejShort) ? "REJECTED (short)" : "-", (bbTouchLong and bbRejLong) ? tblColB : (bbTouchShort and bbRejShort) ? tblColS : tblColIdle)
f_cell(0, 4, entryLbl + " Structure", tblLabel)
f_cell(1, 4, use1M ? sStruct : "OFF", use1M ? cStruct : tblColIdle)
f_cell(0, 5, "Liquidity", tblLabel)
f_cell(1, 5, sLiq, cLiq)
f_cell(0, 6, "Session", tblLabel)
f_cell(1, 6, inSession ? sessName : "outside", inSession ? tblColB : tblColIdle)
f_cell(0, 7, "Stoch RSI K", tblLabel)
f_cell(1, 7, str.tostring(kV, "#.0"), kV >= obLvl ? tblColS : kV <= osLvl ? tblColB : color.silver)
f_cell(0, 8, "Signal", tblLabel)
f_cell(1, 8, sReady, cReady)
else
// five rows: conditions that belong together share a line
bool rej = (bbTouchLong and bbRejLong) or (bbTouchShort and bbRejShort)
f_cell(0, 0, "Bias", tblLabel)
f_cell(1, 0, tfMatch ? sBias : sBias + " · set Setup TF to " + timeframe.period, tfMatch ? cBias : color.orange)
f_cell(0, 1, "Setup", tblLabel)
f_cell(1, 1, sSetup + (rej ? " · BB ok" : ""), cSetup)
f_cell(0, 2, "Structure", tblLabel)
f_cell(1, 2, (use1M ? sStruct : "OFF") + " · Liq " + (not reqSweep ? "not chosen" : (bullSweep or bearSweep) ? "ok" : "wait"), use1M ? cStruct : tblColIdle)
f_cell(0, 3, "Session", tblLabel)
f_cell(1, 3, (inSession ? sessName : "outside") + " · RSI " + str.tostring(kV, "#.0"), inSession ? tblColB : tblColIdle)
f_cell(0, 4, "Signal", tblLabel)
f_cell(1, 4, sReady, cReady)
// =============================================================================
// 12b · OSCILLATOR PANE
// -----------------------------------------------------------------------------
// The script itself lives in the pane below the chart; everything that belongs on
// the price chart is drawn there explicitly. This section is what actually uses
// the pane: the Stoch RSI the setup logic runs on, its levels, and two pieces of
// context that are otherwise invisible - the higher-timeframe bias as a tint, and
// the window during which a setup is still waiting for its entry as a strip along
// the bottom edge.
// =============================================================================
pK = plot(oscK ? kV : na, "Stoch RSI K", color = oscColK, linewidth = 2)
pD = plot(oscD ? dV : na, "Stoch RSI D", color = oscColD, linewidth = 1)
fill(pK, pD, color = oscFill ? (kV >= dV ? oscFillUp : oscFillDn) : color.new(color.white, 100), title = "K/D Fill")
plot(oscLines ? obLvl : na, "Overbought level", color = color.new(oscDotOb, 55), style = plot.style_line, linewidth = 1)
plot(oscLines ? osLvl : na, "Oversold level", color = color.new(oscDotOs, 55), style = plot.style_line, linewidth = 1)
plot(oscLines ? 50 : na, "Mid line", color = color.new(color.gray, 70), style = plot.style_line, linewidth = 1)
plotshape(oscDots and kV >= obLvl, "Overbought", location = location.top, style = shape.circle, size = size.tiny, color = oscDotOb)
// the signal itself, on the K line, so it is not missed while watching the pane
plotshape(oscSignal and markerOK and sniperLong ? kV : na, "Signal long (pane)", location = location.absolute, style = shape.circle, size = size.normal, color = sniperColL)
plotshape(oscSignal and markerOK and sniperShort ? kV : na, "Signal short (pane)", location = location.absolute, style = shape.circle, size = size.normal, color = sniperColS)
plotshape(oscDots and kV <= osLvl, "Oversold", location = location.bottom, style = shape.circle, size = size.tiny, color = oscDotOs)
bgcolor(oscBias ? (biasBull ? oscBiasUp : biasBear ? oscBiasDn : biasTrans ? oscBiasTr : na) : na, title = "Bias background")
// the strip: two invisible plots at the bottom edge, filled while a setup runs
sTop = plot(oscStrip ? 4 : na, "Strip top", display = display.none)
sBot = plot(oscStrip ? 0 : na, "Strip bottom", display = display.none)
fill(sTop, sBot, color = oscStrip and longSetup ? color.new(oscDotOs, 20) : oscStrip and shortSetup ? color.new(oscDotOb, 20) : color.new(color.white, 100), title = "Setup strip")
// =============================================================================
// 13 · ALERTS
// =============================================================================
alertcondition(newLongSetup, "Long Setup", "Long setup active")
alertcondition(newShortSetup, "Short Setup", "Short setup active")
alertcondition(bullSweep and not bullSweep[1], "Bullish Liquidity Sweep", "Bullish liquidity sweep")
alertcondition(bearSweep and not bearSweep[1], "Bearish Liquidity Sweep", "Bearish liquidity sweep")
alertcondition(bosM5 and dirM5 == 1, "Bullish BOS", "Bullish BOS (chart TF)")
alertcondition(bosM5 and dirM5 == -1, "Bearish BOS", "Bearish BOS (chart TF)")
alertcondition(chM5 and dirM5 == 1, "Bullish CHOCH", "Bullish CHOCH (chart TF)")
alertcondition(chM5 and dirM5 == -1, "Bearish CHOCH", "Bearish CHOCH (chart TF)")
alertcondition((bosM5 or chM5) and dirM5 == 1, "Bullish MSB", "Bullish MSB (chart TF)")
alertcondition((bosM5 or chM5) and dirM5 == -1, "Bearish MSB", "Bearish MSB (chart TF)")
alertcondition(sniperLong, "SNIPER LONG", "SNIPER LONG")
alertcondition(sniperShort, "SNIPER SHORT", "SNIPER SHORT")
if sniperLong or sniperShort
string dirTxt = sniperLong ? "SNIPER LONG" : "SNIPER SHORT"
string strTxt = sniperLong ? ((hlBefore ? "HL" : "-") + " + " + (hhBefore ? "HH" : "-")) : ((lhBefore ? "LH" : "-") + " + " + (llBefore ? "LL" : "-"))
string msg = syminfo.ticker + "\n" + dirTxt + "\n\n" + "Price: " + str.tostring(close, format.mintick) + "\n\n" + biasLbl + " Bias: " + (biasBull ? "Bullish" : biasBear ? "Bearish" : transBull ? "Turning up" : transBear ? "Turning down" : "Neutral") + "\n" + "Setup: " + (sniperLong ? "Long" : "Short") + "\n" + entryLbl + " Structure: " + (use1M ? strTxt : "OFF") + "\n" + "Liquidity Sweep: " + (not reqSweep ? "not required" : (sniperLong ? (bullSweep ? "Yes (" + bullSweepNm + ")" : "No") : (bearSweep ? "Yes (" + bearSweepNm + ")" : "No"))) + "\n" + "Session: " + sessName
alert(msg, alert.freq_once_per_bar_close)