Cod 2
Cod 2
hilo2 = g2 * f2 + (1 - g2) * e2
css2 = g2 == 1 ? color.green : color.red
plot(hilo2, color=css2, style=plot.style_line, show_last=1, linewidth=1, transp=0,
trackprice=true)
hilo3 = g3 * f3 + (1 - g3) * e3
css3 = g3 == 1 ? color.green : color.red
plot(hilo3, color=css3, style=plot.style_line, show_last=1, linewidth=1, transp=0,
trackprice=true)
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
//@version=4
//study("Support/Resistance", shorttitle="S/R", overlay=true, scale = scale.right,
linktoseries = true)
//color function
colour(z) => z=="Red"?color.red:z=="Lime"?color.lime:z=="Orange"?
color.orange:z=="Teal"?
color.teal:z=="Yellow"?color.yellow:z=="Black"?color.black:color.white
//Calc Values
rsi_new = rsi(close,9)
lpivot_new = lpivot // use legacy pivots calculation as integrated
pivotlow/pivothigh functions give very different result
hpivot_new = hpivot
ph = pivothigh(leftBars, rightBars)
pl = pivotlow( leftBars, rightBars)
if (ph)
running_ph := ph
if (pl)
running_pl := pl
Fhigh = highest(FPeriod)
Flow = lowest(FPeriod)
Fhigh2 = highest(FPeriod2)
Flow2 = lowest(FPeriod2)
Fhigh3 = highest(FPeriod3)
Flow3 = lowest(FPeriod3)
FH = highestbars(high, FPeriod)
FL = lowestbars(low, FPeriod)
//downfibo = FH < FL
//@version=4
//@version=4
//study("Session min/max points", overlay=true)
res2 = input("D", "Resolution", type=input.resolution)
// © SimpleCryptoLife
//@version=4
//study(title="[SCL] True Market Structure", shorttitle="[SCL] True Market
Structure", overlay=true, linktoseries=true, max_labels_count=100,
max_lines_count=100)
// == COPYRIGHT ==
// Script by @SimpleCrpytoLife. This script is open-source.
// --> If you use ideas from it, you don't need to ask or give credit to me.
// --> If you copy code out of here to adapt for your own script, it must be
open-source. You don't need to ask permission, just credit @SimpleCryptoLife. Let
me know if you make something cool.
// == CREDITS ==
// The rules for Local Highs and Lows come from my trading mentor.
// All code is my own. You can tell 'cos of how needlessly complex and over-
commented it is.
// == DESCRIPTION ==
// This indicator shows market structure. The standard method, of using Williams
Highs and Lows as pivots, is something of an approximation.
// What's original here is that we follow rules to confirm Local Highs and Local
Lows, and strictly enforce that a Low can only follow a confirmed High and vice-
versa.
// -- Highs and Lows
// To confirm a candle as a Local High, you need a later candle to Close below its
Low. To confirm a Local Low, you need a Close above its High.
// A Low can only follow a High (after it's been confirmed). You can't go e.g High,
High, Low, Low, only High, Low, High, Low.
// When price makes Higher Highs and Higher Lows, market structure is said to be
bullish. When price makes Lower Lows and Lower Highs, it's bearish.
// I've defined the in-between Highs and Lows as "Ranging", meaning, neutral. They
could be trend continuation or reversal.
// -- Bullish/Bearish Breaks
// A Bullish break in market structure is when the Close of the current candle goes
higher than the previous confirmed Local High.
// A Bearish Break is when the Close of the current candle goes lower than the most
recent confirmed Local Low.
// I chose to use Close rather than High to reduce edge case weirdness. The
breaking candle often ends up being a big one, thus the close of that candle can be
a poor entry.
// You can get live warnings by setting the alert to Options: Only Once,
because during a candle, the current price is taken as the Close.
// Breaks are like early warnings of a change in market bias, because you're not
waiting for a High or Low to be formed and confirmed.
// -- Buy The Dip / Sell The Rally
// Buy The Dip is a label I gave to the first Higher Low in a bullish market
structure. Sell The Rally is the first Lower High in a bearish market structure.
// These *might* be good buying/selling opportunities, but you still need to do
your own analysis to confirm that.
// == USAGE ==
// The point of knowing market structure is so you don't make bullish bets in a
bearish market and vice versa -
// or if you do at least you're aware that that's what you're doing, and hopefully
have some overwhelmingly good reason to do so.
// These are not signals to be traded on their own. You still need a trade thesis.
Use with support & resistance and your other favourite indicators.
// Works on any market on any timeframe. Be aware that market structure will be
different on different timeframes.
// IMPORTANT: If you're not seeing what you expect, check your settings and re-read
this entire description carefully. Confirming Highs and Lows can get deceptively
complex.
// == SETTINGS ==
// Maximum number of labels displayed. This is hardcoded in the study declaration
on line 3. I don't think there's a way to add it to the Settings.
// You can change the value of max_labels_count up to a system-enforced
maximum of 500. More labels might make it render more slowly.
// The rest of the settings are accessible in the usual way: right-click the
indicator and choose Settings.
// Display Local Highs & Lows - Configure the display of labels for Higher Highs,
Lower Highs, Lower Lows, and Higher Lows.
// Because TradingView only displays a limited number of drawings, you can't
examine old parts of the chart with this indicator. It will only work for the most
recent bars.
// - Short label text is just HH, LL, etc.
// - Full text includes market bias, derived from the Highs, Lows, and Breaks.
// - Off hides Local Highs and Lows (but not Breaks or Buy The Dip/Sell The
Rally).
// Keep Only Most Recent High & Low Label - Deletes previous labels after the
current labels are confirmed on close.
// As you're getting used to the indicator you probably want to see all
labels, and when you're comfortable with it, perhaps only the last High and Low.
// Display Current Market Bias Label - Shows or hides the current
bullish/bearish/ranging bias.
// Show Breaks in Market Structure - Show when market structure breaks from Bearish
or Ranging to Bullish, or from Bullish or Ranging to Bearish.
// - "Reversals Only" shows only those breaks that signal a change from a
bullish to bearish market structure or vice versa, i.e. when the market reverses.
// - "All" also includes breaks out of a ranging structure back into the same
direction as previously, i.e., continuations and reversals.
// Show Close Needed to Break Market Structure - Draw lines that show where price
needs to close in order to flip market bias to bullish or bearish.
// Show Buy The Dip, Sell The Rally - Highlights when a Higher Low is confirmed
after a Higher High, or a Lower High after a Lower Low.
// Force Confirmation of Highs & Lows After N Bars: When you get a range of inside
candles after a big candle, you can wait a long time for a true confirmation.
// While you're waiting, high or low wicks can happen that might not later be
counted as Highs/Lows even though they look like they "should".
// This setting stops waiting for a confirmation on higher/lower close and
just confirms the fractal after a certain number of bars, which can also cause its
own distortion.
// There might not be a perfect solution, but the default settings work just
fine almost all the time.
// ▻▻▻ Number of Bars - The number of bars after which to force confirmation. Using
a high number, like 20, will not change much; it's like insurance against any
unusually long ranges.
// Using a low number will significantly increase the number of Highs and Lows
displayed. It makes the indicator behave a bit more like other "pivot"-based
indicators.
// == ALERTS ==
// This indicator includes the following predefined alert conditions:
// .Lower Low, .Higher Low, .Higher High, .Lower High, .Buy The Dip, .Sell The
Rally, .Bullish Break, .Bearish Break
// These all correspond to the labels as displayed on the chart. Bullish and
Bearish Break alerts trigger on all breaks, not only reversals, irrespective of
which breaks are configured to display.
// NOTE: Check the "REPAINTING" section below to understand on what bar different
alerts will be triggered.
// Be mindful of what you set under the alert Options (Only Once, Once Per Bar
Close, etc), in order to get the results you expect.
// == REPAINTING ==
// By definition, you only know that a Higher High etc has formed when it is
confirmed, an unpredictable number of bars afterwards.
// Therefore, there's a lot of repainting going on. Don't worry. It's still
accurate.
// -- HH, LH, LL, HL
// These are all confirmed on close, after 1 or more bars. But the label is then
applied retroactively, to the candle that was the actual High or Low.
// During a candle, the most recent label can appear and disappear as the current
price changes. Once the candle is closed, the label (or lack of one) is fixed.
// You probably want to set alerts for these on close.
// -- Breaks
// Bullish and Bearish Breaks are confirmed on close. During a candle, the break
label on the current candle can appear and disappear. Once the candle is closed,
the label (or lack of one) is fixed.
// Breaks are fixed immediately the candle closes. They're not retroactively
applied to or removed from previous bars.
// You might want to get an alert for a break as it's happening, before the candle
closes, since they can often end up being large moves. Up to you.
// -- Buy The Dip, Sell The Rally
// These signals are shown on the candle that *confirms* the respective High or
Low, NOT on the High/Low candle itself. They're confirmed on close.
// == DISCLAIMER ==
// You retain full responsibility for your trading at all times. Before trading
with actual money, first make sure your risk management is professional-level.
// Short label text is just HH, LL, etc. Full text includes market bias, derived
from the Highs, Lows, and Breaks. Off hides Local Highs and Lows (but not Breaks or
BTD/STR).
string inputLabelDisplayMode = input(type=input.string, defval="Full Text",
title="Display Local Highs & Lows", options=["Short Text","Full Text","Off"])
// As you're getting used to the indicator you probably want to see all labels, and
when you're comfortable with it, perhaps only the last two.
bool inputKeepOnlyLastLabel = input(type=input.bool, defval=false, title="Keep Only
Most Recent High & Low Label")
string currentStateLabelDisplayMode = input(type=input.string, defval="Full Text",
title="Display Current Market Bias Label", options=["Short Text","Full
Text","Off"]) // Show whether we're bullish, bearish or ranging
int inputCurrentStateLabelOffset = input(type=input.integer, defval=3, minval=0,
maxval=50, title="▻▻▻ How Many Bars Ahead to Draw Label") // Space it out as you
like
bool inputMarketBiasBackgroundFill = input(type=input.bool, defval=true,
title="Colour Background According to Market Bias") // Colour the background
according to current market bias
// Show when market structure breaks from Bearish or Ranging to Bullish, or from
Bullish or Ranging to Bearish.
string inputShowBreakMode = input(type=input.string, defval="Reversals Only",
title="Show Breaks in Market Structure", options=["Reversals Only","All","Off"])
// Draw a line to show where price has to close for market structure to break
bullish/bearish
bool inputShowBreakLines = input(type=input.bool, defval=true, title="Show Close
Needed to Break Market Structure")
// Highlights when a Higher Low is confirmed after a Higher High, or a Lower High
after a Lower Low
bool inputShowEntries = input(type=input.bool, defval=true, title="Show Buy The
Dip, Sell The Rally")
// When you get a range of inside candles, you can wait a long time for a true
confirmation. This setting stops waiting for a break on close and just confirms the
fractal after n bars.
bool inputForceConfirmation = input(type=input.bool, defval=true, title="Force
Confirmation of Highs & Lows After N Bars")
int inputForceBars = input(type=input.integer, minval=1, maxval=999, defval=20,
title="▻▻▻ Number of Bars")
functionUpdatePLLine(_line,_trailMode) =>
// This function updates the Potential Low line
float _outputline = _trailMode == "up" ? low : _trailMode == "down" and low <
_line ? low : _line // When we're trailing up, reset the PL line to each candle
low. When we trail down, persist if the low rises.
potentialLowLine := functionUpdatePLLine(potentialLowLine,lowTrailMode)
functionPrintPH(_line_1,_isCL,_barIndexPH,_barIndexPL,_trailMode) =>
// This function prints a Potential (unconfirmed) High
bool _isPH1 = high > _line_1 // A high that goes higher than the
potentialHighLine is a Potential High.
// When we confirm a Low, make this candle a Potential High if it's higher than
the previous one and if the most recent PH was further back than the Low we just
confirmed.
// This fixes the case where we were confirming Local Highs that were earlier
in time than the Low they were supposed to follow.
bool _isPH2 = _isCL and high > high[1] and _barIndexPH < _barIndexPL
bool _isPH = _isPH1 or _isPH2 // Let's keep the conditions separate for
clarity.
string _internalTrailMode = _isPH ? "up" : _trailMode // When we print a PH,
potentialHighLine switches to trail up.
int _internalBarIndexPH = _isPH ? bar_index : _barIndexPH // Update the
bar_index to be the index of this bar (persists).
[_isPH,_internalTrailMode,_internalBarIndexPH]
// This naming convention prepending r_ for returned value is only used once per
variable, for getting the output from a function. It helps prevent accidentally
using the wrong value from somewhere else.
[r_isPotentialHigh,r_highTrailMode,r_barIndexPH] =
functionPrintPH(potentialHighLine[1],isConfirmLow,barIndexPH,barIndexPL,highTrailMo
de) // Call the function to print a PH if appropriate
isPotentialHigh := r_isPotentialHigh, highTrailMode := r_highTrailMode,
barIndexPH := r_barIndexPH // Some shenanigans to get the values out
functionPrintPL(_line_1,_isCH,_barIndexPH,_barIndexPL,_trailMode) =>
// This function prints a Potential (unconfirmed) Low
bool _isPL1 = low < _line_1 // A low that goes lower than the potentialLowLine
is a Potential Low.
bool _isPL2 = _isCH and low < low[1] and _barIndexPL < _barIndexPH // Fix that
pesky edge case.
bool _isPL = _isPL1 or _isPL2
string _internalTrailMode = _isPL ? "down" : _trailMode // When we print a PL,
potentialLowLine switches to trail down.
int _internalBarIndexPL = _isPL ? bar_index : _barIndexPL // Update the
bar_index to be the index of this bar (persists).
[_isPL,_internalTrailMode,_internalBarIndexPL]
[r_isPotentialLow,r_lowTrailMode,r_barIndexPL] =
functionPrintPL(potentialLowLine[1],isConfirmHigh,barIndexPH,barIndexPL,lowTrailMod
e)
isPotentialLow := r_isPotentialLow, lowTrailMode := r_lowTrailMode, barIndexPL :=
r_barIndexPL
functionUpdateLowToTake(_self,_isPH,_isHigh) =>
// This function updates the line that confirms a Local High, after we have
calculated the Potential Highs and Lows
_output = _isPH ? low : _isHigh ? na : _self // Reset lowToTake line: to the
low of a PH bar, to na if we printed any kind of High this bar, or persist.
lowToTake := functionUpdateLowToTake(lowToTake,isPotentialHigh,isHigh)
functionUpdateHighToTake(_self,_isPL,_isLow) =>
// This function updates the line that confirms a Local Low, after we have
calculated the Potential Highs and Lows
_output = _isPL ? high : _isLow ? na :_self // Reset highToTake line: to the
high of a PL bar, to na if we printed any kind of Low this bar, or persist.
highToTake := functionUpdateHighToTake(highToTake,isPotentialLow,isLow)
functionConfirmHigh(_lowToTake,_isPH,_barIndexPH,_barIndexLocalHigh,_lookingForHigh
) =>
// This function changes a Potential High to a Local (Confirmed) High or
Suppressed High
bool _isHigh = ((close < _lowToTake) or (open < _lowToTake)) and not _isPH //
Print a High if we closed (or gapped open!) below the lowToTake and this bar is not
itself a renewed PH
bool _isConfirmHigh = _isHigh and _lookingForHigh // Confirm a Local High if
the last confirmed fractal wasn't also a Local High
bool _isSuppressedHigh = _isHigh and not _lookingForHigh // If the last
confirmed fractal *was* a Local High, print a Suppressed High instead (Confirmed
and Suppressed are exclusive)
// Confirm the most recent Potential High as the Local High (Note: we cannot
confirm an Interim High. It should have been either upgraded or discarded.)
_internalBarIndexLocalHigh = _isConfirmHigh ? _barIndexPH :
_barIndexLocalHigh // Update the bar index for the Local High to be the index of
the most recent Potential High
[_isHigh,_isConfirmHigh, _isSuppressedHigh,_internalBarIndexLocalHigh]
[r_isHigh,r_isConfirmHigh, r1_isSuppressedHigh,r_barIndexLocalHigh] =
functionConfirmHigh(lowToTake,isPotentialHigh,barIndexPH,barIndexLocalHigh,lookingF
orHigh)
isHigh := r_isHigh, isConfirmHigh := r_isConfirmHigh, isSuppressedHigh :=
r1_isSuppressedHigh, barIndexLocalHigh := r_barIndexLocalHigh // I declare
Shenanigans
functionConfirmLow(_highToTake,_isPL,_barIndexPL,_barIndexLocalLow,_lookingForLow)
=>
// This function changes a Potential Low to a Local (Confirmed) Low or
Suppressed Low
bool _isLow = ((close > _highToTake) or (open > _highToTake)) and not _isPL //
Print a Low if we closed above the highToTake and this bar isn't itself a renewed
PL
bool _isConfirmLow = _isLow and _lookingForLow // Confirm a Local Low if this
low follows a confirmed High
bool _isSuppressedLow = _isLow and not _lookingForLow // Suppress if last
confirmed fractal was also a Low
// Confirm the most recent Potential Low as the Local Low (Note: we cannot
confirm an Interim Low. It should have been either upgraded or discarded.)
_internalBarIndexLocalLow = _isConfirmLow ? _barIndexPL : _barIndexLocalLow //
Update the bar index for the Local Low to be the index of the most recent Potential
Low
[_isLow,_isConfirmLow,_isSuppressedLow,_internalBarIndexLocalLow]
[r_isLow,r_isConfirmLow,r_isSuppressedLow,r_barIndexLocalLow] =
functionConfirmLow(highToTake,isPotentialLow,barIndexPL,barIndexLocalLow,lookingFor
Low)
isLow := r_isLow, isConfirmLow := r_isConfirmLow, isSuppressedLow :=
r_isSuppressedLow, barIndexLocalLow := r_barIndexLocalLow
functionForceHL(_overrideLow,_overrideHigh,_isCL,_isCH,_isPL,_isPH,_isSL,_isSH,_isL
ow,_isHigh,_overrideLowTimer,_overrideHighTimer,
_inputForceBars,_barIndexPL,_barIndexPH,_barIndexLocalLow,_barIndexLocalHigh,_looki
ngForLow,_lookingForHigh) =>
// This function confirms a High/Low after n bars, and makes the same updates
as the main confirm function. If we confirmed already the old-fashioned way then
this will be skipped.
_iOverrideLow = _isCL ? false : _isPL ? true : _overrideLow // The order in
which we evaluate conditions matters here: isConfirmLow is a switch and a filter in
one.
_iOverrideHigh = _isCH ? false : _isPH ? true : _overrideHigh // The order in
which we evaluate conditions matters here: isConfirmHigh is a switch and a filter
in one.
_iOverrideLowTimer = _isPL ? 0 : _iOverrideLow ? _overrideLowTimer+1 : 0 //
Increment the counter each bar. Reset on every new PL. Reset when we lose the
override state.
_iOverrideHighTimer = _isPH ? 0 : _iOverrideHigh ? _overrideHighTimer+1 : 0 //
Copying mutable variables is a workaround to use them inside functions
_forceConfirmLow = _iOverrideLowTimer == _inputForceBars ? true : false //
Force confirmation if we've had n bars
_forceConfirmHigh = _iOverrideHighTimer == _inputForceBars ? true : false
_iIsCL = _forceConfirmLow and _lookingForLow ? true : _isCL // Confirm the low
if it's in season
_iIsCH = _forceConfirmHigh and _lookingForHigh ? true : _isCH // Confirm the
low if it's in season
_iIsSL = _forceConfirmLow and not _lookingForLow ? true : _isSL // Suppress the
low if it's not in season
_iIsSH = _forceConfirmHigh and not _lookingForHigh ? true : _isSH // Suppress
the low if it's not in season
_iIsLow = _iIsCL or _iIsSL ? true : _isLow // A bit of retro-fitting
_iIsHigh = _iIsCH or _iIsSH ? true : _isHigh // A bit of retro-fitting
_internalBarIndexLocalLow = _forceConfirmLow ? _barIndexPL :
_barIndexLocalLow // Update the bar index for the Local Low to be the index of the
most recent Potential Low
_internalBarIndexLocalHigh = _forceConfirmHigh ? _barIndexPH :
_barIndexLocalHigh // Update the bar index for the Local High to be the index of
the most recent Potential High
[_iOverrideLow,_iOverrideHigh,_iOverrideLowTimer,_iOverrideHighTimer,_forceConfirmL
ow,_forceConfirmHigh,_internalBarIndexLocalLow,_internalBarIndexLocalHigh,_iIsCL,_i
IsCH,_iIsSL,_iIsSH,_iIsLow,_iIsHigh]
[r_overrideLow,r_overrideHigh,r_overrideLowTimer,r_overrideHighTimer,r_forceConfirm
Low,r_forceConfirmHigh,r_barIndexLocalLowForce,r_barIndexLocalHighForce,r2_isConfir
mLow,
r2_isConfirmHigh,r2_isSuppressedLow,r2_isSuppressedHigh,r2_isLow,r2_isHigh] =
functionForceHL(overrideLow,overrideHigh,isConfirmLow,isConfirmHigh,isPotentialLow,
isPotentialHigh,isSuppressedLow,isSuppressedHigh,isLow,isHigh,
overrideLowTimer,overrideHighTimer,inputForceBars,barIndexPL,barIndexPH,barIndexLoc
alLow,barIndexLocalHigh,lookingForLow,lookingForHigh)
// Assign the outputs returned from the function to their namesake mutable
variables, only if the user has turned this option on
if inputForceConfirmation
overrideLow := r_overrideLow, overrideHigh := r_overrideHigh,
overrideLowTimer := r_overrideLowTimer, overrideHighTimer := r_overrideHighTimer,
forceConfirmLow := r_forceConfirmLow, forceConfirmHigh := r_forceConfirmHigh,
barIndexLocalLow := r_barIndexLocalLowForce, barIndexLocalHigh :=
r_barIndexLocalHighForce,
isConfirmLow := r2_isConfirmLow, isConfirmHigh := r2_isConfirmHigh,
isSuppressedLow := r2_isSuppressedLow, isSuppressedHigh := r2_isSuppressedHigh,
isLow := r2_isLow, isHigh := r2_isHigh
// Here we need to call the functions to print Potential Highs and Potential Lows
again. By this point, we have all the confirmations, suppressions, and forced
confirmations in.
// By calling them again after we update confirmations, we activate a different
line in the functions to fix an edge case.
// We call them again in exactly the same way, but use r2_ instead of r_ so the
returned variables don't clash. It also neatly lets us know that this is the 2nd
time we're calling the same functions.
[r2_isPotentialHigh,r2_highTrailMode,r2_barIndexPH] =
functionPrintPH(potentialHighLine[1],isConfirmLow,barIndexPH,barIndexPL,highTrailMo
de)
isPotentialHigh := r2_isPotentialHigh, highTrailMode := r2_highTrailMode,
barIndexPH := r2_barIndexPH
[r2_isPotentialLow,r2_lowTrailMode,r2_barIndexPL] =
functionPrintPL(potentialLowLine[1],isConfirmHigh,barIndexPH,barIndexPL,lowTrailMod
e)
isPotentialLow := r2_isPotentialLow, lowTrailMode := r2_lowTrailMode, barIndexPL :=
r_barIndexPL
// Reset the high-low mode after we have both High and Low confirmations in. We
only care about confirmed fractals for these lines.
lookingForHigh := isConfirmHigh ? false : isConfirmLow ? true : lookingForHigh
lookingForLow := isConfirmLow ? false : isConfirmHigh ? true : lookingForLow
functionUpdatePHLineOnHigh(_PHline,_trailMode,_isHigh,_isLow,_barIndexPH,_barIndexP
L) =>
// This function updates the Potential High line after we have the
confirmations in
bool _reset1 = _isHigh // Reset if this bar confirms a High
bool _reset2 = _isLow and (barIndexPH < barIndexPL) // Reset if the most recent
candidate High is before the Low we just confirmed or Suppressed
bool _reset = _reset1 or _reset2 // Consolidate the conditions. Doing it the
long way round for clarity.
float _iPHLine = _reset ? high : _PHline // Reset potentialHighLine to the
high of the current candle if one or more of the conditions has been met
string _iTrailMode = _isHigh ? "down" : _trailMode // Set highTrailMode == down
ONLY on a high
[_iPHLine,_iTrailMode]
[r_potentialHighLine,r_highTrailModeUpdate2] =
functionUpdatePHLineOnHigh(potentialHighLine,highTrailMode,isHigh,isLow,barIndexPH,
barIndexPL)
potentialHighLine := r_potentialHighLine, highTrailMode := r_highTrailModeUpdate2
functionUpdatePLLineOnLow(_PLline,_trailMode,_isHigh,_isLow,_barIndexPH,_barIndexPL
) =>
// This function updates the Potential Low line after we have the confirmations
in
bool _reset1 = _isLow // Reset if this bar confirms a Low
bool _reset2 = _isHigh and (barIndexPL < barIndexPH) // Reset if the most
recent candidate Low is before the High we just confirmed or Suppressed
bool _reset = _reset1 or _reset2 // Consolidate the conditions
_iPLLine = _reset ? low : _PLline // Reset potentialLowLine to the low of the
confirming candle if one or more of the conditions has been met
_iTrailMode = _isLow ? "up" : _trailMode // Set lowTrailMode == up ONLY on low
[_iPLLine,_iTrailMode]
[r_potentialLowLine,r_lowTrailModeUpdate2] =
functionUpdatePLLineOnLow(potentialLowLine,lowTrailMode,isHigh,isLow,barIndexPH,bar
IndexPL)
potentialLowLine := r_potentialLowLine, lowTrailMode := r_lowTrailModeUpdate2
// === Measure whether the Highs and Lows are higher or lower ===
// No matter what bias we are in, a Bullish break is always bullish, and vice-
versa.
// We DO change (or confirm) the bias based on a break, because even if it
reverses, it will just confirm the break and go on to form an opposite H/L.
// All breaks are unconfirmed HH/LLs (although not all HHs/LLs are breaks). We know
the bias will be confirmed, we just don't know on which candle or at what price.
// A common edge case is where a HH/LL is formed by a wick only. This changes (for
the sake of argument) market bias but we don't count it as a break because it
wasn't on close.
// In this case, the next close that exceeds that new HH/LL will be the break.
functionIsBreak(_highLine,_lowLine,_lastReversal) =>
// Is this candle a bullish or bearish break in market structure?
_isBullishBreak = (close > _highLine) and not (close[1] > _highLine[1]) // Is
it the first close above the most recent High?
_isBearishBreak = (close < _lowLine) and not (close[1] < _lowLine[1]) // Or
below the most recent Low?
// Is it a trend-changing break (the first of its name)? Reversals are ALSO
breaks, i.e. these variables are not mutually exclusive.
_isBullishReversal = _lastReversal == "Bullish" ? false : _isBullishBreak //
Only show the first Break of this type (resets on the first opposing Break)
_isBearishReversal = _lastReversal == "Bearish" ? false : _isBearishBreak
[_isBullishBreak,_isBearishBreak,_isBullishReversal,_isBearishReversal]
[r_isBullishBreak,r_isBearishBreak,r_isBullishReversal,r_isBearishReversal] =
functionIsBreak(highLine,lowLine,lastReversal)
isBullishBreak := r_isBullishBreak, isBearishBreak := r_isBearishBreak,
isBullishReversal := r_isBullishReversal, isBearishReversal := r_isBearishReversal
functionSetBullBear(_bullBearCondition,_isLL,_isHL,_isHH,_isLH,_isBullishBreak,_isB
earishBreak) =>
// This function sets the market bias based on my interpretation of the
significance of Highs, Lows, and Breaks appearing in different states.
string _rangeChange = _isBullishBreak ? "Bullish" : _isBearishBreak ? "Bearish"
: _isLL ? "Bearish" : _isHL ? "Ranging" : _isHH ? "Bullish" : _isLH ? "Ranging" :
na
string _bearChange = _isBullishBreak ? "Bullish" : _isBearishBreak ?
"Bearish" : _isLL ? "Bearish" : _isHL ? "Ranging" : _isHH ? "Bullish" : _isLH ?
"Bearish" : na
string _bullChange = _isBullishBreak ? "Bullish" : _isBearishBreak ?
"Bearish" : _isLL ? "Bearish" : _isHL ? "Bullish" : _isHH ? "Bullish" : _isLH ?
"Ranging" : na
string _outputBullBearCondition = _bullBearCondition == "Ranging" ?
_rangeChange : _bullBearCondition == "Bearish" ? _bearChange : _bullBearCondition
== "Bullish" ? _bullChange : na
_outputBullBearCondition
functionHLLabelText(_isHH,_isLH,_isLL,_isHL,_short,_bias) =>
// This function sets the label text based on whether it's a HH etc, and sets
long or short text
string _highText1 = _isHH and _short ? "HH" : _isHH and not _short ? "Higher
High" : _isLH and _short ? "LH" : _isLH and not _short ? "Lower High" : na
string _highText2 = not _short ? "\n("+_bias+")" : na // \n is a newline
string _highText = _highText1+_highText2
string _lowText1 = _isLL and _short ? "LL" : _isLL and not _short ? "Lower Low"
: _isHL and _short ? "HL" : _isHL and not _short ? "Higher Low" : na
string _lowText2 = not _short ? "\n("+_bias+")" : na
string _lowText = _lowText1+_lowText2
string _out = _isHH or _isLH ? _highText : _isLL or _isHL ? _lowText : na
textHLLabel =
functionHLLabelText(isHH,isLH,isLL,isHL,useShortLabelText,bullBearCondition)
if drawBearBreakLine
bearLine := line.new(barIndexLocalLow, lowLine, bar_index, lowLine,
extend=extend.none, color=color.red, style=line.style_dotted, width=1)
line.delete(bearLine[1])
functionDeletePreviousLabel(_labelName,_labelPrintTrigger,_barIndexThisLabel1,_barI
ndexPreviousPrintedLabel,_barIndexPreviousPrintedLabel1) =>
// This function deletes the previous printed label, thus keeping only the most
recently printed label visible.
// It only deletes the previous label on close, so for the duration of the
current bar you can have two labels of the same type.
// If it deleted the previous label when a new label was printed intra-
candle, it wouldn't (AFAIK) be able to reinstate it if the label was unprinted. So
I think this behaviour is for the best.
// Deleting a label[n] simply deletes the label n bars back, whether it was na
or not. To delete the second-to-last label, you need to calculate the bar index of
that label.
// _labelName is the name of the label. This function works only if the label
is named and if the label is set to na each time it is not printed.
// _labelPrintTrigger is the condition that, if it is true, prints the named
label.
_barIndexThisLabel = _labelPrintTrigger ? bar_index : _barIndexThisLabel1
_iBarIndexPreviousPrintedLabel = _labelPrintTrigger ? _barIndexThisLabel1 :
_barIndexPreviousPrintedLabel1
label.delete(_labelName[bar_index-_barIndexPreviousPrintedLabel])
[_barIndexThisLabel,_iBarIndexPreviousPrintedLabel]
if inputKeepOnlyLastLabel
[r_barIndexThisHighLabel,r_barIndexPreviousPrintedHighLabel] =
functionDeletePreviousLabel(localHighLabel,localHighLabelTrigger,barIndexThisHighLa
bel[1],
barIndexPreviousPrintedHighLabel,barIndexPreviousPrintedHighLabel[1])
barIndexThisHighLabel := r_barIndexThisHighLabel,
barIndexPreviousPrintedHighLabel := r_barIndexPreviousPrintedHighLabel
// We can't alter the text on a plotshape. We have to have two separate plotshapes
for short and normal label text.
float isBullishBreakPlotLongText = isBullishBreakPlot and not useShortLabelText ?
low : na
float isBullishBreakPlotShortText = isBullishBreakPlot and useShortLabelText ?
low : na
float isBearishBreakPlotLongText = isBearishBreakPlot and not useShortLabelText ?
high : na
float isBearishBreakPlotShortText = isBearishBreakPlot and useShortLabelText ? high
: na
var label currentStateLabel = na // We need to define the label in the global scope
(not the local scope of the if statement) so that the delete command recognises it
later
timeblock1 = (time - time[1]), futureTime = time + (timeblock1 *
inputCurrentStateLabelOffset) // This is the only way to draw a label in the future
if showCurrentStateLabel
currentStateLabel := label.new(futureTime, ohlc4, stateLabelText,
color=marketBiasColour, textcolor=color.white, style=label.style_label_left,
yloc=yloc.price, xloc=xloc.bar_time)
label.delete(currentStateLabel[1]) // Keep only the most recent label
// ======================================================= //
// //
// (╯°□°)╯︵ sǝᴉD ʎllɐǝR ɹǝʌƎ ǝuo-oN //
// //
// ======================================================= //
// // Leaving the debug in here in case you want to incorporate this into your own
thing. If you do, you must make your own thing open-source.
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © xmd1979
//@version=4
//end of this part
//@version=4
//study("Vkay indicator", overlay=true, max_bars_back=1000)
// Labels
var label labelll = na
var label labelhh = na
// Swing lines
var line line_up = na
var line line_down = na
// FUNCTIONS
obLabelText() =>
if(last_actual_label_hh_price < high)
"HH by Vkay"
else
"LH by Vkay"
//plot(last_actual_label_hh_price)
osLabelText() =>
if(last_actual_label_ll_price < low)
"HL by Vkay"
else
"LL by Vkay"
moveOverBoughtLabel() =>
label.set_x(labelhh, bar_index)
label.set_y(labelhh, high)
label.set_text(labelhh, obLabelText())
line.set_x1(line_up, bar_index)
line.set_y1(line_up, high)
// If we are overbought
if(isOverbought)
if(high >= hhZ)
hhZ := high
moveOverBoughtLabel()
laststate := 1
// If we are oversold
if(isOversold)
if(low <= llZ)
llZ := low
moveOversoldLabel()
laststate := 2
//If we are oversold and the last state was oversold, move the drawings to the
lowest price
if(laststate == 2 and isOversold)
if(low <= llZ)
llZ := low
moveOversoldLabel()
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © Ankit_1618
//@version=4
//study("Vortex Range Breakout System", overlay=true)
//
//*****
//SAME TF PART
//
//
f_vortex(h,l,period) =>
vmp = sum(abs(h - l[1]), period)
vmm = sum(abs(l - h[1]), period)
str = sum(atr(1), period)
vip = vmp/str
vim = vmm/str
[vip, vim]
[vortex_p,vortex_n] = f_vortex(high,low,period)
var highs_sametf = 0.
var lows_sametf = 0.
p_cond_sametf = crossover(vortex_p,vortex_n)
n_cond_sametf = crossunder(vortex_p,vortex_n)
if p_cond_sametf
highs_sametf := high
if n_cond_sametf
lows_sametf := low
//
//*****
//HTF PART
//
//
htf_high = security(syminfo.tickerid, htf_timeframe, high)
htf_low = security(syminfo.tickerid, htf_timeframe, low)
[vortex_p_htf, vortex_n_htf] = security(syminfo.tickerid, htf_timeframe,
f_vortex(htf_high,htf_low,period) )
var highs_htf = 0.
var lows_htf = 0.
p_cond_htf = crossover(vortex_p_htf,vortex_n_htf)
n_cond_htf = crossunder(vortex_p_htf,vortex_n_htf)
if p_cond_htf
highs_htf := high
if n_cond_htf
lows_htf := low
//@version=4
// setting
_1 = input(false, '══════ general setting
══════════════════════════════')
i_lineCount = input(10, "Line count")
i_extendLines = input(true, "Extend lines")
// array declarations
var pivotArray = array.new_line()
var pivotabelArray = array.new_label()
x2 = line.get_x2(array.get(_lineArray, _i))
yValue = line.get_y1(array.get(_lineArray, _i))
if (array.size(pivotArray)==i_lineCount)
line.delete(array.shift(pivotArray))
label.delete(array.shift(pivotabelArray))
array.push(pivotArray, l)
array.push(pivotabelArray, lab)
if (pivotHigh or pivotLow)
float yValue = na
int x1 = na
int x2 = na
if (not na(pivotHigh))
yValue := high[_right]
x1 := bar_index[_right]
x2 := bar_index
f_drawPivotLineAndLabel(x1, x2, yValue, _colorLine)
if (not na(pivotLow))
yValue := low[_right]
x1 := bar_index[_right]
x2 := bar_index
f_drawPivotLineAndLabel(x1, x2, yValue, _colorLine)
if (i_showFirst)
f_addLine(i_firstLeft, i_firstRight, i_firstColor)
if (i_showSecond)
f_addLine(i_secondLeft, i_secondRight, i_secondColor)
if (i_showThird)
f_addLine(i_thirdLeft, i_thirdRight, i_thirdColor)
f_extendArray(pivotArray, i_extendLines)
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © DevLucem
// you can request code usage by messaging me
//@version=4
////////
// Preheat Oven
// [
//study("Semafor", overlay=true, max_labels_count=300)
// ]
////////
// Bake Water With Vinegar For 20 Minutes
// [
repaint = input(false, "Allow Drawing Of Unconfirmed Levels")
zigzag(Depth, Deviation, Color, Size, Type) =>
var lw = 1, var hg = 1
lw := lw + 1, hg := hg + 1
p_lw = -lowestbars(Depth), p_hg = -highestbars(Depth)
lowing = lw == p_lw or low - low[p_lw] > Deviation*syminfo.mintick
highing = hg == p_hg or high[p_hg] - high > Deviation*syminfo.mintick
lh = barssince(not highing), ll = barssince(not lowing)
down = lh > ll, lower = low[lw] > low[p_lw], higher = high[hg] < high[p_hg]
if lw != p_lw and (not down[1] or lower)
lw := p_lw < hg ? p_lw : 0
if hg != p_hg and (down[1] or higher)
hg := p_hg < lw ? p_hg : 0
x1 = down ? lw : hg
y1 = down ? low[lw] : high[hg]
lb = down ? label.style_label_up : label.style_label_down
label point = na
if repaint
point := label.new(bar_index-x1, y1, color=Color, style=label.style_circle,
size=Size)
if down == down[1]
label.delete(point[1])
if not repaint and down != down[1]
nx = down ? hg : lw
point := label.new(bar_index-nx, down ? high[nx] : low[nx], color=Color,
style=label.style_circle, size=Size)
down != down[1]
// ]
////////
// Serve While Hot
// [
switch = false
if input(true, "Large")
switch := zigzag(input(150, "Depth"), input(24.0, "Deviation"),
input(color.red, "Color"), size.normal, "Large") or switch
if input(true, "Medium")
switch := zigzag(input(34, "Depth"), input(6.0, "Deviation"),
input(color.orange, "Color"), size.small, "Medium") or switch
if input(false, "Small")
switch := zigzag(input(14, "Depth"), input(3.0, "Deviation"), input(color.lime,
"Color"), size.tiny, "Small") or switch
// ]
////////
// Monchoka Juu Unajinauwo
// [
alertcondition(switch, "Semafor Alert", "New Semafor Level Confirmed")
// ]
// ( (
// )\ ) )\ )
// (()/( ( ) (()/( ( ( )
// /(_)) ))\ /(( /(_)) ))\ ( ))\ (
// (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ '
// | \ (_)) _)((_) | | (_))( ((_)(_)) _((_))
// | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \()
// |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_|
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue
//@version=4
//study("Support Resistance MTF", overlay = true, max_bars_back = 4900)
src = input(defval = 'High/Low', title = "Source", options = ['High/Low',
'Close/Open'])
TimeframeU = input(defval = 'Auto', title ="Higher Time Frame", options = ['Auto',
'15', '30', '60', '120', '180', '240', '720', 'D', 'W', '2W', 'M', '3M', '6M',
'12M'])
prd = input(defval = 10, title = "Period for Highest/Lowest Bars", minval = 1)
Transp = input(defval = 85, title = "Transparency", minval = 0, maxval = 100)
resistancecol = input(defval = 'Red', title = "Resistance Color", options = ['Red',
'Lime', 'Blue', 'White', 'Black', 'Olive', 'Gray'])
supportcol = input(defval = 'Lime', title = "Support Color", options = ['Red',
'Lime', 'Blue', 'White', 'Black', 'Olive', 'Gray'])
extendlines = input(defval = false, title = "Extend Lines")
Timeframe = timeframe.period
if TimeframeU == 'Auto'
Timeframe := timeframe.period == '1' ? '15' :
timeframe.period == '3' ? '15' :
timeframe.period == '5' ? '60' :
timeframe.period == '15' ? '60' :
timeframe.period == '30' ? '120' :
timeframe.period == '45' ? '120' :
timeframe.period == '60' ? '240' :
timeframe.period == '120' ? 'D' :
timeframe.period == '180' ? 'D' :
timeframe.period == '240' ? 'D' :
timeframe.period == 'D' ? 'W' :
timeframe.period == 'W' ? 'M' :
'12M'
else
Timeframe := TimeframeU
var float hc = na
var float lc = na
srch = src == 'High/Low' ? high : max(close, open)
srcl = src == 'High/Low' ? low : min(close, open)
hc := highestbars(srch, prd) == 0 ? srch : hc
lc := lowestbars(srcl, prd) == 0 ? srcl : lc
get_col(srx)=>
ret = srx == 'Red' ? color.red :
srx == 'Lime' ? color.lime :
srx == 'Blue' ? color.blue :
srx == 'White' ? color.white :
srx == 'Black' ? color.black :
srx == 'Olive' ? color.olive :
color.gray
rcol = get_col(resistancecol)
scol = get_col(supportcol)
highestbar(src, len)=>
ll = 1
if len > 1
for x = 0 to 4000
if na(newbar[x]) or na(close[x + 1])
break
if newbar[x]
if src <= src[x + 1]
break
ll := ll + 1
if ll >= len
break
ret = ll >= len
lowestbar(src, len)=>
ll = 1
if len > 1
for x = 0 to 4000
if na(newbar[x]) or na(close[x + 1])
break
if newbar[x]
if src >= src[x + 1]
break
ll := ll + 1
if ll >= len
break
ret = ll >= len
var float hh = 0
var float ll = 0
bool hbar = highestbar(htfh, prd)
bool lbar = lowestbar(htfl, prd)
hh := hbar ? htfh : hh
ll := lbar ? htfl : ll
fill(hhp, hcp, color = hc == hc[1] and hh == hh[1] ? rcol : na, transp = Transp)
fill(llp, lcp, color = lc == lc[1] and ll == ll[1] ? scol : na, transp = Transp)
// extend lines
if extendlines
var line s1 = na
var line s2 = na
var line r1 = na
var line r2 = na
line.delete(s1)
line.delete(s2)
line.delete(r1)
line.delete(r2)
s1 := line.new(bar_index, lc, bar_index - 1, lc, color = scol, extend =
extend.left)
s2 := line.new(bar_index, ll, bar_index - 1, ll, color = scol, extend =
extend.left)
r1 := line.new(bar_index, hc, bar_index - 1, hc, color = rcol, extend =
extend.left)
r2 := line.new(bar_index, hh, bar_index - 1, hh, color = rcol, extend =
extend.left)