name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Delta Volume Channels [LucF] | https://www.tradingview.com/script/zkBuiFk7-Delta-Volume-Channels-LucF/ | LucF | https://www.tradingview.com/u/LucF/ | 1,428 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© LucF
//@version=5
indicator("Delta Volume Channels [LucF]", "DV Channels", true, precision = 6, max_labels_count = 500)
// Delta Volume Channels [LucF]
// v5, 2023.04.16 17:55
// This code was written using the recommendations from the Pine Scriptβ’ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/Time/2 as PCtime
import PineCoders/lower_tf/4 as PCltf
import LucF/ta/3 as LucfTa
//#region ββββββββββββββββββββ Constants
// Colors
color LIME = #00FF00ff
color LIME_MD = #00FF0090
color LIME_LT = #00FF0040
color TEAL = #008080ff
color TEAL_MD = #00808090
color TEAL_LT = #00808040
color PINK = #FF0080ff
color PINK_MD = #FF008090
color PINK_LT = #FF008040
color MAROON = #800000ff
color MAROON_MD = #80000090
color MAROON_LT = #80000040
color ORANGE = #c56606ff
color ORANGE_BR = #FF8000ff
color GRAY = #808080ff
color GRAY_MD = #80808090
color GRAY_LT = #80808030
color WHITE = #FFFFFFff
color BLACK = #000000ff
// Reference MAs
string MA01 = "Simple MA"
string MA02 = "Exponential MA"
string MA03 = "Wilder MA"
string MA04 = "Weighted MA"
string MA05 = "Volume-weighted MA"
string MA06 = "Arnaud Legoux MA"
string MA07 = "Hull MA"
string MA08 = "Symmetrically-weighted MA"
// Intrabar precisions
string LTF1 = "Covering most chart bars (least precise)"
string LTF2 = "Covering some chart bars (less precise)"
string LTF3 = "Covering less chart bars (more precise)"
string LTF4 = "Covering few chart bars (very precise)"
string LTF5 = "Covering the least chart bars (most precise)"
string LTF6 = "~12 intrabars per chart bar"
string LTF7 = "~24 intrabars per chart bar"
string LTF8 = "~50 intrabars per chart bar"
string LTF9 = "~100 intrabars per chart bar"
string LTF10 = "~250 intrabars per chart bar"
// Line styles
string STL1 = "Line"
string STL2 = "Circles"
string STL3 = "Crosses"
// Marker DV channel transitions
string ST0 = "None"
string ST1 = "DV channel strong bull state"
string ST2 = "DV channel bull or strong bull state"
string ST3 = "DV channel strong bear state"
string ST4 = "DV channel bear or strong bear state"
// Marker Divergence channel transitions
string SV0 = "None"
string SV1 = "Divergence channel strong bull state"
string SV2 = "Divergence channel bull or strong bull state"
string SV3 = "Divergence channel strong bear state"
string SV4 = "Divergence channel bear or strong bear state"
// Bar color choices
string CB0 = "None"
string CB1 = "On divergences only"
string CB2 = "On divergences and on the state of the DV channel"
string CB3 = "On divergences and on the state of the divergence channel"
string CB4 = "On divergences and on the combined state of both channels"
// Channel level sources
string CH1 = "High and Low"
string CH2 = "Open and Close"
// Channel breach sources
string BR1 = "`low` must breach channel's top, `high` must breach channel's bottom"
string BR2 = "`high` must breach channel's top, `low` must breach channel's bottom"
string BR3 = "Close"
string BR4 = "Open"
string BR5 = "The average of high and low (hl2)"
string BR6 = "The average of high, low and close (hlc3)"
string BR7 = "The average of high, low and two times the close (hlcc4)"
string BR8 = "The average of high, low and close and open (ohlc4)"
// Tooltips
string TT_REF = "Your choices here determine the reference that will be used as the DV channel's baseline.
The MA type and length defined here are also used to calculate the MA of the DV% weights."
string TT_CAP = "This is the maximum number of standard deviations away from the reference line that the DV%-weighted line can extend to.
It limits swings of the DV%-weighted line, keeping the chart's vertical scale within acceptable boundaries."
string TT_RVOL = "In addition to the weight of DV, use the weight of the relative volume for the bar.
This weight is determined using the percentile rank of the bar's volume in the specified number of bars."
string TT_LTF = "Your selection here controls how many intrabars will be analyzed for each chart bar.
The more intrabars you analyze, the more precise the calculations will be,
but the less chart bars will be covered by the indicator's calculations because a maximum of 100K intrabars can be analyzed.\n\n
The first five choices determine the lower timeframe used for intrabars using how much chart coverage you want.
The last five choices allow you to select approximately how many intrabars you want analyzed per chart bar."
string TT_LTF_BOX = "Displays the LTF used and intrabar statistics in a configurable position and color."
string TT_BIAS = "This option enables a guess on the bull/bear bias of the channel before it is breached.
It uses the number of changes of the top/bottom channel levels to determine a bias.
When more changes of the top level occur, the bias is bullish. When more changes of the bottom level occur, the bias is bearish.
\n\n Note that enabling this setting will make the channel's states less reliable."
string TT_COLORS = "'π‘π‘' and 'π‘π‘' indicate the colors used for strong bull/bear conditions.
\n'π‘' and 'π‘' indicate bull/bear conditions."
string TT_MARKERS = "The conditions you use to determine when markers appear will also be used to trigger alerts created from this script.
\n\nMarkers are non-repainting; they appear on the close of bars."
string TT_BARS = "If the coloring of bars on divergences is active, their body will always be colored in the divergence color, regardless of this checkbox's state."
string TT_DIV = "A divergence occurs when the slope of the reference line does not match that of the DV%-weighted line."
string TT_FILTERS = "The filters are additional conditions that must be true for a marker to appear.
\n\n'Bar polarity' means that the bar's up/dn polarity must match that of the marker.
\n\n'Close-to-close polarity' means that the `close` must be higher than the previous one for an up marker, and vice versa.
\n\n'Bull/bear CCI' means that CCI (using the same source and length as the reference line) must be above/below 0.
\n\n'Rising volume' means the volume of the bar must be higher than that of the previous bar. This condition is the same for up/dn markers.
\n\nThe filter on divergences requires a divergence to have occurred in the last number of bars you specify.
\n\nThe filter on 'Efficient Work' requires its bull/bear state to match the direction of the marker. ('Efficient Work' is one of my indicators).
\n\nAs markers are non-repainting, keep in mind that marker conditions must be true on the bar's close, which is when the marker will appear."
//#endregion
//#region ββββββββββββββββββββ Inputs
string ltfModeInput = input.string(LTF8, "Intrabar precision", inline = "ltf", options = [LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10], tooltip = TT_LTF)
string GRP0 = "DV channel"
bool reflLineShowInput = input.bool(false, "Reference lineβ", group = GRP0, inline = "refLine")
int refLineWidthInput = input.int(1, "βWidth", group = GRP0, inline = "refLine", minval = 1)
string refLineStyleInput = input.string(STL1, "", group = GRP0, inline = "refLine", options = [STL1, STL2, STL3])
color refLineUpUpColorInput = input.color(LIME, "ββπ‘π‘", group = GRP0, inline = "refLineColors")
color refLineDnDnColorInput = input.color(PINK, "π‘π‘", group = GRP0, inline = "refLineColors")
color refLineUpColorInput = input.color(TEAL, "βπ‘", group = GRP0, inline = "refLineColors")
color refLineDnColorInput = input.color(MAROON, "π‘", group = GRP0, inline = "refLineColors", tooltip = TT_COLORS)
string refTypeInput = input.string(MA06, "ββ", group = GRP0, inline = "ref", options = [MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08], tooltip = TT_REF)
float refSourceInput = input.source(close, "", group = GRP0, inline = "ref")
int refLengthInput = input.int(20, "βLength", group = GRP0, inline = "ref", minval = 2)
bool dvlLineShowInput = input.bool(false, "DV%-weighted line", group = GRP0, inline = "dvLine")
int dvLineWidthInput = input.int(2, "βWidth", group = GRP0, inline = "dvLine", minval = 1)
string dvLineStyleInput = input.string(STL1, "", group = GRP0, inline = "dvLine", options = [STL1, STL2, STL3])
color dvLineUpUpColorInput = input.color(LIME, "ββπ‘π‘", group = GRP0, inline = "dvLineColors")
color dvLineDnDnColorInput = input.color(PINK, "π‘π‘", group = GRP0, inline = "dvLineColors")
color dvLineUpColorInput = input.color(TEAL, "βπ‘", group = GRP0, inline = "dvLineColors")
color dvLineDnColorInput = input.color(MAROON, "π‘", group = GRP0, inline = "dvLineColors")
int sigmaCapInput = input.int(5, "βββCap (in standard deviations)", group = GRP0, inline = "cap", minval = 1, tooltip = TT_CAP)
bool useRelVolWeightInput = input.string("Use", "ββ", group = GRP0, inline = "RelVolW", options = ["Use", "Don't use"], tooltip = TT_RVOL) == "Use"
int relVolLookbackInput = input.int(100, "relative volume over n bars", group = GRP0, inline = "RelVolW", minval = 2)
bool dvFillShowInput = input.bool(true, "DV channel", group = GRP0, inline = "dvFill")
color dvFillUpUpColorInput = input.color(LIME_MD, "βπ‘π‘", group = GRP0, inline = "dvFill")
color dvFillDnDnColorInput = input.color(PINK_MD, "π‘π‘", group = GRP0, inline = "dvFill")
color dvFillUpColorInput = input.color(TEAL_MD, "βπ‘", group = GRP0, inline = "dvFill")
color dvFillDnColorInput = input.color(MAROON_MD, "π‘", group = GRP0, inline = "dvFill")
string GRP1 = "Divergence channel"
bool divLinesShowInput = input.bool(false, "Divergence levels", group = GRP1, inline = "divLines")
int divLinesWidthInput = input.int(1, "βWidth", group = GRP1, inline = "divLines", minval = 1)
string divLinesStyleInput = input.string(STL1, "", group = GRP1, inline = "divLines", options = [STL1, STL2, STL3])
color divLinesUpUpColorInput = input.color(LIME, "ββπ‘π‘", group = GRP1, inline = "divLinesColors")
color divLinesDnDnColorInput = input.color(PINK, "π‘π‘", group = GRP1, inline = "divLinesColors")
color divLinesUpColorInput = input.color(TEAL, "βπ‘", group = GRP1, inline = "divLinesColors")
color divLinesDnColorInput = input.color(MAROON, "π‘", group = GRP1, inline = "divLinesColors")
color divLinesNtColorInput = input.color(GRAY, "N", group = GRP1, inline = "divLinesColors")
bool divFillShowInput = input.bool(true, "Divergence channel", group = GRP1, inline = "divFill")
color divFillUpUpColorInput = input.color(LIME_MD, "βπ‘π‘", group = GRP1, inline = "divFill")
color divFillDnDnColorInput = input.color(PINK_MD, "π‘π‘", group = GRP1, inline = "divFill")
color divFillUpColorInput = input.color(TEAL_MD, "βπ‘", group = GRP1, inline = "divFill")
color divFillDnColorInput = input.color(MAROON_MD, "π‘", group = GRP1, inline = "divFill")
color divFillNtColorInput = input.color(GRAY_MD, "N", group = GRP1, inline = "divFill")
string divChannelLevelsInput = input.string(CH1, "βββLevels are defined using", group = GRP1, options = [CH1, CH2])
string divChannelBreachesInput = input.string(BR1, "βββBreaches are determined using", group = GRP1, options = [BR1, BR2, BR3, BR4, BR5, BR6, BR7, BR8])
bool divChannelBiasInput = input.string("Off", "βββEstimate unbreached channel bias", group = GRP1, options = ["On", "Off"], tooltip = TT_BIAS) == "On"
string GRP2 = "Other visuals"
string colorBarModeInput = input.string(CB2, "Bar colors", group = GRP2, inline = "barMode", options = [CB0, CB1, CB2, CB3, CB4])
bool barsEmptyOnDecVolInput = input.bool(false, "Don't color falling volume bars", group = GRP2, inline = "barMode", tooltip = TT_BARS)
color barsUpUpColorInput = input.color(LIME, "βββββπ‘π‘", group = GRP2, inline = "barColors")
color barsDnDnColorInput = input.color(PINK, "π‘π‘", group = GRP2, inline = "barColors")
color barsUpColorInput = input.color(TEAL, "π‘", group = GRP2, inline = "barColors")
color barsDnColorInput = input.color(MAROON, "π‘", group = GRP2, inline = "barColors")
color barsNtColorInput = input.color(GRAY, "N", group = GRP2, inline = "barColors")
color barsDivColorInput = input.color(ORANGE, "D", group = GRP2, inline = "barColors")
bool showCharDivInput = input.bool(false, "Divergence mark", group = GRP2, inline = "divChar")
string charDivInput = input.string("β’", "", group = GRP2, inline = "divChar")
color charDivColorInput = input.color(ORANGE, "", group = GRP2, inline = "divChar")
bool charDivAboveInput = input.bool(true, "Above bar", group = GRP2, inline = "divChar", tooltip = TT_DIV)
bool showTooltipsInput = input.bool(false, "Tooltips of raw values", group = GRP2)
bool showInfoBoxInput = input.bool(true, "Information box", group = GRP2, tooltip = TT_LTF_BOX)
string infoBoxSizeInput = input.string("small", "ββ", group = GRP2, inline = "infoBox", options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "β", group = GRP2, inline = "infoBox", options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "β", group = GRP2, inline = "infoBox", options = ["left", "center", "right"])
color infoBoxColorInput = input.color(GRAY_MD, "", group = GRP2, inline = "infoBox")
color infoBoxTxtColorInput = input.color(BLACK, "T", group = GRP2, inline = "infoBox")
string GRP3 = "Marker/Alert conditions"
string markerUpDvModeInput = input.string(ST0, "Up markers on transitions toββ", group = GRP3, inline = "upMarker", options = [ST0, ST1, ST2])
string markerUpDivModeInput = input.string(SV0, "", group = GRP3, inline = "upMarker", options = [SV0, SV1, SV2])
color markerUpColorInput = input.color(ORANGE_BR, "π‘", group = GRP3, inline = "upMarker", tooltip = TT_MARKERS)
string markerDnDvModeInput = input.string(ST0, "Down markers on transitions to", group = GRP3, inline = "dnMarker", options = [ST0, ST3, ST4])
string markerDnDivModeInput = input.string(SV0, "", group = GRP3, inline = "dnMarker", options = [SV0, SV3, SV4])
color markerDnColorInput = input.color(ORANGE_BR, "π‘", group = GRP3, inline = "dnMarker")
bool markerBarPolarityInput = input.bool(false, "Filter on bar polarityββ", group = GRP3, inline = "Filters1")
bool markerClosePolarityInput= input.bool(false, "Filter on close-to-close polarity", group = GRP3, inline = "Filters1", tooltip = TT_FILTERS)
bool markerCciStateInput = input.bool(false, "Filter on bull/bear CCIβββββ", group = GRP3, inline = "Filters2")
bool markerRisingVolInput = input.bool(false, "Filter on rising volume", group = GRP3, inline = "Filters2")
bool markerDivInput = input.bool(false, "Filter on divergence in last n bars", group = GRP3, inline = "Filters3")
int markerDivBarsInput = input.int(5, "", group = GRP3, inline = "Filters3", minval = 1)
bool markerEwInput = input.bool(false, "Filter on bull/bear Efficient Work", group = GRP3, inline = "Filters4")
string alertUpMsgInput = input.text_area("β²", "Up alert text", group = GRP3)
string alertDnMsgInput = input.text_area("βΌ", "Down alert text", group = GRP3)
//#endregion
//#region ββββββββββββββββββββ Functions
//@function Determines when a state is entered on a bar where the previous state was different.
//@param state (series bool) The state whose transition into must be identified.
//@returns (series bool) `true` on the bar where we transition into the state, `false` otherwise.
transitionTo(series bool state) =>
bool result = (not state[1] and state)
//@function Determines a "plot_style" to be used from a user's input.
//@param state (input string) The user selection string of his line style choice (depends on the `STL1`, `STL2` and `STL3` string constants).
//@returns (plot_style) The `style` named argument required in `plot()`.
lineStyleFromUserInput(userSelection) =>
result = switch userSelection
STL1 => plot.style_line
STL2 => plot.style_circles
STL3 => plot.style_cross
=> plot.style_line
//#endregion
//#region ββββββββββββββββββββ Calculations
// Lower timeframe (LTF) used to mine intrabars.
var string intrabarTf = PCltf.ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10)
// Get two arrays, one each for up and dn volumes of intrabars. `dnVolumes` values are negative.
[upVolumes, dnVolumes] = request.security_lower_tf(syminfo.tickerid, intrabarTf, LucfTa.upDnIntrabarVolumesByPolarity())
// Total up/dn volumes for intrabars.
float totalUpVolume = array.sum(upVolumes)
float totalDnVolume = array.sum(dnVolumes)
// Total volume for intrabars.
float intrabarVolume = totalUpVolume - totalDnVolume
// Delta volume
float dv = totalUpVolume + totalDnVolume
// Delta volume percent
float dvPct = (dv / intrabarVolume) * 100
float dvWeight = math.abs(dvPct / 100)
// Relative volume weight
float relVolPctRank = ta.percentrank(intrabarVolume, relVolLookbackInput) / 100.
float relVolumeWeight = na(dv) ? na : useRelVolWeightInput ? relVolPctRank : 1
// Combined weight
float combinedWeight = dvWeight * relVolumeWeight
// MAs of reference source and capped dv%-weighted source.
float weightedSource = refSourceInput + (math.sign(dvPct) * math.min(refSourceInput * combinedWeight, sigmaCapInput * ta.stdev(refSourceInput, refLengthInput)))
float reference = LucfTa.ma(refTypeInput, refSourceInput, refLengthInput)
float dvWeightedRef = LucfTa.ma(refTypeInput, weightedSource, refLengthInput)
// Determine bull/bear and strong bull/bear states of the DV channel.
bool dvChannelBull = dvWeightedRef > reference
bool dvChannelBear = not dvChannelBull
bool dvChannelBullStrong = dvChannelBull and close > reference and ta.rising(reference, 1) and ta.rising(dvWeightedRef, 1)
bool dvChannelBearStrong = dvChannelBear and close < reference and ta.falling(reference, 1) and ta.falling(dvWeightedRef, 1)
// Intrabar stats
[intrabars, chartBarsCovered, avgIntrabars] = PCltf.ltfStats(upVolumes)
float volumeOnAllIntrabars = ta.cum(intrabarVolume)
float allIntrabars = ta.cum(intrabars)
// Error detection
if volumeOnAllIntrabars == 0 and barstate.islast
runtime.error("No volume is provided by the data vendor.")
else if allIntrabars == 0 and barstate.islast
runtime.error("No intrabar information exists at the '" + intrabarTf + "' timeframe.")
// βββββ Divergence channel
// Detect divergences between the slope of the reference line and that of the DV-weighted line.
bool divergence = dv != 0 and math.sign(ta.change(reference)) != math.sign(ta.change(dvWeightedRef))
// Level sources
float divChannelHiSrc = divChannelLevelsInput == CH1 ? high : math.max(open, close)
float divChannelLoSrc = divChannelLevelsInput == CH1 ? low : math.min(open, close)
// Breach sources
[divBreachHiSrc, divBreachLoSrc] =
switch divChannelBreachesInput
BR1 => [low, high]
BR2 => [high, low]
BR3 => [close, close]
BR4 => [open, open]
BR5 => [hl2, hl2]
BR6 => [hlc3, hlc3]
BR7 => [hlcc4, hlcc4]
BR8 => [ohlc4, ohlc4]
=> [float(na), float(na)]
// Update the divergence channel.
[divChannelHi, divChannelLo, divChannelBull, divChannelBear, divChannelBreached, newDivChannel, preBreachUpChanges, preBreachDnChanges] =
LucfTa.divergenceChannel(divergence, divChannelHiSrc, divChannelLoSrc, divBreachHiSrc, divBreachLoSrc)
// If needed, take a guess on the state of the channel when it has not yet been breached.
bool preBreachBiasBull = not divChannelBreached and divChannelBiasInput and preBreachUpChanges > preBreachDnChanges
bool preBreachBiasBear = not divChannelBreached and divChannelBiasInput and preBreachUpChanges < preBreachDnChanges
// Strong bull/bear states occur when the divergence channel's bull/bear state matches that of the DV channel.
bool divChannelBullStrong = divChannelBull and dvChannelBullStrong
bool divChannelBearStrong = divChannelBear and dvChannelBearStrong
// βββββ Marker filters and triggers
// Bar polarity
bool barUp = close > open
bool barDn = close < open
// Close-to-close polarity
bool closeToCloseUp = ta.change(close) > 0
bool closeToCloseDn = ta.change(close) < 0
// CCI bull/bear
float cciSignal = ta.cci(close, refLengthInput)
bool cciBull = cciSignal > 0
bool cciBear = cciSignal < 0
// RIsing volume
bool risingVolume = ta.change(volume) > 0
// Divergence in last n bars
bool divPresent = ta.barssince(divergence) <= markerDivBarsInput
// Efficient work
float ew = LucfTa.efficientWork(refLengthInput)
bool ewBull = ew > 0
bool ewBear = ew < 0
// Base conditions for markers to appear.
bool upMarkerDvCondition =
switch markerUpDvModeInput
ST1 => transitionTo(dvChannelBullStrong)
ST2 => transitionTo(dvChannelBull) or transitionTo(dvChannelBullStrong)
=> false
bool upMarkerDivCondition =
switch markerUpDivModeInput
SV1 => transitionTo(divChannelBullStrong)
SV2 => transitionTo(divChannelBull) or transitionTo(divChannelBullStrong)
=> false
bool dnMarkerDvCondition =
switch markerDnDvModeInput
ST3 => transitionTo(dvChannelBearStrong)
ST4 => transitionTo(dvChannelBear) or transitionTo(dvChannelBearStrong)
=> false
bool dnMarkerDivCondition =
switch markerDnDivModeInput
SV3 => transitionTo(divChannelBearStrong)
SV4 => transitionTo(divChannelBear) or transitionTo(divChannelBearStrong)
=> false
// Apply filters to base conditions.
bool upMarker = upMarkerDvCondition or upMarkerDivCondition
bool dnMarker = dnMarkerDvCondition or dnMarkerDivCondition
upMarker :=
(markerUpDvModeInput != ST0 or markerUpDivModeInput != SV0) and upMarker and barstate.isconfirmed and
(not markerBarPolarityInput or barUp) and
(not markerClosePolarityInput or closeToCloseUp) and
(not markerCciStateInput or cciBull) and
(not markerRisingVolInput or risingVolume) and
(not markerDivInput or divPresent) and
(not markerEwInput or ewBull)
dnMarker :=
(markerDnDvModeInput != ST0 or markerDnDivModeInput != SV0) and dnMarker and barstate.isconfirmed and
(not markerBarPolarityInput or barDn) and
(not markerClosePolarityInput or closeToCloseDn) and
(not markerCciStateInput or cciBear) and
(not markerRisingVolInput or risingVolume) and
(not markerDivInput or divPresent) and
(not markerEwInput or ewBear)
//#endregion
//#region ββββββββββββββββββββ Visuals
// βββββ DV Channel lines and fill.
// Determine colors.
[refLineColor, dvLineColor, dvFillColor] =
switch
dvChannelBullStrong => [refLineUpUpColorInput, dvLineUpUpColorInput, dvFillUpUpColorInput]
dvChannelBearStrong => [refLineDnDnColorInput, dvLineDnDnColorInput, dvFillDnDnColorInput]
dvChannelBull => [refLineUpColorInput, dvLineUpColorInput, dvFillUpColorInput]
dvChannelBear => [refLineDnColorInput, dvLineDnColorInput, dvFillDnColorInput]
=> [color(na), color(na), color(na)]
color dvColor = dv > 0 ? dvLineUpUpColorInput : dv < 0 ? dvLineDnDnColorInput : color.silver
// Styles for lines.
var refLineStyle = lineStyleFromUserInput(refLineStyleInput)
var dvLineStyle = lineStyleFromUserInput(dvLineStyleInput)
// Plot lines and fill them.
var bool plotDvLineValues = reflLineShowInput or dvlLineShowInput or dvFillShowInput
dvRefPlot = plot(plotDvLineValues ? dvWeightedRef : na, "DV-weighted Reference", dvlLineShowInput ? dvLineColor : na, dvLineWidthInput, dvLineStyle)
refPlot = plot(plotDvLineValues and not na(dv) ? reference : na, "Reference", reflLineShowInput ? refLineColor : na, refLineWidthInput, refLineStyle)
fill(dvRefPlot, refPlot, reference, dvWeightedRef, dvFillShowInput ? dvFillColor : na, dvFillShowInput ? color.new(dvFillColor, 90) : na, "Fill")
// βββββ Divergence channel lines and fill.
// Determine colors.
[divLinesColor, divFillColor] =
switch
divChannelBreached =>
switch
divChannelBullStrong => [divLinesUpUpColorInput, divFillUpUpColorInput]
divChannelBearStrong => [divLinesDnDnColorInput, divFillDnDnColorInput]
divChannelBull => [divLinesUpColorInput, divFillUpColorInput]
divChannelBear => [divLinesDnColorInput, divFillDnColorInput]
=> [divLinesNtColorInput, divFillNtColorInput]
=>
switch
divChannelBiasInput and preBreachBiasBull => [divLinesUpColorInput, divFillUpColorInput]
divChannelBiasInput and preBreachBiasBear => [divLinesDnColorInput, divFillDnColorInput]
=> [divLinesNtColorInput, divFillNtColorInput]
// Plot the channel levels and fill.
var bool plotDivLineValues = divLinesShowInput or divFillShowInput
var divLineStyle = lineStyleFromUserInput(divLinesStyleInput)
float divChannelMid = math.avg(divChannelHi, divChannelLo)
divChannelHiPlot = plot(plotDivLineValues ? divChannelHi : na, "Divergence Channel Hi", not newDivChannel and divLinesShowInput ? divLinesColor : na, divLinesWidthInput, divLineStyle)
divChannelLoPlot = plot(plotDivLineValues ? divChannelLo : na, "Divergence Channel Lo", not newDivChannel and divLinesShowInput ? divLinesColor : na, divLinesWidthInput, divLineStyle)
// This midline is used to start/end the two different gradient fills used to fill the divergence channel.
divChannelMidPlot = plot(plotDivLineValues ? divChannelMid : na, "Divergence Channel Mid", na, display = display.none)
// Fill from the middle going up and down.
fill(divChannelHiPlot, divChannelMidPlot, divChannelHi, divChannelMid, not newDivChannel and divFillShowInput ? divFillColor : na, not newDivChannel and divFillShowInput ? color.new(divFillColor, 99) : na)
fill(divChannelMidPlot, divChannelLoPlot, divChannelMid, divChannelLo, not newDivChannel and divFillShowInput ? color.new(divFillColor, 99) : na, not newDivChannel and divFillShowInput ? divFillColor : na)
// βββββ Display key values in indicator values and Data Window.
float signedDvWeight = dvPct / 100
float signedCombinedWeight = math.sign(signedDvWeight) * combinedWeight
displayLocations = display.status_line + display.data_window
plot(na, "βββββββββββββββββ", display = displayLocations)
plot(signedDvWeight, "DV% weight (1=100%)", display = displayLocations, color = dvColor)
plot(relVolumeWeight, "Relative Volume weight", display = displayLocations)
plot(signedCombinedWeight, "Combined weight", display = displayLocations, color = dvColor)
plot(na, "βββββββββββββββββ", display = displayLocations)
plot(dv, "Volume delta", display = displayLocations, color = dvColor)
plot(totalUpVolume, "Up volume for the bar", display = displayLocations, color = dvLineUpUpColorInput)
plot(totalDnVolume, "Dn volume for the bar", display = displayLocations, color = dvLineDnDnColorInput)
plot(intrabarVolume, "Total intrabar volume", display = displayLocations)
plot(na, "βββββββββββββββββ", display = displayLocations)
plot(intrabars, "Intrabars in this bar", display = displayLocations)
plot(avgIntrabars, "Average intrabars", display = displayLocations)
plot(chartBarsCovered, "Chart bars covered", display = displayLocations)
plot(bar_index + 1, "Chart bars", display = displayLocations)
// βββββ Markers
plotchar(upMarker, "Up Marker", "β²", location.belowbar, markerUpColorInput, size = size.tiny)
plotchar(dnMarker, "Down Marker", "βΌ", location.abovebar, markerDnColorInput, size = size.tiny)
// βββββ Alerts
switch
upMarker => alert(alertUpMsgInput)
dnMarker => alert(alertDnMsgInput)
// βββββ Chart bars.
// Color
color barColor =
switch colorBarModeInput
CB0 =>
na
CB1 =>
switch
divergence => barsDivColorInput
CB2 =>
switch
divergence => barsDivColorInput
dvChannelBullStrong => barsUpUpColorInput
dvChannelBearStrong => barsDnDnColorInput
dvChannelBull => barsUpColorInput
dvChannelBear => barsDnColorInput
=> barsNtColorInput
CB3 =>
switch
divergence => barsDivColorInput
divChannelBullStrong => barsUpUpColorInput
divChannelBearStrong => barsDnDnColorInput
divChannelBull => barsUpColorInput
divChannelBear => barsDnColorInput
=> barsNtColorInput
CB4 =>
switch
divergence => barsDivColorInput
dvChannelBullStrong and divChannelBullStrong => barsUpUpColorInput
dvChannelBearStrong and divChannelBearStrong => barsDnDnColorInput
(dvChannelBull or dvChannelBullStrong) and (divChannelBull or divChannelBullStrong) => barsUpColorInput
(dvChannelBear or dvChannelBearStrong) and (divChannelBear or divChannelBearStrong) => barsDnColorInput
=> barsNtColorInput
=> na
// Empty bodies on decreasing chart volume.
if barsEmptyOnDecVolInput and ta.falling(volume, 1) and not divergence
barColor := na
barcolor(barColor)
// βββββ Plot character showing divergences.
plotchar(showCharDivInput ? divergence : na, "Divergence character", charDivInput, charDivAboveInput ? location.abovebar : location.belowbar, charDivColorInput, size = size.tiny)
// βββββ Tooltips containing bar stats.
if showTooltipsInput
string tooltipText =
"DV = " + str.tostring(totalUpVolume, format.volume) +
"βββ" + str.tostring(math.abs(totalDnVolume), format.volume) +
" = " + str.tostring(dv, format.volume) +
"\nDV% = " + str.tostring(dv, format.volume) +
"β/ " + str.tostring(intrabarVolume, format.volume) +
" = " + str.tostring(dvPct, format.percent) +
str.format("\n\nDV weight = {0,number,0.000}\nRelVol weight = {1,number,0.000}\nCombined weight = {2,number,0.000}", signedDvWeight, relVolumeWeight, signedCombinedWeight)
label.new(bar_index, high, "β\nβ\nβ\nβ\nβ\nβ\nβ", style = label.style_none, color = color(na), tooltip = tooltipText)
// βββββ Display information box only once on the last historical bar because it doesn't need to update in real time.
// Display information box only once on the last historical bar, instead of on all realtime updates, as when `barstate.islast` is used.
if showInfoBoxInput and barstate.islastconfirmedhistory
var table infoBox = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
color infoBoxBgColor = infoBoxColorInput
string txt = str.format(
"Uses intrabars at {0}\nAvg intrabars per chart bar: {1,number,#.##}\nChart bars covered: {2}β/β{3} ({4,number,percent})",
PCtime.formattedNoOfPeriods(timeframe.in_seconds(intrabarTf) * 1000),
avgIntrabars, chartBarsCovered, bar_index + 1, chartBarsCovered / (bar_index + 1))
if avgIntrabars < 5
txt += "\nThis quantity of intrabars is dangerously small.\nResults will not be as reliable with so few."
infoBoxBgColor := color.red
table.cell(infoBox, 0, 0, txt, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxBgColor)
//#endregion
|
Divergence Detector | https://www.tradingview.com/script/aGVsqaph-Divergence-Detector/ | reees | https://www.tradingview.com/u/reees/ | 512 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© reees
//@version=5
indicator("Divergence Detector",overlay=true,max_lines_count=500,max_labels_count=50)
import reees/Utilities/1 as u
//-----------------------------------------
// inputs
//-----------------------------------------
var iType = input.string("RSI","Indicator", options=["RSI","OBV"], group="Indicator")
var iLength = input.int(14,"Length", minval=1, group="Indicator")
var bullSwitch = input.bool(true, "Show bullish", inline="dswitch", group="Divergence Params")
var bearSwitch = input.bool(true, "Show bearish", inline="dswitch", group="Divergence Params")
var showHidden = input.bool(true, "Show hidden", inline="dswitch", group="Divergence Params")
var ppLength = input.int(3,"Previous pivot bars before/after",minval=1,group="Divergence Params",tooltip="Min # bars before and after a previous pivot high/low to consider it valid for divergence check")
var cpLengthBefore = input.int(3,"Next (divergent) pivot bars before",minval=1,group="Divergence Params",tooltip="Min # leading bars before the next (divergent) pivot high/low to consider it valid for divergence check")
var cpLengthAfter = input.int(2,"Next (divergent) pivot bars after",minval=1,group="Divergence Params",tooltip="# trailing bars after the next (divergent) pivot high/low to consider it valid for divergence check. Decreasing this value may detect divergence sooner, but with less confidence.")
var lbBars = input.int(50,"Look back bars",minval=1,group="Divergence Params",tooltip="# of bars to look back for a previous pivot high/low. If you increase this value, you may also want to increase the pivot lengths above, or switch to a higher timeframe.")
bullPsource = input.source(low,"Bullish divergence price source",group="Divergence Params")
bearPsource = input.source(high,"Bearish divergence price source",group="Divergence Params")
var noBroken = input.bool(true,"Exclude if broken trendline",group="Divergence Params",tooltip="If set, divergence is not considered valid if an intermediate pivot high/low breaks the divergence trendline (on a linear scale). If using a logarithmic scale, you may want to turn this switch off as some trendlines that are broken on a linear scale may not be broken on a log scale.")
//-----------------------------------------
// functions
//-----------------------------------------
// TODO: move to TA library
// @function Test for bullish divergence
div_bull(s,pivot_length=3,cp_length_before=3,cp_length_after=2,draw_label=true,lookback=50) =>
p = ta.pivotlow(bullPsource,pivot_length,pivot_length)
cpp = ta.pivotlow(bullPsource,cp_length_before,cp_length_after)
flag = false
degree = 0.0
type = 0
pWeight=.8
iWeight=1.2
hidWeight=.75
regWeight=1.25
// if price is pivoting low...
if not na(cpp)
// check last <#> bars before current pivot low for any previous pivot low
for i=cp_length_after to lookback+cp_length_after
if not na(p[i])
// test for divergence
if p[i] > bullPsource[cp_length_after] and s[i+pivot_length] < s[cp_length_after]
flag := true
degree := ((p[i]-bullPsource[cp_length_after])/p[i]*pWeight + (s[cp_length_after]-s[i+pivot_length])/s[cp_length_after]*iWeight)*regWeight
type := 1
else if (p[i] < bullPsource[cp_length_after] and s[i+pivot_length] > s[cp_length_after]) and showHidden
flag := true
degree := ((bullPsource[cp_length_after]-p[i])/bullPsource[cp_length_after]*pWeight + (s[i+pivot_length]-s[cp_length_after])/s[i+pivot_length]*iWeight)*hidWeight
type := 2
// if divergence exists, draw line and label
if flag == true
lx1 = bar_index-i-pivot_length
lx2 = bar_index-cp_length_after
dLine = line.new(lx1,p[i],lx2,bullPsource[cp_length_after],color=color.new(color.green,30),width=1)
if noBroken == true
// invalidate divergence if an intermediate low breaks divergence trendline
for k=lx1 to lx2
if bullPsource[bar_index-k] < (line.get_price(dLine,k)*.99)
flag := false
degree := 0
type := 0
line.delete(dLine)
break
if flag==true and draw_label==true
ltxtD = if degree > .75
"Extreme"
else if degree > .5
"Very Strong"
else if degree > .25
"Strong"
else if degree > .1
"Moderate"
else
"Minimal"
ltxt="Type: Bullish"+(type==2?" hidden":"")+" divergence\nDegree: "+ltxtD
ltxt2=""
trans=50
if degree > .75
ltxt2:="!!!"
trans:=10
else if degree > .5
ltxt2:="!!"
trans:=20
else if degree > .25
ltxt2:="!"
trans:=30
label.new(lx2,bullPsource[cp_length_after],tooltip=ltxt,text=ltxt2,textalign=text.align_center,style=label.style_label_up,size=size.tiny,color=color.new(color.green,trans),textcolor=color.white)
break
[flag,degree,type]
// TODO: move to TA library
// @function Test for bearish divergence
div_bear(s,pivot_length=3,cp_length_before=3,cp_length_after=2,draw_label=true,lookback=50) =>
p = ta.pivothigh(bearPsource,pivot_length,pivot_length)
cpp = ta.pivothigh(bearPsource,cp_length_before,cp_length_after)
flag = false
degree = 0.0
type = 0
pWeight=.8
iWeight=1.2
hidWeight=.75
regWeight=1.25
// if price is pivoting high...
if not na(cpp)
// check last <#> bars before current pivot high for any previous pivot high
for i=cp_length_after to lookback+cp_length_after
if not na(p[i])
// test for divergence
if (p[i] > bearPsource[cp_length_after] and s[i+pivot_length] < s[cp_length_after]) and showHidden
flag := true
degree := ((p[i]-bearPsource[cp_length_after])/p[i]*pWeight + (s[cp_length_after]-s[i+pivot_length])/s[cp_length_after]*iWeight)*hidWeight
type := 2
else if p[i] < bearPsource[cp_length_after] and s[i+pivot_length] > s[cp_length_after]
flag := true
degree := ((bearPsource[cp_length_after]-p[i])/bearPsource[cp_length_after]*pWeight + (s[i+pivot_length]-s[cp_length_after])/s[i+pivot_length]*iWeight)*regWeight
type := 1
// if divergence exists, draw line and label
if flag == true
lx1 = bar_index-i-pivot_length
lx2 = bar_index-cp_length_after
dLine = line.new(lx1,p[i],lx2,bearPsource[cp_length_after],color=color.new(color.red,30),width=1)
if noBroken == true
// invalidate divergence if an intermediate high breaks divergence trendline
for k=lx1 to lx2
if bearPsource[bar_index-k] > (line.get_price(dLine,k)*1.01)
flag := false
degree := 0
type := 0
line.delete(dLine)
break
if flag==true and draw_label==true
ltxtD = if degree > .75
"Extreme"
else if degree > .5
"Very Strong"
else if degree > .25
"Strong"
else if degree > .1
"Moderate"
else
"Minimal"
ltxt="Type: Bearish"+(type==2?" hidden":"")+" divergence\nDegree: "+ltxtD
ltxt2=""
trans=50
if degree > .75
ltxt2:="!!!"
trans:=10
else if degree > .5
ltxt2:="!!"
trans:=20
else if degree > .25
ltxt2:="!"
trans:=30
label.new(lx2,bearPsource[cp_length_after],tooltip=ltxt,text=ltxt2,textalign=text.align_center,style=label.style_label_down,size=size.tiny,color=color.new(color.red,trans),textcolor=color.white)
break
[flag,degree,type]
//-----------------------------------------
// data/vars
//-----------------------------------------
// TODO: Add support for MACD, etc
i_bear = if iType=="OBV"
ta.obv
// MACD coming soon...
// else if iType=="MACD"
// [_,_,m]=ta.macd(bearPsource,12,26,9)
// m
else
ta.rsi(bearPsource, iLength)
i_bull = if iType=="OBV"
ta.obv
// MACD coming soon...
// else if iType=="MACD"
// [_,_,m]=ta.macd(bearPsource,12,26,9)
// m
else
ta.rsi(bullPsource, iLength)
//-----------------------------------------
// test for divergence
//-----------------------------------------
if bearSwitch==true
div_bear(i_bear,ppLength,cpLengthBefore,cpLengthAfter,lookback=lbBars)
if bullSwitch==true
div_bull(i_bull,ppLength,cpLengthBefore,cpLengthAfter,lookback=lbBars) |
TPO Profile with Day Stat | https://www.tradingview.com/script/ZWlDJchT-TPO-Profile-with-Day-Stat/ | Vignesh_vish | https://www.tradingview.com/u/Vignesh_vish/ | 520 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Vignesh_vish
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© noop42
//@version=5
indicator("TPO with Day Stat", overlay=true, max_bars_back=5000, max_boxes_count = 500, max_lines_count = 500)
IBRcheck=input.bool(true,"Show/ Hide IBR",group="IBR")
dataLabelCheck=input.bool(true,"Show/ Hide Data-Label",group="Data Label")
dataLabelColor=input.color(color.black,"Data Label Color",group="Data Label")
IBlineColor=input.color(color.new(color.white,0),"IB Line Color",group="IBR")
secu(tikr, res, source,pre=0) =>
request.security(tikr, res, source[pre], lookahead=barmerge.lookahead_on)
currentBarState=secu(syminfo.ticker,"D",barstate.isrealtime)?1:0
mkt_start_hh=09
mkt_start_mm=15
mkt_end_hh=15
mkt_end_mm=25
ib_session=""
session = ""
MM=15
if syminfo.prefix=="NSE" or syminfo.prefix=="BSE"
mkt_start_hh:=09
mkt_start_mm:=15
mkt_end_hh:=15
mkt_end_mm:=25
ib_session:="0915-1015"
session:="0915-1515"
MM:=30
else if syminfo.prefix=="MCX"
mkt_start_mm:=00
mkt_end_hh:=23
ib_session:="0900-1000"
session:="0000-2300"//input.session("0930-1600", title="Session calculation", group="Session configuration")
MM:=15
var string Ibtimes= na
var ibRange = 0.0
var ibhigh =0.0
var iblow =0.0
var sessionBarCount = 0
ib = na(time('D', ib_session + ':23456')) == false
drange() =>
math.round(secu(syminfo.ticker, 'D', high) - secu(syminfo.ticker, 'D', low),0)
if ib
ibRange := math.round(secu(syminfo.ticker, '60', high) - secu(syminfo.ticker, '60', low),0)
ibhigh := secu(syminfo.ticker, '60', high)
iblow :=secu(syminfo.ticker, '60', low)
nl = '\n'
Ibtimes:=math.round((drange()/ibRange),1)>=2?" ("+str.tostring(int((drange()/ibRange)))+"-IB)":na
//1000->1K 100000->1L Convertor
numberShort(number) =>
len = str.length(str.tostring(number))
if len >= 4 //and len <= 5
str.tostring(math.round(number / 1000, 0)) + "K"
else if len < 4
str.tostring(number)
vix() =>
str.tostring(math.round(secu("INDIAVIX","D",close),2))+" ("+str.tostring(math.round(((secu("INDIAVIX","D",close)-secu("INDIAVIX","D",close[1]))/secu("INDIAVIX","D",close[1]))*100,2))+"%)"
_atr() =>
str.tostring(math.round(ta.atr(14), 0))+" ("+str.tostring(math.round(secu(syminfo.ticker,"D",ta.atr(14)), 0))+")"
dayVolume(tf) =>
dayVol = if syminfo.ticker == 'NIFTY'
secu('NIFTY1!', tf, volume)
else if syminfo.ticker == 'BANKNIFTY'
secu('BANKNIFTY1!', tf, volume)
else
secu(syminfo.ticker, tf, volume)
numberShort(dayVol)
futspotpricediff = if syminfo.ticker == 'NIFTY' or syminfo.ticker == 'NIFTY1!'
secu('NIFTY1!', timeframe.period, close) - secu('NIFTY', timeframe.period, close)
else if syminfo.ticker == 'BANKNIFTY' or syminfo.ticker == 'BANKNIFTY1!'
secu('BANKNIFTY1!', timeframe.period, close) - secu('BANKNIFTY', timeframe.period, close)
//combaine Text and and formatting
strHelper(prefix, stat) =>
res = str.tostring(stat)
nl + prefix + ': ' + res
dynamicText() =>
strHelper('IBR', str.tostring(ibRange)+Ibtimes) + strHelper('Day Range', drange()) + strHelper('Day Volume', dayVolume('D')) + strHelper('ATR', _atr()) + strHelper('VIX', vix()) + strHelper('Fut Delta', futspotpricediff)
_label(barInx) =>
x1=timestamp(year(time), month(time), dayofmonth(time), mkt_start_hh, mkt_start_mm, 00)
x2=timestamp(year(time), month(time), dayofmonth(time), mkt_end_hh, mkt_end_mm, 00)
if dataLabelCheck
lbl = label.new(x1, secu(syminfo.ticker, 'D', low) - (syminfo.mintick * 5), dynamicText(),xloc=xloc.bar_time, style=label.style_label_upper_left, textalign=text.align_left, color=color.new(#d0cec2,100), textcolor=dataLabelColor)
if ta.barssince(ta.change(time("D")))>=1 or dayofmonth(time)==dayofmonth(chart.left_visible_bar_time)
label.delete(lbl[1])
if IBRcheck
linib=line.new(x1,ibhigh,x1,iblow,xloc.bar_time,color=IBlineColor,width=2,style= line.style_solid)
if ta.barssince(ta.change(time("D")))>=1 or dayofmonth(time)==dayofmonth(chart.left_visible_bar_time)
line.delete(linib[1])
day= switch dayofweek(timenow)
1 => "Sunday"
2 => "Monday"
3 => "Tuesday"
4 => "Wednesday"
5 => "Thursday"
6 => "Friday"
7 => "Saturday"
holydaycolor= dayofweek(timenow) == 1 or dayofweek(timenow) == 7 ?color.new(color.red,50):color.new(color.teal,50)
daytable=table.new(position.bottom_right,columns=1,rows=1,border_width=0)
if barstate.islast
table.cell(table_id=daytable,column=0,row=0,text=day,bgcolor=color.new(color.teal,50))
if ta.change(time("D"))
sessionBarCount:=1
if (ta.barssince(ta.change(time("D")))>=1 or ta.change(time("D"))) and (timeframe.period== "30" or timeframe.period == "5" or timeframe.period=="15" or timeframe.period=="1") and (syminfo.prefix=="NSE" or syminfo.prefix=="BSE_DLY" or syminfo.prefix=="MCX") and time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
sessionBarCount += 1
_label(sessionBarCount - 2)
from=0
var TRangeRMA=0.0
// auto tick size
TrRMA(tf,pre)=>
tRange=math.max(secu(syminfo.ticker,tf,high)-secu(syminfo.ticker,tf,low),math.abs(secu(syminfo.ticker,tf,high)-secu(syminfo.ticker,tf,close[1])),math.abs(secu(syminfo.ticker,tf,low)-secu(syminfo.ticker,tf,close[1])))
ta.rma(tRange,pre)
if timeframe.period=="30"
from:= 90
if ta.change(time("D"))
divisor=0.0
if syminfo.prefix=="NSE" or syminfo.prefix=="BSE"
divisor:=2.5
else if syminfo.prefix=="MCX"
divisor:=80
TRangeRMA:=(TrRMA("D",14))/divisor
auto_tick_size = input.bool(true,"Auto Tick Size",group="Global Options")
float tick_size = 0.0
if auto_tick_size==true
tick_size :=(TRangeRMA*syminfo.mintick)
else
tick_size := input.int(25, "Ticks number per tpo", group="Global Options") * syminfo.mintick
round_values = input.bool(true, "Round TPO levels on Tick number", group="Global Options")
letters_size = input.string("Small", options=["Normal", "Small", "Tiny"], title="TPO letters size", group="Global Options")
extend_levels = input.bool(false, "Extend yesterday's levels", group="Global Options")
show_va_background = input.bool(false, "Show Market Profile calculation area background", group="Global Options")
va_bg_color=input.color(color.new(#2a2e39,90), "Value area background color", group="Global Options")
show_histogram = input.bool(true, "Show TPO's", group="Global Options")
tpo_va_color = input.color(color.new(#2962ff,0), "TPO Color (in VA)", group="Global Options")//787b86
tpo_nova_color = input.color(color.new(color.black,0), "TPO Color (out of VA)", group="Global Options")//9598a1
limits_color=input.color(color.black, "High and Low colors", group="Highs & Lows")
show_high_low = input.bool(false, "Show high/low levels", group="Highs & Lows")
poc_col = input.color(#2962ff, "POC color", group="POC Options")//
show_poc = input.bool(true, "Show POC as line", group="POC Options")
show_poc_tpo_count=input.bool(true, "Show POC TPO Count", group="POC Options")
show_initial_balance = input.bool(true, "Show Initial Balance", group="IB")
ib_color = input.color(#ffffff, "IB Color", group="IB")
va_line_color = input.color(#ffffff, "Value area lines color", group="Value area options")
show_va_lines = input.bool(true, "Show value areas as lines",group="Value area options")
va_percent = input.int(70, "Value area percent",group="Value area options") / 100
show_singleprints = input.bool(true, "Highlight Single prints", group="Single prints")
sp_col = input.color(#0F4D92, "Single prints color", group="Single prints")//#2962ff 8caad8
extend_sp = input.bool(true, "Extend single prints", group="Single prints")
sp_ext_trans = input.int(80, "Extended single prints transparency", group="Single prints", minval=0, maxval=100)
open_color = input.color(color.yellow, "Opening price color", group="Open/Close")
close_color = input.color(#ff0000, "Closing price color", group="Open/Close")
tpo_spacing = input.int(1, "TPO Spacing")
inSession(sess) => na(time(timeframe.period, sess)) == false
sess = inSession(session)
session_over = sess[1] and not sess
session_start = sess and not sess[1]
currentDate=timestamp(year(timenow),month(timenow),dayofmonth(timenow))
plot_history=false
print_as_bars=false
if timestamp(year(timenow),month(timenow),dayofmonth(timenow),hour(timenow),minute(timenow),second(timenow))<=timestamp(year(currentDate),month(currentDate),dayofmonth(currentDate),mkt_end_hh,MM,00)
plot_history:=timestamp(year(time),month(time),dayofmonth(time))>=chart.left_visible_bar_time and timestamp(year(time),month(time),dayofmonth(time))<=timestamp(year(chart.right_visible_bar_time),month(chart.right_visible_bar_time),dayofmonth(chart.right_visible_bar_time))and not(currentBarState)
print_as_bars:=false//input.bool(false, "Display TPO as bars", group="Global Options")// plot_history?true:
else if session_over
plot_history:=timestamp(year(time),month(time),dayofmonth(time))>=chart.left_visible_bar_time and timestamp(year(time),month(time),dayofmonth(time))<=timestamp(year(chart.right_visible_bar_time),month(chart.right_visible_bar_time),dayofmonth(chart.right_visible_bar_time))and not(currentBarState)//timestamp(year(time),month(time),dayofmonth(time))>=timestamp(year(currentDate),month(currentDate),dayofmonth(currentDate)-from)
print_as_bars:=false
letters = input.string("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$β¬Β£{}[]()*+-/=%&?!", "TPO letters")
letters_size_value = letters_size == "Small" ? size.small : letters_size == "Normal" ? size.normal : size.tiny
bars_nb = 0
var line topline = na
var line botline = na
var line vah_line = na
var line val_line = na
var line poc = na
var label poc_tpo_count= na
//var max_score = 0
var poc_price = 0.0
var bars_score = array.new<int>(bars_nb)
var profile_bars = array.new<box>(bars_nb)
var letter_bars = array.new<string>(bars_nb)
var vah_offset = 0
var val_offset = 0
spaces_string(n) =>
r = ""
if n > 0
for i=0 to n
r += " "
r
find_h(x) =>
h = high
for i=0 to x
if high[i] > h
h := high[i]
h
find_l(x) =>
l = low
for i=0 to x
if low[i] < l
l := low[i]
l
count_tpo(x, y) =>
r = 0
for i=x to y
r += array.get(bars_score,i)
r
biggest_tpo(x, y) =>
t1 = array.get(bars_score, x)
t2 = array.get(bars_score, y)
t1 >= t2 ? "h": "l"
var session_candles_count = 0
var poc_position = 0
var total_tpo = 0
var open_price = open
if session_start
session_candles_count := 0
open_price := open
//if candle_offset == candles_nb -1
if session_over and plot_history
ext = extend_levels ? extend.right: extend.none
if extend_levels
line.set_extend(vah_line, extend.none)
line.set_extend(val_line, extend.none)
line.set_extend(poc, extend.none)
line.set_extend(topline, extend.none)
line.set_extend(botline, extend.none)
max_score = 0
total_tpo := 0
h = find_h(session_candles_count)
highest=h
l = find_l(session_candles_count)
bars_nb := int((h-l) / tick_size)
if round_values
h := h+tick_size - (h % tick_size)
l := l - (l % tick_size)
box_width = (h-l) / bars_nb
if show_poc
poc := line.new(bar_index-session_candles_count, 0.0, bar_index, 0.0, color=poc_col, width=2, extend=ext)
if show_poc_tpo_count
poc_tpo_count :=label.new(bar_index,0.0,text="",style=label.style_none, textcolor=tpo_nova_color, size=letters_size_value,textalign=text.align_left)
if show_high_low
topline := line.new(bar_index-session_candles_count, h, bar_index, h, color=limits_color, extend=ext)
botline := line.new(bar_index-session_candles_count, l, bar_index, l, color=limits_color, extend=ext)
// TPO calculation
for i=0 to bars_nb-1
tpo_letters = ""
score = 0
for x=0 to session_candles_count
in_bar = (high[x] <= h and high[x] >= h-box_width) or (low[x] <= h and low[x] >= h-box_width) or (high[x] > h and low[x] < h-box_width)
if in_bar
score += 1
if x <= session_candles_count and session_candles_count <= str.length(letters) -1
tpo_letters := str.substring(letters, session_candles_count-(x), (session_candles_count - (x-1)))+spaces_string(tpo_spacing)+tpo_letters
if score >= max_score
max_score := score
poc_price := h - (box_width/2)
poc_position := i
line.set_y1(poc, poc_price)
line.set_y2(poc, poc_price)
label.set_y(poc_tpo_count,poc_price)
label.set_text(poc_tpo_count,str.tostring(max_score))
if print_as_bars
tpo_letters := ""
array.insert(profile_bars,i, box.new(bar_index-session_candles_count, h, bar_index-(session_candles_count-score), h-box_width, text=tpo_letters, text_size=letters_size_value, text_color=tpo_va_color, text_halign=text.align_left, bgcolor=#00000000, border_color=#00000000))
array.insert(bars_score, i, score)
h -= box_width
total_tpo += score
// VA Calculation
vah_price = 0.0
val_price = 0.0
vah_offset := poc_position > 0 ? poc_position -1 : poc_position
val_offset := poc_position < bars_nb -1 ? poc_position +1 : poc_position
for i=0 to bars_nb-1
d = vah_offset == 0 ? "l" : val_offset == bars_nb-1 ? "h" : biggest_tpo(vah_offset, val_offset)
if d == "h"
vah_offset := vah_offset > 0 ? vah_offset -1 : vah_offset
else
val_offset := val_offset < bars_nb-1 ? val_offset +1 : val_offset
if count_tpo(vah_offset, val_offset) / total_tpo >= va_percent
break
vah_price := box.get_top(array.get(profile_bars, vah_offset))-(box_width/2)
val_price := box.get_bottom(array.get(profile_bars, val_offset))+(box_width/2)
// Set tpo colors
for i=0 to bars_nb-1
bar_col = #00000000
text_col = (i > vah_offset and i < val_offset ? tpo_va_color : tpo_nova_color)
text_col := val_offset == i or vah_offset == i ? tpo_va_color : poc_position == i ? poc_col : (array.get(bars_score, i) == 1 and show_singleprints) ? sp_col : text_col
if not show_histogram
text_col := #00000000
if print_as_bars
if not extend_sp
box.set_border_color(array.get(profile_bars, i), text_col)
box.set_bgcolor(array.get(profile_bars, i), text_col)
if extend_sp and (array.get(bars_score, i) == 1 and show_singleprints)
extended_sp_color = color.new(sp_col, transp=sp_ext_trans)
box.set_right(array.get(profile_bars, i), bar_index-11)
box.set_bgcolor(array.get(profile_bars, i), extended_sp_color)
box.set_text_color(array.get(profile_bars, i), text_col)
//plot vah/val
if show_va_lines
vah_line := line.new(bar_index-session_candles_count, vah_price, bar_index, vah_price, color=va_line_color, extend=ext)
val_line := line.new(bar_index-session_candles_count, val_price, bar_index, val_price, color=va_line_color, extend=ext)
label.new(bar_index-session_candles_count-1, open_price, text="π’", style=label.style_none, textcolor=open_color)
label.new(bar_index-session_candles_count-1, close, text="x", style=label.style_none, textcolor=close_color)
line.new(bar_index-session_candles_count-1, open_price, bar_index-session_candles_count, open_price, color=open_color, width=3)
line.new(bar_index-session_candles_count-1, close, bar_index-session_candles_count, close, color=close_color, width=3)
//if show_initial_balance
// ibh = high[session_candles_count] > high[session_candles_count-1] ? high[session_candles_count] : high[session_candles_count-1]
// ibl = low[session_candles_count] < low[session_candles_count-1] ? low[session_candles_count] : low[session_candles_count-1]
// line.new(bar_index-session_candles_count, ibh, bar_index-session_candles_count, ibl, color=ib_color, width=2)
if show_va_background
box.new(bar_index-session_candles_count, vah_price, bar_index, val_price, bgcolor=va_bg_color, border_color=#00000000)
label.new(bar_index-(session_candles_count/2), highest,text=str.tostring(total_tpo)+" TPO\n", style=label.style_none, textcolor=tpo_va_color, size=size.small)
session_candles_count += 1
|
STD/Clutter Filtered, One-Sided, N-Sinc-Kernel, EFIR Filt [Loxx] | https://www.tradingview.com/script/1QsW0h0R-STD-Clutter-Filtered-One-Sided-N-Sinc-Kernel-EFIR-Filt-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 149 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD/Clutter Filtered, One-Sided, N-Sinc-Kernel, EFIR Filt [Loxx]",
shorttitle = "STDCFOSNSKEFIRF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
duelElementLagReducer(float[] coeff, int LagReductionFactor)=>
if LagReductionFactor > 0
per = array.size(coeff)
for i = per - 1 to 0
if i >= LagReductionFactor
array.set(coeff, i, 2 * array.get(coeff, i) - array.get(coeff, i - LagReductionFactor))
else
array.set(coeff, i, 2 * array.get(coeff, i))
coeff
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
sincKernel(int dpth, float cutoff)=>
float[] kernel = array.new<float>(dpth, 0.)
for i = 0 to dpth - 1
// Center of sinc kernel.
if i - (dpth / 2) == 0
array.set(kernel, i, 2.0 * math.pi * (1 / cutoff))
//Left or right lobe of sinc kernel
if i - (dpth / 2) != 0
array.set(kernel, i, math.sin(2.0 * math.pi * (1 / cutoff) * (i - dpth / 2)) / (i - dpth / 2))
//blackman window
array.set(kernel, i, array.get(kernel, i) * (0.54 - 0.46 * math.cos(2.0 * math.pi * i - dpth / 2)))
// Normalize filter kernel for unity gain at DC.
float sumh = 0
for i = 0 to dpth - 1
sumh += array.get(kernel, i)
for i = 0 to dpth - 1
array.set(kernel, i, array.get(kernel, i) / sumh)
// Slice to right-sided
float[] coeffout = array.slice(kernel, int(dpth / 2) - 1, dpth - 1)
coeffout
ehlerFilter(float src, float[] coeff)=>
float num = 0
float sumCoeff = 0
float out = 0
for k = 0 to array.size(coeff) - 1
num += array.get(coeff, k) * nz(src[k])
sumCoeff += array.get(coeff, k)
out := num/sumCoeff
out
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(100, "Period", group = "Basic Settings")
lagr = input.int(0, "Lag Reduction Factor", group = "Basic Settings")
cutoff = input.float(10, "Kernel Noise Cut-Off", group = "Basic Settings")
sth = input.float(0.1, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFOSNSKEFIRF", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
var array<float> coeffout = array.new<float>(per, 0)
if barstate.isfirst
coeffout := sincKernel(per, cutoff)
duelElementLagReducer(coeffout, lagr)
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
out = ehlerFilter(src, coeffout)
out := filterop == "Both" or filterop == "STDCFOSNSKEFIRF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFOSNSKEFIRF MA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD/Clutter Filtered, One-Sided, N-Sinc-Kernel, EFIR Filt [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD/Clutter Filtered, One-Sided, N-Sinc-Kernel, EFIR Filt [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Stochastic RSI | https://www.tradingview.com/script/PEUmnWqH-Stochastic-RSI/ | kallumks123 | https://www.tradingview.com/u/kallumks123/ | 17 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© kallumks123
//@version=5
//@version=5
indicator(title="Stochastic RSI", shorttitle="Stoch RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
plot(k, "K", color=#2962FF)
plot(d, "D", color=#FF6D00)
h0 = hline(80, "Upper Band", color=#787B86)
hline(50, "Middle Band", color=color.new(#787B86, 50))
h1 = hline(20, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background") |
Trend Surfers - Momentum + ADX + EMA | https://www.tradingview.com/script/kSB1fRyl-Trend-Surfers-Momentum-ADX-EMA/ | TrendSurfersSignals | https://www.tradingview.com/u/TrendSurfersSignals/ | 135 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© TrendSurfersSignals
// This script is a mix between the Lazybear Momentum indicator, ADX indicator and EMA.
// Histogram meaning:
// Green = The momentum is growing and the ADX is growing or above your set value
// Red = The momentum is growing on the down side and the ADX is growing or above your set value
// Orange = The market doesn't have enough momentum or the ADX is not growing or above your value (no trend)
// Background meaning:
// Blue = The price is above the EMA
// Purple = The price is under the EMA
// Cross color on 0 line:
// Dark = The market might be sideway still
// Light = The market is in a bigger move
//@version=5
indicator('Trend Surfers - Momentum + ADX + EMA', 'TS - MOMADXEMA',
overlay=false)
// Momentum
length = input(20, title="BB Length", group = "Momentum")
mult = input(2.0,title="BB MultFactor", group = "Momentum")
lengthKC=input(20, title="KC Length", group = "Momentum")
multKC = input(1.5, title="KC MultFactor", group = "Momentum")
useTrueRange = input.bool(true, title="Use TrueRange (KC)", group = "Momentum")
// ADX
adxminval = input.int(20, minval=1, title="ADX min. value", group = "ADX", tooltip = "Determine if market is still trending. Higher number = bigger trend")
len = input.int(14, minval=1, title="DI Length", group = "ADX")
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50, group = "ADX")
[diplus, diminus, adx] = ta.dmi(len, lensig)
//EMA
emalen = input.int(5, minval=1, title="Length", group = "EMA")
src = input(close, title="Source", group = "EMA")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500, group = "EMA")
i_res = input.timeframe('D', "Resolution", group = "EMA")
out = ta.ema(src, emalen)
emaval = request.security(syminfo.tickerid, i_res, out)
// Calculate BB
source = close
basis = ta.sma(source, length)
dev = multKC * ta.stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev
// Calculate KC
ma = ta.sma(source, lengthKC)
range1 = useTrueRange ? ta.tr : (high - low)
rangema = ta.sma(range1, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC
sqzOn = (lowerBB > lowerKC) and (upperBB < upperKC)
sqzOff = (lowerBB < lowerKC) and (upperBB > upperKC)
noSqz = (sqzOn == false) and (sqzOff == false)
val = ta.linreg(source - math.avg(math.avg(ta.highest(high, lengthKC), ta.lowest(low, lengthKC)),ta.sma(close,lengthKC)), lengthKC,0)
momupadxup = val > 0 and val > nz(val[1]) and (adx >= adx[1] or adx > adxminval)
momdownadxup = val < 0 and val < nz(val[1]) and (adx >= adx[1] or adx > adxminval)
// Plot
scolor = noSqz ? color.blue : sqzOn ? color.black : color.gray
bcolor = momupadxup ? color.rgb(25, 255, 25) : momdownadxup ? color.rgb(255, 25, 25) : color.rgb(255, 140, 25)
bgcolor = close > emaval ? color.rgb(25, 25, 255, transp = 80) : close < emaval ? color.rgb(255, 25, 140, transp = 80) : color.yellow
bgcolor(bgcolor)
plot(val, color=bcolor, style=plot.style_histogram, linewidth=4)
plot(0, color=scolor, style=plot.style_cross, linewidth=2)
|
Stochastic RSI | https://www.tradingview.com/script/SEkk2Got-Stochastic-RSI/ | kallumks123 | https://www.tradingview.com/u/kallumks123/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© kallumks123
//@version=5
//@version=5
indicator(title="Stochastic RSI", shorttitle="Stoch RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
plot(k, "K", color=#2962FF)
plot(d, "D", color=#FF6D00)
h0 = hline(80, "Upper Band", color=#787B86)
hline(50, "Middle Band", color=color.new(#787B86, 50))
h1 = hline(20, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background") |
CosmoSet | https://www.tradingview.com/script/fyNET0h5-CosmoSet/ | TradeWithHitesh | https://www.tradingview.com/u/TradeWithHitesh/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© TradeWithHitesh
//@version=5
indicator("Scalp", overlay=true)
Ema1=input.int(title="Ema1", defval=5)
Ema2=input.int(title="Ema2", defval=20)
Ema3=input.int(title="Ema1", defval=50)
Ema4=input.int(title="Ema2", defval=200)
Sma1=input.int(title="Sma1", defval=5)
Sma2=input.int(title="Sma2", defval=20)
VWEma1=input.int(title="Volume Weighted Ema1", defval=5)
VWEma2=input.int(title="Volume Weighted Ema2", defval=20)
rsiVal=input.int(title="Volume Weighted Ema2", defval=14)
WMA1=input.int(title="Weighted MA1", defval=20)
WMA2=input.int(title="Weighted MA2", defval=20)
//Sources
WMA1source= input.source(close,"WMA Source 1")
WMA2source= input.source(close,"WMA Source 2")
VWMA1source= input.source(close,"VWMA source 1")
VWMA2source= input.source(close,"VWMA source 2")
EMA1source= input.source(close,"EMA Source 1")
EMA2source= input.source(close,"EMA Source 2")
EMA3source= input.source(close,"EMA Source 3")
EMA4source= input.source(close,"EMA Source 4")
SMA1source= input.source(close,"SMA Source 1")
SMA2source= input.source(close,"SMA Source 2")
averageEma1 = ta.ema(EMA1source, Ema1)
averageEma2 = ta.ema(EMA2source, Ema2)
averageEma3 = ta.ema(EMA3source, Ema3)
averageEma4 = ta.ema(EMA4source, Ema4)
averageSma1 = ta.sma(SMA1source, Sma1)
averageSma2 = ta.sma(SMA2source, Sma2)
vwAverageEma1 = ta.vwma(VWMA1source, VWEma1)
vwAverageEma2 = ta.vwma(VWMA2source, VWEma2)
weightedAverage1 = ta.wma(WMA1source, WMA1)
weightedAverage2 = ta.wma(WMA2source, WMA2)
plot(averageEma1, color=color.white, title="EMA 1")
plot(averageEma2, color=color.red, title="EMA 2")
plot(averageEma3, color=color.red, title="EMA 3")
plot(averageEma4, color=color.red, title="EMA 4")
plot(averageSma1, color=color.white, title="SMA 1")
plot(averageSma2, color=color.red, title="SMA 2")
plot(vwAverageEma1, color=color.white, title="VWEMA 1")
plot(vwAverageEma2, color=color.blue, title="VWEMA 2")
plot(weightedAverage1, color=color.red, title="WMA1")
plot(weightedAverage2, color=color.red, title="WMA2")
plot(ta.vwap(hlc3), color=ta.rising(ta.vwap(hlc3),2)?color.green:color.red,style=plot.style_linebr,linewidth=1,linewidth=3,title="VWAP")
plot(ta.rsi(close,rsiVal))
//superTrend
superTrendFactor=input.int(title="Super Trend Factor", defval=3)
superTrendATR=input.int(title="Super Trend ATR", defval=10)
[supertrend, direction] = ta.supertrend(superTrendFactor, superTrendATR)
plot(direction < 0 ? supertrend : na, "Super Trend Up direction", color = color.green, style=plot.style_linebr)
plot(direction > 0 ? supertrend : na, "Super Trend Down direction", color = color.red, style=plot.style_linebr)
|
STD/Clutter-Filtered, Kaiser Window FIR Digital Filter [Loxx] | https://www.tradingview.com/script/u8Ht9GA8-STD-Clutter-Filtered-Kaiser-Window-FIR-Digital-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD/Clutter-Filtered, Kaiser Window FIR Digital Filter [Loxx]",
shorttitle = "STDCFKWFDF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
//Bessel function, z-order hyperbolic
zorderHyperbolicBessel(float x)=>
float besselAccuracy = 0.000001
float bessel = 1.0
float summ = 0
float temp = 0
float k = 2.0
float factorial = 1.0
temp := x / 2
summ := temp * temp
bessel += summ
while summ > besselAccuracy
factorial := factorial * k
temp *= x / 2
summ := temp / factorial
summ := summ * summ
bessel += summ
k += 1.0
bessel
//Filter length estimations
filterOrder(float PassBandRipple, float StopBandAttenuation, float PassBandBars, float StopBandBars)=>
float sbripple = 0
float pbripple = 0
float ripple = 0
float attenuation = 0
float bandwidth = 0
float d = 0
float n = 0
float x = 0
float alpha = 0
float FilterLength = 0.
PassBand = 1 / PassBandBars
StopBand = 1 / StopBandBars
bandwidth := PassBand + StopBand
if bandwidth >= 0.5
PassBand := 0.5 * PassBand / bandwidth
StopBand := 0.5 * StopBand / bandwidth
sbripple := math.pow(10.0, (-0.05 * StopBandAttenuation))
pbripple := math.pow(10.0, (0.05 * PassBandRipple)) - 1.0
ripple := math.min(sbripple, pbripple)
attenuation := -20 * math.log(ripple) / math.log(10)
if math.round(attenuation, 5) <= 21.0
alpha := 0.0
d := 0.9222
if math.round(attenuation, 5) > 50.0
alpha := 0.1102 * (attenuation - 8.7)
d := (attenuation - 7.95) / 14.36
if math.round(attenuation, 5) > 21.0 and math.round(attenuation, 5) <= 50
alpha := (0.5842 * math.pow((attenuation - 21.0), 0.4)) + (0.07886 * (attenuation - 21.0))
d := (attenuation - 7.95) / 14.36
n := (d / StopBand) + 1.0
x := math.round(n)
if x % 2 < 1
FilterLength := x
else
FilterLength := x - 1
[int(FilterLength), alpha, PassBand, StopBand]
Normalization(float PassBandRipple, float StopBandAttenuation, float PassBandBars, float StopBandBars)=>
float filter = 0
float Ioalfa = 0
float temp = 0
float norm = 0
[FilterLength, alpha, PassBand, StopBand] = filterOrder(PassBandRipple, StopBandAttenuation, PassBandBars, StopBandBars)
int M = int(FilterLength / 2)
float[] filterCoeff = array.new<float>(FilterLength + 1, 0)
float[] kaiserWindow = array.new<float>(M + 1, 0)
//Window function
norm := M
Ioalfa := zorderHyperbolicBessel(alpha)
for i = 1 to M
temp := i / norm
array.set(kaiserWindow, i, zorderHyperbolicBessel(alpha * math.sqrt(1 - (temp * temp))) / Ioalfa)
//filter coefficients
array.set(filterCoeff, 0, 2.0 * (PassBand + (0.5 * StopBand)))
norm := array.get(filterCoeff, 0)
temp := math.pi * array.get(filterCoeff, 0)
for i = 1 to M
array.set(filterCoeff, i, math.sin(i * temp) * array.get(kaiserWindow, i) / (i * math.pi))
norm := norm + (2 * array.get(filterCoeff, i))
//casual conversion and normalization
float[] NormCoef = array.new<float>(FilterLength + 1, 0)
for i = M + 1 to FilterLength
array.set(filterCoeff, i, array.get(filterCoeff, i - M))
for i = 0 to M - 1
array.set(filterCoeff, i, array.get(filterCoeff, FilterLength - i))
array.set(filterCoeff, M, 2.0 * (PassBand + (0.5 * StopBand)))
for i = 0 to FilterLength
array.set(NormCoef, i, array.get(filterCoeff, i) / norm)
[NormCoef, FilterLength]
filterResponse(float src, float[] NormCoef, int per)=>
float valueBuf = 0
float temp = 0
float temp1 = 0
float Response = 0.0
int i = 0
int filterlength = 0
while filterlength <= per
valueBuf := nz(src[filterlength])
Response := Response + valueBuf * array.get(NormCoef, filterlength)
filterlength += 1
Response
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
//PassBand=1/PassBandBars -> relative range of filter pass band, possible range is from 0.0 to (0.5-StopBand)
// It is normalized and it's maximum value (0.5-StopBand) is 1/2
//StopBand=1/StopBandBars -> relative range of filter stop band, possible range is from 0.0 to (0.5-PassBand)
// It is normalized and it's maximum value (0.5-PassBand) is 1/2
// (PassBand + StopBand) < 0.5, Relative F_sampling=1, Abs F_sampling= Bar's frequency
// If (PassBand + StopBand) >= 0.5, they would be normalized
// Gain(dB)
// | .. <------pass band ripple (in dB)
// 0dB|.... . . PassBand=Fpass;
// | .. . StopBand=Fstop-Fpass; width of stop band
// | . Fstop<0.5*F_sample
// | .
// | . .. <-----stop band attenuation (in dB)
// | . . .
// |---------+-------+--------*-------+----------------------------------+------Frequency
// 0 Fpass Fstop 0.5F_sample F_sample
//
PassBandBars = input.float(250.0, "Passband Bars", group = "Basic Settings")
StopBandBars = input.float(4, "Stopband Bars", group = "Basic Settings")
StopBandAttenuation = input.float(21.0, "Stopband Attenuation", group = "Basic Settings")
PassBandRipple = input.float(30.0, "Pass Band Ripple", group = "Basic Settings")
sth = input.float(0.1, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFKWFDF", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
[NormCoef, _filterLength] = Normalization(PassBandRipple, StopBandAttenuation, PassBandBars, StopBandBars)
out = filterResponse(src, NormCoef, _filterLength)
out := filterop == "Both" or filterop == "STDCFKWFDF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFKWFDF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD/Clutter-Filtered, Kaiser Window FIR Digital Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD/Clutter-Filtered, Kaiser Window FIR Digital Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Multi EMA - Saurabh | https://www.tradingview.com/script/P4hvcYxW-Multi-EMA-Saurabh/ | saurabh_gupta_ | https://www.tradingview.com/u/saurabh_gupta_/ | 8 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© saurabh_gupta_
//@version=4
//Multi EMA 2
study(title="Multi EMA", shorttitle="Multi EMA", overlay=true)
src = close,
len1 = input(20, minval=1, title="EMA 1")
len2 = input(50, minval=1, title="EMA 2")
len3 = input(200, minval=1, title="EMA 3")
ema1 = ema(src, len1)
ema2 = ema(src, len2)
ema3 = ema(src, len3)
//Color based on close price above or below
ema2Col=(close>ema2 ? color.lime :color.red)
//EMA Plots
plot(ema1, title="EMA 1", linewidth=2, color=color.blue)
plot(ema2, title="EMA 2", linewidth=3, color=ema2Col)
plot(ema3, title="EMA 3", linewidth=2, color=color.purple)
//
toggleBreaks = input(true, title = "Show Breaks" )
leftBars = input(15, title = "Left Bars ")
rightBars = input(15, title = "Right Bars")
volumeThresh = input(20, title = "Volume Threshold")
//
highUsePivot = fixnan(pivothigh(leftBars, rightBars)[1])
lowUsePivot = fixnan(pivotlow(leftBars, rightBars)[1])
r1 = plot(highUsePivot, color=change(highUsePivot) ? na : #FF0000, linewidth=3, offset=-(rightBars+1), title="Resistance")
s1 = plot(lowUsePivot, color=change(lowUsePivot) ? na : #233dee, linewidth=3, offset=-(rightBars+1), title="Support")
//Volume %
short = ema(volume, 5)
long = ema(volume, 10)
osc = 100 * (short - long) / long
//For breaks with volume
plotshape(toggleBreaks and crossunder(close,lowUsePivot) and not (open - close < high - open) and osc > volumeThresh, title = "Break", text = 'B', style = shape.labeldown, location = location.abovebar, color= color.red,textcolor = color.white, transp = 0, size = size.tiny)
plotshape(toggleBreaks and crossover(close,highUsePivot ) and not(open - low > close - open) and osc > volumeThresh, title = "Break", text = 'B', style = shape.labelup, location = location.belowbar, color= color.green,textcolor = color.white, transp = 0, size = size.tiny)
//For bull / bear wicks
plotshape(toggleBreaks and crossover(close,highUsePivot ) and open - low > close - open , title = "Break", text = 'Bull Wick', style = shape.labelup, location = location.belowbar, color= color.green,textcolor = color.white, transp = 0, size = size.tiny)
plotshape(toggleBreaks and crossunder(close,lowUsePivot) and open - close < high - open , title = "Break", text = 'Bear Wick', style = shape.labeldown, location = location.abovebar, color= color.red,textcolor = color.white, transp = 0, size = size.tiny)
alertcondition(crossunder(close,lowUsePivot) and osc > volumeThresh , title = "Support Broken" , message = "Support Broken")
alertcondition(crossover(close,highUsePivot) and osc > volumeThresh, title = "Resistance Broken" , message = "Resistance Broken")
// //MA
// sma =ema(close,50)
// multp = input(type=input.float, defval=2)
// len = input(type=input.integer, defval=7)
// [superTrend, dir] = supertrend(multp, len)
// col1 = (dir==1?color.red:color.lime)
// // longStopPlot = plot(dir == -1 ? superTrend : na, style=plot.style_linebr, color=color.gray, linewidth=1)
// // shortStopPlot = plot(dir == 1 ? superTrend : na, style=plot.style_linebr, color=color.gray, linewidth=1)
// col2=(close<sma ? (close>superTrend? color.blue :color.red) : (close<superTrend ? color.purple :color.lime))
// ma=plot(sma,color=col2,linewidth=2)
// // fill(ma, longStopPlot, title="Long State Filling", color=col2, transp=70)
// // fill(ma, shortStopPlot, title="Short State Filling", color=col2,transp=70)
//Previous and current VWap
//Previous Day's Closing Vwap (Pvwap)
// newday(res) =>
// t = time(res)
// change(t) != 0 ? 1 : 0
// new_day = newday("D")
// // prev_vwap = valuewhen(new_day, int(vwap[1]), 0)
// show = timeframe.isintraday
// var line vwapLine = na
// if show
// // if prev_vwap[1] != prev_vwap
// // line.set_x2(vwapLine, bar_index)
// // line.set_extend(vwapLine, extend.none)
// // vwapLine := line.new(bar_index, prev_vwap, bar_index, prev_vwap, width=1, style=line.style_dashed,color=color.black)
// // label.new(bar_index, prev_vwap, "\n" + tostring(prev_vwap, "#.##"), style=label.style_none, size=size.large, textcolor=color.black)
// if not na(vwapLine) and line.get_x2(vwapLine) != bar_index
// line.set_x2(vwapLine, bar_index)
// // col = close>prev_vwap?(close>vwap?color.lime:color.blue):(close<vwap?color.red:color.purple)
hideonDWM = input(false, title="Hide VWAP on 1D or Above", group="VWAP Settings")
// if not (hideonDWM and timeframe.isdwm)
plot(vwap,linewidth=3, color=color.orange)
// barcolor(col) |
STD/Clutter-Filtered, Variety FIR Filters [Loxx] | https://www.tradingview.com/script/Y18MFW25-STD-Clutter-Filtered-Variety-FIR-Filters-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 65 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD/Clutter-Filtered, Variety FIR Filters [Loxx]",
shorttitle = "STDCFVFIRF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
fir_rect = "Rectangular - simple moving average"
fir_hann = "Hanning"
fir_hamm = "Hamming"
fir_blck = "Blackman"
fir_blha = "Blackman/Harris"
fir_lwma = "Linear weighted"
fir_tma = "Triangular"
design(int per, string type)=>
float[] coeffs = array.new<float>(per, 0)
float coeffsSum = 0
float _div = per + 1.0
float _coeff = 1
for i = 0 to per - 1
switch type
fir_rect =>
_coeff := 1.0
fir_hann =>
_coeff := 0.50 - 0.50 * math.cos(2.0 * math.pi * (i + 1) / _div)
fir_hamm =>
_coeff := 0.54 - 0.46 * math.cos(2.0 * math.pi * (i + 1) / _div)
fir_blck =>
_coeff := 0.42 - 0.50 * math.cos(2.0 * math.pi * (i + 1) / _div) + 0.08 * math.cos(4.0 * math.pi * i / _div)
fir_blha =>
_coeff := 0.35875 - 0.48829 * math.cos(2.0 * math.pi * (i + 1) / _div) + 0.14128 * math.cos(4.0 * math.pi * (i + 1) / _div) - 0.01168 * math.cos(6.0 * math.pi * (i + 1) / _div)
fir_lwma =>
_coeff := per - i
fir_tma =>
_coeff := i + 1.0
if (_coeff > ((per + 1.0) / 2.0))
_coeff := per - i
array.set(coeffs,i, _coeff)
coeffsSum += _coeff
[coeffs, coeffsSum]
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
type = input.string(fir_lwma, "FIR Digital Filter Type", options = [fir_rect, fir_hann, fir_hamm, fir_blck, fir_blha, fir_lwma, fir_tma], group = "Basic Settings")
sth = input.float(0.15, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFVFIRF", "Both", "None"], group= "Filter Settings")
filter = input.float(1, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
[coeffs, coeffsSum] = design(per, type)
float dSum = 0
for k = 0 to per - 1
dSum += nz(src[k]) * array.get(coeffs, k)
out = coeffsSum != 0 ? dSum / coeffsSum : 0
out := filterop == "Both" or filterop == "STDCFVFIRF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFVFIRF MA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD/Clutter Filtered, One-Sided, N-Sinc-Kernel, EFIR Filt [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD/Clutter Filtered, One-Sided, N-Sinc-Kernel, EFIR Filt [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Average Daily Range Lines + VWAP by Tenozen | https://www.tradingview.com/script/fcFJaCgM-Average-Daily-Range-Lines-VWAP-by-Tenozen/ | Tenozen | https://www.tradingview.com/u/Tenozen/ | 100 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Tenozen
//@version=5
indicator("Average Daily Range Lines + VWAP by Tenozen", shorttitle="ADRL + VWAP", overlay=true)
lengthInput = input.int(19, title="ADR Length")
smaHigh = ta.sma(high, lengthInput)
smaLow = ta.sma(low, lengthInput)
adr_per = input.int(100, title="ADR percent value target?")
adr = smaHigh - smaLow
sum = ta.cum(adr)
is_new_day = ta.change(time("D"))
var float adr_target = 0
if (is_new_day)
adr_target := is_new_day? adr*adr_per : na
var float adr_total = 0
if (is_new_day)
adr_total := sum
adr_total_fix = sum - adr_total
cross = ta.crossover(adr_total_fix, adr_target) //the key point
cm = ta.valuewhen(cross, (high+low)/2, 0)
ch = ta.valuewhen(cross, high, 0)
cl = ta.valuewhen(cross, low, 0)
plot(cm, title="Mid line", style = plot.style_stepline, color= #311adf)
h_line = plot(ch, title="High line", style = plot.style_stepline, color= #311adf)
l_line = plot(cl, title="Low line", style = plot.style_stepline, color= #311adf)
bgcolor(is_new_day ? color.new(color.blue, 85) : na)
plot(adr_total_fix)
plot(adr_target, color=color.yellow)
fill(h_line, l_line, color=color.new(color.white, 95), title= "Box Fill Color")
///////////////////////////////VWAP///////////////////////////////////////////////
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
computeVWAP(src, isNewPeriod) =>
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
// sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]
_vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
stDev = math.sqrt(variance)
[_vwap, stDev]
computeStdevBands(value, stdev, bandMult) =>
float upperBand = value + stdev * bandMult
float lowerBand = value - stdev * bandMult
[upperBand, lowerBand]
hideonDWM = input(false, title="Hide VWAP on 1D or Above", group="VWAP Settings")
var anchor = input.string(defval = "ADR", title="Anchor Period",
options=["ADR","Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], group="VWAP Settings")
src = input(title = "Source", defval = hlc3, group="VWAP Settings")
offset = input(0, title="Offset", group="VWAP Settings")
showBand_1 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_1")
stdevMult_1 = input(1.0, title="Bands Multiplier #1", group="Standard Deviation Bands Settings", inline="band_1")
showBand_2 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_2")
stdevMult_2 = input(2.0, title="Bands Multiplier #2", group="Standard Deviation Bands Settings", inline="band_2")
showBand_3 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_3")
stdevMult_3 = input(3.0, title="Bands Multiplier #3", group="Standard Deviation Bands Settings", inline="band_3")
timeChange(period) =>
ta.change(time(period))
new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
isNewPeriod = switch anchor
"Earnings" => not na(new_earnings)
"Dividends" => not na(new_dividends)
"Splits" => not na(new_split)
"Session" => timeChange("D")
"Week" => timeChange("W")
"Month" => timeChange("M")
"Quarter" => timeChange("3M")
"Year" => timeChange("12M")
"Decade" => timeChange("12M") and year % 10 == 0
"Century" => timeChange("12M") and year % 100 == 0
"ADR" => ta.crossover(adr_total_fix, adr_target)
=> false
isEsdAnchor = anchor == "Earnings" or anchor == "Dividends" or anchor == "Splits"
if na(src[1]) and not isEsdAnchor
isNewPeriod := true
float vwapValue = na
float stdev = na
float upperBandValue1 = na
float lowerBandValue1 = na
float upperBandValue2 = na
float lowerBandValue2 = na
float upperBandValue3 = na
float lowerBandValue3 = na
if not (hideonDWM and timeframe.isdwm)
[_vwap, _stdev] = computeVWAP(src, isNewPeriod)
vwapValue := _vwap
stdev := _stdev
[upBV1, loBV1] = computeStdevBands(vwapValue, stdev, stdevMult_1)
upperBandValue1 := showBand_1 ? upBV1 : na
lowerBandValue1 := showBand_1 ? loBV1 : na
[upBV2, loBV2] = computeStdevBands(vwapValue, stdev, stdevMult_2)
upperBandValue2 := showBand_2 ? upBV2 : na
lowerBandValue2 := showBand_2 ? loBV2 : na
[upBV3, loBV3] = computeStdevBands(vwapValue, stdev, stdevMult_3)
upperBandValue3 := showBand_3 ? upBV3 : na
lowerBandValue3 := showBand_3 ? loBV3 : na
plot(vwapValue, title="VWAP", color=color.white, offset=offset)
upperBand_1 = plot(upperBandValue1, title="Upper Band #1", color=color.green, offset=offset)
lowerBand_1 = plot(lowerBandValue1, title="Lower Band #1", color=color.green, offset=offset)
fill(upperBand_1, lowerBand_1, title="Bands Fill #1", color= color.new(color.green, 95))
upperBand_2 = plot(upperBandValue2, title="Upper Band #2", color=color.olive, offset=offset)
lowerBand_2 = plot(lowerBandValue2, title="Lower Band #2", color=color.olive, offset=offset)
fill(upperBand_2, lowerBand_2, title="Bands Fill #2", color= color.new(color.olive, 95))
upperBand_3 = plot(upperBandValue3, title="Upper Band #3", color=color.teal, offset=offset)
lowerBand_3 = plot(lowerBandValue3, title="Lower Band #3", color=color.teal, offset=offset)
fill(upperBand_3, lowerBand_3, title="Bands Fill #3", color= color.new(color.teal, 95))
|
Clutter-Filtered, D-Lag Reducer, Spec. Ops FIR Filter [Loxx] | https://www.tradingview.com/script/Ouud7pfZ-Clutter-Filtered-D-Lag-Reducer-Spec-Ops-FIR-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 187 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Clutter-Filtered, D-Lag Reducer, Spec. Ops FIR Filter [Loxx]",
shorttitle = "CFDLLRFF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
duelElementLagReducer(float[] coeff, int LagReductionFactor)=>
if LagReductionFactor > 0
per = array.size(coeff)
for i = per - 1 to 0
if i >= LagReductionFactor
array.set(coeff, i, 2 * array.get(coeff, i) - array.get(coeff, i - LagReductionFactor))
else
array.set(coeff, i, 2 * array.get(coeff, i))
coeff
directFormFIR(float src, int per, float[] coeff)=>
float sum = 0.0
for n = 0 to per - 1
sum += nz(src[n]) * array.get(coeff, n)
sum
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
var array<float> coeff = array.new<float>(40, 0)
array.set(coeff, 0, 0.2682078129301)
array.set(coeff, 1, 0.240689662817)
array.set(coeff, 2, 0.2034776029464)
array.set(coeff, 3, 0.1630112541839)
array.set(coeff, 4, 0.1238604113978)
array.set(coeff, 5, 0.08882117730373)
array.set(coeff, 6, 0.0592575366455)
array.set(coeff, 7, 0.0355091376143)
array.set(coeff, 8, 0.01726488214552)
array.set(coeff, 9, 0.003859198612914)
array.set(coeff, 10, -0.005516867700847)
array.set(coeff, 11, -0.01167964519718)
array.set(coeff, 12, -0.01537516433377)
array.set(coeff, 13, -0.01724253310596)
array.set(coeff, 14, -0.01780402378186)
array.set(coeff, 15, -0.01747064024502)
array.set(coeff, 16, -0.01655561037259)
array.set(coeff, 17, -0.01529076983704)
array.set(coeff, 18, -0.01384290192686)
array.set(coeff, 19, -0.01232850220073)
array.set(coeff, 20, -0.0108262356619)
array.set(coeff, 21, -0.009387057661213)
array.set(coeff, 22, -0.008042117218492)
array.set(coeff, 23, -0.006808722524782)
array.set(coeff, 24, -0.005694738789271)
array.set(coeff, 25, -0.004701770313144)
array.set(coeff, 26, -0.003827379758726)
array.set(coeff, 27, -0.003066597695855)
array.set(coeff, 28, -0.002412921398684)
array.set(coeff, 29, -0.001858955235279)
array.set(coeff, 30, -0.001396806658866)
array.set(coeff, 31, -0.001018320955267)
array.set(coeff, 32, -0.0007152136335629)
array.set(coeff, 33, -0.0004791407494877)
array.set(coeff, 34, -0.0003017336191226)
array.set(coeff, 35, -0.0001746144517018)
array.set(coeff, 36, -0.00008940260506336)
array.set(coeff, 37, -0.00003771672382874)
array.set(coeff, 38, -0.00001117532554157)
array.set(coeff, 39, -0.000001396915692344)
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
lagr = input.int(0, "Lag Reduction Factor", group = "Basic Settings")
per = 39
sth = input.float(0.1, "Threshold", group = "Basic Settings", step = 0.001)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = src
color colorout = na
goLong = false
goShort = false
duelElementLagReducer(coeff, lagr)
out := directFormFIR(src, per, coeff)
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong := pregoLong and nz(contsw[1]) == -1
goShort := pregoShort and nz(contsw[1]) == 1
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "CFDLLRFF MA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Clutter-Filtered, D-Lag Reducer, Spec. Ops FIR Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Clutter-Filtered, D-Lag Reducer, Spec. Ops FIR Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Auto Fibonacci with .88 | https://www.tradingview.com/script/WabzZunG-Auto-Fibonacci-with-88/ | BeastBoy7309 | https://www.tradingview.com/u/BeastBoy7309/ | 92 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @TrendCrypto2022
//@version=5
indicator("Fibonacci", overlay=true, max_lines_count = 500)
//Input
buyonly = input.bool (title="Find entry Long", defval=true, group="Set up Find entry")
sellonly = input.bool (title="Find entry Short", defval=false, group="Set up Find entry")
leftbars = input.int(10, minval=1, title='Pivot Detection: Left Bars', group = "Set up Pivot High/Low")
rightbars = input.int(5, minval=1, title='Pivot Detection: Right Bars', group = "Set up Pivot High/Low")
width_fibo = input.int(2, minval=1, title='Width Fibonacci levels', group = "Custom Selection", inline = "1")
width_sup_res = input.int(2, minval=1, title='Width Sup/Res levels', group = "Custom Selection", inline = "2")
width_trendline = input.int(2, minval=1, title='Width Trendline', group = "Custom Selection")
extend_fibo = input.int(5, minval=1, title='Extention', group = "Custom Selection", inline = "1")
color_fibo_label = input.color(color.new(color.yellow, 0), title="Color Labels", group = "Custom Selection", inline = "1")
extend_sup_res = input.int(5, minval=1, title='Extention', group = "Custom Selection", inline = "2")
// Pivots
ph = ta.pivothigh(high, leftbars, rightbars)
pl = ta.pivotlow(low, leftbars, rightbars)
//Caculate Support/Resistant levels based on Pivots
phvalue1 = ta.valuewhen(ph, high[rightbars], 0)
phbar1 = ta.valuewhen(ph, bar_index[rightbars], 0), phv1low = ta.valuewhen(ph, close[rightbars]>open[rightbars] ? close[rightbars] : open[rightbars], 0)
phvalue2 = ta.valuewhen(ph, high[rightbars], 1)
phbar2 = ta.valuewhen(ph, bar_index[rightbars], 1), phv2low = ta.valuewhen(ph, close[rightbars]>open[rightbars] ? close[rightbars] : open[rightbars], 1)
phbar3 = ta.valuewhen(ph, bar_index[rightbars], 2),
phvalue3 = ta.valuewhen(ph, high[rightbars], 2)
plvalue1 = ta.valuewhen(pl, low[rightbars], 0)
plbar1 = ta.valuewhen(pl, bar_index[rightbars], 0), plv1low = ta.valuewhen(pl, close[rightbars]<open[rightbars] ? close[rightbars] : open[rightbars], 0)
plvalue2 = ta.valuewhen(pl, low[rightbars], 1)
plbar2 = ta.valuewhen(pl, bar_index[rightbars], 1)
plbar3 = ta.valuewhen(pl, bar_index[rightbars], 2), plv2low = ta.valuewhen(pl, close[rightbars]<open[rightbars] ? close[rightbars] : open[rightbars], 1)
plvalue3 = ta.valuewhen(pl, low[rightbars], 2)
plotshape(ph, style=shape.diamond, location=location.abovebar, color=color.new(color.red, 0), title='Pivot High', offset=-rightbars)
plotshape(pl, style=shape.diamond, location=location.belowbar, color=color.new(color.green, 0), title='Pivot Low', offset=-rightbars)
//Calculate trendlines
_slope(x1, x2, y1, y2) =>
m = (y2 - y1) / (x2 - x1)
m
get_y_oxy(m, x1, y1) =>
b = y1 - m * x1
b
get_y(m, b, ts) =>
Y = m * ts + b
Y
int res_x1 = na
float res_y1 = na
int res_x2 = na
float res_y2 = na
int sup_x1 = na
float sup_y1 = na
int sup_x2 = na
float sup_y2 = na
res_x1 := ph ? phbar2 : res_x1[1]
res_y1 := ph ? phvalue2 : res_y1[1]
res_x2 := ph ? phbar3 : res_x2[1]
res_y2 := ph ? phvalue3 : res_y2[1]
res_m = _slope(res_x1, res_x2, res_y1, res_y2)
res_b = get_y_oxy(res_m, res_x1, res_y1)
res_y = get_y(res_m, res_b, bar_index)
sup_x1 := pl ? plbar2 : sup_x1[1]
sup_y1 := pl ? plvalue2 : sup_y1[1]
sup_x2 := pl ? plbar3 : sup_x2[1]
sup_y2 := pl ? plvalue3 : sup_y2[1]
sup_m = _slope(sup_x1, sup_x2, sup_y1, sup_y2)
sup_b = get_y_oxy(sup_m, sup_x1, sup_y1)
sup_y = get_y(sup_m, sup_b, bar_index)
// Setup Alert
alert_input = input.string(title='Set alert Long Trade when price test', defval='Fibo 0.5', options=['Fibo 0.382', 'Fibo 0.5', 'Fibo 0.618', 'Fibo 0.786', 'Support Zone', 'Trendline'], group='Set up Alert')
alertshort_input = input.string(title='Set alert Short Trade when price test', defval='Fibo 0.5', options=['Fibo 0.382', 'Fibo 0.5', 'Fibo 0.618', 'Fibo 0.786', 'Resistant Zone', 'Trendline'], group='Set up Alert')
distance_x = timenow + math.round(ta.change(time) * 1)
//Draw Fibonacci levels, Support levels and labels
if ph and phvalue1 > phvalue2 and buyonly == true
line.new(plbar1, plvalue1, phbar1, phvalue1, style=line.style_arrow_right, color=color.lime, width = 2)
line.new(plbar1, phvalue1, phbar1+ rightbars+extend_fibo, phvalue1, style=line.style_solid, color=color.new(color.silver, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.88, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.88, style=line.style_solid, color=color.new(color.red, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.382, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.382, style=line.style_solid, color=color.new(#81c784, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.500, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.500, style=line.style_solid, color=color.new(color.green, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.618, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.618, style=line.style_solid, color=color.new(#089981, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.786, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.786, style=line.style_solid, color=color.new(color.aqua, 60), width = width_fibo)
if close<phvalue1-(phvalue1-plvalue1)*0.382 and alert_input == 'Fibo 0.382'
alert(message = "Fibo 0.382", freq = alert.freq_once_per_bar)
if close<phvalue1-(phvalue1-plvalue1)*0.500 and alert_input == 'Fibo 0.5'
alert(message = "Fibo 0.5", freq = alert.freq_once_per_bar)
if close<phvalue1-(phvalue1-plvalue1)*0.618 and alert_input == 'Fibo 0.618'
alert(message = "Fibo 0.618", freq = alert.freq_once_per_bar)
if close<phvalue1-(phvalue1-plvalue1)*0.786 and alert_input == 'Fibo 0.786'
alert(message = "Fibo 0.786", freq = alert.freq_once_per_bar)
if close<phvalue2 and alert_input == 'Support Zone'
alert(message = "Support Zone", freq = alert.freq_once_per_bar)
if close<res_y + res_y*0.005 and alert_input == 'Trendline'
alert(message = "Trendline", freq = alert.freq_once_per_bar)
var label labelfibo0 = na
label.delete(labelfibo0)
labelfibo0 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0, text='0', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo88 = na
label.delete(labelfibo88)
labelfibo88 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.88, text='0.88', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo382 = na
label.delete(labelfibo382)
labelfibo382 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.382, text='0.382', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo5 = na
label.delete(labelfibo5)
labelfibo5 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.5, text='0.5', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo618 = na
label.delete(labelfibo618)
labelfibo618 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.618, text='0.618', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo786 = na
label.delete(labelfibo786)
labelfibo786 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.786, text='0.786', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo1 = na
label.delete(labelfibo1)
labelfibo1 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*1, text='1', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
//Draw Fibonacci levels, Resistant levels and labels
if pl and plvalue1 < plvalue2 and sellonly == true
line.new(phbar1, phvalue1, plbar1, plvalue1, style=line.style_arrow_right, color=color.red, width = 2)
line.new(phbar1, plvalue1, plbar1+ rightbars+extend_fibo, plvalue1, style=line.style_solid, color=color.new(color.silver, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.88, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.88, style=line.style_solid, color=color.new(color.red, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.382, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.382, style=line.style_solid, color=color.new(#81c784, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.500, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.500, style=line.style_solid, color=color.new(color.green, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.618, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.618, style=line.style_solid, color=color.new(#089981, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.786, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.786, style=line.style_solid, color=color.new(color.aqua, 60), width = width_fibo)
line.new(phbar1, phvalue1, plbar1+ rightbars+extend_fibo, phvalue1, style=line.style_solid, color=color.new(color.purple, 60), width = width_fibo)
if close>plvalue1-(plvalue1-phvalue1)*0.382 and alertshort_input == 'Fibo 0.382'
alert(message = "Fibo 0.382", freq = alert.freq_once_per_bar)
if close>plvalue1-(plvalue1-phvalue1)*0.500 and alertshort_input == 'Fibo 0.5'
alert(message = "Fibo 0.5", freq = alert.freq_once_per_bar)
if close>plvalue1-(plvalue1-phvalue1)*0.618 and alertshort_input == 'Fibo 0.618'
alert(message = "Fibo 0.618", freq = alert.freq_once_per_bar)
if close>plvalue1-(plvalue1-phvalue1)*0.786 and alertshort_input == 'Fibo 0.786'
alert(message = "Fibo 0.786", freq = alert.freq_once_per_bar)
if close>plvalue2 and alertshort_input == 'Resistant Zone'
alert(message = "Resistant Zone", freq = alert.freq_once_per_bar)
if close>sup_y - sup_y*0.005 and alertshort_input == 'Trendline'
alert(message = "Trendline", freq = alert.freq_once_per_bar)
var label labelfibo0 = na
label.delete(labelfibo0)
labelfibo0 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0, text='0', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo88 = na
label.delete(labelfibo88)
labelfibo88 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.88, text='0.88', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo382 = na
label.delete(labelfibo382)
labelfibo382 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.382, text='0.382', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo5 = na
label.delete(labelfibo5)
labelfibo5 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.5, text='0.5', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo618 = na
label.delete(labelfibo618)
labelfibo618 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.618, text='0.618', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo786 = na
label.delete(labelfibo786)
labelfibo786 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.786, text='0.786', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo1 = na
label.delete(labelfibo1)
labelfibo1 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*1, text='1', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) |
STD- and Clutter-Filtered, Non-Lag Moving Average [Loxx] | https://www.tradingview.com/script/SdtILzrT-STD-and-Clutter-Filtered-Non-Lag-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 164 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD- and Clutter-Filtered, Non-Lag Moving Average [Loxx]",
shorttitle = "STFDFNLMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
nonlagma(float src, int len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0., float alfa = 0., float out = 0.
float[] alphas = array.new_float(_len, 0.)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
float beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(25, "Period", group = "Basic Settings")
sth = input.float(0.1, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
filterop = input.string("Both", "Filter Options", options = ["Price", "STFDFNLMA", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
out = nonlagma(src, per)
out := filterop == "Both" or filterop == "ULLMA" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STFDFNLMA MA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD- and Clutter-Filtered, Non-Lag Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD- and Clutter-Filtered, Non-Lag Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Fractals + Alligator + Divergent Bars + Squat Bars | https://www.tradingview.com/script/s50udRlg-Fractals-Alligator-Divergent-Bars-Squat-Bars/ | sakis-me | https://www.tradingview.com/u/sakis-me/ | 166 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© sakis-me
//@version=5
indicator("Fractals + Alligator + Divergent Bars + Squat Bars", shorttitle="FADS by sakis-me", overlay=true)
showFractals = input.bool(defval=true, title="Show Fractals", group="Fractals")
n = input.int(title="Fractal Periods", defval=2, minval=2, group="Fractals")
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
// downFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
plotshape(showFractals and downFractal, style=shape.triangledown, location=location.belowbar, offset=-n, color=#F44336, size = size.small)
plotshape(showFractals and upFractal, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size = size.small)
showAlligator = input.bool(defval=true, title="Show Alligator", group="Alligator")
smma(src, length) =>
smma = 0.0
smma := na(smma[1]) ? ta.sma(src, length) : (smma[1] * (length - 1) + src) / length
smma
jawLength = input.int(13, minval=1, title="Jaw Length", group="Alligator")
teethLength = input.int(8, minval=1, title="Teeth Length", group="Alligator")
lipsLength = input.int(5, minval=1, title="Lips Length", group="Alligator")
jawOffset = input(8, title="Jaw Offset", group="Alligator")
teethOffset = input(5, title="Teeth Offset", group="Alligator")
lipsOffset = input(3, title="Lips Offset", group="Alligator")
jaw = smma(hl2, jawLength)
teeth = smma(hl2, teethLength)
lips = smma(hl2, lipsLength)
plot(showAlligator ? jaw : na, "Jaw", offset = jawOffset, color=#2962FF)
plot(showAlligator ? teeth : na, "Teeth", offset = teethOffset, color=#E91E63)
plot(showAlligator ? lips : na, "Lips", offset = lipsOffset, color=#66BB6A)
showDivergentBar = input.bool(defval=true, title="Show Divergent Bars", group="Divergent Bars")
ATR_function = ta.rma(ta.tr(true), 14)
Jaw = 0.0
Jaw := na(Jaw[1]) ? ta.sma(close, 13) : (Jaw[1] * (13 - 1) + close) / 13
Jaw_ = Jaw[8]
bear = ((close > hl2 and open > hl2) and (hl2 < (Jaw_ - ATR_function))) and (high - low > ATR_function) ? true : false
bull = ((close < hl2 and open < hl2) and (hl2 > (Jaw_ + ATR_function))) and (high - low > ATR_function) ? true : false
plotshape(showDivergentBar and bull, style=shape.circle, location=location.abovebar, color=color.fuchsia, size = size.tiny, title="Bull")
plotshape(showDivergentBar and bear, style=shape.circle, location=location.belowbar, color=color.lime, size = size.tiny, title="Bear")
showSquatBars = input.bool(defval=true, title="Show Squat Bars", group="Squat Bars")
r_hl=ta.roc((high-low)/volume,1)
r_v=ta.roc(volume,1)
squat_f=(r_hl < 0) and (r_v > 0)
barcolor(showSquatBars and squat_f ? color.blue : na, title="Squat Bars")
|
STD/C-Filtered, Truncated Taylor Family FIR Filter [Loxx] | https://www.tradingview.com/script/UJdKs6lI-STD-C-Filtered-Truncated-Taylor-Family-FIR-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 101 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD/C-Filtered, Truncated Taylor Family FIR Filter [Loxx]",
shorttitle = "STDCFTTFFIRF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
design(int per, float taylorK)=>
float[] coeffs = array.new<float>(per, 0)
float coeffsSum = 0
float _div = per + 1.0
float _coeff = 1
for i = 0 to per - 1
_coeff := (1 + taylorK) / 2 - (1 - taylorK) / 2 * math.cos(2.0 * math.pi * (i + 1) / _div)
array.set(coeffs,i, _coeff)
coeffsSum += _coeff
[coeffs, coeffsSum]
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
taylorK = input.float(0.5, "Truncated Taylor Family of Windows K-Value", group = "Basic Settings", maxval = 1, minval = 0., step = 0.01)
sth = input.float(0.0, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFTTFFIRF", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
[coeffs, coeffsSum] = design(per, taylorK)
float dSum = 0
for k = 0 to per - 1
dSum += nz(src[k]) * array.get(coeffs, k)
out = coeffsSum != 0 ? dSum / coeffsSum : 0
out := filterop == "Both" or filterop == "STDCFTTFFIRF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFTTFFIRF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD/C-Filtered, Truncated Taylor Family FIR Filter[Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD/C-Filtered, Truncated Taylor Family FIR Filter[Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
MACD x SuperTrend with trailing stoploss | https://www.tradingview.com/script/5WFu2Zwe-MACD-x-SuperTrend-with-trailing-stoploss/ | ChamodSachin | https://www.tradingview.com/u/ChamodSachin/ | 55 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© ChamodSachin
//@version=5
indicator("MACD x SuperTrend with trailing stoploss", "MACDxSTxTSL", overlay=true)
// Switches for long and short entries. They act to filter out multiple signals in adjacent candles.
var longEntry = false
var shortEntry = false
// holds short and long stoploss and take profit
var longSLPrice = 0.0
var longTPPrice = 0.0
var shortSLPrice = 0.0
var shortTPPrice = 0.0
long = false
short = false
// Risk to reward ratio
var RR = input(title="Risk to Reward", defval=2.0)
// supertrend indicator initiation
factor = input(title="Factor", defval=3.0)
atrPeriod = input(title="ATR Period", defval=10)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
// Determine the trend. Uptrend for long entries, downtrend for short entries
upTrend = direction < 0
downTrend = direction > 0
// get macd data as user input
fastlen = input(title="Fast Length", defval=12)
slowlen = input(title="Slow Length", defval=26)
siglen = input(title="Signal Smoothing", defval=9)
[macdLine, signalLine, histLine] = ta.macd(close, fastlen, slowlen, siglen)
// cross points of macd and signalLine. crossover for bullish signals. crossunder for bearish signals
crossover = ta.crossover(macdLine, signalLine)
crossunder = ta.crossunder(macdLine, signalLine)
// above or below zero line
above = true
below = true
consider = input(title="Consider Zero Line", defval=true)
if consider
above := macdLine > 0 and signalLine > 0
below := macdLine < 0 and signalLine < 0
// long entry signal logic
long := upTrend and crossover and not longEntry and not shortEntry and below
if long
longEntry := true
longTPPrice := close + (close-supertrend) * RR
shortSLPrice := na
shortTPPrice := na
if longEntry
longSLPrice := supertrend
longProfit = longTPPrice < high and longEntry
if longProfit
longEntry := false
longSLPrice := na
longTPPrice := na
longLoss = longSLPrice > low and longEntry
if longLoss
longEntry := false
longSLPrice := na
longTPPrice := na
plotshape(long, style=shape.triangleup, size=size.tiny, color=color.green, text='long', location=location.abovebar)
plotshape(longProfit, style=shape.diamond, size=size.tiny, color=color.green, text='long profit', location=location.abovebar)
plotshape(longLoss, style=shape.xcross, size=size.tiny, color=color.orange, text='long loss', location=location.abovebar)
// short entry signal logic
short := downTrend and crossunder and not shortEntry and not longEntry and above
if short
shortEntry := true
shortTPPrice := close - (supertrend-close) * RR
longSLPrice := na
longTPPrice := na
if shortEntry
shortSLPrice := supertrend
shortProfit = shortTPPrice > low and shortEntry
if shortProfit
shortEntry := false
shortSLPrice := na
shortTPPrice := na
shortLoss = shortSLPrice < high and shortEntry
if shortLoss
shortEntry := false
shortSLPrice := na
shortTPPrice := na
plotshape(short, style=shape.triangledown, size=size.tiny, color=color.red, text='short', location=location.belowbar)
plotshape(shortProfit, style=shape.diamond, size=size.tiny, color=color.red, text='short profit', location=location.belowbar)
plotshape(shortLoss, style=shape.xcross, size=size.tiny, color=color.orange, text='short loss', location=location.belowbar)
profit = color.new(#4cbb17, 20)
loss = color.new(#800000, 20)
plot(shortSLPrice, style=plot.style_linebr, color=loss, title="short loss", offset=1, linewidth=3)
plot(shortTPPrice, style=plot.style_linebr, color=profit, title="short profit", offset=1, linewidth=3)
plot(longSLPrice, style=plot.style_linebr, color=loss, title="long loss", offset=1, linewidth=3)
plot(longTPPrice, style=plot.style_linebr, color=profit, title="long profit", offset=1, linewidth=3)
ema = ta.ema(close,200)
plot(ema, color=color.purple, linewidth=2) |
Customisable Stoch RSI [10 PRESETS INCLUDED] | https://www.tradingview.com/script/QFqPYPp1-Customisable-Stoch-RSI-10-PRESETS-INCLUDED/ | crypteisfuture | https://www.tradingview.com/u/crypteisfuture/ | 48 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© crypteisfuture
//@version=5
indicator("Customisable Stoch RSI", shorttitle = 'Custom Stoch RSI [PRESETS INCLUDED]')
// StochRSI Set
// --------------------
// 5 -- 5 -- 3
// 8 -- 8 -- 5
// 13 -- 13 -- 13
// 21 -- 15 -- 13
// 21 -- 21 -- 13
// 34 -- 34 -- 13
// 55 -- 55 -- 21
// 89 -- 13 -- 34
// 89 -- 89 -- 21
// 233 -- 233 -- 34
group_preset = 'Presets'
group_custom = 'Custom'
group_plot = 'Plot Levels'
usePreset = input.string('Preset', title = 'Settings from', options = ['Preset', 'Custom'], group = group_preset)
preset = input.int(defval = 10, minval = 1, maxval = 10, group = group_preset)
mp1 = input.int(defval = 233, minval = 2, title = "RSI Period", group = group_custom)
mp2 = input.int(defval = 233, minval = 2, title = "Stoch Period", group = group_custom)
mp3 = input.int(defval = 34, minval = 2, title = "Lowest Period", group = group_custom)
mp4 = input.int(defval = 5, minval = 2, title = "Smooth", group = group_custom)
if usePreset == 'Preset'
switch preset
1 => mp1 := 5, mp2 := 5, mp3 := 3
2 => mp1 := 8, mp2 := 8, mp3 := 5
3 => mp1 := 13, mp2 := 13, mp3 := 13
4 => mp1 := 21, mp2 := 15, mp3 := 13
5 => mp1 := 21, mp2 := 21, mp3 := 13
6 => mp1 := 34, mp2 := 34, mp3 := 13
7 => mp1 := 55, mp2 := 55, mp3 := 21
8 => mp1 := 89, mp2 := 13, mp3 := 34
9 => mp1 := 89, mp2 := 89, mp3 := 21
10 => mp1 := 233, mp2 := 233, mp3 := 34
// formula by Nicholas Kormanik
custom_stoch_rsi = ta.ema( math.sum( ( ta.rsi( close, mp1) - ta.lowest( ta.rsi(close, mp1) , mp2) ) , mp3) / math.sum( ( .0000001+ ( ta.highest( ta.rsi(close, mp1) , mp2) - (ta.lowest( ta.rsi(close, mp1) , mp2) ) ) ) , mp3) , mp4) * 100
// < Plot >
ON = 'ON'
OFF = 'OFF'
bg = input.string(ON, 'Dark Background', options=[OFF, ON]) == ON
bgcolor(bg ? color.new(#000000, 20) : na, title='Dark Background')
s_upper = input.int(70, title = 'Standart Upper', group = group_plot)
s_lower = input.int(30, title = 'Standart Lower', group = group_plot)
ex_upper = input.int(95, title = 'Extra Upper', group = group_plot)
ex_lower = input.int(5, title = 'Extra Lower', group = group_plot)
st_upper = input.int(80, title = 'Semi-Standart Upper', group = group_plot)
st_lower = input.int(20, title = 'Semi-Standart Lower', group = group_plot)
plot(custom_stoch_rsi, title = 'Customisable Stoch', linewidth = 2, style = plot.style_stepline, color = color.new(color.from_gradient(1337, 228, 1488, color.new(color.yellow, 0), color.new(color.yellow, 0)), 50))
plot(math.avg(custom_stoch_rsi[1], custom_stoch_rsi[2], custom_stoch_rsi[3]), title = 'Average Stoch', linewidth = 1, style = plot.style_stepline, color = color.new(color.aqua, 60))
standart_upper = plot(s_upper, title = 'Standart Upper', linewidth = 1, style = plot.style_cross, color = color.new(color.red, 30))
standart_lower = plot(s_lower, title = 'Standart Lower', linewidth = 1, style = plot.style_cross, color = color.new(color.green, 30))
extra_upper = plot(ex_upper, title = 'Extra Upper', linewidth = 2, style = plot.style_line, color = color.new(color.red, 50))
upper = plot(st_upper, title = 'Upper', linewidth = 2, style = plot.style_line, color = color.new(color.red, 50))
extra_lower = plot(ex_lower, title = 'Extra Lower', linewidth = 2, style = plot.style_line, color = color.new(color.green, 50))
lower = plot(st_lower, title = 'Lower', linewidth = 2, style = plot.style_line, color = color.new(color.green, 50))
fill(upper, extra_upper, color = color.new(color.from_gradient(1337, 228, 1488, color.new(color.red, 0), color.new(color.maroon, 0)), 70))
fill(lower, extra_lower, color = color.new(color.from_gradient(1337, 228, 1488, color.new(color.green, 0), color.new(color.lime, 0)), 70))
plot(math.avg(st_upper, ex_upper), linewidth = 1, color = color.new(color.white, 45), style = plot.style_cross)
plot(math.avg(st_lower, ex_lower), linewidth = 1, color = color.new(color.white, 45), style = plot.style_cross) |
BTC Dominance Exclude Stablecoins(USDT, USDC, DAI) | https://www.tradingview.com/script/XXF89ngK-BTC-Dominance-Exclude-Stablecoins-USDT-USDC-DAI/ | xiaolaichen | https://www.tradingview.com/u/xiaolaichen/ | 396 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© xiaolaiseanchen
//@version=5
indicator("BTC Dominance Exclude Stablecoins(USDT, USDC, DAI)", overlay=false)
// this index's goal is to show the true bitcoin dominance relative to other risky crypto assets,
// excluding stablecoin(USDT, USDC, DAI)'s diluting effect on btc dominance.
timeframeInput = input.timeframe("D", "Timeframe")
sourceInput = input.source(hl2, "Source")
periodInput = input(1, "Period")
btc_cap = request.security(input.symbol("BTC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
crypto_cap = request.security(input.symbol("TOTAL", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdc_cap = request.security(input.symbol("USDC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdt_cap = request.security(input.symbol("USDT_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
busd_cap = request.security(input.symbol("BUSD_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
dai_cap = request.security(input.symbol("DAI_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
index = btc_cap / (crypto_cap - usdc_cap - usdt_cap - busd_cap - dai_cap) *100
plot(index)
|
Stable Coin Dominance RSI | https://www.tradingview.com/script/4zauaOcE-Stable-Coin-Dominance-RSI/ | DamonAndTheSea | https://www.tradingview.com/u/DamonAndTheSea/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© DamonAndTheSea
//@version=5
indicator("Stable Coin Dominance RSI")
//Inputs
rsiLengthInput = input.int(14, minval=1, title="RSI Length")
includesUSDCInput = input.bool(true, "USDC", group="Included Stables")
includesUSDTInput = input.bool(true, "USDT", group="Included Stables")
includesBTC = input.bool(true, "BTC", group="Included Crypto")
includesALTS = input.bool(true, "ALTS", group="Included Crypto")
//Collect candle data for stables and total crypto market cap
usdc = request.security('CRYPTOCAP:USDC', timeframe.period, expression=close)
usdt = request.security('CRYPTOCAP:USDT', timeframe.period, expression=close)
btc = request.security('CRYPTOCAP:BTC', timeframe.period, expression=close)
total2 = request.security('CRYPTOCAP:TOTAL2', timeframe.period, expression=close)
//Calculate dominance and rsi
dom = ((includesUSDCInput == true ? usdc : 0) + (includesUSDTInput == true ? usdt : 0)) /
((includesBTC == true ? btc : 0) + (includesALTS == true ? total2 : 0))
rsi = ta.rsi(dom, rsiLengthInput)
//UI
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
plot(rsi, color=color.fuchsia) |
TASC 2022.10 RS VA EMA | https://www.tradingview.com/script/kGIcnSdD-TASC-2022-10-RS-VA-EMA/ | PineCodersTASC | https://www.tradingview.com/u/PineCodersTASC/ | 106 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© PineCodersTASC
// TASC Issue: October 2022 - Vol. 40, Issue 11
// Article: Relative Strength Moving Averages
// Part 2: The Relative Strength Volume-Adjusted
// Exponential Moving Average (RS VA EMA)
// Article By: Vitali Apirine
// Language: TradingView's Pine Script v5
// Provided By: PineCoders, for tradingview.com
//@version=5
indicator('TASC 2022.10 RS VA EMA', overlay=true)
float src = input.source(close, 'Source:')
int periods = input.int(10, 'EMA Length:', minval=1)
int pds = input.int(10, 'VS Length:', minval=1)
float mltp = input.int(10, 'VS Multiplier:', minval=0)
rsvaema(float source = close,
simple int emaPeriod = 50,
simple int vsPeriod = 50,
float multiplier = 10.0
) =>
var float mltp1 = 2.0 / (emaPeriod + 1.0)
var float coef1 = 2.0 / (vsPeriod + 1.0)
var float coef2 = 1.0 - coef1
float pv = source > source[1] ? volume : 0.0
float nv = source < source[1] ? volume : 0.0
float apv = na, apv := coef1 * pv + coef2 * nz(apv[1])
float anv = na, anv := coef1 * nv + coef2 * nz(anv[1])
float vs = math.abs(apv - anv) / (apv + anv)
float rate = mltp1 * (1.0 + nz(vs, 0.00001) * multiplier)
float rsma = na
rsma := rate * source + (1.0 - rate) * nz(rsma[1],source)
rsma
float rsvaema = rsvaema(src, periods, pds, mltp)
plot(rsvaema, title='RS VA EMA', color=#B21BD8, linewidth=2) |
Intrisic Value by Enterprise value - GVP | https://www.tradingview.com/script/6ot0gNog-Intrisic-Value-by-Enterprise-value-GVP/ | girbeap | https://www.tradingview.com/u/girbeap/ | 8 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© girbeap
//@version=5
indicator("Intrisic Value by Enterprise value - GVP", overlay = true)
MarketCap = request.financial(syminfo.tickerid, "ENTERPRISE_VALUE", "FQ")
TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
Instrisic_value = MarketCap/TSO
Sell = Instrisic_value * 1.2
Buy = Instrisic_value * 0.8
plot(Sell, linewidth = 3, color = color.red)
plot(Buy, linewidth = 3, color = color.green)
|
Full Volatility Statistics and Forecast | https://www.tradingview.com/script/pzfWp5RW-Full-Volatility-Statistics-and-Forecast/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© exlux99
//@version=5
indicator("Full Volatility Statistics and Forecast", overlay=true)
////////////////////////
// FUNCTIONS
source = input.source(open, title="Source of the Candle", group="Source", group="Candle")
candle_point = 0//input.int(0, title="Candle Calculation", group="Candle")
volatility_source = input.symbol("TVC:VIX", title= "External Source Volatility", group="Volatility")
coeficient = input.float(1.0, step=0.25, title="Coefficient", group="Volatility")
vix = request.security(volatility_source, timeframe.period, open)
vix_close = request.security(volatility_source, timeframe.period, close[1])
vix_length = 1//input.int(1)
vix_sma_hv = ta.sma(vix_close,(vix_length))
vix_sma = ta.sma(vix,(vix_length))
// label Panel Function
_label(T, color_PnL) =>
label PnL_Label = na
label.delete(PnL_Label[1])
PnL_Label := label.new(time, 0, text=T, color=color_PnL, textcolor=color.white, size=size.normal, style=label.style_label_lower_left, xloc=xloc.bar_time, textalign=text.align_left)
label.set_x(PnL_Label, label.get_x(PnL_Label) + math.round(ta.change(time) * 3))
// Round Function
Round(src, digits) =>
p = math.pow(10, digits)
math.round(math.abs(src) * p) / p * math.sign(src)
sqrt_movement = input.float(252, title="Timeframe Adaptation", group="Volatility")
// Historical Volatiity Models
Hv_zero = vix_sma_hv*coeficient
var int min_hv_iv_plus =0
var int max_hv_iv_plus =0
var int min_temp_hv_iv_plus =0
var int max_temp_hv_iv_plus =0
var int min_hv_iv_minus =0
var int max_hv_iv_minus =0
var int min_temp_hv_iv_minus =0
var int max_temp_hv_iv_minus =0
var float avg_distance_top_hv_iv_plus = 0
var float daily_bull_movement_hv_iv_plus = 0
var float avg_distance_bot_hv_iv_plus = 0
var float daily_bear_movement_hv_iv_plus = 0
var float avg_distance_top_hv_iv_minus = 0
var float daily_bull_movement_hv_iv_minus = 0
var float avg_distance_bot_hv_iv_minus = 0
var float daily_bear_movement_hv_iv_minus = 0
var float daily_bull_movement = 0
var int count_bull = 0
var float daily_bear_movement = 0
var int count_bear = 0
Hv = Hv_zero/ math.sqrt(sqrt_movement)
top_channel = source + (source*Hv)/100
bot_channel = source - (source*Hv)/100
plot(top_channel)
plot(bot_channel)
var bool data_top_cross = false
var bool data_bot_cross = false
var bool suma_velas = false
var bool data_top_cross_partial_high = false
var bool data_bot_cross_partial_high = false
var bool suma_velas_partial_high = false
fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Time Condition')
fromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12, group='Time Condition')
fromYear = input.int(defval=2000, title='From Year', minval=1970, group='Time Condition')
//monday and session
// To Date Inputs
toDay = input.int(defval=31, title='To Day', minval=1, maxval=31, group='Time Condition')
toMonth = input.int(defval=12, title='To Month', minval=1, maxval=12, group='Time Condition')
toYear = input.int(defval=2029, title='To Year', minval=1970, group='Time Condition')
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
data_top_cross := close >= top_channel[candle_point] and time_cond
data_bot_cross := close <= bot_channel[candle_point] and time_cond
suma_velas := close!=0
plotshape(data_top_cross, style=shape.xcross, location=location.abovebar, color=color.yellow)
plotshape(data_bot_cross, style=shape.xcross, location=location.belowbar, color=color.yellow)
data_top_cross_partial_high := high >= top_channel[candle_point] and time_cond
data_bot_cross_partial_high := low <= bot_channel[candle_point] and time_cond
suma_velas_partial_high := close!=0
var int count_top_crosses_hv_iv_plus = 0
var int count_bot_crosses_hv_iv_plus = 0
if(data_top_cross and Hv<= vix_sma)
count_top_crosses_hv_iv_plus:=count_top_crosses_hv_iv_plus+1
if(data_bot_cross and Hv<= vix_sma )
count_bot_crosses_hv_iv_plus:=count_bot_crosses_hv_iv_plus+1
var int count_candles_hv_iv_plus = 0
if(suma_velas and time_cond and Hv <= vix_sma)
count_candles_hv_iv_plus := count_candles_hv_iv_plus+1
ratio_hv_iv_plus = (count_top_crosses_hv_iv_plus + count_bot_crosses_hv_iv_plus) / count_candles_hv_iv_plus
///////////////////////////////////////////////
var int count_top_crosses_hv_iv_plus_partial_high = 0
var int count_bot_crosses_hv_iv_plus_partial_high = 0
if(data_top_cross_partial_high and Hv<= vix_sma)
count_top_crosses_hv_iv_plus_partial_high:=count_top_crosses_hv_iv_plus_partial_high+1
if(data_bot_cross_partial_high and Hv<= vix_sma )
count_bot_crosses_hv_iv_plus_partial_high:=count_bot_crosses_hv_iv_plus_partial_high+1
var int count_candles_hv_iv_plus_partial_high = 0
if(suma_velas_partial_high and time_cond and Hv <= vix_sma)
count_candles_hv_iv_plus_partial_high := count_candles_hv_iv_plus_partial_high+1
ratio_hv_iv_plus_partial_high = (count_top_crosses_hv_iv_plus_partial_high + count_bot_crosses_hv_iv_plus_partial_high) / count_candles_hv_iv_plus_partial_high
if(time_cond and (data_top_cross or data_bot_cross) and Hv <= vix_sma )
min_temp_hv_iv_plus:=0
max_temp_hv_iv_plus := max_temp_hv_iv_plus+1
if(max_temp_hv_iv_plus>max_hv_iv_plus )
max_hv_iv_plus:=max_temp_hv_iv_plus
if(time_cond and Hv <= vix_sma and not (data_top_cross or data_bot_cross ) )
max_temp_hv_iv_plus:=0
min_temp_hv_iv_plus := min_temp_hv_iv_plus+1
if(min_temp_hv_iv_plus > min_hv_iv_plus )
min_hv_iv_plus:=min_temp_hv_iv_plus
var int count_top_crosses_hv_iv_minus = 0
var int count_bot_crosses_hv_iv_minus = 0
if(data_top_cross and Hv > vix_sma)
count_top_crosses_hv_iv_minus:=count_top_crosses_hv_iv_minus+1
if(data_bot_cross and Hv > vix_sma)
count_bot_crosses_hv_iv_minus:=count_bot_crosses_hv_iv_minus+1
var int count_candles_hv_iv_minus = 0
if(suma_velas and time_cond and Hv > vix_sma)
count_candles_hv_iv_minus := count_candles_hv_iv_minus+1
ratio_hv_iv_minus = (count_top_crosses_hv_iv_minus + count_bot_crosses_hv_iv_minus) / count_candles_hv_iv_minus
//////////////////////////////////////////////////////////////////
var int count_top_crosses_hv_iv_minus_partial_high = 0
var int count_bot_crosses_hv_iv_minus_partial_high = 0
if(data_top_cross_partial_high and Hv > vix_sma)
count_top_crosses_hv_iv_minus_partial_high:=count_top_crosses_hv_iv_minus_partial_high+1
if(data_bot_cross_partial_high and Hv > vix_sma)
count_bot_crosses_hv_iv_minus_partial_high:=count_bot_crosses_hv_iv_minus_partial_high+1
var int count_candles_hv_iv_minus_partial_high = 0
if(suma_velas_partial_high and time_cond and Hv > vix_sma)
count_candles_hv_iv_minus_partial_high := count_candles_hv_iv_minus_partial_high+1
ratio_hv_iv_minus_partial_high = (count_top_crosses_hv_iv_minus_partial_high + count_bot_crosses_hv_iv_minus_partial_high) / count_candles_hv_iv_minus_partial_high
if(time_cond and (data_top_cross or data_bot_cross) and Hv> vix_sma )
min_temp_hv_iv_minus:=0
max_temp_hv_iv_minus := max_temp_hv_iv_minus+1
if(max_temp_hv_iv_minus>max_hv_iv_minus)
max_hv_iv_minus:=max_temp_hv_iv_minus
if(time_cond and Hv > vix_sma and not (data_top_cross or data_bot_cross ) )
max_temp_hv_iv_minus:=0
min_temp_hv_iv_minus := min_temp_hv_iv_minus+1
if(min_temp_hv_iv_minus > min_hv_iv_minus )
min_hv_iv_minus:=min_temp_hv_iv_minus
total_candles = count_candles_hv_iv_minus + count_candles_hv_iv_plus
avg_Occurence = ((ratio_hv_iv_minus * count_candles_hv_iv_minus) + (ratio_hv_iv_plus *count_candles_hv_iv_plus )) / total_candles
avg_Occurence_max_loss = ((max_hv_iv_minus * count_candles_hv_iv_minus) + (max_hv_iv_plus *count_candles_hv_iv_plus )) / total_candles
avg_Occurence_max_win = ((min_hv_iv_minus * count_candles_hv_iv_minus) + (min_hv_iv_plus *count_candles_hv_iv_plus )) / total_candles
////////////////////////////////////////////////////////////////////////////
if (data_top_cross and Hv> vix_sma)
avg_distance_top_hv_iv_minus:=avg_distance_top_hv_iv_minus+ ((close - top_channel[candle_point])/top_channel[candle_point])
//daily_bull_movement_hv_iv_minus:=daily_bull_movement_hv_iv_minus+((close-open)/open)
if (data_bot_cross and Hv > vix_sma )
avg_distance_bot_hv_iv_minus:=avg_distance_bot_hv_iv_minus+ ((bot_channel[candle_point] - close)/close)
//daily_bear_movement_hv_iv_minus:=daily_bear_movement_hv_iv_minus+((open-close)/close)
if (data_top_cross and Hv<= vix_sma)
avg_distance_top_hv_iv_plus:=avg_distance_top_hv_iv_plus+ ((close - top_channel[candle_point])/top_channel[candle_point])
//daily_bull_movement_hv_iv_plus:=daily_bull_movement_hv_iv_plus+((close-open)/open)
if (data_bot_cross and Hv<= vix_sma )
avg_distance_bot_hv_iv_plus:=avg_distance_bot_hv_iv_plus+((bot_channel[candle_point] - close)/close)
//daily_bear_movement_hv_iv_plus:=daily_bear_movement_hv_iv_plus+((open-close)/close)
////////////////////////////////////////////////////////////////////////////
if(close > open and time_cond )
count_bull:=count_bull+1
daily_bull_movement:=daily_bull_movement+((close-open)/open)
if(close < open and time_cond)
count_bear:=count_bear+1
daily_bear_movement:=daily_bear_movement+((open-close)/close)
////////////////////////////////////////////////////////////////////////////
posInput = input.string(title='Position', defval='Middle Right', options=['Bottom Left', 'Bottom Right', 'Top Left', 'Top Right', 'Middle Right'])
var pos = posInput == 'Bottom Left' ? position.bottom_left : posInput == 'Bottom Right' ? position.bottom_right : posInput == 'Top Left' ? position.top_left : posInput == 'Top Right' ? position.top_right : posInput == 'Middle Right' ? position.middle_right: na
var table table_atr = table.new(pos, 15, 15, border_width=1)
table_fillCell(_table, _column, _row, _value, _timeframe, _c_color) =>
_transp = 70
_cellText = str.tostring(_value, '#.###')
table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_c_color, _transp), text_color=_c_color, width=5)
//table.cell_set_text_size(table_atr, 0, 2, text)
if barstate.islast
table.cell(table_atr, 0, 0, 'Total C', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 0, 1, count_top_crosses_hv_iv_plus+ count_bot_crosses_hv_iv_plus, 'Text', color.white)
table.cell(table_atr, 1, 0, 'BOT Ξ¨ C', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 1, 1, count_bot_crosses_hv_iv_plus, 'Text', color.white)
table.cell(table_atr, 2, 0, 'TOP Ξ¨ C', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 2, 1, count_top_crosses_hv_iv_plus, 'Text', color.white)
table.cell(table_atr, 3, 0, 'Candles Ξ¨ C', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 3, 1, count_candles_hv_iv_plus, 'Text', color.white)
table.cell(table_atr, 4, 0, 'Occurence Ξ¨ C', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 4, 1, ratio_hv_iv_plus, 'Text HV<IV', color.white)
table.cell(table_atr, 5, 0, 'OUT', text_color=color.white, text_size=size.normal, bgcolor= coeficient < 1?color.lime: color.red)
table_fillCell(table_atr, 5, 1, max_hv_iv_plus, 'Text HV<IV', color.white)
table.cell(table_atr, 6, 0, 'IN ', text_color=color.white, text_size=size.normal, bgcolor= coeficient < 1? color.red : color.lime)
table_fillCell(table_atr, 6, 1, min_hv_iv_plus, 'Text HV<IV', color.white)
table.cell(table_atr, 7, 0, '% D top', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
table_fillCell(table_atr, 7, 1, (avg_distance_top_hv_iv_plus/count_top_crosses_hv_iv_plus)*100, 'AVG Distance HV<IV', color.white)
table.cell(table_atr, 8, 0, '% D bot', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
table_fillCell(table_atr, 8, 1, (avg_distance_bot_hv_iv_plus/count_bot_crosses_hv_iv_plus)*100, 'AVG Distance HV<IV', color.white)
// table.cell(table_atr, 9, 0, 'AVG Bull', text_color=color.white, text_size=size.normal, bgcolor=color.lime)
// table_fillCell(table_atr, 9, 1, (daily_bull_movement_hv_iv_plus/count_top_crosses_hv_iv_plus)*100, 'AVG Distance HV<IV', color.white)
// table.cell(table_atr, 10, 0, 'AVG Bear', text_color=color.white, text_size=size.normal, bgcolor=color.red)
// table_fillCell(table_atr, 10, 1, (daily_bear_movement_hv_iv_plus/count_bot_crosses_hv_iv_plus)*100, 'AVG Distance HV<IV', color.white)
// table.cell(table_atr, 0, 4, 'Total Ξ© C', text_color=color.white, text_size=size.normal, bgcolor=color.aqua)
// table_fillCell(table_atr, 0, 5, count_top_crosses_hv_iv_minus + count_bot_crosses_hv_iv_minus, 'Text', color.white)
// table.cell(table_atr, 1, 4, 'BOT Ξ© C', text_color=color.white, text_size=size.normal, bgcolor=color.aqua)
// table_fillCell(table_atr, 1, 5, count_bot_crosses_hv_iv_minus, 'Text', color.white)
// table.cell(table_atr, 2, 4, 'TOP Ξ© C', text_color=color.white, text_size=size.normal, bgcolor=color.aqua)
// table_fillCell(table_atr, 2, 5, count_top_crosses_hv_iv_minus, 'Text', color.white)
// table.cell(table_atr, 3, 4, 'Candles Ξ© C', text_color=color.white, text_size=size.normal, bgcolor=color.aqua)
// table_fillCell(table_atr, 3, 5, count_candles_hv_iv_minus, 'Text', color.white)
// table.cell(table_atr, 4, 4, 'Occurence Ξ© C', text_color=color.white, text_size=size.normal, bgcolor=color.aqua)
// table_fillCell(table_atr, 4, 5, ratio_hv_iv_minus, 'Text', color.white)
// table.cell(table_atr, 5, 4, 'OUT', text_color=color.white, text_size=size.normal, bgcolor=color.red)
// table.cell(table_atr, 6, 4, 'IN', text_color=color.white, text_size=size.normal, bgcolor=color.lime)
// table_fillCell(table_atr, 5, 5, max_hv_iv_minus, 'Text', color.white)
// table_fillCell(table_atr, 6, 5, min_hv_iv_minus, 'Text', color.white)
// table.cell(table_atr, 7, 4, '% D top', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
// table_fillCell(table_atr, 7, 5, (avg_distance_top_hv_iv_minus/count_top_crosses_hv_iv_minus)*100, 'AVG Distance HV>IV', color.white)
// table.cell(table_atr, 8, 4, '% D bot', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
// table_fillCell(table_atr, 8, 5, (avg_distance_bot_hv_iv_minus/count_bot_crosses_hv_iv_minus)*100, 'AVG Distance HV>IV', color.white)
// // table.cell(table_atr, 9, 2, 'AVG Bull', text_color=color.white, text_size=size.normal, bgcolor=color.lime)
// // table_fillCell(table_atr, 9, 3, (daily_bull_movement_hv_iv_minus/count_top_crosses_hv_iv_minus)*100, 'AVG Distance HV>IV', color.white)
// // table.cell(table_atr, 10, 2, 'AVG Bear', text_color=color.white, text_size=size.normal, bgcolor=color.red)
// // table_fillCell(table_atr, 10, 3, (daily_bear_movement_hv_iv_minus/count_bot_crosses_hv_iv_minus)*100, 'AVG Distance HV>IV', color.white)
table.cell(table_atr, 0, 8, 'β', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table_fillCell(table_atr, 0, 9, close*(vix_sma/ math.sqrt(sqrt_movement))/100, 'Text', color.white)
table.cell(table_atr, 1, 8, 'TOP β', text_color=color.white, text_size=size.normal, bgcolor=color.lime)
table_fillCell(table_atr, 1, 9, top_channel[candle_point], 'Text', color.white)
table.cell(table_atr, 2, 8, 'BOT β', text_color=color.white, text_size=size.normal, bgcolor=color.orange)
table_fillCell(table_atr, 2, 9, bot_channel[candle_point], 'Text', color.white)
table.cell(table_atr, 3, 8, 'Total Candles', text_color=color.white, text_size=size.normal, bgcolor=color.navy)
table_fillCell(table_atr, 3, 9, total_candles, 'Text', color.white)
table.cell(table_atr, 4, 8, 'AVG Occurence', text_color=color.white, text_size=size.normal, bgcolor=color.navy)
table_fillCell(table_atr, 4, 9, avg_Occurence, 'Text', color.white)
table.cell(table_atr, 5, 8, 'AVG OUT', text_color=color.white, text_size=size.normal, bgcolor=color.navy)
table_fillCell(table_atr, 5, 9, avg_Occurence_max_loss, 'Text', color.white)
table.cell(table_atr, 6, 8, 'AVG IN', text_color=color.white, text_size=size.normal, bgcolor=color.navy)
table_fillCell(table_atr, 6, 9, avg_Occurence_max_win, 'Text', color.white)
table.cell(table_atr, 7, 8, 'AVG Bull', text_color=color.white, text_size=size.normal, bgcolor=color.lime)
table_fillCell(table_atr, 7, 9, (daily_bull_movement/count_bull)*100, 'Text', color.white)
table.cell(table_atr, 8, 8, 'AVG Bear', text_color=color.white, text_size=size.normal, bgcolor=color.red)
table_fillCell(table_atr, 8, 9, (daily_bear_movement/count_bear)*100, 'Text', color.white)
|
position size for short selling-Roy Lee | https://www.tradingview.com/script/7S8pAuAE-position-size-for-short-selling-Roy-Lee/ | snagy23 | https://www.tradingview.com/u/snagy23/ | 8 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© snagy23
//@version=4
study("position size", overlay= true)
InputLookBack = input(title="lookback period", type = input.integer, defval=50, minval=1)
InputRiskVal = input(title="dollar risk value", type = input.integer, defval=100, minval=1)
InputOffSet = input(title="postion offset by precentage above Highest price period", type = input.integer, defval=0, minval=0)
InputStopLoss = input(title="Stop Loss Price", type = input.float, defval=0, minval=0)
InputAvgPrice = input(title="Your current average price", type = input.float, defval=0, minval=0)
InputTotalShares = input(title="Your current total shares", type = input.integer, defval=0, minval=0)
ShareVal = InputAvgPrice*InputTotalShares
Highesthigh = highest(high,InputLookBack)
StopLossPrice = if InputStopLoss >0
InputStopLoss
else
Highesthigh*((InputOffSet/100)+1)
CurrentVal = if InputStopLoss > 0
InputStopLoss
else
close
PositionSize = if InputAvgPrice > 0 and InputTotalShares > 0
InputRiskVal/ShareVal
else
InputRiskVal/(StopLossPrice-CurrentVal)
labelexample = if PositionSize > 0
label.new(bar_index, na, tostring(PositionSize,"#"), color=color.green, textcolor=color.white, style=label.style_label_down, yloc=yloc.abovebar)
else
label.new(bar_index, na, ("Max Size reached"), color=color.green, textcolor=color.red, style=label.style_label_down, yloc=yloc.abovebar)
label.delete(labelexample[1])
plot(StopLossPrice, color=color.red, linewidth =2)
|
STD-Filtered, Adaptive Exponential Hull Moving Average [Loxx] | https://www.tradingview.com/script/UYfYiSKe-STD-Filtered-Adaptive-Exponential-Hull-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 328 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD-Filtered, Adaptive Exponential Hull Moving Average [Loxx]",
shorttitle = "STDAEHMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
aEMA(float src, float alpha) =>
ema = src
ema := na(ema[1]) ? src : nz(ema[1]) + alpha * (src - nz(ema[1]))
ema
adaptiveAlpha(float SNR, float periodL, float periodH)=>
float al = 2.0 / (periodL + 1.0)
float ah = 2.0 / (periodH + 1.0)
out = (ah + SNR * (al - ah))
out
hullAdaptiveMovingAverage(float src, int persnr, int perfast, int perslow, int gain, float beta)=>
float signal = math.abs(src - nz(src[persnr]))
float noise = 0
for i = 0 to persnr - 1
noise += math.abs(nz(src[i]) - nz(src[i + 1]))
float SNR = beta * signal / noise * math.sqrt(persnr)
float exp2SNR = math.exp(2.0 * SNR)
float tanhSNR = (exp2SNR - 1.0) / (exp2SNR + 1.0)
float w = math.pow(tanhSNR, gain)
float a1 = adaptiveAlpha(w, perfast * 0.5, perslow * 0.5)
float a2 = adaptiveAlpha(w, perfast, perslow)
float a3 = adaptiveAlpha(w, math.sqrt(perfast), math.sqrt(perslow))
float h1 = src
float h2 = src
float h3 = src
h1 := aEMA(h1, a1)
h2 := aEMA(h2, a2)
h3 := (2 * h1 - h2)
h3 := aEMA(h3, a3)
h3
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
persnr = input.int(10, "Signl-to-Noise Ratio (SNR) Period", group = "Basic Settings")
perfast = input.int(7, "Fast Period", group = "Basic Settings")
perslow = input.int(30, "Slow Period", group = "Basic Settings")
gain = input.int(2, "Gain", group = "Basic Settings")
beta = input.float(.25, "Beta", group = "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "AEHMA", "Both", "None"], group= "Filter Settings")
filter = input.float(1, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(10, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
out = hullAdaptiveMovingAverage(src, persnr, perfast, perslow, gain, beta)
out := filterop == "Both" or filterop == "AEHMA" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
state = out > sig ? 1 : out < sig ? -1 : 0
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "Step AEHMA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD-Filtered, Adaptive Exponential Hull Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD-Filtered, Adaptive Exponential Hull Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
STD-Filtered, Ultra Low Lag Moving Average [Loxx] | https://www.tradingview.com/script/YQpwxN78-STD-Filtered-Ultra-Low-Lag-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 132 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD-Filtered, Ultra Low Lag Moving Average [Loxx]",
shorttitle = "STDFULLMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
sinc(float x)=>
out = x == 0.0 ? 1. : math.sin(math.pi * x) / (math.pi * x)
out
design(int type, int per)=>
float[] coeff = array.new<float>(per, 0)
float cycles = 0.
switch type
0=> cycles := 1.25
1=> cycles := 2.5
2=> cycles := 3.75
3=> cycles := 6.25
=> cycles := 6.25
float sum = 0.0
float w = per
for n = 0 to per - 1
float x = sinc((n / w) * (cycles * math.pi))
array.set(coeff, n, x)
sum += x
sum := 1.0 / sum
for i = 0 to per - 1
array.set(coeff, i, array.get(coeff, i) * sum)
coeff
directFormFIR(int type, float src, int per)=>
float[] coeff = design(type, per)
float sum = 0.0
for n = 0 to per - 1
sum += nz(src[n]) * array.get(coeff, n)
sum
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(39, "Period", group= "Basic Settings")
type = input.int(0, "Type", minval = 0, group= "Basic Settings")
filterop = input.string("ULLMA", "Filter Options", options = ["Price", "ULLMA", "Both", "None"], group= "Filter Settings")
filter = input.float(1, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
out = directFormFIR(type, src, per)
out := filterop == "Both" or filterop == "ULLMA" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
state = out > sig ? 1 : out < sig ? -1 : 0
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "Step ULLMA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD-Filtered, Ultra Low Lag Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD-Filtered, Ultra Low Lag Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Instrisic Value by FCF - GVP | https://www.tradingview.com/script/y1UATSDM-Instrisic-Value-by-FCF-GVP/ | girbeap | https://www.tradingview.com/u/girbeap/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© girbeap
//@version=5
indicator("Instrisic Value by FCF - GVP", overlay = true)
Growth_Multiple = request.financial(syminfo.tickerid, "SUSTAINABLE_GROWTH_RATE", "FQ")
Free_Cash_Flow = request.financial(syminfo.tickerid, "FREE_CASH_FLOW", "FQ")/1000000
Total_Stockholders_Equity = request.financial(syminfo.tickerid, "SHRHLDRS_EQUITY", "FQ")/1000000
Shares_Outstanding = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")/1000000
Projected_FCF = (Growth_Multiple * Free_Cash_Flow + Total_Stockholders_Equity * 0.8) / Shares_Outstanding
Sell = Projected_FCF * 1.2
Buy = Projected_FCF * 0.8
plot(Sell, linewidth = 3, color = color.red)
plot(Buy, linewidth = 3, color = color.green)
|
Regression Channel, Candles and Candlestick Patterns by Monty | https://www.tradingview.com/script/IwvOsBHC-Regression-Channel-Candles-and-Candlestick-Patterns-by-Monty/ | MontyTheGuy | https://www.tradingview.com/u/MontyTheGuy/ | 204 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© MontyTheGuy
//Regression Candles by ugurvu
//Regression Channel by Tradingview
//All Candlestick Patterns By Tradingview
//@version=5
indicator("Regression Channel, Candles and Candlestick Patterns", shorttitle = "RegChannel & Candlesticks By Monty", overlay=true)
C_DownTrend = true
C_UpTrend = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = input.string(trendRule1, "Detect Trend Based On", options=[trendRule1, trendRule2, "No detection"])
if trendRule == trendRule1
priceAvg = ta.sma(close, 50)
C_DownTrend := close < priceAvg
C_UpTrend := close > priceAvg
if trendRule == trendRule2
sma200 = ta.sma(close, 200)
sma50 = ta.sma(close, 50)
C_DownTrend := close < sma50 and sma50 < sma200
C_UpTrend := close > sma50 and sma50 > sma200
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body
C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high-low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
patternLabelPosLow = low - (ta.atr(30) * 0.6)
patternLabelPosHigh = high + (ta.atr(30) * 0.6)
label_color_bullish = input(color.blue, "Label Color Bullish")
label_color_bearish = input(color.red, "Label Color Bearish")
label_color_neutral = input(color.gray, "Label Color Neutral")
CandleType = input.string(title = "Pattern Type", defval="Both", options=["Bullish", "Bearish", "Both"])
AbandonedBabyInput = input(title = "Abandoned Baby" ,defval=true)
DarkCloudCoverInput = input(title = "Dark Cloud Cover" ,defval=false)
DojiInput = input(title = "Doji" ,defval=true)
DojiStarInput = input(title = "Doji Star" ,defval=false)
DownsideTasukiGapInput = input(title = "Downside Tasuki Gap" ,defval=false)
DragonflyDojiInput = input(title = "Dragonfly Doji" ,defval=true)
EngulfingInput = input(title = "Engulfing" ,defval=true)
EveningDojiStarInput = input(title = "Evening Doji Star" ,defval=false)
EveningStarInput = input(title = "Evening Star" ,defval=false)
FallingThreeMethodsInput = input(title = "Falling Three Methods" ,defval=false)
FallingWindowInput = input(title = "Falling Window" ,defval=false)
GravestoneDojiInput = input(title = "Gravestone Doji" ,defval=false)
HammerInput = input(title = "Hammer" ,defval=true)
HangingManInput = input(title = "Hanging Man" ,defval=false)
HaramiCrossInput = input(title = "Harami Cross" ,defval=false)
HaramiInput = input(title = "Harami" ,defval=false)
InvertedHammerInput = input(title = "Inverted Hammer" ,defval=false)
KickingInput = input(title = "Kicking" ,defval=false)
LongLowerShadowInput = input(title = "Long Lower Shadow" ,defval=false)
LongUpperShadowInput = input(title = "Long Upper Shadow" ,defval=false)
MarubozuBlackInput = input(title = "Marubozu Black" ,defval=false)
MarubozuWhiteInput = input(title = "Marubozu White" ,defval=false)
MorningDojiStarInput = input(title = "Morning Doji Star" ,defval=false)
MorningStarInput = input(title = "Morning Star" ,defval=false)
OnNeckInput = input(title = "On Neck" ,defval=false)
PiercingInput = input(title = "Piercing" ,defval=false)
RisingThreeMethodsInput = input(title = "Rising Three Methods" ,defval=false)
RisingWindowInput = input(title = "Rising Window" ,defval=false)
ShootingStarInput = input(title = "Shooting Star" ,defval=false)
SpinningTopBlackInput = input(title = "Spinning Top Black" ,defval=false)
SpinningTopWhiteInput = input(title = "Spinning Top White" ,defval=false)
ThreeBlackCrowsInput = input(title = "Three Black Crows" ,defval=false)
ThreeWhiteSoldiersInput = input(title = "Three White Soldiers" ,defval=false)
TriStarInput = input(title = "Tri-Star" ,defval=false)
TweezerBottomInput = input(title = "Tweezer Bottom" ,defval=false)
TweezerTopInput = input(title = "Tweezer Top" ,defval=false)
UpsideTasukiGapInput = input(title = "Upside Tasuki Gap" ,defval=false)
C_OnNeckBearishNumberOfCandles = 2
C_OnNeckBearish = false
if C_DownTrend and C_BlackBody[1] and C_LongBody[1] and C_WhiteBody and open < close[1] and C_SmallBody and C_Range!=0 and math.abs(close-low[1])<=C_BodyAvg*0.05
C_OnNeckBearish := true
alertcondition(C_OnNeckBearish, title = "On Neck β Bearish", message = "New On Neck β Bearish pattern detected")
if C_OnNeckBearish and OnNeckInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishOnNeck = "On Neck\nOn Neck is a two-line continuation pattern found in a downtrend. The first candle is long and red, the second candle is short and has a green body. The closing price of the second candle is close or equal to the first candle's low price. The pattern hints at a continuation of a downtrend, and penetrating the low of the green candlestick is sometimes considered a confirmation. "
label.new(bar_index, patternLabelPosHigh, text="ON", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishOnNeck)
C_RisingWindowBullishNumberOfCandles = 2
C_RisingWindowBullish = false
if C_UpTrend[1] and (C_Range!=0 and C_Range[1]!=0) and low > high[1]
C_RisingWindowBullish := true
alertcondition(C_RisingWindowBullish, title = "Rising Window β Bullish", message = "New Rising Window β Bullish pattern detected")
if C_RisingWindowBullish and RisingWindowInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishRisingWindow = "Rising Window\nRising Window is a two-candle bullish continuation pattern that forms during an uptrend. Both candles in the pattern can be of any type with the exception of the Four-Price Doji. The most important characteristic of the pattern is a price gap between the first candle's high and the second candle's low. That gap (window) between two bars signifies support against the selling pressure."
label.new(bar_index, patternLabelPosLow, text="RW", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishRisingWindow)
C_FallingWindowBearishNumberOfCandles = 2
C_FallingWindowBearish = false
if C_DownTrend[1] and (C_Range!=0 and C_Range[1]!=0) and high < low[1]
C_FallingWindowBearish := true
alertcondition(C_FallingWindowBearish, title = "Falling Window β Bearish", message = "New Falling Window β Bearish pattern detected")
if C_FallingWindowBearish and FallingWindowInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishFallingWindow = "Falling Window\nFalling Window is a two-candle bearish continuation pattern that forms during a downtrend. Both candles in the pattern can be of any type, with the exception of the Four-Price Doji. The most important characteristic of the pattern is a price gap between the first candle's low and the second candle's high. The existence of this gap (window) means that the bearish trend is expected to continue."
label.new(bar_index, patternLabelPosHigh, text="FW", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishFallingWindow)
C_FallingThreeMethodsBearishNumberOfCandles = 5
C_FallingThreeMethodsBearish = false
if C_DownTrend[4] and (C_LongBody[4] and C_BlackBody[4]) and (C_SmallBody[3] and C_WhiteBody[3] and open[3]>low[4] and close[3]<high[4]) and (C_SmallBody[2] and C_WhiteBody[2] and open[2]>low[4] and close[2]<high[4]) and (C_SmallBody[1] and C_WhiteBody[1] and open[1]>low[4] and close[1]<high[4]) and (C_LongBody and C_BlackBody and close<close[4])
C_FallingThreeMethodsBearish := true
alertcondition(C_FallingThreeMethodsBearish, title = "Falling Three Methods β Bearish", message = "New Falling Three Methods β Bearish pattern detected")
if C_FallingThreeMethodsBearish and FallingThreeMethodsInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishFallingThreeMethods = "Falling Three Methods\nFalling Three Methods is a five-candle bearish pattern that signifies a continuation of an existing downtrend. The first candle is long and red, followed by three short green candles with bodies inside the range of the first candle. The last candle is also red and long and it closes below the close of the first candle. This decisive fifth strongly bearish candle hints that bulls could not reverse the prior downtrend and that bears have regained control of the market."
label.new(bar_index, patternLabelPosHigh, text="FTM", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishFallingThreeMethods)
C_RisingThreeMethodsBullishNumberOfCandles = 5
C_RisingThreeMethodsBullish = false
if C_UpTrend[4] and (C_LongBody[4] and C_WhiteBody[4]) and (C_SmallBody[3] and C_BlackBody[3] and open[3]<high[4] and close[3]>low[4]) and (C_SmallBody[2] and C_BlackBody[2] and open[2]<high[4] and close[2]>low[4]) and (C_SmallBody[1] and C_BlackBody[1] and open[1]<high[4] and close[1]>low[4]) and (C_LongBody and C_WhiteBody and close>close[4])
C_RisingThreeMethodsBullish := true
alertcondition(C_RisingThreeMethodsBullish, title = "Rising Three Methods β Bullish", message = "New Rising Three Methods β Bullish pattern detected")
if C_RisingThreeMethodsBullish and RisingThreeMethodsInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishRisingThreeMethods = "Rising Three Methods\nRising Three Methods is a five-candle bullish pattern that signifies a continuation of an existing uptrend. The first candle is long and green, followed by three short red candles with bodies inside the range of the first candle. The last candle is also green and long and it closes above the close of the first candle. This decisive fifth strongly bullish candle hints that bears could not reverse the prior uptrend and that bulls have regained control of the market."
label.new(bar_index, patternLabelPosLow, text="RTM", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishRisingThreeMethods)
C_TweezerTopBearishNumberOfCandles = 2
C_TweezerTopBearish = false
if C_UpTrend[1] and (not C_IsDojiBody or (C_HasUpShadow and C_HasDnShadow)) and math.abs(high-high[1]) <= C_BodyAvg*0.05 and C_WhiteBody[1] and C_BlackBody and C_LongBody[1]
C_TweezerTopBearish := true
alertcondition(C_TweezerTopBearish, title = "Tweezer Top β Bearish", message = "New Tweezer Top β Bearish pattern detected")
if C_TweezerTopBearish and TweezerTopInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishTweezerTop = "Tweezer Top\nTweezer Top is a two-candle pattern that signifies a potential bearish reversal. The pattern is found during an uptrend. The first candle is long and green, the second candle is red, and its high is nearly identical to the high of the previous candle. The virtually identical highs, together with the inverted directions, hint that bears might be taking over the market."
label.new(bar_index, patternLabelPosHigh, text="TT", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishTweezerTop)
C_TweezerBottomBullishNumberOfCandles = 2
C_TweezerBottomBullish = false
if C_DownTrend[1] and (not C_IsDojiBody or (C_HasUpShadow and C_HasDnShadow)) and math.abs(low-low[1]) <= C_BodyAvg*0.05 and C_BlackBody[1] and C_WhiteBody and C_LongBody[1]
C_TweezerBottomBullish := true
alertcondition(C_TweezerBottomBullish, title = "Tweezer Bottom β Bullish", message = "New Tweezer Bottom β Bullish pattern detected")
if C_TweezerBottomBullish and TweezerBottomInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishTweezerBottom = "Tweezer Bottom\nTweezer Bottom is a two-candle pattern that signifies a potential bullish reversal. The pattern is found during a downtrend. The first candle is long and red, the second candle is green, its lows nearly identical to the low of the previous candle. The virtually identical lows together with the inverted directions hint that bulls might be taking over the market."
label.new(bar_index, patternLabelPosLow, text="TB", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishTweezerBottom)
C_DarkCloudCoverBearishNumberOfCandles = 2
C_DarkCloudCoverBearish = false
if (C_UpTrend[1] and C_WhiteBody[1] and C_LongBody[1]) and (C_BlackBody and open >= high[1] and close < C_BodyMiddle[1] and close > open[1])
C_DarkCloudCoverBearish := true
alertcondition(C_DarkCloudCoverBearish, title = "Dark Cloud Cover β Bearish", message = "New Dark Cloud Cover β Bearish pattern detected")
if C_DarkCloudCoverBearish and DarkCloudCoverInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishDarkCloudCover = "Dark Cloud Cover\nDark Cloud Cover is a two-candle bearish reversal candlestick pattern found in an uptrend. The first candle is green and has a larger than average body. The second candle is red and opens above the high of the prior candle, creating a gap, and then closes below the midpoint of the first candle. The pattern shows a possible shift in the momentum from the upside to the downside, indicating that a reversal might happen soon."
label.new(bar_index, patternLabelPosHigh, text="DCC", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishDarkCloudCover)
C_DownsideTasukiGapBearishNumberOfCandles = 3
C_DownsideTasukiGapBearish = false
if C_LongBody[2] and C_SmallBody[1] and C_DownTrend and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_BlackBody[1] and C_WhiteBody and C_BodyHi <= C_BodyLo[2] and C_BodyHi >= C_BodyHi[1]
C_DownsideTasukiGapBearish := true
alertcondition(C_DownsideTasukiGapBearish, title = "Downside Tasuki Gap β Bearish", message = "New Downside Tasuki Gap β Bearish pattern detected")
if C_DownsideTasukiGapBearish and DownsideTasukiGapInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishDownsideTasukiGap = "Downside Tasuki Gap\nDownside Tasuki Gap is a three-candle pattern found in a downtrend that usually hints at the continuation of the downtrend. The first candle is long and red, followed by a smaller red candle with its opening price that gaps below the body of the previous candle. The third candle is green and it closes inside the gap created by the first two candles, unable to close it fully. The bullβs inability to close that gap hints that the downtrend might continue."
label.new(bar_index, patternLabelPosHigh, text="DTG", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishDownsideTasukiGap)
C_UpsideTasukiGapBullishNumberOfCandles = 3
C_UpsideTasukiGapBullish = false
if C_LongBody[2] and C_SmallBody[1] and C_UpTrend and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_WhiteBody[1] and C_BlackBody and C_BodyLo >= C_BodyHi[2] and C_BodyLo <= C_BodyLo[1]
C_UpsideTasukiGapBullish := true
alertcondition(C_UpsideTasukiGapBullish, title = "Upside Tasuki Gap β Bullish", message = "New Upside Tasuki Gap β Bullish pattern detected")
if C_UpsideTasukiGapBullish and UpsideTasukiGapInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishUpsideTasukiGap = "Upside Tasuki Gap\nUpside Tasuki Gap is a three-candle pattern found in an uptrend that usually hints at the continuation of the uptrend. The first candle is long and green, followed by a smaller green candle with its opening price that gaps above the body of the previous candle. The third candle is red and it closes inside the gap created by the first two candles, unable to close it fully. The bearβs inability to close the gap hints that the uptrend might continue."
label.new(bar_index, patternLabelPosLow, text="UTG", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishUpsideTasukiGap)
C_EveningDojiStarBearishNumberOfCandles = 3
C_EveningDojiStarBearish = false
if C_LongBody[2] and C_IsDojiBody[1] and C_LongBody and C_UpTrend and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_BlackBody and C_BodyLo <= C_BodyMiddle[2] and C_BodyLo > C_BodyLo[2] and C_BodyLo[1] > C_BodyHi
C_EveningDojiStarBearish := true
alertcondition(C_EveningDojiStarBearish, title = "Evening Doji Star β Bearish", message = "New Evening Doji Star β Bearish pattern detected")
if C_EveningDojiStarBearish and EveningDojiStarInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishEveningDojiStar = "Evening Doji Star\nThis candlestick pattern is a variation of the Evening Star pattern. It is bearish and continues an uptrend with a long-bodied, green candle day. It is then followed by a gap and a Doji candle and concludes with a downward close. The close would be below the first dayβs midpoint. It is more bearish than the regular evening star pattern because of the existence of the Doji."
label.new(bar_index, patternLabelPosHigh, text="EDS", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEveningDojiStar)
C_DojiStarBearishNumberOfCandles = 2
C_DojiStarBearish = false
if C_UpTrend and C_WhiteBody[1] and C_LongBody[1] and C_IsDojiBody and C_BodyLo > C_BodyHi[1]
C_DojiStarBearish := true
alertcondition(C_DojiStarBearish, title = "Doji Star β Bearish", message = "New Doji Star β Bearish pattern detected")
if C_DojiStarBearish and DojiStarInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishDojiStar = "Doji Star\nThis is a bearish reversal candlestick pattern that is found in an uptrend and consists of two candles. First comes a long green candle, followed by a Doji candle (except 4-Price Doji) that opens above the body of the first one, creating a gap. It is considered a reversal signal with confirmation during the next trading day."
label.new(bar_index, patternLabelPosHigh, text="DS", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishDojiStar)
C_DojiStarBullishNumberOfCandles = 2
C_DojiStarBullish = false
if C_DownTrend and C_BlackBody[1] and C_LongBody[1] and C_IsDojiBody and C_BodyHi < C_BodyLo[1]
C_DojiStarBullish := true
alertcondition(C_DojiStarBullish, title = "Doji Star β Bullish", message = "New Doji Star β Bullish pattern detected")
if C_DojiStarBullish and DojiStarInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishDojiStar = "Doji Star\nThis is a bullish reversal candlestick pattern that is found in a downtrend and consists of two candles. First comes a long red candle, followed by a Doji candle (except 4-Price Doji) that opens below the body of the first one, creating a gap. It is considered a reversal signal with confirmation during the next trading day."
label.new(bar_index, patternLabelPosLow, text="DS", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishDojiStar)
C_MorningDojiStarBullishNumberOfCandles = 3
C_MorningDojiStarBullish = false
if C_LongBody[2] and C_IsDojiBody[1] and C_LongBody and C_DownTrend and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_WhiteBody and C_BodyHi >= C_BodyMiddle[2] and C_BodyHi < C_BodyHi[2] and C_BodyHi[1] < C_BodyLo
C_MorningDojiStarBullish := true
alertcondition(C_MorningDojiStarBullish, title = "Morning Doji Star β Bullish", message = "New Morning Doji Star β Bullish pattern detected")
if C_MorningDojiStarBullish and MorningDojiStarInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishMorningDojiStar = "Morning Doji Star\nThis candlestick pattern is a variation of the Morning Star pattern. A three-day bullish reversal pattern, which consists of three candlesticks will look something like this: The first being a long-bodied red candle that extends the current downtrend. Next comes a Doji that gaps down on the open. After that comes a long-bodied green candle, which gaps up on the open and closes above the midpoint of the body of the first day. It is more bullish than the regular morning star pattern because of the existence of the Doji."
label.new(bar_index, patternLabelPosLow, text="MDS", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishMorningDojiStar)
C_PiercingBullishNumberOfCandles = 2
C_PiercingBullish = false
if (C_DownTrend[1] and C_BlackBody[1] and C_LongBody[1]) and (C_WhiteBody and open <= low[1] and close > C_BodyMiddle[1] and close < open[1])
C_PiercingBullish := true
alertcondition(C_PiercingBullish, title = "Piercing β Bullish", message = "New Piercing β Bullish pattern detected")
if C_PiercingBullish and PiercingInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishPiercing = "Piercing\nPiercing is a two-candle bullish reversal candlestick pattern found in a downtrend. The first candle is red and has a larger than average body. The second candle is green and opens below the low of the prior candle, creating a gap, and then closes above the midpoint of the first candle. The pattern shows a possible shift in the momentum from the downside to the upside, indicating that a reversal might happen soon."
label.new(bar_index, patternLabelPosLow, text="P", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishPiercing)
C_HammerBullishNumberOfCandles = 1
C_HammerBullish = false
if C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow
if C_DownTrend
C_HammerBullish := true
alertcondition(C_HammerBullish, title = "Hammer β Bullish", message = "New Hammer β Bullish pattern detected")
if C_HammerBullish and HammerInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishHammer = "Hammer\nHammer candlesticks form when a security moves lower after the open, but continues to rally into close above the intraday low. The candlestick that you are left with will look like a square attached to a long stick-like figure. This candlestick is called a Hammer if it happens to form during a decline."
label.new(bar_index, patternLabelPosLow, text="H", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishHammer)
C_HangingManBearishNumberOfCandles = 1
C_HangingManBearish = false
if C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow
if C_UpTrend
C_HangingManBearish := true
alertcondition(C_HangingManBearish, title = "Hanging Man β Bearish", message = "New Hanging Man β Bearish pattern detected")
if C_HangingManBearish and HangingManInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishHangingMan = "Hanging Man\nWhen a specified security notably moves lower after the open, but continues to rally to close above the intraday low, a Hanging Man candlestick will form. The candlestick will resemble a square, attached to a long stick-like figure. It is referred to as a Hanging Man if the candlestick forms during an advance."
label.new(bar_index, patternLabelPosHigh, text="HM", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishHangingMan)
C_ShootingStarBearishNumberOfCandles = 1
C_ShootingStarBearish = false
if C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow
if C_UpTrend
C_ShootingStarBearish := true
alertcondition(C_ShootingStarBearish, title = "Shooting Star β Bearish", message = "New Shooting Star β Bearish pattern detected")
if C_ShootingStarBearish and ShootingStarInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishShootingStar = "Shooting Star\nThis single day pattern can appear during an uptrend and opens high, while it closes near its open. It trades much higher as well. It is bearish in nature, but looks like an Inverted Hammer."
label.new(bar_index, patternLabelPosHigh, text="SS", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishShootingStar)
C_InvertedHammerBullishNumberOfCandles = 1
C_InvertedHammerBullish = false
if C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow
if C_DownTrend
C_InvertedHammerBullish := true
alertcondition(C_InvertedHammerBullish, title = "Inverted Hammer β Bullish", message = "New Inverted Hammer β Bullish pattern detected")
if C_InvertedHammerBullish and InvertedHammerInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishInvertedHammer = "Inverted Hammer\nIf in a downtrend, then the open is lower. When it eventually trades higher, but closes near its open, it will look like an inverted version of the Hammer Candlestick. This is a one-day bullish reversal pattern."
label.new(bar_index, patternLabelPosLow, text="IH", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishInvertedHammer)
C_MorningStarBullishNumberOfCandles = 3
C_MorningStarBullish = false
if C_LongBody[2] and C_SmallBody[1] and C_LongBody
if C_DownTrend and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_WhiteBody and C_BodyHi >= C_BodyMiddle[2] and C_BodyHi < C_BodyHi[2] and C_BodyHi[1] < C_BodyLo
C_MorningStarBullish := true
alertcondition(C_MorningStarBullish, title = "Morning Star β Bullish", message = "New Morning Star β Bullish pattern detected")
if C_MorningStarBullish and MorningStarInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishMorningStar = "Morning Star\nA three-day bullish reversal pattern, which consists of three candlesticks will look something like this: The first being a long-bodied red candle that extends the current downtrend. Next comes a short, middle candle that gaps down on the open. After comes a long-bodied green candle, which gaps up on the open and closes above the midpoint of the body of the first day."
label.new(bar_index, patternLabelPosLow, text="MS", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishMorningStar)
C_EveningStarBearishNumberOfCandles = 3
C_EveningStarBearish = false
if C_LongBody[2] and C_SmallBody[1] and C_LongBody
if C_UpTrend and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_BlackBody and C_BodyLo <= C_BodyMiddle[2] and C_BodyLo > C_BodyLo[2] and C_BodyLo[1] > C_BodyHi
C_EveningStarBearish := true
alertcondition(C_EveningStarBearish, title = "Evening Star β Bearish", message = "New Evening Star β Bearish pattern detected")
if C_EveningStarBearish and EveningStarInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishEveningStar = "Evening Star\nThis candlestick pattern is bearish and continues an uptrend with a long-bodied, green candle day. It is then followed by a gapped and small-bodied candle day, and concludes with a downward close. The close would be below the first dayβs midpoint."
label.new(bar_index, patternLabelPosHigh, text="ES", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEveningStar)
C_MarubozuWhiteBullishNumberOfCandles = 1
C_MarubozuShadowPercentWhite = 5.0
C_MarubozuWhiteBullish = C_WhiteBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentWhite/100*C_Body and C_DnShadow <= C_MarubozuShadowPercentWhite/100*C_Body and C_WhiteBody
alertcondition(C_MarubozuWhiteBullish, title = "Marubozu White β Bullish", message = "New Marubozu White β Bullish pattern detected")
if C_MarubozuWhiteBullish and MarubozuWhiteInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishMarubozuWhite = "Marubozu White\nA Marubozu White Candle is a candlestick that does not have a shadow that extends from its candle body at either the open or the close. Marubozu is Japanese for βclose-croppedβ or βclose-cut.β Other sources may call it a Bald or Shaven Head Candle."
label.new(bar_index, patternLabelPosLow, text="MW", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishMarubozuWhite)
C_MarubozuBlackBearishNumberOfCandles = 1
C_MarubozuShadowPercentBearish = 5.0
C_MarubozuBlackBearish = C_BlackBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentBearish/100*C_Body and C_DnShadow <= C_MarubozuShadowPercentBearish/100*C_Body and C_BlackBody
alertcondition(C_MarubozuBlackBearish, title = "Marubozu Black β Bearish", message = "New Marubozu Black β Bearish pattern detected")
if C_MarubozuBlackBearish and MarubozuBlackInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishMarubozuBlack = "Marubozu Black\nThis is a candlestick that has no shadow, which extends from the red-bodied candle at the open, the close, or even at both. In Japanese, the name means βclose-croppedβ or βclose-cut.β The candlestick can also be referred to as Bald or Shaven Head."
label.new(bar_index, patternLabelPosHigh, text="MB", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishMarubozuBlack)
C_DojiNumberOfCandles = 1
C_DragonflyDoji = C_IsDojiBody and C_UpShadow <= C_Body
C_GravestoneDojiOne = C_IsDojiBody and C_DnShadow <= C_Body
alertcondition(C_Doji and not C_DragonflyDoji and not C_GravestoneDojiOne, title = "Doji", message = "New Doji pattern detected")
if C_Doji and not C_DragonflyDoji and not C_GravestoneDojiOne and DojiInput
var ttDoji = "Doji\nWhen the open and close of a security are essentially equal to each other, a doji candle forms. The length of both upper and lower shadows may vary, causing the candlestick you are left with to either resemble a cross, an inverted cross, or a plus sign. Doji candles show the playout of buyer-seller indecision in a tug-of-war of sorts. As price moves either above or below the opening level during the session, the close is either at or near the opening level."
label.new(bar_index, patternLabelPosLow, text="D", style=label.style_label_up, color = label_color_neutral, textcolor=color.white, tooltip = ttDoji)
C_GravestoneDojiBearishNumberOfCandles = 1
C_GravestoneDojiBearish = C_IsDojiBody and C_DnShadow <= C_Body
alertcondition(C_GravestoneDojiBearish, title = "Gravestone Doji β Bearish", message = "New Gravestone Doji β Bearish pattern detected")
if C_GravestoneDojiBearish and GravestoneDojiInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishGravestoneDoji = "Gravestone Doji\nWhen a doji is at or is close to the dayβs low point, a doji line will develop."
label.new(bar_index, patternLabelPosHigh, text="GD", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishGravestoneDoji)
C_DragonflyDojiBullishNumberOfCandles = 1
C_DragonflyDojiBullish = C_IsDojiBody and C_UpShadow <= C_Body
alertcondition(C_DragonflyDojiBullish, title = "Dragonfly Doji β Bullish", message = "New Dragonfly Doji β Bullish pattern detected")
if C_DragonflyDojiBullish and DragonflyDojiInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishDragonflyDoji = "Dragonfly Doji\nSimilar to other Doji days, this particular Doji also regularly appears at pivotal market moments. This is a specific Doji where both the open and close price are at the high of a given day."
label.new(bar_index, patternLabelPosLow, text="DD", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishDragonflyDoji)
C_HaramiCrossBullishNumberOfCandles = 2
C_HaramiCrossBullish = C_LongBody[1] and C_BlackBody[1] and C_DownTrend[1] and C_IsDojiBody and high <= C_BodyHi[1] and low >= C_BodyLo[1]
alertcondition(C_HaramiCrossBullish, title = "Harami Cross β Bullish", message = "New Harami Cross β Bullish pattern detected")
if C_HaramiCrossBullish and HaramiCrossInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishHaramiCross = "Harami Cross\nThis candlestick pattern is a variation of the Harami Bullish pattern. It is found during a downtrend. The two-day candlestick pattern consists of a Doji candle that is entirely encompassed within the body of what was once a red-bodied candle."
label.new(bar_index, patternLabelPosLow, text="HC", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishHaramiCross)
C_HaramiCrossBearishNumberOfCandles = 2
C_HaramiCrossBearish = C_LongBody[1] and C_WhiteBody[1] and C_UpTrend[1] and C_IsDojiBody and high <= C_BodyHi[1] and low >= C_BodyLo[1]
alertcondition(C_HaramiCrossBearish, title = "Harami Cross β Bearish", message = "New Harami Cross β Bearish pattern detected")
if C_HaramiCrossBearish and HaramiCrossInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishHaramiCross = "Harami Cross\nThis candlestick pattern is a variation of the Harami Bearish pattern. It is found during an uptrend. This is a two-day candlestick pattern with a Doji candle that is entirely encompassed within the body that was once a green-bodied candle. The Doji shows that some indecision has entered the minds of sellers, and the pattern hints that the trend might reverse."
label.new(bar_index, patternLabelPosHigh, text="HC", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishHaramiCross)
C_HaramiBullishNumberOfCandles = 2
C_HaramiBullish = C_LongBody[1] and C_BlackBody[1] and C_DownTrend[1] and C_WhiteBody and C_SmallBody and high <= C_BodyHi[1] and low >= C_BodyLo[1]
alertcondition(C_HaramiBullish, title = "Harami β Bullish", message = "New Harami β Bullish pattern detected")
if C_HaramiBullish and HaramiInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishHarami = "Harami\nThis two-day candlestick pattern consists of a small-bodied green candle that is entirely encompassed within the body of what was once a red-bodied candle."
label.new(bar_index, patternLabelPosLow, text="BH", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishHarami)
C_HaramiBearishNumberOfCandles = 2
C_HaramiBearish = C_LongBody[1] and C_WhiteBody[1] and C_UpTrend[1] and C_BlackBody and C_SmallBody and high <= C_BodyHi[1] and low >= C_BodyLo[1]
alertcondition(C_HaramiBearish, title = "Harami β Bearish", message = "New Harami β Bearish pattern detected")
if C_HaramiBearish and HaramiInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishHarami = "Harami\nThis is a two-day candlestick pattern with a small, red-bodied candle that is entirely encompassed within the body that was once a green-bodied candle."
label.new(bar_index, patternLabelPosHigh, text="BH", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishHarami)
C_LongLowerShadowBullishNumberOfCandles = 1
C_LongLowerShadowPercent = 75.0
C_LongLowerShadowBullish = C_DnShadow > C_Range/100*C_LongLowerShadowPercent
alertcondition(C_LongLowerShadowBullish, title = "Long Lower Shadow β Bullish", message = "New Long Lower Shadow β Bullish pattern detected")
if C_LongLowerShadowBullish and LongLowerShadowInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishLongLowerShadow = "Long Lower Shadow\nTo indicate seller domination of the first part of a session, candlesticks will present with long lower shadows and short upper shadows, consequently lowering prices."
label.new(bar_index, patternLabelPosLow, text="LLS", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishLongLowerShadow)
C_LongUpperShadowBearishNumberOfCandles = 1
C_LongShadowPercent = 75.0
C_LongUpperShadowBearish = C_UpShadow > C_Range/100*C_LongShadowPercent
alertcondition(C_LongUpperShadowBearish, title = "Long Upper Shadow β Bearish", message = "New Long Upper Shadow β Bearish pattern detected")
if C_LongUpperShadowBearish and LongUpperShadowInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishLongUpperShadow = "Long Upper Shadow\nTo indicate buyer domination of the first part of a session, candlesticks will present with long upper shadows, as well as short lower shadows, consequently raising bidding prices."
label.new(bar_index, patternLabelPosHigh, text="LUS", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishLongUpperShadow)
C_SpinningTopWhiteNumberOfCandles = 1
C_SpinningTopWhitePercent = 34.0
C_IsSpinningTopWhite = C_DnShadow >= C_Range / 100 * C_SpinningTopWhitePercent and C_UpShadow >= C_Range / 100 * C_SpinningTopWhitePercent and not C_IsDojiBody
C_SpinningTopWhite = C_IsSpinningTopWhite and C_WhiteBody
alertcondition(C_SpinningTopWhite, title = "Spinning Top White", message = "New Spinning Top White pattern detected")
if C_SpinningTopWhite and SpinningTopWhiteInput
var ttSpinningTopWhite = "Spinning Top White\nWhite spinning tops are candlestick lines that are small, green-bodied, and possess shadows (upper and lower) that end up exceeding the length of candle bodies. They often signal indecision between buyer and seller."
label.new(bar_index, patternLabelPosLow, text="STW", style=label.style_label_up, color = label_color_neutral, textcolor=color.white, tooltip = ttSpinningTopWhite)
C_SpinningTopBlackNumberOfCandles = 1
C_SpinningTopBlackPercent = 34.0
C_IsSpinningTop = C_DnShadow >= C_Range / 100 * C_SpinningTopBlackPercent and C_UpShadow >= C_Range / 100 * C_SpinningTopBlackPercent and not C_IsDojiBody
C_SpinningTopBlack = C_IsSpinningTop and C_BlackBody
alertcondition(C_SpinningTopBlack, title = "Spinning Top Black", message = "New Spinning Top Black pattern detected")
if C_SpinningTopBlack and SpinningTopBlackInput
var ttSpinningTopBlack = "Spinning Top Black\nBlack spinning tops are candlestick lines that are small, red-bodied, and possess shadows (upper and lower) that end up exceeding the length of candle bodies. They often signal indecision."
label.new(bar_index, patternLabelPosLow, text="STB", style=label.style_label_up, color = label_color_neutral, textcolor=color.white, tooltip = ttSpinningTopBlack)
C_ThreeWhiteSoldiersBullishNumberOfCandles = 3
C_3WSld_ShadowPercent = 5.0
C_3WSld_HaveNotUpShadow = C_Range * C_3WSld_ShadowPercent / 100 > C_UpShadow
C_ThreeWhiteSoldiersBullish = false
if C_LongBody and C_LongBody[1] and C_LongBody[2]
if C_WhiteBody and C_WhiteBody[1] and C_WhiteBody[2]
C_ThreeWhiteSoldiersBullish := close > close[1] and close[1] > close[2] and open < close[1] and open > open[1] and open[1] < close[2] and open[1] > open[2] and C_3WSld_HaveNotUpShadow and C_3WSld_HaveNotUpShadow[1] and C_3WSld_HaveNotUpShadow[2]
alertcondition(C_ThreeWhiteSoldiersBullish, title = "Three White Soldiers β Bullish", message = "New Three White Soldiers β Bullish pattern detected")
if C_ThreeWhiteSoldiersBullish and ThreeWhiteSoldiersInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishThreeWhiteSoldiers = "Three White Soldiers\nThis bullish reversal pattern is made up of three long-bodied, green candles in immediate succession. Each one opens within the body before it and the close is near to the daily high."
label.new(bar_index, patternLabelPosLow, text="3WS", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishThreeWhiteSoldiers)
C_ThreeBlackCrowsBearishNumberOfCandles = 3
C_3BCrw_ShadowPercent = 5.0
C_3BCrw_HaveNotDnShadow = C_Range * C_3BCrw_ShadowPercent / 100 > C_DnShadow
C_ThreeBlackCrowsBearish = false
if C_LongBody and C_LongBody[1] and C_LongBody[2]
if C_BlackBody and C_BlackBody[1] and C_BlackBody[2]
C_ThreeBlackCrowsBearish := close < close[1] and close[1] < close[2] and open > close[1] and open < open[1] and open[1] > close[2] and open[1] < open[2] and C_3BCrw_HaveNotDnShadow and C_3BCrw_HaveNotDnShadow[1] and C_3BCrw_HaveNotDnShadow[2]
alertcondition(C_ThreeBlackCrowsBearish, title = "Three Black Crows β Bearish", message = "New Three Black Crows β Bearish pattern detected")
if C_ThreeBlackCrowsBearish and ThreeBlackCrowsInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishThreeBlackCrows = "Three Black Crows\nThis is a bearish reversal pattern that consists of three long, red-bodied candles in immediate succession. For each of these candles, each day opens within the body of the day before and closes either at or near its low."
label.new(bar_index, patternLabelPosHigh, text="3BC", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishThreeBlackCrows)
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_DownTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close >= open[1] and open <= close[1] and ( close > open[1] or open < close[1] )
alertcondition(C_EngulfingBullish, title = "Engulfing β Bullish", message = "New Engulfing β Bullish pattern detected")
if C_EngulfingBullish and EngulfingInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trendβs opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
C_EngulfingBearishNumberOfCandles = 2
C_EngulfingBearish = C_UpTrend and C_BlackBody and C_LongBody and C_WhiteBody[1] and C_SmallBody[1] and close <= open[1] and open >= close[1] and ( close < open[1] or open > close[1] )
alertcondition(C_EngulfingBearish, title = "Engulfing β Bearish", message = "New Engulfing β Bearish pattern detected")
if C_EngulfingBearish and EngulfingInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishEngulfing = "Engulfing\nAt the end of a given uptrend, a reversal pattern will most likely appear. During the first day, this candlestick pattern uses a small body. It is then followed by a day where the candle body fully overtakes the body from the day before it and closes in the trendβs opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to fully overtake the range (high to low), rather only the open and the close."
label.new(bar_index, patternLabelPosHigh, text="BE", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEngulfing)
C_AbandonedBabyBullishNumberOfCandles = 3
C_AbandonedBabyBullish = C_DownTrend[2] and C_BlackBody[2] and C_IsDojiBody[1] and low[2] > high[1] and C_WhiteBody and high[1] < low
alertcondition(C_AbandonedBabyBullish, title = "Abandoned Baby β Bullish", message = "New Abandoned Baby β Bullish pattern detected")
if C_AbandonedBabyBullish and AbandonedBabyInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishAbandonedBaby = "Abandoned Baby\nThis candlestick pattern is quite rare as far as reversal patterns go. The first of the pattern is a large down candle. Next comes a doji candle that gaps below the candle before it. The doji candle is then followed by another candle that opens even higher and swiftly moves to the upside."
label.new(bar_index, patternLabelPosLow, text="AB", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishAbandonedBaby)
C_AbandonedBabyBearishNumberOfCandles = 3
C_AbandonedBabyBearish = C_UpTrend[2] and C_WhiteBody[2] and C_IsDojiBody[1] and high[2] < low[1] and C_BlackBody and low[1] > high
alertcondition(C_AbandonedBabyBearish, title = "Abandoned Baby β Bearish", message = "New Abandoned Baby β Bearish pattern detected")
if C_AbandonedBabyBearish and AbandonedBabyInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishAbandonedBaby = "Abandoned Baby\nA bearish abandoned baby is a specific candlestick pattern that often signals a downward reversal trend in terms of security price. It is formed when a gap appears between the lowest price of a doji-like candle and the candlestick of the day before. The earlier candlestick is green, tall, and has small shadows. The doji candle is also tailed by a gap between its lowest price point and the highest price point of the candle that comes next, which is red, tall and also has small shadows. The doji candle shadows must completely gap either below or above the shadows of the first and third day in order to have the abandoned baby pattern effect."
label.new(bar_index, patternLabelPosHigh, text="AB", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishAbandonedBaby)
C_TriStarBullishNumberOfCandles = 3
C_3DojisBullish = C_Doji[2] and C_Doji[1] and C_Doji
C_BodyGapUpBullish = C_BodyHi[1] < C_BodyLo
C_BodyGapDnBullish = C_BodyLo[1] > C_BodyHi
C_TriStarBullish = C_3DojisBullish and C_DownTrend[2] and C_BodyGapDnBullish[1] and C_BodyGapUpBullish
alertcondition(C_TriStarBullish, title = "Tri-Star β Bullish", message = "New Tri-Star β Bullish pattern detected")
if C_TriStarBullish and TriStarInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishTriStar = "Tri-Star\nA bullish TriStar candlestick pattern can form when three doji candlesticks materialize in immediate succession at the tail-end of an extended downtrend. The first doji candle marks indecision between bull and bear. The second doji gaps in the direction of the leading trend. The third changes the attitude of the market once the candlestick opens in the direction opposite to the trend. Each doji candle has a shadow, all comparatively shallow, which signify an interim cutback in volatility."
label.new(bar_index, patternLabelPosLow, text="3S", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishTriStar)
C_TriStarBearishNumberOfCandles = 3
C_3Dojis = C_Doji[2] and C_Doji[1] and C_Doji
C_BodyGapUp = C_BodyHi[1] < C_BodyLo
C_BodyGapDn = C_BodyLo[1] > C_BodyHi
C_TriStarBearish = C_3Dojis and C_UpTrend[2] and C_BodyGapUp[1] and C_BodyGapDn
alertcondition(C_TriStarBearish, title = "Tri-Star β Bearish", message = "New Tri-Star β Bearish pattern detected")
if C_TriStarBearish and TriStarInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishTriStar = "Tri-Star\nThis particular pattern can form when three doji candlesticks appear in immediate succession at the end of an extended uptrend. The first doji candle marks indecision between bull and bear. The second doji gaps in the direction of the leading trend. The third changes the attitude of the market once the candlestick opens in the direction opposite to the trend. Each doji candle has a shadow, all comparatively shallow, which signify an interim cutback in volatility."
label.new(bar_index, patternLabelPosHigh, text="3S", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishTriStar)
C_KickingBullishNumberOfCandles = 2
C_MarubozuShadowPercent = 5.0
C_Marubozu = C_LongBody and C_UpShadow <= C_MarubozuShadowPercent/100*C_Body and C_DnShadow <= C_MarubozuShadowPercent/100*C_Body
C_MarubozuWhiteBullishKicking = C_Marubozu and C_WhiteBody
C_MarubozuBlackBullish = C_Marubozu and C_BlackBody
C_KickingBullish = C_MarubozuBlackBullish[1] and C_MarubozuWhiteBullishKicking and high[1] < low
alertcondition(C_KickingBullish, title = "Kicking β Bullish", message = "New Kicking β Bullish pattern detected")
if C_KickingBullish and KickingInput and (("Bullish" == CandleType) or CandleType == "Both")
var ttBullishKicking = "Kicking\nThe first day candlestick is a bearish marubozu candlestick with next to no upper or lower shadow and where the price opens at the dayβs high and closes at the dayβs low. The second day is a bullish marubozu pattern, with next to no upper or lower shadow and where the price opens at the dayβs low and closes at the dayβs high. Additionally, the second day gaps up extensively and opens above the opening price of the day before. This gap or window, as the Japanese call it, lies between day one and day twoβs bullish candlesticks."
label.new(bar_index, patternLabelPosLow, text="K", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishKicking)
C_KickingBearishNumberOfCandles = 2
C_MarubozuBullishShadowPercent = 5.0
C_MarubozuBearishKicking = C_LongBody and C_UpShadow <= C_MarubozuBullishShadowPercent/100*C_Body and C_DnShadow <= C_MarubozuBullishShadowPercent/100*C_Body
C_MarubozuWhiteBearish = C_MarubozuBearishKicking and C_WhiteBody
C_MarubozuBlackBearishKicking = C_MarubozuBearishKicking and C_BlackBody
C_KickingBearish = C_MarubozuWhiteBearish[1] and C_MarubozuBlackBearishKicking and low[1] > high
alertcondition(C_KickingBearish, title = "Kicking β Bearish", message = "New Kicking β Bearish pattern detected")
if C_KickingBearish and KickingInput and (("Bearish" == CandleType) or CandleType == "Both")
var ttBearishKicking = "Kicking\nA bearish kicking pattern will occur, subsequently signaling a reversal for a new downtrend. The first day candlestick is a bullish marubozu. The second day gaps down extensively and opens below the opening price of the day before. There is a gap between day one and twoβs bearish candlesticks."
label.new(bar_index, patternLabelPosHigh, text="K", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishKicking)
var ttAllCandlestickPatterns = "All Candlestick Patterns\n"
label.new(bar_index, patternLabelPosLow, text="Collection", style=label.style_label_up, color = label_color_neutral, textcolor=color.white, tooltip = ttAllCandlestickPatterns)
//==========================================================================================REGRESSION CANDLES========================================================
signal_length = input.int(title='Signal Smoothing', minval=1, maxval=200, defval=11)
sma_signal = input(title='Simple MA (Signal Line)', defval=true)
lin_reg = input(title='Lin Reg', defval=true)
linreg_length = input.int(title='Linear Regression Length', minval=1, maxval=200, defval=11)
bopen = lin_reg ? ta.linreg(open, linreg_length, 0) : open
bhigh = lin_reg ? ta.linreg(high, linreg_length, 0) : high
blow = lin_reg ? ta.linreg(low, linreg_length, 0) : low
bclose = lin_reg ? ta.linreg(close, linreg_length, 0) : close
r = bopen < bclose
signal = sma_signal ? ta.sma(bclose, signal_length) : ta.ema(bclose, signal_length)
plotcandle(r ? bopen : na, r ? bhigh : na, r ? blow : na, r ? bclose : na, title='LinReg Candles', color=color.green, wickcolor=color.green, bordercolor=color.green, editable=true)
plotcandle(r ? na : bopen, r ? na : bhigh, r ? na : blow, r ? na : bclose, title='LinReg Candles', color=color.red, wickcolor=color.red, bordercolor=color.red, editable=true)
plot(signal, color=color.new(color.white, 0))
//==========================================================================================REGRESSION CHANNEL========================================================
lengthInput = input.int(100, title="Length", minval = 1, maxval = 5000)
sourceInput = input.source(close, title="Source")
group1 = "Channel Settings"
useUpperDevInput = input.bool(true, title="Upper Deviation", inline = "Upper Deviation", group = group1)
upperMultInput = input.float(2.0, title="", inline = "Upper Deviation", group = group1)
useLowerDevInput = input.bool(true, title="Lower Deviation", inline = "Lower Deviation", group = group1)
lowerMultInput = input.float(2.0, title="", inline = "Lower Deviation", group = group1)
group2 = "Display Settings"
showPearsonInput = input.bool(true, "Show Pearson's R", group = group2)
extendLeftInput = input.bool(false, "Extend Lines Left", group = group2)
extendRightInput = input.bool(true, "Extend Lines Right", group = group2)
extendStyle = switch
extendLeftInput and extendRightInput => extend.both
extendLeftInput => extend.left
extendRightInput => extend.right
=> extend.none
group3 = "Color Settings"
colorUpper = input.color(color.new(color.blue, 85), "", inline = group3, group = group3)
colorLower = input.color(color.new(color.red, 85), "", inline = group3, group = group3)
calcSlope(source, length) =>
max_bars_back(source, 5000)
if not barstate.islast or length <= 1
[float(na), float(na), float(na)]
else
sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for i = 0 to length - 1 by 1
val = source[i]
per = i + 1.0
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
average = sumY / length
intercept = average - slope * sumX / length + slope
[slope, average, intercept]
[s, a, i] = calcSlope(sourceInput, lengthInput)
startPrice = i + s * (lengthInput - 1)
endPrice = i
var line baseLine = na
if na(baseLine) and not na(startPrice)
baseLine := line.new(bar_index - lengthInput + 1, startPrice, bar_index, endPrice, width=1, extend=extendStyle, color=color.new(colorLower, 0))
else
line.set_xy1(baseLine, bar_index - lengthInput + 1, startPrice)
line.set_xy2(baseLine, bar_index, endPrice)
na
calcDev(source, length, slope, average, intercept) =>
upDev = 0.0
dnDev = 0.0
stdDevAcc = 0.0
dsxx = 0.0
dsyy = 0.0
dsxy = 0.0
periods = length - 1
daY = intercept + slope * periods / 2
val = intercept
for j = 0 to periods by 1
price = high[j] - val
if price > upDev
upDev := price
price := val - low[j]
if price > dnDev
dnDev := price
price := source[j]
dxt = price - average
dyt = val - daY
price -= val
stdDevAcc += price * price
dsxx += dxt * dxt
dsyy += dyt * dyt
dsxy += dxt * dyt
val += slope
stdDev = math.sqrt(stdDevAcc / (periods == 0 ? 1 : periods))
pearsonR = dsxx == 0 or dsyy == 0 ? 0 : dsxy / math.sqrt(dsxx * dsyy)
[stdDev, pearsonR, upDev, dnDev]
[stdDev, pearsonR, upDev, dnDev] = calcDev(sourceInput, lengthInput, s, a, i)
upperStartPrice = startPrice + (useUpperDevInput ? upperMultInput * stdDev : upDev)
upperEndPrice = endPrice + (useUpperDevInput ? upperMultInput * stdDev : upDev)
var line upper = na
lowerStartPrice = startPrice + (useLowerDevInput ? -lowerMultInput * stdDev : -dnDev)
lowerEndPrice = endPrice + (useLowerDevInput ? -lowerMultInput * stdDev : -dnDev)
var line lower = na
if na(upper) and not na(upperStartPrice)
upper := line.new(bar_index - lengthInput + 1, upperStartPrice, bar_index, upperEndPrice, width=1, extend=extendStyle, color=color.new(colorUpper, 0))
else
line.set_xy1(upper, bar_index - lengthInput + 1, upperStartPrice)
line.set_xy2(upper, bar_index, upperEndPrice)
na
if na(lower) and not na(lowerStartPrice)
lower := line.new(bar_index - lengthInput + 1, lowerStartPrice, bar_index, lowerEndPrice, width=1, extend=extendStyle, color=color.new(colorUpper, 0))
else
line.set_xy1(lower, bar_index - lengthInput + 1, lowerStartPrice)
line.set_xy2(lower, bar_index, lowerEndPrice)
na
linefill.new(upper, baseLine, color = colorUpper)
linefill.new(baseLine, lower, color = colorLower)
// Pearson's R
var label ra = na
label.delete(ra[1])
if showPearsonInput and not na(pearsonR)
ra := label.new(bar_index - lengthInput + 1, lowerStartPrice, str.tostring(pearsonR, "#.################"), color = color.new(color.white, 100), textcolor=color.new(colorUpper, 0), size=size.normal, style=label.style_label_up)
|
OMXS30 Volume | https://www.tradingview.com/script/gxRm9fkC-OMXS30-Volume/ | Ohellas | https://www.tradingview.com/u/Ohellas/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Ohellas
// This indicator summarizes the volume for all stock in the OMXS30 index. Wait until the candle closes before reading the volume.
//If you want to hide the volume until close of candle you can replace the request.security with the f_secureSecurity function defined below
// Each row for each stock would look like this for example f_secureSecurity("OMXSTO:ABB",timeframe,volume)
//Or if you know how to fix this issue please let me know
//@version=5
indicator("OMXS30 Volume", overlay=false)
showMA = input(false, title="Show Volume Moving Average")
showVSA = input(false, title="Show Volume Spread Analysis")
showVolumeChange = input(false, title="Color of bar indicates if volume increases or decreases, must disable VSA to work")
timefilter = input(true, title="Enable timefilter to remove first and last bar")
int lengthVolumeMA = input(20, title="Length of MA applied on Volume")
float ratioUltraVolume = input(2.2, title="Ultra High Volume Ratio")
float ratioVeryHighVolume = input(1.8, title="Very High Volume Ratio")
float ratioHighVolume = input(1.2, title="High Volume Ratio")
float ratioNormalVolume = input(0.8, title="Normal Volume Ratio")
float ratioLowVolume = input(0.4, title="Low Volume Ratio")
float ratioVeryLowVolume = input(0.4, title="Very Low Volume Ratio")
timeframe=timeframe.period
f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
totvol = request.security("OMXSTO:ABB",timeframe,volume) +
request.security("OMXSTO:ALFA",timeframe,volume) +
request.security("OMXSTO:ALIV_SDB",timeframe,volume) +
request.security("OMXSTO:ASSA_B",timeframe,volume) +
request.security("OMXSTO:ATCO_A",timeframe,volume) +
request.security("OMXSTO:ATCO_B",timeframe,volume) +
request.security("OMXSTO:AZN",timeframe,volume) +
request.security("OMXSTO:BOL",timeframe,volume) +
request.security("OMXSTO:ELUX_B",timeframe,volume) +
request.security("OMXSTO:ERIC_B",timeframe,volume) +
request.security("OMXSTO:ESSITY_B",timeframe,volume) +
request.security("OMXSTO:EVO",timeframe,volume) +
request.security("OMXSTO:GETI_B",timeframe,volume) +
request.security("OMXSTO:HEXA_B",timeframe,volume) +
request.security("OMXSTO:HM_B",timeframe,volume) +
request.security("OMXSTO:INVE_B",timeframe,volume) +
request.security("OMXSTO:KINV_B",timeframe,volume) +
request.security("OMXSTO:NDA_SE",timeframe,volume) +
request.security("OMXSTO:NIBE_B",timeframe,volume) +
request.security("OMXSTO:SAND",timeframe,volume) +
request.security("OMXSTO:SBB_B",timeframe,volume) +
request.security("OMXSTO:SCA_B",timeframe,volume) +
request.security("OMXSTO:SEB_A",timeframe,volume) +
request.security("OMXSTO:SHB_A",timeframe,volume) +
request.security("OMXSTO:SINCH",timeframe,volume) +
request.security("OMXSTO:SKF_B",timeframe,volume) +
request.security("OMXSTO:SWED_A",timeframe,volume) +
request.security("OMXSTO:TEL2_B",timeframe,volume) +
request.security("OMXSTO:TELIA",timeframe,volume) +
request.security("OMXSTO:VOLV_B",timeframe,volume)
//Since the first and last bar per day is so much larger than the rest it can be filtered out to make the scale more readable
t=1
if timefilter and timeframe=="1"
t := time(timeframe.period, "0901-1729")
if timefilter and timeframe=="5"
t := time(timeframe.period, "0906-1724")
if timefilter and timeframe=="15"
t := time(timeframe.period, "0915-1714")
if timefilter and timeframe=="30"
t := time(timeframe.period, "0930-1659")
// WILDERS MA
float volumeMA = 0
if t // If timefilter is used the MA does not take into account the first and last bar and the VSA is more useful
volumeMA := nz(volumeMA[1]) + (totvol-nz(volumeMA[1])) / lengthVolumeMA
ultraHighVolumeMin = volumeMA * ratioUltraVolume
veryHighVolumeMin = volumeMA * ratioVeryHighVolume
highVolumeMin = volumeMA * ratioHighVolume
normalVolumeMin = volumeMA * ratioNormalVolume
lowVolumeMin = volumeMA * ratioLowVolume
veryLowVolumeMin = volumeMA * ratioVeryLowVolume
volUltraHigh = totvol >= ultraHighVolumeMin ? true : false
volVeryHigh = totvol >= veryHighVolumeMin and totvol < ultraHighVolumeMin ? true : false
volHigh = totvol >= highVolumeMin and totvol < veryHighVolumeMin ? true : false
volNormal = totvol >= normalVolumeMin and totvol < highVolumeMin ? true : false
volLow = totvol >= lowVolumeMin and totvol < normalVolumeMin ? true : false
volVeryLow = totvol < lowVolumeMin ? true : false
// Determine histogram bar colour
palette = close>open ? color.green : color.red
if showVolumeChange
palette := totvol>totvol[1] ? color.aqua : color.orange
if showVSA
palette := volUltraHigh ? color.purple : volVeryHigh ? color.red : volHigh ? color.orange : volNormal ? color.green : volLow ? color.blue : color.silver
plot(na(t) ? na : totvol, color = palette, style=plot.style_columns, title="Volume", transp=0)
plot(showMA ? volumeMA : na, style=plot.style_line, color=color.green, title="Volume MA")
|
OB EmaCross + BB | https://www.tradingview.com/script/QcXK4M4h/ | OdirBrasil | https://www.tradingview.com/u/OdirBrasil/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© OdirBrasil (07-dec-2021)
//@version=5
indicator("OB EmaCross + BB", overlay=true)
bcolorbars = input(true, "Colored Bars?")
iEma1 = input(9, "Fast EMA")
iEma2 = input(21, "Fast EMA")
iEma3 = input(200, "Slow EMA")
length = input.int(20, "Lenght BB", minval=1)
src = input(close, title="Source BB")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev BB")
ema1 = ta.ema(close, iEma1)
ema2 = ta.ema(close, iEma2)
ema3 = ta.ema(close, iEma3)
fColorUp = color.rgb(77, 60, 235)
fColorDown = color.rgb(139, 4, 99)
//fColorUp = ta.crossover(ema3, sma1) ? color.yellow : color.green
//fColorDown = ta.crossover(sma1, ema3) ? color.yellow : color.red
p1 = plot(ema1, color=ema1 > ema2 ? fColorUp : fColorDown, linewidth=2)
p2 = plot(ema2, color=ema1 > ema2 ? fColorUp : fColorDown, linewidth=3)
p3 = plot(ema3, color=color.gray, linewidth=5)
fill(p1, p2, title = "Background", color=ema1 > ema2 ? fColorUp : fColorDown)
bColor = close > ema1 and close > ema2 ? color.green : close < ema1 and close < ema2 ? color.red : color.white
plotcandle(open, high, low, close, color=bcolorbars ? bColor : na, wickcolor=bcolorbars ? bColor : na, bordercolor=bcolorbars ? bColor : na)
// *** ALERTAS ***
//bLong = high > ema1 and low > ema1 and ema1 > ema2 and ema2 > ema3 and ( high[1] < ema1 or low[1] < ema1 or ema1 < ema2 or ema2 < ema3)
//bShort = high < ema1 and low < ema1 and ema1 < ema2 and ema2 < ema3 and ( high[1] > ema1 or low[1] > ema1 or ema1 > ema2 or ema2 > ema3)
alertcondition(ta.crossover(ema1, ema2), title="Medias em Tendencia de ALTA.", message="{{ticker}} - price: {{close}} - TendΓͺncia de Alta")
alertcondition(ta.crossover(ema2, ema1), title="Medias em Tendencia de BAIXA.", message="{{ticker}} - price: {{close}} - TendΓͺncia de Baixa")
//alertcondition(bLong, title="Medias em Tendencia de ALTA.", message="{{ticker}} 1H - price: {{close}} - TendΓͺncia de Alta")
//alertcondition(bShort,title="Medias em Tendencia de BAIXA.", message="{{ticker}} 1H - price: {{close}} - TendΓͺncia de BAIXA")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
//plot(basis, "Basis", color=#FF6D00, offset = offset)
p100 = plot(upper, "Upper", color=#2962FF, offset = offset)
p200 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p100, p200, title = "Background", color=color.rgb(81, 28, 20, 95)) |
Signal Moving Average [LuxAlgo] | https://www.tradingview.com/script/L1NqQsyw-Signal-Moving-Average-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 4,729 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// Β© LuxAlgo
//@version=5
indicator("Signal Moving Average [LuxAlgo]", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(50)
src = input(close)
//------------------------------------------------------------------------------
//Signal moving average
//-----------------------------------------------------------------------------{
var ma = 0.
var os = 0.
target = ta.sma(src, length)
abs_diff = math.abs(target - target[1])
r2 = math.pow(ta.correlation(close, bar_index, length), 2)
os := r2 > 0.5 ? math.sign(src[1] - target[1]) : os
ma := r2 > 0.5 ? r2 * target + (1 - r2) * nz(ma[1], target)
: ma[1] - abs_diff * os
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot0 = plot(src, display = display.none, editable = false)
css = os == 1 ? #0cb51a : #ff1100
plot1 = plot(ma, 'Signal MA'
, css)
fill_css = src > ma ? color.new(#0cb51a, 80) : color.new(#ff1100, 80)
fill(plot0, plot1, fill_css, 'Fill')
//-----------------------------------------------------------------------------}
|
Variety N-Tuple Moving Averages w/ Variety Stepping [Loxx] | https://www.tradingview.com/script/aTNYBVHq-Variety-N-Tuple-Moving-Averages-w-Variety-Stepping-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 200 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Variety N-Tuple Moving Averages w/ Variety Stepping [Loxx]",
shorttitle='VNTMAVS [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
lightgreencolor = #96E881
lightredcolor = #DF4F6C
fact(int n)=>
float out = 1
for i = 1 to n
out *= i
out
// TradingView user @lejmer was a key player in making this function come to life
nema(string nematype, float src, int per, int dpth, int mxdpth) =>
var float[] coeff = array.new<float>(mxdpth + 1, 0.)
if barstate.isfirst
int nemadpth = math.max(math.min(dpth, mxdpth), 1)
for k = 0 to dpth
array.set(coeff, k, nz(fact(dpth) / (fact(dpth - k) * fact(k)), 1))
var float[] workarr = array.new<float>(dpth + 1, 0)
array.set(workarr, 0, src)
int sign = 1
float nema = 0.
float alpha = nematype == "EMA" ? 2.0 / (1.0 + per) : 1 / per
for k = 0 to dpth - 1
temp = array.get(workarr, k + 1) + alpha * (array.get(workarr, k) - array.get(workarr, k + 1))
array.set(workarr, k + 1, temp)
nema += temp * sign * array.get(coeff, k + 1)
sign *= -1
nema
adaptvieATR(float src, int per)=>
float mper = (per > 1) ? per : 1
float mfast = math.max(mper / 2.0, 1)
float mslow = mper * 5
float mperDiff = mslow - mfast
float noise = 0., float aatr = 0.
float diff = math.abs(src - nz(src[1]))
float signal = math.abs(src - nz(src[mper]))
noise := nz(noise[1]) + diff - nz(diff[mper])
float avgper = (noise != 0) ? (signal / noise) * mperDiff + mfast : mper
aatr := nz(aatr[1]) + (2.0 / (1.0 + avgper)) * ((high - low) - nz(aatr[1]))
aatr
adaptiveDeviation(float price, int per)=>
float m_per = (per > 1) ? per : 1
float m_fastEnd = math.max(m_per / 2.0, 1)
float m_slowEnd = m_per * 5
float m_perDiff = m_slowEnd - m_fastEnd
float difference = math.abs(ta.change(price))
float signal = 0.
float noise = 0.
if bar_index > m_per
signal := math.abs(price - nz(price[m_per]))
noise := nz(noise[1]) + difference - nz(difference[m_per])
else
for k = 0 to m_per - 1
noise += nz(difference[k])
float averageper = (signal /noise) * m_perDiff + m_fastEnd
float alpha = 2.0 / (1.0 + averageper)
float ema0 = 0., float ema1 = 0.
ema0 := nz(ema0[1]) + alpha * (price - nz(ema0[1]))
ema1 := nz(ema1[1]) + alpha * (price * price - nz(ema1[1]))
float out = math.sqrt(averageper * (ema1 - ema0 * ema0) / math.max(averageper - 1, 1))
out
fmedian(float src, int per)=>
int midlea = 0
int midleb = 0
float[] sortMed = array.new<float>(per, 0.)
if (per % 2) == 0
midlea := int((per / 2) - 1)
midleb := int(per / 2)
else
midlea := int((per - 1) / 2)
midleb := int(midlea)
for k = 0 to per - 1
array.set(sortMed, k, nz(src[k]))
array.sort(sortMed)
out = (array.get(sortMed, midlea) + array.get(sortMed, midleb)) / 2
out
filt(float src, simple int len, float filter, filtper, type)=>
float price = src
float atr = ta.atr(len)
float std = ta.stdev(src, len)
float addev = adaptiveDeviation(src, len)
float aatr = adaptvieATR(src, len)
float out = fmedian(src, len)
float mad = fmedian(math.abs(src - out), filtper)
float filtdev = filter * (type == "ATR" ? atr: type == "Standard Deviation" ? std : type == "Median Absolute Deviation" ? mad : type == "Adaptive Deviation" ? addev : aatr)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
banVal(float src, simple int len, float filter, filtper, type)=>
float atr = ta.atr(len)
float std = ta.stdev(src, len)
float addev = adaptiveDeviation(src, len)
float aatr = adaptvieATR(src, len)
float out = fmedian(src, len)
float mad = fmedian(math.abs(src - out), filtper)
float regdev = ta.dev(src, len)
float filtdev = filter * (type == "ATR" ? atr : type == "Standard Deviation" ? std :
type == "Median Absolute Deviation" ? mad : type == "Adaptive Deviation" ? addev : type == "ER-Adaptive ATR" ? aatr : regdev)
filtdev
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
nemadpth = input.int(3, "Depth", maxval = 50, minval = 1, group = "Basic Settings")
nematype = input.string("EMA", "Moving Average Type", options = ["EMA", "RMA"] , group = "Basic Settings")
ptype = input.string("ATR", "Price Filter Type", options = ["ATR", "Standard Deviation", "Median Absolute Deviation", "Adaptive Deviation", "ER-Adaptive ATR", "Mean Absolute Deviation"], group= "Filter Settings")
matype = input.string("ATR", "Moving Average Filter Type", options = ["ATR", "Standard Deviation", "Median Absolute Deviation", "Adaptive Deviation", "ER-Adaptive ATR", "Mean Absolute Deviation"], group= "Filter Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "Moving Average Filter", "Both", "None"], group= "Filter Settings")
filter = input.float(1, "Filter Multiplier", minval = 0, group= "Filter Settings")
filterperiod = input.int(10, "Filter Period", minval = 0, group= "Filter Settings")
madper = input.int(10, "MAD Internal Filter Period", minval = 0, group= "Filter Settings", tooltip = "Median Absolute Deviation only")
bndtype = input.string("ATR", "Band Type Type", options = ["ATR", "Standard Deviation", "Median Absolute Deviation", "Adaptive Deviation", "ER-Adaptive ATR", "Mean Absolute Deviation"], group= "Bands Settings")
bndmult = input.float(1, "Band Multiplier", minval = 0, group= "Bands Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showBands = input.bool(true, "Show bands?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? filt(src, filterperiod, filter, madper, ptype) : src
out = nema(nematype, src, per, nemadpth, 50)
out := filterop == "Both" or filterop == "Moving Average Filter" and filter > 0 ? filt(out, filterperiod, filter, madper, matype) : out
sig = nz(out[1])
state = out > sig ? 1 : out < sig ? -1 : 0
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
bandout = banVal(src, filterperiod, bndmult, madper, bndtype)
bndup = out + bandout
bnddn = out - bandout
plot(showBands ? bndup : na, "Upper Band", color = color.gray, linewidth = 1)
plot(showBands ? bnddn : na, "Lower Band", color = color.gray, linewidth = 1)
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "Step NTMA", color = colorout, linewidth = 2)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Variety N-Tuple Moving Averages w/ Variety Stepping [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Variety N-Tuple Moving Averages w/ Variety Stepping [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Liquidity Engulfing Candles [upslidedown] | https://www.tradingview.com/script/QpnPfNK6-Liquidity-Engulfing-Candles-upslidedown/ | upslidedown | https://www.tradingview.com/u/upslidedown/ | 311 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© upslidedown
// This is an interesting take on a common engulfing candle pattern with 2 additional filter critera to ensure there is a liquidity play
// Idea came from AtaBankz based on trade setup 4H candles. Thanks mate!
//@version=5
indicator("Liquidity Engulfing Candles [upslidedown]", overlay=true)
prior_open = open[1]
prior_close = close[1]
current_open = open
current_close = close
bullcol = #2c7bb6
bearcol = color.red
// identify "normal" engulfing candles
bull_engulf = (current_open <= prior_close) and (current_open < prior_open) and (current_close > prior_open)
bear_engulf = (current_open >= prior_close) and (current_open > prior_open) and (current_close < prior_open)
// "stop hunt" logic
filter_liqudity = input.bool(true, "Apply Stop Hunt Wick Filter", tooltip="Require candle wick into prior candle retracement zone")
if filter_liqudity
bull_engulf := bull_engulf and low <= low[1]
bear_engulf := bear_engulf and high >= high[1]
// require LL/HH on the candle
filter_close = input.bool(true, "Apply Close Filter", tooltip="Require LL/HH on candle in order to print a valid engulfing signal")
if filter_close
bull_engulf := bull_engulf and close >= high[1]
bear_engulf := bear_engulf and close <= low[1]
// plots
plotshape(bull_engulf, style=shape.triangleup, location=location.belowbar, color=bullcol, size=size.tiny)
plotshape(bear_engulf, style=shape.triangledown , location=location.abovebar, color=bearcol, size=size.tiny)
// alert inputs
group_alerts = "Alerts"
a_require_close = input.bool(true, 'Wait for bar close to send alerts', group=group_alerts)
a_bull_enable = input.bool(true, "Bullish Alert", group=group_alerts, inline="abull")
a_bull = input.string("Bullish LEC detected", "", group=group_alerts, inline="abull")
a_bear_enable = input.bool(true, "Bearish Alert", group=group_alerts, inline="abear")
a_bear = input.string("Bearish LEC detected", "", group=group_alerts, inline="abear")
if bull_engulf and a_bull_enable
alert(a_bull, a_require_close ? alert.freq_once_per_bar_close : alert.freq_once_per_bar)
else if bear_engulf and a_bear_enable
alert(a_bear, a_require_close ? alert.freq_once_per_bar_close : alert.freq_once_per_bar)
// strategy signal for my backtester
//strategy_inverse = input.bool(false, "Inverse Strategy")
strategy_inverse = false
strategy = 0
if bull_engulf
strategy := strategy_inverse ? -1 : 1
else if bear_engulf
strategy := strategy_inverse ? 1 : -1
plot(strategy, "Strategy Signal", display=display.data_window) |
TR | https://www.tradingview.com/script/8ZGh8cnK-TR/ | Pandemik699 | https://www.tradingview.com/u/Pandemik699/ | 132 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Original pattern formation by plasmapug, rise retrace continuation to the upside by infernix and peshocore
// Please note while the code is open source and you are free to use it however you like - the 'TR' name is not - ie if you produce derivatives of this
// source code you to name those scripts using "TR", "Pattern Watchers" or any other name that relates to Traders Reality in any way.
//Session Local Time DST OFF (UCT+0) DST ON (UTC+0) DST ON 2022 DST OFF 2022 DST ON 2023 DST OFF 2023 DST ON 2024 DST OFF 2024
//London 8am-430pm 0800-1630 0700-1530 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27
//NewYork 930am-4pm 1430-2100 1330-2000 March, 13 November, 6 March, 12 November, 5 March, 10 November, 3
//Tokyo 9am-3pm 0000-0600 0000-0600 N/A N/A N/A N/A N/A N/A
//HongKong 930am-4pm 0130-0800 0130-0800 N/A N/A N/A N/A N/A N/A
//Sydney (NZX+ASX) NZX start 10am, ASX end 4pm 2200-0600 2100-0500 October, 2 April, 3 October, 1 April, 2 October, 6 April, 7
//EU Brinx 730am-830am 0730-0830 0630-0730 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27
//US Brinx 900am-10am 1400-1500 1300-1400 March, 13 November, 6 March, 12 November, 5 March, 10 November, 3
//Frankfurt 800am-530pm 0700-1630 0600-1530 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27
//@version=5
indicator('TR', overlay=true, max_bars_back=300)
// ----------------------------
// Config
adr_offset_input = input.int(group='Label offsets', title='ADR', defval=25, inline='labeloffset')
pivot_offset_input = input.int(group='Label offsets', title='Pivot', defval=-5, inline='labeloffset')
label_offset_input = input.int(group='Label offsets', title='MA/HiLo', defval=5, inline='labeloffset')
showEmas = input.bool(group='EMAs', title='Show EMAs?', defval=true, inline='showemas')
labelEmas = input.bool(group='EMAs', title='EMA Labels?', defval=false, inline='showemas')
oneEmaColor = input.color(group='EMAs', title='EMA Color: 5', defval=color.rgb(254, 234, 74, 0), inline='emacolors')
twoEmaColor = input.color(group='EMAs', title='13', defval=color.rgb(253, 84, 87, 0), inline='emacolors')
threeEmaColor = input.color(group='EMAs', title='50', defval=color.rgb(31, 188, 211, 0), inline='emacolors')
fourEmaColor = input.color(group='EMAs', title='200', defval=color.rgb(255, 255, 255, 0), inline='emacolors')
fiveEmaColor = input.color(group='EMAs', title='800', defval=color.rgb(50, 34, 144, 0), inline='emacolors')
EmaCloudColor = input.color(group='EMAs', title='EMA Cloud', defval=color.rgb(155, 47, 174, 60), inline='emacloud')
EmaCloudBorderColor = input.color(group='EMAs', title='Border', defval=color.rgb(18, 137, 123, 100), inline='emacloud')
//Daily Pivot Points
showLevelOnePivotPoints = input.bool(group='Pivot Points', title='Show Level: 1 R/S?', defval=false, inline='pivotlevels')
showLevelTwoPivotPoints = input.bool(group='Pivot Points', title='2 R/S?', defval=false, inline='pivotlevels')
showLevelThreePivotPoints = input.bool(group='Pivot Points', title=' 3 R/S?', defval=false, inline='pivotlevels')
showPivotLabels = input.bool(group='Pivot Points', title='Show labels?', defval=true, inline='pivotlevels')
string rsStyleX = input.string(group='Pivot Points', defval='Dashed', title='R/S Levels Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='pivotcolorsRS')
rsStyle = rsStyleX == 'Dotted' ? line.style_dotted : (rsStyleX == 'Dashed' ? line.style_dashed : (rsStyleX == 'Solid' ? line.style_solid : line.style_dashed))
activeM = input.bool(group='Pivot Points', title='Show M levels?', defval=true, inline='mlevels')
showMLabels = input.bool(group='Pivot Points', title='Labels?', defval=true, inline='mlevels')
extendPivots = input.bool(group='Pivot Points', title='Extend lines in both directions?', defval=false)
pivotColor = input.color(group='Pivot Points', title='Colors: Pivot Point', defval=color.rgb(254, 234, 78, 50), inline='pivotcolors')
mColor = input.color(group='Pivot Points', title='M Levels', defval=color.rgb(255, 255, 255, 50), inline='pivotcolors')
string mStyleX = input.string(group='Pivot Points', defval='Dashed', title='M Levels Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='pivotcolors')
mStyle = mStyleX == 'Dotted' ? line.style_dotted : (mStyleX == 'Dashed' ? line.style_dashed : (mStyleX == 'Solid' ? line.style_solid : line.style_dashed))
showDayHighLow = input.bool(group="Yesterday's and Last Week's High/low", title='Show Hi/Lo: Daily?', defval=true, inline='highlow')
showWeekHighLow = input.bool(group="Yesterday's and Last Week's High/low", title='Weekly?', defval=true, inline='highlow')
showDayHighLowLabels = input.bool(group="Yesterday's and Last Week's High/low", title='Show labels?', defval=true, inline='highlow')
showADR = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Show ADR?', defval=true, inline='adr')
showADRLabels = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Labels?', defval=true, inline='adr')
showADRRange = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Range label?', defval=false, inline='adr')
adrColor = input.color(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='ADR Color', defval=color.new(color.silver, 50), inline='adr1')
string adrStyleX = input.string(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', defval='Dotted', title='ADR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='adr1')
adrStyle = adrStyleX == 'Dotted' ? line.style_dotted : (adrStyleX == 'Dashed' ? line.style_dashed : (adrStyleX == 'Solid' ? line.style_solid : line.style_dotted))
showAWR = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Show AWR?', defval=false, inline='awr')
showAWRLabels = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Labels?', defval=false, inline='awr')
showAWRRange = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Range label?', defval=false, inline='awr')
awrColor = input.color(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='AWR Color', defval=color.new(color.orange, 50), inline='awr1')
string awrStyleX = input.string(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', defval='Dotted', title='AWR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='awr1')
awrStyle = awrStyleX == 'Dotted' ? line.style_dotted : (awrStyleX == 'Dashed' ? line.style_dashed : (awrStyleX == 'Solid' ? line.style_solid : line.style_dotted))
showAMR = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Show AMR?', defval=false, inline='amr')
showAMRLabels = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Labels?', defval=false, inline='amr')
showAMRRange = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Range label?', defval=false, inline='amr')
amrColor = input.color(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='AMR Color', defval=color.new(color.red, 50), inline='amr1')
string amrStyleX = input.string(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', defval='Dotted', title='AMR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='amr1')
amrStyle = amrStyleX == 'Dotted' ? line.style_dotted : (amrStyleX == 'Dashed' ? line.style_dashed : (amrStyleX == 'Solid' ? line.style_solid : line.style_dotted))
showAdrTable = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show ADR Table : ', inline='adrt', defval=true)
choiceAdrTable = input.string(group='ADR/ADRx3/AWR/AMR Table', title='ADR Table postion', inline='adrt', defval='top_right', options=['top_right', 'top_left', 'top_center', 'bottom_right', 'bottom_left', 'bottom_center'])
adrTableBgColor = input.color(group='ADR/ADRx3/AWR/AMR Table', title='ADR Table: Background Color', inline='adrtc', defval=color.rgb(93, 96, 107, 70))
adrTableTxtColor = input.color(group='ADR/ADRx3/AWR/AMR Table', title='Text Color', inline='adrtc', defval=color.rgb(31, 188, 211, 0))
/// market boxes and daily open only on intraday
bool show = timeframe.isminutes and timeframe.multiplier <= 240 and timeframe.multiplier >= 1
time_now_exchange = timestamp(year, month, dayofmonth, hour, minute, second)
bool show_dly = timeframe.isminutes //and timeframe.multiplier < 240
bool show_rectangle9 = input.bool(group='Daily Open', defval=true, title='Show: line ?', inline='dopenconf') and show_dly
bool show_label9 = input.bool(group='Daily Open', defval=true, title='Label?', inline='dopenconf') and show_rectangle9 and show_dly
bool showallDly = input.bool(group='Daily Open', defval=false, title='Show historical daily opens?', inline='dopenconf')
color sess9col = input.color(group='Daily Open', title='Daily Open Color', defval=color.rgb(254, 234, 78, 0), inline='dopenconf1')
//color sess9colLabel = input(group="Daily Open", title="", type=input.color, defval=color.rgb(254,234,78,0), inline="dopenconf1")
bool overridesym = input.bool(group='PVSRA', title='Override chart symbol?', defval=false, inline='pvsra')
string pvsra_sym = input.symbol(group='PVSRA', title='', defval='INDEX:BTCUSD', tooltip='You can use INDEX:BTCUSD or you can combine multiple feeds, for example \'(BINANCE:BTCUSDT+COINBASE:BTCUSD)\'. Note that adding too many will slow things down.', inline='pvsra')
string rectStyle = input.string(group='Market sessions', defval='Dashed', title='Line style of Market Session hi/lo line', options=['Dashed', 'Solid'])
sessLineStyle = line.style_dashed
bool show_markets = input.bool(true, group='Market sessions', title='Show Market Sessions?', tooltip='Turn on or off all market sessions') and show
bool show_markets_weekends = input.bool(false, group='Market sessions', title='Show Market Session on Weekends?', tooltip='Turn on or off market sessions in the weekends. Note do not turn this on for exchanges that dont have weekend data like OANDA') and show
string weekend_sessions = ':1234567'
string no_weekend_sessions = ':23456'
bool show_rectangle1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=true, title='Show: session?', inline='session1conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=true, title='Label?', inline='session1conf') and show_rectangle1 and show_markets
bool show_or1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=true, title='Opening Range?', inline='session1conf', tooltip='This controls the shaded area for the session') and show_rectangle1 and show_markets
string sess1Label = input.string(group='Market session: London (0800-1630 UTC+0)', defval='London', title='Name:', inline='session1style')
color sess1col = input.color(group='Market session: London (0800-1630 UTC+0)', title='Color: Box', defval=color.rgb(120, 123, 134, 75), inline='session1style')
color sess1colLabel = input.color(group='Market session: London (0800-1630 UTC+0)', title='Label', defval=color.rgb(120, 123, 134, 0), inline='session1style')
string sess1TimeX = '0800-1630'//input.session(group='Market session 1', defval='0800-1630', title='Time (UTC+0):', inline='session1style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst1_startTime = input.time(group='Market session 1', defval=timestamp('27 Mar 2022 02:00 +0000'), title='DST Start', inline='ms11', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst1_endTime = input.time(group='Market session 1', defval=timestamp('30 Oct 2022 03:00 +0000'), title='DST End ', inline='ms12', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess1Time = show_markets_weekends ? sess1TimeX + weekend_sessions : sess1TimeX + no_weekend_sessions
//sess_dst_on1 = time_now_exchange >= dst1_startTime and time_now_exchange <= dst1_endTime
bool sess_dst_on1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=false, title='DST On?', inline='session1dst', tooltip='When checked (signifies that London is in DST) and this effectively makes the London session be 0700-1530 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=true, title='Show: session?', inline='session2conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=true, title='Label?', inline='session2conf') and show_rectangle2 and show_markets
bool show_or2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=true, title='Opening Range?', inline='session2conf', tooltip='This controls the shaded area for the session') and show_rectangle2 and show_markets
string sess2Label = input.string(group='Market session: New York (1430-2100 UTC+0)', defval='NewYork', title='Name:', inline='session2style')
color sess2col = input.color(group='Market session: New York (1430-2100 UTC+0)', title='Color: Box', defval=color.rgb(251, 86, 91, 75), inline='session2style')
color sess2colLabel = input.color(group='Market session: New York (1430-2100 UTC+0)', title='Label', defval=color.rgb(253, 84, 87, 25), inline='session2style')
string sess2TimeX = '1430-2100'//input.session(group='Market session 2', defval='1430-2100', title='Time (UTC+0):', inline='session2style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst2_startTime = input.time(group='Market session 2', defval=timestamp('13 Mar 2022 02:00 +0000'), title='DST Start', inline='ms21', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst2_endTime = input.time(group='Market session 2', defval=timestamp('06 Nov 2022 03:00 +0000'), title='DST End ', inline='ms22', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess2Time = show_markets_weekends ? sess2TimeX + weekend_sessions : sess2TimeX + no_weekend_sessions
//sess_dst_on2 = time_now_exchange >= dst2_startTime and time_now_exchange <= dst2_endTime
bool sess_dst_on2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=false, title='DST On?', inline='session2dst', tooltip='When checked (signifies that New York is in DST) and this effectively makes the New York session be 1330-2000 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle3 = input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=true, title='Show: session?', inline='session3conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label3 = input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=true, title='Label?', inline='session3conf') and show_rectangle3 and show_markets
bool show_or3 = input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=true, title='Opening Range?', inline='session3conf', tooltip='This controls the shaded area for the session') and show_rectangle3 and show_markets
string sess3Label = input.string(group='Market session: Tokio (0000-0600 UTC+0)', defval='Tokyo', title='Name:', inline='session3style')
color sess3col = input.color(group='Market session: Tokio (0000-0600 UTC+0)', title='Color: Box', defval=color.rgb(80, 174, 85, 75), inline='session3style')
color sess3colLabel = input.color(group='Market session: Tokio (0000-0600 UTC+0)', title='Label', defval=color.rgb(80, 174, 85, 25), inline='session3style')
string sess3TimeX = '0000-0600'//input.session(group='Market session 3', defval='0000-0600', title='Time (UTC+0):', inline='session3style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst3_startTime = input.time(group='Market session 3', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST Start', inline='ms31', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst3_endTime = input.time(group='Market session 3', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST End ', inline='ms32', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for the past year. Note each year the day for starting and ending DST is different.')
sess3Time = show_markets_weekends ? sess3TimeX + weekend_sessions : sess3TimeX + no_weekend_sessions
//sess_dst_on3 = time_now_exchange >= dst3_startTime and time_now_exchange <= dst3_endTime
bool sess_dst_on3 = false//input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=false, title='DST On?', inline='session3dst', tooltip='Tokio does not observe DST so do not check this checkbox. When checked (signifies that Tokio is in DST) and this effectively makes the Tokio session be 2300-0500 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=true, title='Show: session?', inline='session4conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=true, title='Label?', inline='session4conf') and show_rectangle4 and show_markets
bool show_or4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=true, title='Opening Range?', inline='session4conf', tooltip='This controls the shaded area for the session') and show_rectangle4 and show_markets
string sess4Label = input.string(group='Market session: Hong Kong (0130-0800 UTC+0)', defval='HongKong', title='Name:', inline='session4style')
color sess4col = input.color(group='Market session: Hong Kong (0130-0800 UTC+0)', title='Color: Box', defval=color.rgb(128, 127, 23, 75), inline='session4style')
color sess4colLabel = input.color(group='Market session: Hong Kong (0130-0800 UTC+0)', title='Label', defval=color.rgb(128, 127, 23, 25), inline='session4style')
string sess4TimeX = '0130-0800'//input.session(group='Market session 4', defval='0130-0800', title='Time (UTC+0):', inline='session4style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst4_startTime = input.time(group='Market session 4', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST Start', inline='ms41', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst4_endTime = input.time(group='Market session 4', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST End ', inline='ms42', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess4Time = show_markets_weekends ? sess4TimeX + weekend_sessions : sess4TimeX + no_weekend_sessions
//sess_dst_on4 = time_now_exchange >= dst4_startTime and time_now_exchange <= dst4_endTime
bool sess_dst_on4 = false//input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=false, title='DST On?', inline='session4dst', tooltip='Hong Kong does not observe DST so do not check this checkbox. When checked (signifies that Hong Kong is in DST) and this effectively makes the Hong Kong session be 0030-0700 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='Show: session?', inline='session5conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='Label?', inline='session5conf') and show_rectangle5 and show_markets
bool show_or5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='Opening Range?', inline='session5conf', tooltip='This controls the shaded area for the session') and show_rectangle5 and show_markets
string sess5Label = input.string(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval='Sydney', title='Name:', inline='session5style')
color sess5col = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', title='Color: Box', defval=color.rgb(37, 228, 123, 75), inline='session5style')
color sess5colLabel = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', title='Label', defval=color.rgb(37, 228, 123, 25), inline='session5style')
string sess5TimeX = '2200-0600'//input.session(group='Market session 5', defval='2200-0600', title='Time (UTC+0):', inline='session5style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst5_startTime = input.time(group='Market session 5', defval=timestamp('02 Oct 2021 07:01 +0000'), title='DST Start', inline='ms51', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst5_endTime = input.time(group='Market session 5', defval=timestamp('03 Apr 2022 08:01 +0000'), title='DST End ', inline='ms52', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess5Time = show_markets_weekends ? sess5TimeX + weekend_sessions : sess5TimeX + no_weekend_sessions
//sess_dst_on5 = time_now_exchange >= dst5_startTime and time_now_exchange <= dst5_endTime
bool sess_dst_on5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='DST On?', inline='session5dst', tooltip='When checked (signifies that Sydney is in DST) and this effectively makes the Sydney session be 2100-0500 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=true, title='Show: session?', inline='session6conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=true, title='Label?', inline='session6conf') and show_rectangle6 and show_markets
bool show_or6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=true, title='Opening Range?', inline='session6conf', tooltip='This controls the shaded area for the session') and show_rectangle6 and show_markets
string sess6Label = input.string(group='Market session: EU Brinks (0730-0830 UTC+0)', defval='EU Brinks', title='Name:', inline='session6style')
color sess6col = input.color(group='Market session: EU Brinks (0730-0830 UTC+0)', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session6style')
color sess6colLabel = input.color(group='Market session: EU Brinks (0730-0830 UTC+0)', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session6style')
string sess6TimeX = '0730-0830'//input.session(group='Market session 6', defval='0730-0830', title='Time (UTC+0):', inline='session6style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst6_startTime = input.time(group='Market session 6', defval=timestamp('27 Mar 2022 02:00 +0000'), title='DST Start', inline='ms61', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst6_endTime = input.time(group='Market session 6', defval=timestamp('30 Oct 2022 03:00 +0000'), title='DST End ', inline='ms62', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess6Time = show_markets_weekends ? sess6TimeX + weekend_sessions : sess6TimeX + no_weekend_sessions
//sess_dst_on6 = time_now_exchange >= dst6_startTime and time_now_exchange <= dst6_endTime
bool sess_dst_on6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=false, title='DST On?', inline='session6dst', tooltip='When checked (signifies that EU Brinks - London is in DST) and this effectively makes the EU Brinks session be 0630-0730 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=true, title='Show: session?', inline='session7conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=true, title='Label?', inline='session7conf') and show_rectangle7 and show_markets
bool show_or7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=true, title='Opening Range?', inline='session7conf', tooltip='This controls the shaded area for the session') and show_rectangle7 and show_markets
string sess7Label = input.string(group='Market session: US Brinks (1400-1500 UTC+0)', defval='US Brinks', title='Name:', inline='session7style')
color sess7col = input.color(group='Market session: US Brinks (1400-1500 UTC+0)', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session7style')
color sess7colLabel = input.color(group='Market session: US Brinks (1400-1500 UTC+0)', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session7style')
string sess7TimeX = '1400-1500'//input.session(group='Market session 7', defval='1400-1500', title='Time (UTC+0):', inline='session7style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst7_startTime = input.time(group='Market session 7', defval=timestamp('13 Mar 2022 02:00 +0000'), title='DST Start', inline='ms71', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst7_endTime = input.time(group='Market session 7', defval=timestamp('06 Nov 2022 03:00 +0000'), title='DST End ', inline='ms72', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess7Time = show_markets_weekends ? sess7TimeX + weekend_sessions : sess7TimeX + no_weekend_sessions
//sess_dst_on7 = time_now_exchange >= dst7_startTime and time_now_exchange <= dst7_endTime
bool sess_dst_on7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=false, title='DST On?', inline='session7dst', tooltip='When checked (signifies that US Brinks - New York is in DST) and this effectively makes the US Brinks session be 1300-1400 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool show_rectangle8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=false, title='Show: session?', inline='session8conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=true, title='Label?', inline='session8conf') and show_rectangle8 and show_markets
bool show_or8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=true, title='Opening Range?', inline='session8conf', tooltip='This controls the shaded area for the session') and show_rectangle8 and show_markets
string sess8Label = input.string(group='Market session: Frankfurt (0700-1630 UTC+0)', defval='Frankfurt', title='Name:', inline='session8style')
color sess8col = input.color(group='Market session: Frankfurt (0700-1630 UTC+0)', title='Color: Box', defval=color.rgb(253, 152, 39, 75), inline='session8style')
color sess8colLabel = input.color(group='Market session: Frankfurt (0700-1630 UTC+0)', title='Label', defval=color.rgb(253, 152, 39, 25), inline='session8style')
string sess8TimeX = '0700-1630'//input.session(group='Market session 8', defval='0800-1630', title='Time (UTC+0):', inline='session8style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst8_startTime = input.time(group='Market session 8', defval=timestamp('27 Mar 2022 02:00 +0000'), title='DST Start', inline='ms81', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst8_endTime = input.time(group='Market session 8', defval=timestamp('30 Oct 2022 03:00 +0000'), title='DST End ', inline='ms82', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess8Time = show_markets_weekends ? sess8TimeX + weekend_sessions : sess8TimeX + no_weekend_sessions
//sess_dst_on8 = time_now_exchange >= dst8_startTime and time_now_exchange <= dst8_endTime
bool sess_dst_on8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=false, title='DST On?', inline='session8dst', tooltip='When checked (signifies that Frankfurt is in DST) and this effectively makes the Frankfurt session be 0600-1530 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')
bool showPsy = timeframe.isminutes and (timeframe.multiplier == 60 or timeframe.multiplier == 30 or timeframe.multiplier == 15 or timeframe.multiplier == 5 or timeframe.multiplier == 3 or timeframe.multiplier == 1)
bool show_psylevels = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Show: Levels?', inline='psyconf') and showPsy
bool show_psylabel = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Labels?', inline='psyconf', tooltip="The Psy High/Low will only show on these timeframes: 1h/30min/15min/5min/3min/1min. It is disabled on all others. This is because the calculation requires a candle to start at the correct time for Sydney but in other timeframes the data does not have values at the designated time for the Sydney session.") and show_psylevels
bool showallPsy = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=false, title='Show historical psy levels?', inline='psyconf')
color psycolH = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Hi Color', defval=color.new(color.orange, 30), inline='psyconf1')
color psycolL = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Low Color', defval=color.new(color.orange, 30), inline='psyconf1')
string psyType = input.string(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval='crypto', title='Psy calc type', options=['crypto', 'forex'], inline='psyconf12', tooltip="Are you looking at Crypto or Forex? Crypto calculations start with the Sydney session on Saturday night. Forex calculations start with the Tokyo session on Monday morning. Note some exchanges like Oanda do not have sessions on the weekends so you might be forced to select Forex for exchanges like Oanda even when looking at symbols like BITCOIN on Oanda.")
//int dstPsy_startTime = input.time(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=timestamp('02 Oct 2021 02:00 +0000'), title='DST Start (crypto only)', inline='psyconf13', tooltip='Sydney observes DST. Sydney DST start is generally the first Sunday of October. BUT since Sydney is in the southern hemishpere this setting should basically be set to the first Sunday of October for the previous year. This setting thus must be changed once a year when Sydney is out of DST. Note for different years the first Sunday of October will have a different date each year. This setting has no effect when forex is selected for the psy calc type - this is because Tokio does not observe DST at all.')
//int dstPsy_endTime = input.time(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=timestamp('03 Apr 2022 03:00 +0000'), title='DST End (crypto only)', inline='psyconf14', tooltip='Sydney observes DST. Sydney DST end is generally the first Sunday of April. BUT since Sydney is in the southern hemishpere this setting should basically be set to the first Sunday of April for the current year. This setting thus must be changed once a year when Sydney is out of DST. Note for different years the first Sunday of April will have a different date each year. This setting has no effect when forex is selected for the psy calc type - this is because Tokio does not observe DST at all.')
var string cryptoCalcSession = '2200-0600:1'
var string forexCalcSession = '0000-0800:2'
//sess_dst_onPsy = time_now_exchange >= dstPsy_startTime and time_now_exchange <= dstPsy_endTime
bool sess_dst_onPsy = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='DST On?', inline='psyconf13', tooltip="This only affects Psy calc type of crypto. For crypto - the psy hi/lo calculations in general start at the start of the Sydney market and since Sydney observes DST the calculation needs to shift in respect to when Sydney is in or out of DST. The Psy calc type for forex is taken as the Tokio session and since Tokio does not observe DST this check box value has no effect for forex sessions.")
showDstTable = input.bool(group='Daylight Saving Time Info (DST)', title='Show DST Table : ', inline='dstt', defval=false)
choiceDstTable = input.string(group='Daylight Saving Time Info (DST)', title='DST Table postion', inline='dstt', defval='bottom_center', options=['top_right', 'top_left', 'top_center', 'bottom_right', 'bottom_left', 'bottom_center'])
dstTableBgColor = input.color(group='Daylight Saving Time Info (DST)', title='DST Table: Background Color', inline='dsttc', defval=color.rgb(93, 96, 107, 70))
dstTableTxtColor = input.color(group='Daylight Saving Time Info (DST)', title='Text Color', inline='dsttc', defval=color.rgb(31, 188, 211, 0))
//Non repainting security
f_security(_symbol, _res, _src, _repaint) =>
request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1]
// Basic vars (needed in functions)
// Only render intraday
validTimeFrame = timeframe.isintraday == true
// If above the 5 minute, we start drawing yesterday. below, we start today
levelsstart = timeframe.isseconds == true or timeframe.isminutes == true and timeframe.multiplier < 5 ? time('D') : time('D') - 86400 * 1000
levelsstartbar = ta.barssince(levelsstart)
// Functions
// new_bar: check if we're on a new bar within the session in a given resolution
new_bar(res) =>
ta.change(time(res)) != 0
// adr: Calculate average daily range for a given length
adr(length) =>
// This is effectively an atr, which is what is used in MT4 to get those levels. FWIW, true range can be also calculated with tr(true)
trueRange = na(high[1]) ? high - low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
// Switched to SMA from RMA because somehow it matches MT4 better
ta.sma(trueRange[1], length)
// adr_high: Calculate the ADR high given an ADR
adr_high(adr) =>
high - low < adr ? low + adr : close >= open ? low + adr : high
// adr_low: Calculate the ADR low given an ADR
adr_low(adr) =>
high - low < adr ? high - adr : close >= open ? low : high - adr
// to_pips: Convert to pips
to_pips(val) =>
math.round(val / syminfo.mintick * 100) / 100
pivot_label_x_offset = time_close + pivot_offset_input * timeframe.multiplier * 60 * 1000
label_x_offset = time_close + label_offset_input * timeframe.multiplier * 60 * 1000
adr_label_x_offset = time_close + adr_offset_input * timeframe.multiplier * 60 * 1000
//Right_Label
r_label(ry, rtext, rstyle, rcolor, valid) =>
if valid and barstate.isrealtime
rLabel = label.new(x=label_x_offset, y=ry, text=rtext, xloc=xloc.bar_time, style=rstyle, textcolor=rcolor, textalign=text.align_right)
label.delete(rLabel[1])
draw_line(x_series, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset) =>
var line x_line = na
if new_bar(res) and validTimeFrame
line.set_x2(x_line, bar_index)
line.set_extend(x_line, extend.none)
x_line := line.new(bar_index, x_series, bar_index, x_series, extend=xExtend, color=xColor, style=xStyle, width=xWidth)
line.delete(x_line[1])
if not na(x_line) and line.get_x2(x_line) != bar_index
line.set_x2(x_line, bar_index)
if isLabelValid //showADRLabels and validTimeFrame
x_label = label.new(xLabelOffset, x_series, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=xColor)
label.delete(x_label[1])
draw_pivot(pivot_level, res, tag, pivotColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid) =>
var line pivot_line = na
// Start drawing yesterday
if new_bar(res) and validTimeFrame
line.set_x2(pivot_line, bar_index)
line.set_extend(pivot_line, extend.none)
pivot_line := line.new(bar_index, pivot_level, bar_index, pivot_level, extend=pivotExtend, color=pivotColor, style=pivotStyle, width=pivotWidth)
line.delete(pivot_line[1])
if not na(pivot_line) and line.get_x2(pivot_line) != bar_index
line.set_x2(pivot_line, bar_index)
if isLabelValid //showADRLabels and validTimeFrame
pivot_label = label.new(pivot_label_x_offset, pivot_level, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=pivotColor, textalign=text.align_right)
label.delete(pivot_label[1])
if not barstate.islast
line.set_x2(pivot_line, x=bar_index)
else
line.set_xloc(pivot_line, levelsstart, time_close + 1 * 86400000, xloc=xloc.bar_time)
pivot_line
draw_linelabel_gmt_custSession(pivot_level, res, sessionString, tag, pivotColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, label_offset, gmt_off_val) =>
var line pivot_line = na
gmtD = gmt_off_val
current_session = time(res, sessionString, gmtD)
if not na(current_session)
pivot_line = line.new(current_session, pivot_level, timenow, pivot_level, xloc=xloc.bar_time, extend=pivotExtend, color=pivotColor, style=pivotStyle, width=pivotWidth)
line.delete(pivot_line[1])
if isLabelValid
pivot_label = label.new(label_offset, pivot_level, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=pivotColor, textalign=text.align_right)
label.delete(pivot_label[1])
pivot_line
update_pivot(pivot_line, pivot_level, res, tag, pivotColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid) =>
if new_bar(res) and validTimeFrame
line.set_x1(pivot_line, bar_index)
line.set_y1(pivot_line, pivot_level)
line.set_y2(pivot_line, pivot_level)
if not barstate.islast
line.set_x2(pivot_line, x=bar_index)
else
line.set_xloc(pivot_line, levelsstart, time_close + 1 * 86400000, xloc=xloc.bar_time)
//Emas
oneEmaLength = 5
twoEmaLength = 13
threeEmaLength = 50
fourEmaLength = 200
fiveEmaLength = 800
oneEma = ta.ema(close, oneEmaLength)
plot(showEmas ? oneEma : na, color=oneEmaColor, title='5 Ema')
twoEma = ta.ema(close, twoEmaLength)
plot(showEmas ? twoEma : na, color=twoEmaColor, title='13 Ema')
threeEma = ta.ema(close, threeEmaLength)
plot(showEmas ? threeEma : na, color=threeEmaColor, title='50 Ema')
fourEma = ta.ema(close, fourEmaLength)
plot(showEmas ? fourEma : na, color=fourEmaColor, title='200 Ema')
fiveEma = ta.ema(close, fiveEmaLength)
plot(showEmas ? fiveEma : na, color=fiveEmaColor, linewidth=2, title='800 Ema')
// Ema 50 cloud placed here for readability on data window
cloudSize = ta.stdev(close, threeEmaLength * 2) / 4
p1 = plot(showEmas ? threeEma + cloudSize : na, 'Upper 50 Ema Cloud', color=EmaCloudBorderColor, offset=0)
p2 = plot(showEmas ? threeEma - cloudSize : na, 'Lower 50 Ema Cloud', color=EmaCloudBorderColor, offset=0)
fill(p1, p2, title='EMA 50 Cloud', color=EmaCloudColor, transp=90)
//Label emas
r_label(oneEma, '5 Ema', label.style_none, oneEmaColor, labelEmas) //ry, rtext, rstyle, rcolor,valid
r_label(twoEma, '13 Ema', label.style_none, twoEmaColor, labelEmas)
r_label(threeEma, '50 Ema', label.style_none, threeEmaColor, labelEmas)
r_label(fourEma, '200 Ema', label.style_none, fourEmaColor, labelEmas)
r_label(fiveEma, '800 Ema', label.style_none, fiveEmaColor, labelEmas)
// Get Daily price data
dayHigh = f_security(syminfo.tickerid, 'D', high, false)
dayLow = f_security(syminfo.tickerid, 'D', low, false)
dayOpen = f_security(syminfo.tickerid, 'D', open, false)
dayClose = f_security(syminfo.tickerid, 'D', close, false)
//Compute Values
pivotPoint = (dayHigh + dayLow + dayClose) / 3
// Updated 2021-03-25 by infernix
pivR1 = 2 * pivotPoint - dayLow
pivS1 = 2 * pivotPoint - dayHigh
pivR2 = pivotPoint - pivS1 + pivR1
pivS2 = pivotPoint - pivR1 + pivS1
pivR3 = 2 * pivotPoint + dayHigh - 2 * dayLow
pivS3 = 2 * pivotPoint - (2 * dayHigh - dayLow)
//Plot Values
//plot(validTimeFrame and showLevelOnePivotPoints? pivotPoint : na, linewidth = 1, color = color.yellow, style = plot.style_circles, transp = 25, title = "Daily Pivot Point", show_last = plot_bars)
pivline = draw_pivot(validTimeFrame and (showLevelOnePivotPoints or showLevelTwoPivotPoints or showLevelThreePivotPoints or activeM) ? pivotPoint : na, 'D', 'PP', pivotColor, mStyle, 1, extendPivots ? extend.both : extend.right, showPivotLabels and validTimeFrame)
pivr1line = draw_pivot(validTimeFrame and showLevelOnePivotPoints ? pivR1 : na, 'D', 'R1', color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)
pivs1line = draw_pivot(validTimeFrame and showLevelOnePivotPoints ? pivS1 : na, 'D', 'S1', color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)
pivr2line = draw_pivot(validTimeFrame and showLevelTwoPivotPoints ? pivR2 : na, 'D', 'R2', color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)
pivs2line = draw_pivot(validTimeFrame and showLevelTwoPivotPoints ? pivS2 : na, 'D', 'S2', color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)
pivr3line = draw_pivot(validTimeFrame and showLevelThreePivotPoints ? pivR3 : na, 'D', 'R3', color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)
pivs3line = draw_pivot(validTimeFrame and showLevelThreePivotPoints ? pivS3 : na, 'D', 'S3', color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)
if not na(pivotPoint)
update_pivot(pivline, validTimeFrame and (showLevelOnePivotPoints or showLevelTwoPivotPoints or showLevelThreePivotPoints or activeM) ? pivotPoint : na, 'D', 'PP', pivotColor, line.style_dashed, 1, extendPivots ? extend.both : extend.right, showPivotLabels and validTimeFrame)
if not na(pivR1)
update_pivot(pivr1line, validTimeFrame and showLevelOnePivotPoints ? pivR1 : na, 'D', 'R1', color.new(color.green, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)
if not na(pivS1)
update_pivot(pivs1line, validTimeFrame and showLevelOnePivotPoints ? pivS1 : na, 'D', 'S1', color.new(color.red, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)
if not na(pivR2)
update_pivot(pivr2line, validTimeFrame and showLevelTwoPivotPoints ? pivR2 : na, 'D', 'R2', color.new(color.green, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)
if not na(pivS2)
update_pivot(pivs2line, validTimeFrame and showLevelTwoPivotPoints ? pivS2 : na, 'D', 'S2', color.new(color.red, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)
if not na(pivR3)
update_pivot(pivr3line, validTimeFrame and showLevelThreePivotPoints ? pivR3 : na, 'D', 'R3', color.new(color.green, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)
if not na(pivS3)
update_pivot(pivs3line, validTimeFrame and showLevelThreePivotPoints ? pivS3 : na, 'D', 'S3', color.new(color.red, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)
// Daily H/L
weekHigh = f_security(syminfo.tickerid, 'W', high, false)
weekLow = f_security(syminfo.tickerid, 'W', low, false)
validDHLTimeFrame = timeframe.isintraday == true
validWHLTimeFrame = timeframe.isintraday == true or timeframe.isdaily == true
isToday = year(timenow) == year(time) and month(timenow) == month(time) and dayofmonth(timenow) == dayofmonth(time)
isThisWeek = year(timenow) == year(time) and weekofyear(timenow) == weekofyear(time)
plot(validDHLTimeFrame and showDayHighLow and (showDayHighLow ? true : isToday) ? dayHigh : na, linewidth=2, color=color.new(color.blue, 50), style=plot.style_circles, title="YDay Hi")
plot(validDHLTimeFrame and showDayHighLow and (showDayHighLow ? true : isToday) ? dayLow : na, linewidth=2, color=color.new(color.blue, 50), style=plot.style_circles, title="YDay Lo")
r_label(dayHigh, 'YDay Hi', label.style_none, color.blue, validDHLTimeFrame and showDayHighLow and showDayHighLowLabels) //ry, rtext, rstyle, rcolor, valid
r_label(dayLow, 'YDay Lo', label.style_none, color.blue, validDHLTimeFrame and showDayHighLow and showDayHighLowLabels)
plot(validWHLTimeFrame and showWeekHighLow and (showWeekHighLow ? true : isThisWeek) ? weekHigh : na, linewidth=2, color=color.new(color.green, 60), style=plot.style_circles, title="LWeek Hi")
plot(validWHLTimeFrame and showWeekHighLow and (showWeekHighLow ? true : isThisWeek) ? weekLow : na, linewidth=2, color=color.new(color.green, 60), style=plot.style_circles, title="LWeek Lo")
r_label(weekHigh, 'LWeek Hi', label.style_none, color.green, validWHLTimeFrame and showWeekHighLow and showDayHighLowLabels) //ry, rtext, rstyle, rcolor, valid
r_label(weekLow, 'LWeek Lo', label.style_none, color.green, validWHLTimeFrame and showWeekHighLow and showDayHighLowLabels)
// PVSRA
// From MT4 source:
// Situation "Climax"
// Bars with volume >= 200% of the average volume of the 10 previous chart TFs, and bars
// where the product of candle spread x candle volume is >= the highest for the 10 previous
// chart time TFs.
// Default Colors: Bull bars are green and bear bars are red.
// Situation "Volume Rising Above Average"
// Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
// Default Colors: Bull bars are blue and bear are blue-violet.
// We want to be able to override where we get the volume data for the candles.
pvsra_security(sresolution, sseries) =>
request.security(overridesym ? pvsra_sym : syminfo.tickerid, sresolution, sseries[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)
pvsra_security_1 = pvsra_security('', volume)
pvsra_volume = overridesym == true ? pvsra_security_1 : volume
pvsra_security_2 = pvsra_security('', high)
pvsra_high = overridesym == true ? pvsra_security_2 : high
pvsra_security_3 = pvsra_security('', low)
pvsra_low = overridesym == true ? pvsra_security_3 : low
pvsra_security_4 = pvsra_security('', close)
pvsra_close = overridesym == true ? pvsra_security_4 : close
pvsra_security_5 = pvsra_security('', open)
pvsra_open = overridesym == true ? pvsra_security_5 : open
r_label(high - (high - low) / 2, 'PVSRA Override Active!', label.style_none, color.orange, overridesym) //ry, rtext, rstyle, rcolor, valid
//label.new(overridesym ? 0 : na, low, text = "PVSRA Override: " + pvsra_sym, xloc = xloc.bar_index, yloc=yloc.belowbar,style=label.style_label_down, size=size.huge)
// The below math matches MT4 PVSRA indicator source
// average volume from last 10 candles
sum_1 = math.sum(pvsra_volume, 10)
sum_2 = math.sum(volume, 10)
av = overridesym == true ? sum_1 / 10 : sum_2 / 10
//climax volume on the previous candle
value2 = overridesym == true ? pvsra_volume * (pvsra_high - pvsra_low) : volume * (high - low)
// highest climax volume of the last 10 candles
hivalue2 = ta.highest(value2, 10)
// VA value determines the bar color. va = 0: normal. va = 1: climax. va = 2: rising
iff_1 = pvsra_volume >= av * 1.5 ? 2 : 0
iff_2 = pvsra_volume >= av * 2 or value2 >= hivalue2 ? 1 : iff_1
iff_3 = volume >= av * 1.5 ? 2 : 0
iff_4 = volume >= av * 2 or value2 >= hivalue2 ? 1 : iff_3
va = overridesym == true ? iff_2 : iff_4
// Bullish or bearish coloring
isBull = overridesym == true ? pvsra_close > pvsra_open : close > open
CUColor = color.lime // Climax up (bull) bull and bear both start with b so it would be weird hence up down
CDColor = color.red // Climax down (bear)
AUColor = color.blue //Avobe average up (bull)
ADColor = color.fuchsia //Above average down (bear))
NUColor = #999999
NDColor = #4d4d4d
// candleColor = iff(climax,iff(isBull,CUColor,CDColor),iff(aboveA,iff(isBull,AUColor,ADColor),iff(isBull,NUColor,NDColor)))
iff_5 = va == 2 ? AUColor : NUColor
iff_6 = va == 1 ? CUColor : iff_5
iff_7 = va == 2 ? ADColor : NDColor
iff_8 = va == 1 ? CDColor : iff_7
candleColor = isBull ? iff_6 : iff_8
barcolor(candleColor)
alertcondition(va > 0, title='Alert on Any Vector Candle', message='{{ticker}} Vector Candle on the {{interval}}')
redGreen = candleColor == color.lime and candleColor[1] == color.red
greenRed = candleColor == color.red and candleColor[1] == color.lime
redBlue = candleColor == color.blue and candleColor[1] == color.red
blueRed = candleColor == color.red and candleColor[1] == color.blue
greenPurpule = candleColor == color.fuchsia and candleColor[1] == color.green
purpleGreen = candleColor == color.green and candleColor[1] == color.fuchsia
bluePurpule = candleColor == color.fuchsia and candleColor[1] == color.blue
purpleBlue = candleColor == color.blue and candleColor[1] == color.fuchsia
alertcondition(redGreen, title='Red/Green Vector Candle Pattern', message='{{ticker}} Red/Green Vector Candle Pattern on the {{interval}}')
alertcondition(greenRed, title='Green/Red Vector Candle Pattern', message='{{ticker}} Green/Red Vector Candle Pattern on the {{interval}}')
alertcondition(redBlue, title='Red/Blue Vector Candle Pattern', message='{{ticker}} Red/Blue Vector Candle Pattern on the {{interval}}')
alertcondition(blueRed, title='Blue/Red Vector Candle Pattern', message='{{ticker}} Blue/Red Vector Candle Pattern on the {{interval}}')
alertcondition(greenPurpule, title='Green/Purple Vector Candle Pattern', message='{{ticker}} Green/Purple Vector Candle Pattern on the {{interval}}')
alertcondition(purpleGreen, title='Purple/Green Vector Candle Pattern', message='{{ticker}} Purple/Green Vector Candle Pattern on the {{interval}}')
alertcondition(bluePurpule, title='Blue/Purple Vector Candle Pattern', message='{{ticker}} Blue/Purple Vector Candle Pattern on the {{interval}}')
alertcondition(purpleBlue, title='Purple/Blue Vector Candle Pattern', message='{{ticker}} Purple/Blue Vector Candle Pattern on the {{interval}}')
//ADR
// Daily ADR
//
day_adr = request.security(syminfo.tickerid, 'D', adr(15), lookahead=barmerge.lookahead_on)
day_adr_high = request.security(syminfo.tickerid, 'D', adr_high(day_adr), lookahead=barmerge.lookahead_on)
day_adr_low = request.security(syminfo.tickerid, 'D', adr_low(day_adr), lookahead=barmerge.lookahead_on)
if showADR
draw_line(day_adr_high, 'D', 'Hi-ADR', adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adr_label_x_offset)
draw_line(day_adr_low, 'D', 'Lo-ADR', adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adr_label_x_offset)
r_label((day_adr_high + day_adr_low) / 2, 'ADR ' + str.tostring(to_pips(day_adr)), label.style_none, adrColor, showADRLabels and validTimeFrame and showADRRange) //ry, rtext, rstyle, rcolor, valid
alertcondition(close >= day_adr_high and day_adr_high != 0 , "ADR High reached", "PA has reached the calculated ADR High")
alertcondition(close <= day_adr_low and day_adr_low != 0 , "ADR Low reached", "PA has reached the calculated ADR Low")
//Weekly ADR
week_adr = request.security(syminfo.tickerid, 'W', adr(1), lookahead=barmerge.lookahead_on)
week_adr_high = request.security(syminfo.tickerid, 'W', adr_high(week_adr), lookahead=barmerge.lookahead_on)
week_adr_low = request.security(syminfo.tickerid, 'W', adr_low(week_adr), lookahead=barmerge.lookahead_on)
if showAWR
draw_line(week_adr_high, 'W', 'Hi-AWR', awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adr_label_x_offset)
draw_line(week_adr_low, 'W', 'Lo-AWR', awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adr_label_x_offset)
r_label((week_adr_high + week_adr_low) / 2, 'AWR ' + str.tostring(to_pips(week_adr)), label.style_none, awrColor, showAWRLabels and validTimeFrame and showAWRRange) //ry, rtext, rstyle, rcolor, valid
alertcondition(close >= week_adr_high and week_adr_high != 0 , "AWR High reached", "PA has reached the calculated AWR High")
alertcondition(close <= week_adr_low and week_adr_low != 0 , "AWR Low reached", "PA has reached the calculated AWR Low")
//Monthly ADR
month_adr = request.security(syminfo.tickerid, 'M', adr(1), lookahead=barmerge.lookahead_on)
month_adr_high = request.security(syminfo.tickerid, 'M', adr_high(week_adr), lookahead=barmerge.lookahead_on)
month_adr_low = request.security(syminfo.tickerid, 'M', adr_low(week_adr), lookahead=barmerge.lookahead_on)
if showAMR
draw_line(month_adr_high, 'M', 'Hi-AMR', amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adr_label_x_offset)
draw_line(month_adr_low, 'M', 'Lo-AMR', amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adr_label_x_offset)
r_label((month_adr_high + month_adr_low) / 2, 'AMR ' + str.tostring(to_pips(month_adr)), label.style_none, amrColor, showAMRLabels and validTimeFrame and showAMRRange) //ry, rtext, rstyle, rcolor, valid
alertcondition(close >= month_adr_high and month_adr_high != 0 , "AMR High reached", "PA has reached the calculated AMR High")
alertcondition(close <= month_adr_low and month_adr_low != 0 , "AMR Low reached", "PA has reached the calculated AMR Low")
if barstate.islast and showAdrTable and validTimeFrame
var table panel = table.new(choiceAdrTable, 2, 5, bgcolor=adrTableBgColor)
// Table header.
table.cell(panel, 0, 0, '')
table.cell(panel, 1, 0, '')
table.cell(panel, 0, 1, 'ADR', text_color=adrTableTxtColor)
table.cell(panel, 1, 1, str.format('{0,number,#.##}', to_pips(day_adr)) , text_color=adrTableTxtColor)
table.cell(panel, 0, 2, 'ADRx3', text_color=adrTableTxtColor)
table.cell(panel, 1, 2, str.format('{0,number,#.##}', to_pips(day_adr) * 3), text_color=adrTableTxtColor)
table.cell(panel, 0, 3, 'AWR', text_color=adrTableTxtColor)
table.cell(panel, 1, 3, str.format('{0,number,#.##}', to_pips(week_adr)), text_color=adrTableTxtColor)
table.cell(panel, 0, 4, 'AMR', text_color=adrTableTxtColor)
table.cell(panel, 1, 4, str.format('{0,number,#.##}', to_pips(month_adr)), text_color=adrTableTxtColor)
// M - Levels
//Calculate Pivot Point
// 2021-03025 updated by infernix
//M calculations
m0C = (pivS2 + pivS3) / 2
m1C = (pivS1 + pivS2) / 2
m2C = (pivotPoint + pivS1) / 2
m3C = (pivotPoint + pivR1) / 2
m4C = (pivR1 + pivR2) / 2
m5C = (pivR2 + pivR3) / 2
m0line = draw_pivot(validTimeFrame and activeM and m0C ? m0C : na, 'D', 'M0', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m1line = draw_pivot(validTimeFrame and activeM and m1C ? m1C : na, 'D', 'M1', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m2line = draw_pivot(validTimeFrame and activeM and m2C ? m2C : na, 'D', 'M2', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m3line = draw_pivot(validTimeFrame and activeM and m3C ? m3C : na, 'D', 'M3', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m4line = draw_pivot(validTimeFrame and activeM and m4C ? m4C : na, 'D', 'M4', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m5line = draw_pivot(validTimeFrame and activeM and m5C ? m5C : na, 'D', 'M5', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m0C)
update_pivot(m0line, validTimeFrame and activeM and m0C ? m0C : na, 'D', 'M0', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m1C)
update_pivot(m1line, validTimeFrame and activeM and m1C ? m1C : na, 'D', 'M1', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m2C)
update_pivot(m2line, validTimeFrame and activeM and m2C ? m2C : na, 'D', 'M2', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m3C)
update_pivot(m3line, validTimeFrame and activeM and m3C ? m3C : na, 'D', 'M3', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m4C)
update_pivot(m4line, validTimeFrame and activeM and m4C ? m4C : na, 'D', 'M4', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m5C)
update_pivot(m5line, validTimeFrame and activeM and m5C ? m5C : na, 'D', 'M5', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
//*****************
// Market sessions
//*****************
splitSessionString(sessXTime) =>
//session stirng looks like this: 0000-0000:1234567 ie start time, end time, day of the week
//we need to parse the sessXTime string into hours and min for start and end times so we can use those in the timestampfunction below
//string times contains "0000-2300" as an example
string times = array.get(str.split(sessXTime, ':'), 0)
//string startTime contains "0000"
string startTime = array.get(str.split(times, '-'), 0)
//string endTime contains "2300"
string endTime = array.get(str.split(times, '-'), 1)
//now we need to get the start hour and start min, sing 0 index - hour is the characters in index 0 and index 1 while min is the chars at index 2 and 3
string[] startTimeChars = str.split(startTime, '')
string[] endTimeChars = str.split(endTime, '')
//so now startHour contains 00 and start min contains 00
string startHour = array.get(startTimeChars, 0) + array.get(startTimeChars, 1)
string startMin = array.get(startTimeChars, 2) + array.get(startTimeChars, 3)
//so now endHour contains 23 and end min contains 00
string endHour = array.get(endTimeChars, 0) + array.get(endTimeChars, 1)
string endMin = array.get(endTimeChars, 2) + array.get(endTimeChars, 3)
[startHour, startMin, endHour, endMin]
calc_session_startend(sessXTime, gmt) =>
[startHour, startMin, endHour, endMin] = splitSessionString(sessXTime)
targetstartTimeX = timestamp(gmt, year, month, dayofmonth, math.round(str.tonumber(startHour)), math.round(str.tonumber(startMin)), 00)
targetendTimeX = timestamp(gmt, year, month, dayofmonth, math.round(str.tonumber(endHour)), math.round(str.tonumber(endMin)), 00)
time_now = timestamp(year, month, dayofmonth, hour, minute, 00)
midnight_exchange = timestamp(year, month, dayofmonth, 00, 00, 00)
//if start hour is greater than end hour we are dealing with a session that starts towards the end of one day
//and ends the next day. ie advance the end time by 24 hours - its the next day
bool adjusted = false
if gmt == 'GMT+0'
if math.round(str.tonumber(startHour)) > math.round(str.tonumber(endHour))
if time_now - targetstartTimeX >= 0
targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
adjusted := true
targetendTimeX
if gmt == 'GMT+1'
if math.round(str.tonumber(startHour)) == 0
startHour := '24'
if math.round(str.tonumber(endHour)) == 0
endHour := '24'
if math.round(str.tonumber(startHour))-1 > math.round(str.tonumber(endHour))-1
if time_now - targetstartTimeX >= 0
targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
adjusted := true
targetendTimeX
//now is the exchange is at some utc offset and the market session crosses days even when start hour is not greater than end hour
//we still need to adjust the end time.
if targetstartTimeX < midnight_exchange and midnight_exchange < targetendTimeX and not adjusted
targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
targetendTimeX
[targetstartTimeX,targetendTimeX]
draw_open_range(sessXTime, sessXcol, show_orX, gmt)=>
if show_orX
// Initialize variables on bar zero only, so they preserve their values across bars.
var hi = float(na)
var lo = float(na)
var box hiLoBox = na
// Detect changes in timeframe.
session = time(timeframe.period, sessXTime, gmt)
bool newTF = session and not session[1]
if newTF
// New bar in higher timeframe; reset values and create new lines and box.
[targetstartTimeX,targetendTimeX] = calc_session_startend(sessXTime, gmt)
sessionDuration = math.round(math.abs(time - targetendTimeX)/(timeframe.multiplier*60*1000))
hi := high
lo := low
hiLoBox := box.new(bar_index, hi, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, lo, border_color = na, bgcolor = sessXcol)
int(na)
else
if timeframe.multiplier == 1 and (na(session[1]) and not na(session) or session[1] < session)
box.set_right(hiLoBox, bar_index+1)
int(na)
draw_session_hilo(sessXTime, show_rectangleX, show_labelX, sessXcolLabel, sessXLabel, gmt)=>
if show_rectangleX
// Initialize variables on bar zero only, so they preserve their values across bars.
var hi = float(0)
var lo = float(10000000000.0)
var beginIndex = int(na)
var line line_t = na
var line line_b = na
var label line_label = na
// var box hiLoBox = na
// Detect changes in timeframe.
session = time(timeframe.period, sessXTime, gmt)
sessLineStyleX = rectStyle == 'Solid' ? line.style_solid : line.style_dashed
bool newTF = session and not session[1]
hi := newTF ? high : session ? math.max(high, hi[1]) : hi[1]
lo := newTF ? low : session ? math.min(low, lo[1]) : lo[1]
difference = timestamp(year,month,dayofmonth,00,00,00) - (10*24*60*60*1000)
if newTF and timenow > difference
beginIndex := bar_index
[targetstartTimeX,targetendTimeX] = calc_session_startend(sessXTime, gmt)
sessionDuration = math.round(math.abs(time - targetendTimeX)/(timeframe.multiplier*60*1000))
line_t := line.new(beginIndex, hi, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, hi, xloc=xloc.bar_index, style=sessLineStyleX, color=sessXcolLabel)
line_b := line.new(beginIndex, lo, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, lo, xloc=xloc.bar_index, style=sessLineStyleX, color=sessXcolLabel)
line.delete(line_t[1])
line.delete(line_b[1])
if show_labelX
line_label := label.new(beginIndex, hi, sessXLabel, xloc=xloc.bar_index, textcolor=sessXcolLabel, style=label.style_none, size=size.normal, textalign=text.align_right)
label.delete(line_label[1])
int(na)
else
if na(session[1]) and not na(session) or session[1] < session
if timeframe.multiplier == 1
line.set_x2(line_t,bar_index+1)
line.set_x2(line_b,bar_index+1)
line.set_y1(line_t,hi)
line.set_y2(line_t,hi)
line.set_y1(line_b,lo)
line.set_y2(line_b,lo)
if show_labelX and not na(line_label)
label.set_xy(line_label, beginIndex, hi)
int(na)
if sess_dst_on1
draw_open_range(sess1Time,sess1col,show_or1,'GMT+1')
draw_session_hilo(sess1Time, show_rectangle1, show_label1, sess1colLabel, sess1Label, 'GMT+1')
else
draw_open_range(sess1Time,sess1col,show_or1,'GMT+0')
draw_session_hilo(sess1Time, show_rectangle1, show_label1, sess1colLabel, sess1Label, 'GMT+0')
if sess_dst_on2
draw_open_range(sess2Time,sess2col,show_or2,'GMT+1')
draw_session_hilo(sess2Time, show_rectangle2, show_label2, sess2colLabel, sess2Label, 'GMT+1')
else
draw_open_range(sess2Time,sess2col,show_or2,'GMT+0')
draw_session_hilo(sess2Time, show_rectangle2, show_label2, sess2colLabel, sess2Label, 'GMT+0')
if sess_dst_on3
draw_open_range(sess3Time,sess3col,show_or3,'GMT+1')
draw_session_hilo(sess3Time, show_rectangle3, show_label3, sess3colLabel, sess3Label, 'GMT+1')
else
draw_open_range(sess3Time,sess3col,show_or3,'GMT+0')
draw_session_hilo(sess3Time, show_rectangle3, show_label3, sess3colLabel, sess3Label, 'GMT+0')
if sess_dst_on4
draw_open_range(sess4Time,sess4col,show_or4,'GMT+1')
draw_session_hilo(sess4Time, show_rectangle4, show_label4, sess4colLabel, sess4Label, 'GMT+1')
else
draw_open_range(sess4Time,sess4col,show_or4,'GMT+0')
draw_session_hilo(sess4Time, show_rectangle4, show_label4, sess4colLabel, sess4Label, 'GMT+0')
if sess_dst_on5
draw_open_range(sess5Time,sess5col,show_or5,'GMT+1')
draw_session_hilo(sess5Time, show_rectangle5, show_label5, sess5colLabel, sess5Label, 'GMT+1')
else
draw_open_range(sess5Time,sess5col,show_or5,'GMT+0')
draw_session_hilo(sess5Time, show_rectangle5, show_label5, sess5colLabel, sess5Label, 'GMT+0')
if sess_dst_on6
draw_open_range(sess6Time,sess6col,show_or6,'GMT+1')
draw_session_hilo(sess6Time, show_rectangle6, show_label6, sess6colLabel, sess6Label, 'GMT+1')
else
draw_open_range(sess6Time,sess6col,show_or6,'GMT+0')
draw_session_hilo(sess6Time, show_rectangle6, show_label6, sess6colLabel, sess6Label, 'GMT+0')
if sess_dst_on7
draw_open_range(sess7Time,sess7col,show_or7,'GMT+1')
draw_session_hilo(sess7Time, show_rectangle7, show_label7, sess7colLabel, sess7Label, 'GMT+1')
else
draw_open_range(sess7Time,sess7col,show_or7,'GMT+0')
draw_session_hilo(sess7Time, show_rectangle7, show_label7, sess7colLabel, sess7Label, 'GMT+0')
if sess_dst_on8
draw_open_range(sess8Time,sess8col,show_or8,'GMT+1')
draw_session_hilo(sess8Time, show_rectangle8, show_label8, sess8colLabel, sess8Label, 'GMT+1')
else
draw_open_range(sess8Time,sess8col,show_or8,'GMT+0')
draw_session_hilo(sess8Time, show_rectangle8, show_label8, sess8colLabel, sess8Label, 'GMT+0')
//***********
// Daily open
//***********
getdayOpen()=>
in_sessionDly = time('D', '24x7')
bool isDly = ta.change(time('D'))//ta.change(in_sessionDly)//in_sessionDly and not in_sessionDly[1]
var dlyOpen = float(na)
if isDly
dlyOpen := open
dlyOpen
daily_open = getdayOpen()
//this plot is only to show historical values when the option is selected.
plot(show_rectangle9 and validTimeFrame and showallDly ? daily_open : na, color=sess9col, style=plot.style_stepline, linewidth=2, editable=false, title="Daily Open")
if showallDly
//if historical values are selected to be shown - then add a label to the plot
r_label(daily_open, 'Daily Open', label.style_none, sess9col, validTimeFrame and show_label9)
showallDly
else
if show_rectangle9
//othewise we draw the line and label together - showing only todays line.
draw_line(daily_open, 'D', 'Daily Open', sess9col, line.style_solid, 1, extend.none, validTimeFrame and show_label9, label_x_offset)
//************//
// Psy Levels //
//************//
calc_psy_hilo(gmtoffsetPsy, sessionPsyX) =>
//4 hour res based on how mt4 does it
//mt4 code
//int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
//ObjectCreate("PsychHi", OBJ_TREND, 0, Time[0], iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
//iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
//so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
//we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
//keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
in_session = time('240', sessionPsyX, gmtoffsetPsy)
new_session = in_session and not in_session[1]
float psy_high = 0.0
float psy_low = 100000000000.0
psy_high := new_session ? high : in_session ? math.max(high, psy_high[1]) : psy_high[1]
psy_low := new_session ? low : in_session ? math.min(low, psy_low[1]) : psy_low[1]
//if barstate.isnew
psy_calc_start = timestamp(gmtoffsetPsy, year, month, dayofweek.wednesday, 00, 00, 00)
psy_calc_end = timestamp(gmtoffsetPsy, year, month, dayofweek.wednesday, 08, 00, 00)
time_now_gmt = time('D', sessionPsyX, gmtoffsetPsy)
psy_calc_inProgress = not na(time_now_gmt - psy_calc_start >= 0) and not na(time_now_gmt - psy_calc_end <= 0)
psy_hi_label = 'Psy-Hi'
psy_lo_label = 'Psy-Lo'
if psy_calc_inProgress
//stylePsy := line.style_dashed //this does not work for style correctly but it does for the label which is odd
psy_hi_label := 'Psy-Hi calculating...'
psy_lo_label := 'Psy-Lo calculating...'
psy_lo_label
else
psy_hi_label := 'Psy-Hi'
psy_lo_label := 'Psy-Lo'
[psy_high, psy_low, psy_hi_label, psy_lo_label]
draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label,sessionPsyX, gmt) =>
if showallPsy
r_label(psy_high, psy_hi_label, label.style_none, psycolH, validTimeFrame and show_psylabel)
r_label(psy_low, psy_lo_label, label.style_none, psycolL, validTimeFrame and show_psylabel)
showallPsy //just here to trick if-else into working
else
if show_psylevels
draw_linelabel_gmt_custSession(psy_high, 'D', sessionPsyX, psy_hi_label, psycolH, line.style_solid, 1, extend.none, show_psylabel and show_psylevels, label_x_offset, gmt)
draw_linelabel_gmt_custSession(psy_low, 'D', sessionPsyX, psy_lo_label, psycolL, line.style_solid, 1, extend.none, show_psylabel and show_psylevels, label_x_offset, gmt)
showallPsy //just here to trick if-else into working
float psy_high = na
float psy_low = na
if psyType == 'crypto'
if sess_dst_onPsy
[psy_highX, psy_lowX, psy_hi_label, psy_lo_label] = calc_psy_hilo("GMT+1", cryptoCalcSession)
psy_high := psy_highX
psy_low := psy_lowX
draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label, cryptoCalcSession, "GMT+1")
else
[psy_highX, psy_lowX, psy_hi_label, psy_lo_label] = calc_psy_hilo("GMT+0", cryptoCalcSession)
psy_high := psy_highX
psy_low := psy_lowX
draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label,cryptoCalcSession,"GMT+0")
else
[psy_highX, psy_lowX, psy_hi_label, psy_lo_label] = calc_psy_hilo("GMT+0",forexCalcSession)
psy_high := psy_highX
psy_low := psy_lowX
draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label,forexCalcSession,"GMT+0")
plot(showPsy and show_psylevels and showallPsy ? psy_high : na, color=psycolH, style=plot.style_stepline, linewidth=2, editable=false, title="Psy-Hi") //, offset=psy_plot_offset)
plot(showPsy and show_psylevels and showallPsy ? psy_low : na, color=psycolL, style=plot.style_stepline, linewidth=2, editable=false, title="Psy-Lo") //, offset=psy_plot_offset)
//London DST Starts Last Sunday of March DST Edns Last Sunday of October
//New York DST Starts 2nd Sunday of March DST Edns 1st Sunday of November
//Sydney DST Start on 1st Sunday of October DST ends 1st Sunday of Arpil
//Frankfurt DST Starts Last Sunday of March DST Edns Last Sunday of October
if barstate.islast and showDstTable
var table dstTable = table.new(choiceDstTable, 2, 8, bgcolor=dstTableBgColor)
//general
table.cell(dstTable, 0, 0, 'London DST Starts Last Sunday of March | DST Edns Last Sunday of October', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 1, 'New York DST Starts 2nd Sunday of March | DST Edns 1st Sunday of November', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 2, 'Tokio does not observe DST', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 3, 'Hong Kong does not observe DST', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 4, 'Sydney DST Start on 1st Sunday of October | DST ends 1st Sunday of Arpil', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 5, 'EU Brinks DST Starts Last Sunday of March | DST Edns Last Sunday of October', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 6, 'US Brinks DST Starts 2nd Sunday of March | DST Edns 1st Sunday of November', text_color=adrTableTxtColor)
table.cell(dstTable, 0, 7, 'Frankfurt DST Starts Last Sunday of March | DST Edns Last Sunday of October', text_color=adrTableTxtColor) |
INEVITRADE Pro + | https://www.tradingview.com/script/4EZaPSEb-INEVITRADE-Pro/ | youngnfree4life | https://www.tradingview.com/u/youngnfree4life/ | 232 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© jojou
//@version=5
// RSI+ Open source
indicator(title="INEVITRADE Pro +", shorttitle="INEVITRADE Pro +", format=format.price, precision=1)
ma(source, length, type) =>
switch type
"EMA" => ta.ema(source, length)
// βββββ Inputs
rsiLengthInput = input.int(14, minval=1, title="RSI Length")
rsiSourceInput = input.source(close, "Source")
rsiC1Input = input.color(#64ffda, title="Color 1")
rsiC2Input = input.color(#F43E32, title="Color 2")
rsiBandColorInput = input.color(color.rgb(230, 230, 230, 90), title="RSI Band Color")
showBand = input(true, title="Highlight RSI Overbought/Oversold")
showCloud = input(true, title="Show RSI Cloud")
showFlagCloudFlip = input(false, title="Flag Cloud Flip")
rsiExtendedUpperBand = input.int(75, minval=1, title="Extended Upper Band")
rsiUpperBand = input.int(70, minval=1, title="Upper Band")
rsiLowerBand = input.int(30, minval=1, title="Lower Band")
rsiExtendedLowerBand = input.int(25, minval=1, title="Extended Lower Band")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = ((down == 0) ? 100 : up == 0) ? 0 : 100 - (100 / (1 + up / down))
rsiEMA = ma(rsi, rsiLengthInput, "EMA")
previousRSI = rsi[1]
previousRSIEMA = rsiEMA[1]
// RSI Colours
rsiColour = rsi >= rsiEMA ? rsiC1Input : rsiC2Input
flagColour = (rsi > rsiEMA and previousRSI < previousRSIEMA) ? rsiC1Input : (rsi < rsiEMA and previousRSI > previousRSIEMA ? rsiC2Input : na)
// RSI Plots
rsiPlot = plot(rsi, title="RSI", color=rsiColour)
rsiEMAPlot = plot(showCloud ? rsiEMA : na, title="RSI EMA", editable=false, display=display.none)
// RSI Flag Cloud Flip
flagCloudFlip = (rsi > rsiEMA and previousRSI < previousRSIEMA) ? rsiEMA : (rsi < rsiEMA and previousRSI > previousRSIEMA ? rsiEMA : na)
plot(showFlagCloudFlip ? flagCloudFlip : na, title="Flag Cloud Flip", color=color.new(flagColour, 20), linewidth=3, style=plot.style_circles, editable=false)
// RSI Highlights
bgcolor(rsi >= rsiUpperBand ? color.new(rsiC1Input, 90) : na, title="Overbought Highlight")
bgcolor(rsi >= rsiExtendedUpperBand ? color.new(rsiC1Input, 90) : na, title="Extended Overbought Highlight")
bgcolor(rsi <= rsiLowerBand ? color.new(#F43E32, 85) : na, title="Oversold Highlight")
bgcolor(rsi <= rsiExtendedLowerBand ? color.new(#F43E32, 85) : na, title="Extended Oversold Highlight")
// RSI EMA Cloud
fill(rsiPlot, rsiEMAPlot, color=color.new(rsiColour, 70), title="RSI Cloud")
// RSI Baseline
hline(50, "Baseline", color=color.new(#787B86, 50), linestyle=hline.style_solid)
// RSI Overbought & Oversold
fill(hline(showBand ? rsiUpperBand : na, editable=false, display=display.none), hline(showBand ? rsiExtendedUpperBand : na, editable=false, display=display.none), color=rsiBandColorInput, title="Overbought Fill")
fill(hline(showBand ? rsiLowerBand : na, editable=false, display=display.none), hline(showBand ? rsiExtendedLowerBand : na, editable=false, display=display.none), color=rsiBandColorInput, title="Oversold Fill")
// Strength vs BTC
btc = input.symbol("BYBIT:BTCUSDT", title = "Compare To", group="Strength vs BTC Settings")
period = input("5", title = "timeframe")
candleAmount = input(100,title = "Number Of Candles to Include in Avg." )
upColor = input(color.green, title = "Up Color")
downColor = input(color.red, title = "Down Color")
float candleSum = 0
float candleAvg = 0
float btcCandleSum = 0
float btcCandleAvg = 0
float lowCandleSum = 0
float lowCandleAvg = 0
float lowBtcCandleSum = 0
float lowBtcCandleAvg = 0
thisHigh = request.security(syminfo.tickerid, period, high)
btcHigh = request.security(btc, period, high)
btcLow = request.security(btc, period, low)
ticker = syminfo.tickerid
// get ticker
getPair(_str, _n) =>
string[] _pair = str.split(_str, ":")
string[] _chars = str.split(array.get(_pair, 1), "")
int _len = array.size(_chars)
int _end = math.min(_len, math.max(0, _n))
string[] _substr = array.new_string(0)
if _end <= _len
_substr := array.slice(_chars, 0, _end)
string _return = array.join(_substr, "")
// normalize series within range
normalize(_src, _min, _max) =>
// Normalizes series with unknown min/max using historical min/max.
// _src : series to rescale.
// _min, _min: min/max values of rescaled series.
var _historicMin = 10e10
var _historicMax = -10e10
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10)
for i=1 to candleAmount
candleSum:= candleSum + thisHigh[i]
btcCandleSum:= btcCandleSum + btcHigh[i]
if i == candleAmount
candleAvg:= candleSum / candleAmount
btcCandleAvg:= btcCandleSum / candleAmount
pairPCT = (thisHigh - candleAvg) / thisHigh
btcPCT = (btcHigh - btcCandleAvg) / btcHigh
plotColor = color.white
multiplier = str.tonumber(period)
plotPCT = ((multiplier * pairPCT - multiplier * btcPCT) * 100 + 135)
if plotPCT < 135
plotColor := downColor
if plotPCT > 135
plotColor := upColor
if getPair(ticker, 3) == "BTC"
plotColor:=color(na)
// plot(135, color=color.gray)
plot(normalize(plotPCT, 90, 180), "Normalized Strength vs BTC", color=plotColor)
hline(180)
hline(90)
|
BTC Miner Netflows with smoothing | https://www.tradingview.com/script/rsSU5cpK-BTC-Miner-Netflows-with-smoothing/ | Powerscooter | https://www.tradingview.com/u/Powerscooter/ | 44 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Powerscooter
// Since IntoTheBlock only provides daily Inflow and Outflow data, this chart might look chunky on lower timeframes, even with smoothing.
//@version=5
indicator("BTC Miner Netflows")
smoothing = input.string(title="Smoothing", defval="SMA", options=["SMA", "RMA", "EMA", "WMA"], group="Netflow Settings")
ma_function(source, length) =>
switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
SmoothLength = input(21, 'MA Length', group="Netflow Settings")
//Plotting
Netflows = request.security("INTOTHEBLOCK:BTC_MINERNETFLOWS", "D", close)
SmoothFlow = ma_function(Netflows, SmoothLength)
Netflow = plot(SmoothFlow, "Exchange Inflows", color.white, transp = 10)
ZeroLine = plot(0, "Zero Line", color=color.white, transp = 60) //We need this because the fill() function only takes plot, not int.
fill(plot1=Netflow, plot2=ZeroLine, color=SmoothFlow > 0 ? color.new(color.green, 60) : color.new(color.red, 60)) |
The Hummingbird - MA Ribbon by Joe (EMA, SMA, SMMA, WMA, VWMA) | https://www.tradingview.com/script/1WCNHb93-The-Hummingbird-MA-Ribbon-by-Joe-EMA-SMA-SMMA-WMA-VWMA/ | crypto-with-joe | https://www.tradingview.com/u/crypto-with-joe/ | 71 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© 2022 crypto-with-joe
// @version=5
indicator("The Hummingbird - MA Ribbon by Joe", shorttitle = "The Hummingbird v1.0", explicit_plot_zorder = true, overlay = true)
// Build Moving Average Types
ma(source, length, type) =>
type == "EMA" ? ta.ema(source, length) :
type == "SMA" ? ta.sma(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
na
// OPTIONS
// ====================
// Moving Averages
// --------------------
ma01_type = input.string("EMA", "MA 01", inline = "MA01", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma01_source = input(close, "Source", inline = "MA01", group = "====== Moving Averages ======")
ma01_length = input.int(5, "Length", inline = "MA01", group = "====== Moving Averages ======", minval = 1)
ma01 = ma(ma01_source, ma01_length, ma01_type)
ma02_type = input.string("EMA", "MA 02", inline = "MA02", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma02_source = input(close, "Source", inline = "MA02", group = "====== Moving Averages ======")
ma02_length = input.int(10, "Length", inline = "MA02", group = "====== Moving Averages ======", minval = 1)
ma02 = ma(ma02_source, ma02_length, ma02_type)
ma03_type = input.string("EMA", "MA 03", inline = "MA03", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma03_source = input(close, "Source", inline = "MA03", group = "====== Moving Averages ======")
ma03_length = input.int(15, "Length", inline = "MA03", group = "====== Moving Averages ======", minval = 1)
ma03 = ma(ma03_source, ma03_length, ma03_type)
ma04_type = input.string("EMA", "MA 04", inline = "MA04", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma04_source = input(close, "Source", inline = "MA04", group = "====== Moving Averages ======")
ma04_length = input.int(20, "Length", inline = "MA04", group = "====== Moving Averages ======", minval = 1)
ma04 = ma(ma04_source, ma04_length, ma04_type)
ma05_type = input.string("EMA", "MA 05", inline = "MA05", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma05_source = input(close, "Source", inline = "MA05", group = "====== Moving Averages ======")
ma05_length = input.int(25, "Length", inline = "MA05", group = "====== Moving Averages ======", minval = 1)
ma05 = ma(ma05_source, ma05_length, ma05_type)
ma06_type = input.string("EMA", "MA 06", inline = "MA06", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma06_source = input(close, "Source", inline = "MA06", group = "====== Moving Averages ======")
ma06_length = input.int(30, "Length", inline = "MA06", group = "====== Moving Averages ======", minval = 1)
ma06 = ma(ma06_source, ma06_length, ma06_type)
ma07_type = input.string("EMA", "MA 07", inline = "MA07", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma07_source = input(close, "Source", inline = "MA07", group = "====== Moving Averages ======")
ma07_length = input.int(35, "Length", inline = "MA07", group = "====== Moving Averages ======", minval = 1)
ma07 = ma(ma07_source, ma07_length, ma07_type)
ma08_type = input.string("EMA", "MA 08", inline = "MA08", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma08_source = input(close, "Source", inline = "MA08", group = "====== Moving Averages ======")
ma08_length = input.int(40, "Length", inline = "MA08", group = "====== Moving Averages ======", minval = 1)
ma08 = ma(ma08_source, ma08_length, ma08_type)
ma09_type = input.string("EMA", "MA 09", inline = "MA09", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma09_source = input(close, "Source", inline = "MA09", group = "====== Moving Averages ======")
ma09_length = input.int(45, "Length", inline = "MA09", group = "====== Moving Averages ======", minval = 1)
ma09 = ma(ma09_source, ma09_length, ma09_type)
ma10_type = input.string("EMA", "MA 10", inline = "MA10", group = "====== Moving Averages ======", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma10_source = input(close, "Source", inline = "MA10", group = "====== Moving Averages ======")
ma10_length = input.int(50, "Length", inline = "MA10", group = "====== Moving Averages ======", minval = 1)
ma10 = ma(ma10_source, ma10_length, ma10_type)
ma100_type = input.string("EMA", "100 MA", inline = "100 MA", group = "Fixed Moving Averages", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma100 = ma(close, 100, ma100_type)
ma200_type = input.string("EMA", "200 MA", inline = "200 MA", group = "Fixed Moving Averages", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma200 = ma(close, 200, ma200_type)
ma200htf_type = input.string("EMA", "200 MA HTF", inline = "200 MA HTF", group = "Fixed Moving Averages", options = ["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"])
ma200htf_tf = input.timeframe(defval = "60", title="Timeframe", inline = "200 MA HTF", group = "Fixed Moving Averages")
ma200htf = ma(close, 200, ma200_type)
ma200htf_smoothstep = input.bool(false, title="Smooth", inline = "200 MA HTF")
ma200htf_smooth = request.security(syminfo.tickerid, ma200htf_tf, ma200htf, barmerge.gaps_on, barmerge.lookahead_off)
ma200htf_step = request.security(syminfo.tickerid, ma200htf_tf, ma200htf, barmerge.gaps_off, barmerge.lookahead_off)
// Plots
// ================
// Plot MA's
plot(ma01, color = color.aqua, title = "MA 01", linewidth = 1, editable = true)
plot(ma02, color = color.blue, title = "MA 02", linewidth = 1, editable = true)
plot(ma03, color = color.teal, title = "MA 03", linewidth = 1, editable = true)
plot(ma04, color = color.green, title = "MA 04", linewidth = 1, editable = true)
plot(ma05, color = color.lime, title = "MA 05", linewidth = 1, editable = true)
plot(ma06, color = color.yellow, title = "MA 06", linewidth = 1, editable = true)
plot(ma07, color = color.orange, title = "MA 07", linewidth = 1, editable = true)
plot(ma08, color = color.purple, title = "MA 08", linewidth = 1, editable = true)
plot(ma09, color = color.fuchsia, title = "MA 09", linewidth = 1, editable = true)
plot(ma10, color = color.red, title = "MA 10", linewidth = 1, editable = true)
plot(ma100, color = #b2b5be, title = "100 MA", linewidth = 2, editable = true)
plot(ma200, color = #ffffff, title = "200 MA", linewidth = 3, editable = true)
plot(ma200, color = #ff1c15, title = "200 MA (2nd)", linewidth = 1, style = plot.style_line, editable = true)
plot(ma200htf_smoothstep ? ma200htf_smooth : ma200htf_step, color = #ff1c15, title = "200 MA HTF", linewidth = 3, editable = true)
plot(ma200htf_smoothstep ? ma200htf_smooth : ma200htf_step, color = #ffffff, title = "200 MA HTF (2nd)", linewidth = 1, style = plot.style_line, editable = true)
|
The Killer Whale - Multiple Keltner Channels by Joe | https://www.tradingview.com/script/LNcBkSRw-The-Killer-Whale-Multiple-Keltner-Channels-by-Joe/ | crypto-with-joe | https://www.tradingview.com/u/crypto-with-joe/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© 2022 crypto-with-joe
//@version=5
indicator(title="The Killer Whale - Multiple Keltner Channels by Joe", shorttitle="The Killer Whale v1.0", overlay=true, timeframe="", timeframe_gaps=true)
// Keltner Channel Settings
kw_kelt_length = input.int(20, "Length", minval=1)
kw_kelt_src = input(close, "Source")
kw_kelt_mult1 = input.float(1.0, "Channel 1 Multiplier")
kw_kelt_mult2 = input.float(2.0, "Channel 2 Multiplier")
kw_kelt_mult3 = input.float(3.0, "Channel 3 Multiplier")
kw_kelt_mult4 = input.float(4.0, "Channel 4 Multiplier")
kw_kelt_exp = input.bool(true, "Use Exponential MA")
kw_kelt_bands_style = input.string("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style")
kw_atr_length = input.int(20, "ATR Length", tooltip = "Typically, when the Keltner Length is 20, the ATR length is either 10 or 20.")
// Style Settings
kw_kelt_1_show = input.bool(true, "Show Channel 1", group = "Channel Styles")
kw_kelt_upper1_color = input.color(#ffffff50, "Channel 1 Colors - Upper", group = "Channel Styles", inline = "Channel 1a")
kw_kelt_lower1_color = input.color(#ffffff50, "Lower", group = "Channel Styles", inline = "Channel 1a")
kw_kelt_bg1_color = input.color(#ffffff20, "Background", group = "Channel Styles", inline = "Channel 1b")
kw_kelt_2_show = input.bool(true, "Show Channel 2", group = "Channel Styles")
kw_kelt_upper2_color = input.color(#ffdf0050, "Channel 2 Colors - Upper", group = "Channel Styles", inline = "Channel 2a")
kw_kelt_lower2_color = input.color(#ffdf0050, "Lower", group = "Channel Styles", inline = "Channel 2a")
kw_kelt_bgu2_color = input.color(#ffdf0020, "Upper Background", group = "Channel Styles", inline = "Channel 2b")
kw_kelt_bgl2_color = input.color(#ffdf0020, "Lower Background", group = "Channel Styles", inline = "Channel 2b")
kw_kelt_3_show = input.bool(true, "Show Channel 3", group = "Channel Styles")
kw_kelt_upper3_color = input.color(#2962ff50, "Channel 3 Colors - Upper", group = "Channel Styles", inline = "Channel 3a")
kw_kelt_lower3_color = input.color(#2962ff50, "Lower", group = "Channel Styles", inline = "Channel 3a")
kw_kelt_bgu3_color = input.color(#2962ff20, "Upper Background", group = "Channel Styles", inline = "Channel 3b")
kw_kelt_bgl3_color = input.color(#2962ff20, "Upper Background", group = "Channel Styles", inline = "Channel 3b")
kw_kelt_4_show = input.bool(true, "Show Channel 4", group = "Channel Styles")
kw_kelt_upper4_color = input.color(#ff525250, "Channel 4 Colors - Upper", group = "Channel Styles", inline = "Channel 4a")
kw_kelt_lower4_color = input.color(#ff525250, "Lower", group = "Channel Styles", inline = "Channel 4a")
kw_kelt_bgu4_color = input.color(#ff525220, "Upper Background", group = "Channel Styles", inline = "Channel 4b")
kw_kelt_bgl4_color = input.color(#ff525220, "Upper Background", group = "Channel Styles", inline = "Channel 4b")
// Variables
kw_kelt_1_display = kw_kelt_1_show == true ? display.all : display.none
kw_kelt_2_display = kw_kelt_2_show == true ? display.all : display.none
kw_kelt_3_display = kw_kelt_3_show == true ? display.all : display.none
kw_kelt_4_display = kw_kelt_4_show == true ? display.all : display.none
esma(kw_kelt_src, kw_kelt_length)=>
s = ta.sma(kw_kelt_src, kw_kelt_length)
e = ta.ema(kw_kelt_src, kw_kelt_length)
kw_kelt_exp ? e : s
kw_ma = esma(kw_kelt_src, kw_kelt_length)
kw_range_ma = kw_kelt_bands_style == "True Range" ? ta.tr(true) : kw_kelt_bands_style == "Average True Range" ? ta.atr(kw_atr_length) : ta.rma(high - low, kw_kelt_length)
kw_kelt_upper1 = kw_ma + kw_range_ma * kw_kelt_mult1
kw_kelt_lower1 = kw_ma - kw_range_ma * kw_kelt_mult1
kw_kelt_upper2 = kw_ma + kw_range_ma * kw_kelt_mult2
kw_kelt_lower2 = kw_ma - kw_range_ma * kw_kelt_mult2
kw_kelt_upper3 = kw_ma + kw_range_ma * kw_kelt_mult3
kw_kelt_lower3 = kw_ma - kw_range_ma * kw_kelt_mult3
kw_kelt_upper4 = kw_ma + kw_range_ma * kw_kelt_mult4
kw_kelt_lower4 = kw_ma - kw_range_ma * kw_kelt_mult4
// Plots
kw_kelt_u1 = plot(kw_kelt_upper1, color = kw_kelt_upper1_color, title = "Keltner 1 Upper", display = kw_kelt_1_display, editable = false)
kw_kelt_l1 = plot(kw_kelt_lower1, color = kw_kelt_lower1_color, title = "Keltner 1 Lower", display = kw_kelt_1_display, editable = false)
kw_kelt_u2 = plot(kw_kelt_upper2, color = kw_kelt_upper2_color, title = "Keltner 2 Upper", display = kw_kelt_2_display, editable = false)
kw_kelt_l2 = plot(kw_kelt_lower2, color = kw_kelt_lower2_color, title = "Keltner 2 Lower", display = kw_kelt_2_display, editable = false)
kw_kelt_u3 = plot(kw_kelt_upper3, color = kw_kelt_upper3_color, title = "Keltner 3 Upper", display = kw_kelt_3_display, editable = false)
kw_kelt_l3 = plot(kw_kelt_lower3, color = kw_kelt_lower3_color, title = "Keltner 3 Lower", display = kw_kelt_3_display, editable = false)
kw_kelt_u4 = plot(kw_kelt_upper4, color = kw_kelt_upper4_color, title = "Keltner 4 Upper", display = kw_kelt_4_display, editable = false)
kw_kelt_l4 = plot(kw_kelt_lower4, color = kw_kelt_lower4_color, title = "Keltner 4 Lower", display = kw_kelt_4_display, editable = false)
fill(kw_kelt_u1, kw_kelt_l1, color = kw_kelt_bg1_color, title = "Channel 1 Background", display = kw_kelt_1_display, editable = false)
fill(kw_kelt_u2, kw_kelt_u1, color = kw_kelt_bgu2_color, title = "Channel 2 Upper Background", display = kw_kelt_2_display, editable = false)
fill(kw_kelt_l1, kw_kelt_l2, color = kw_kelt_bgl2_color, title = "Channel 2 Lower Background", display = kw_kelt_2_display, editable = false)
fill(kw_kelt_u3, kw_kelt_u2, color = kw_kelt_bgu3_color, title = "Channel 3 Upper Background", display = kw_kelt_3_display, editable = false)
fill(kw_kelt_l2, kw_kelt_l3, color = kw_kelt_bgl3_color, title = "Channel 3 Lower Background", display = kw_kelt_3_display, editable = false)
fill(kw_kelt_u4, kw_kelt_u3, color = kw_kelt_bgu4_color, title = "Channel 4 Upper Background", display = kw_kelt_4_display, editable = false)
fill(kw_kelt_l3, kw_kelt_l4, color = kw_kelt_bgl4_color, title = "Channel 4 Lower Background", display = kw_kelt_4_display, editable = false)
plot(kw_ma, style = plot.style_line, linewidth = 1, color = #ffffffff, title = "Basis")
|
Exchange sessions | https://www.tradingview.com/script/nuYy7JCy-exchange-sessions/ | Shuttle_Trader | https://www.tradingview.com/u/Shuttle_Trader/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// Β© Shuttle_Trader
indicator('Exchange sessions', overlay=true)
// To align the description of input parameters, i use - Unicode Em Space = 'β', Unicode Thin Space = 'β' and Space = 'β'
showSS = input.bool(false,' Sydney β βββ', inline='ss', group='>> EXCHANGE << TIME SESSIONS')
showAS = input.bool(true, ' Asia β β βββ', inline='as', group='>> EXCHANGE << TIME SESSIONS')
showLS = input.bool(false,' London β β', inline='ls', group='>> EXCHANGE << TIME SESSIONS')
showNS = input.bool(true, ' NewYorkβββ', inline='ns', group='>> EXCHANGE << TIME SESSIONS')
sess_SS = input.session('0800-1700:23456', '', inline='ss', group='>> EXCHANGE << TIME SESSIONS')
sess_AS = input.session('0800-1700:23456', '', inline='as', group='>> EXCHANGE << TIME SESSIONS')
sess_LS = input.session('0900-1800:23456', '', inline='ls', group='>> EXCHANGE << TIME SESSIONS')
sess_NS = input.session('0900-1700:23456', '', inline='ns', group='>> EXCHANGE << TIME SESSIONS')
colorSS = input.color(color.new(color.green,80), '', inline='ss', group='>> EXCHANGE << TIME SESSIONS')
colorAS = input.color(color.new(color.orange,80),'', inline='as', group='>> EXCHANGE << TIME SESSIONS')
colorLS = input.color(color.new(color.blue,80), '', inline='ls', group='>> EXCHANGE << TIME SESSIONS')
colorNS = input.color(color.new(color.red,80), '', inline='ns', group='>> EXCHANGE << TIME SESSIONS')
showSSopen = input.bool(false, ' Start', inline='ss', group='>> EXCHANGE << TIME SESSIONS')
showASopen = input.bool(false, ' Start', inline='as', group='>> EXCHANGE << TIME SESSIONS')
showLSopen = input.bool(false, ' Start', inline='ls', group='>> EXCHANGE << TIME SESSIONS')
showNSopen = input.bool(false, ' Start', inline='ns', group='>> EXCHANGE << TIME SESSIONS')
// To link the given session time to the time zone, I use the name of the time zone from the IANA time zone database.
ss = time(timeframe.period, sess_SS, 'Australia/Sydney')
asia = time(timeframe.period, sess_AS, 'Asia/Hong_Kong')
ls = time(timeframe.period, sess_LS, 'Europe/London')
ns = time(timeframe.period, sess_NS, 'America/New_York')
SS = na(ss) ? na : colorSS
Asia = na(asia) ? na : colorAS
LS = na(ls) ? na : colorLS
NY = na(ns) ? na : colorNS
bgcolor(showSS and timeframe.isintraday ? SS : na, title='Sydney')
bgcolor(showAS and timeframe.isintraday ? Asia : na, title='Asia')
bgcolor(showLS and timeframe.isintraday ? LS : na, title='London')
bgcolor(showNS and timeframe.isintraday ? NY : na, title='New York')
SSstart = na(ss)[1] and ss
bgcolor(color = showSSopen and SSstart and timeframe.isintraday ? color.new(color.yellow,40) : na, title='Show start Sydney session')
ASstart = na(asia)[1] and asia
bgcolor(color = showASopen and ASstart and timeframe.isintraday ? color.new(color.yellow,40) : na, title='Show start Asia session')
LSstart = na(ls)[1] and ls
bgcolor(color = showLSopen and LSstart and timeframe.isintraday ? color.new(color.yellow,40) : na, title='Show start London session')
NSstart = na(ns)[1] and ns
bgcolor(color = showNSopen and NSstart and timeframe.isintraday ? color.new(color.yellow,40) : na, title='Show start New-York session')
|
Intraday Range Calculator | https://www.tradingview.com/script/BDNLoMt8-Intraday-Range-Calculator/ | seba34e | https://www.tradingview.com/u/seba34e/ | 91 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© seba34e
//@version=5
indicator("Intraday Range Calculator", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500)
deviation = input.float(1.70, title="Deviation [%]", step=0.1)
beginTime = input.int(1030, title="Begin Time [24-hour clock]", step=5, minval=0, maxval=2359)
endTime = input.int(1600, title="End Time [24-hour clock]" , step=5, minval=0, maxval=2359)
addTime = input.bool(true, title = "Add Date and Time")
addChanges= input.bool(true, title = "Add Range Changes")
tablePosition = input.string(title = 'Table Position', defval="Top right", options = ["Top right", "Top left", "Bottom right", "Bottom left"], tooltip='Position of the table')
var PositiveChange = 0
var NegativeChange = 0
var ChangeSum = 0.0
var PercentageDiff=0.0
var PriceTimeTest=0.0
var TimeCloseDay=0.0
var TotalBars=0
var TrueBars=0
var x1=0
var y1=0.0
var x2=0
var y2=0.0
var upperband = 999999999.9
var lowerband = -999999999.9
var yy1 = 0.0
beginTime2 = str.tostring(beginTime,"0000") + "-" + str.tostring(beginTime+1,"0000")
endTime2 = str.tostring(endTime,"0000") + "-" + str.tostring(endTime+1,"0000")
if time("5", beginTime2)
PriceTimeTest := open
x1 := bar_index
y1 := PriceTimeTest + PriceTimeTest * deviation / 100
// Detectar el punto mas cercano a multiplo de 5 del open en el rango
yy1 := PriceTimeTest % 5
if yy1 > 2.5
PriceTimeTest := PriceTimeTest + (5-yy1)
else
PriceTimeTest := PriceTimeTest - yy1
upperband := PriceTimeTest + PriceTimeTest * deviation / 100
lowerband := PriceTimeTest - PriceTimeTest * deviation / 100
TotalBars := TotalBars + 1
if math.abs(PercentageDiff) > deviation
TrueBars := TrueBars + 1
if ta.crossover(high, upperband)
label.new(bar_index,upperband, style = label.style_circle, color = color.yellow, size=size.tiny)
if ta.crossunder(low, lowerband)
label.new(bar_index, lowerband, style = label.style_circle, color = color.yellow, size=size.tiny)
if time("5", endTime2)
TimeCloseDay := open
PercentageDiff := (1-(PriceTimeTest/TimeCloseDay)) * 100
x2 := bar_index
y2 := PriceTimeTest - PriceTimeTest * deviation / 100
//dibuja el rectangulo
box.new(x1,y1,x2,y2,border_color = math.abs(PercentageDiff) >= deviation ? color.red : color.green ,bgcolor = na, text = addTime == true ? str.format("{0,date,M/d/YYYY}", time) + "\n" + str.tostring(beginTime) + " To " + str.tostring(endTime) : na, text_size = size.normal, text_color = color.white, text_halign = text.align_left, text_valign = text.align_top)
upperband := 999999999.9
lowerband := -999999999.9
if addChanges==true
labelDiff=label.new(bar_index,y1, str.tostring(1-(open[x2-x1]/close),"0.00%"), color= (open[x2-x1] < close) ? color.green:color.red, textcolor=color.white)
ChangeSum := ChangeSum + math.abs(1-(close[x2-x1]/close))
if (close[x2-x1] < close)
PositiveChange := PositiveChange + 1
else
NegativeChange := NegativeChange + 1
//line.new(x1,y2,x2,y2+(y2*0.005), style = line.style_dashed, color=color.blue)
//line.new(x1,y1,x2,y1-(y1*0.005), style = line.style_dashed, color=color.blue)
line.new(x1, PriceTimeTest, x2, PriceTimeTest, style = line.style_dashed, color=color.white)
//label.new (x1,y1, text= str.format("{0,date,M-d-YYYY}", time) + "\n" + str.tostring(beginTime) + " To " + str.tostring(endTime), color=na, textcolor = color.yellow , textalign = text.align_right )
var table TheTable = table.new(tablePosition == "Top right" ? position.top_right : tablePosition == "Top left" ? position.top_left : tablePosition == "Bottom right" ? position.bottom_right : position.bottom_left, 2, 8, border_width=2)
fill_Cell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + '' + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_halign=text.align_right)
//Prepare cells
if barstate.islast
fill_Cell(TheTable, 0, 0, "", 'Range Time:' , color.blue, color.yellow)
fill_Cell(TheTable, 1, 0, str.tostring(beginTime) + " To " + str.tostring(endTime), " ", color.blue, color.yellow)
fill_Cell(TheTable, 0, 1, "", 'Deviation:' , color.black, color.yellow)
fill_Cell(TheTable, 1, 1, "", str.tostring(deviation,"0.00") + "%" , color.black, color.yellow)
fill_Cell(TheTable, 0, 2, "", 'Total Days:' , color.blue, color.yellow)
fill_Cell(TheTable, 1, 2, "", str.tostring(TotalBars) , color.blue, color.yellow)
fill_Cell(TheTable, 0, 3, "", 'Out of Range Days:' , color.black, color.yellow)
fill_Cell(TheTable, 1, 3, "", str.tostring(TrueBars) , color.black, color.yellow)
fill_Cell(TheTable, 0, 4, "", 'Percentage:' , color.blue, color.yellow)
fill_Cell(TheTable, 1, 4, "", str.tostring(TrueBars/TotalBars, "0.00%") , color.blue, color.yellow)
fill_Cell(TheTable, 0, 5, "", 'Change Average:' , color.black, color.yellow)
fill_Cell(TheTable, 1, 5, "", str.tostring(ChangeSum/TotalBars,"0.00%") , color.black, color.yellow)
fill_Cell(TheTable, 0, 6, "", 'Positive Changes:' , color.green, color.white)
fill_Cell(TheTable, 1, 6, "", str.tostring(PositiveChange) , color.green, color.white)
fill_Cell(TheTable, 0, 7, "", 'Negative Changes:' , color.red, color.white)
fill_Cell(TheTable, 1, 7, "", str.tostring(NegativeChange) , color.red, color.white) |
Ultimate Oscillator + Realtime Divergences | https://www.tradingview.com/script/0x3VlXKj-Ultimate-Oscillator-Realtime-Divergences/ | tvenn | https://www.tradingview.com/u/tvenn/ | 153 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© tvenn
//@version=5
indicator("Ultimate Oscillator + Realtime Divergences", shorttitle="UO+", overlay=false, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400, precision=3)
pulldatafromtimeframe = input.string("Chart", title="Select alternate timeframe in mins", options=["Chart", "1", "2", "3", "4", "5", "10", "15", "30", "45", "60", "120", "240"])
green = color.new(#95BD5F, 30)
red = color.new(#EA1889, 30)
transp = color.new(#FFFFFF, 100)
haTicker = ticker.heikinashi(syminfo.tickerid)
[haO, haH, haL, haC] = request.security(haTicker, timeframe.period, [open, high, low, close])
//Divergence Settings
grp_DIVS = "Divergence Settings"
showlines = input(defval = true, title = "Show Divergence Lines", group=grp_DIVS)
showlast = input(defval = true, title = "Show Only Last Divergence", group=grp_DIVS)
dontconfirm = input(defval = true, title = "Don't Wait for Confirmation", group=grp_DIVS)
searchdiv = input.string(defval = "Regular/Hidden", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group=grp_DIVS)
//Detail
grp_Detail = "Details"
showCenterBand = input(true, title="Centerline", group=grp_Detail, inline="0", tooltip="To add a solid centerline that stays behind the oscillator, simply adjust the color of the 'Alt centerline' within the styles section below and disable this centerline")
showBands = input(false, title="Range bands", group=grp_Detail, inline="1", tooltip="The color and style of the range bands can be further customised in the 'Style' tab of this settings menu.")
convertToHAbands = input(false, title="Heikin Ashi range band levels", group=grp_Detail, inline="1", tooltip="This will adjust the overbought and oversold levels to 35 and 65.\n\nIf you are working on a Heikin Ashi chart, select this option and it will increase the height of the oscillator in the panel.")
fadeOutOsc = input(false, title="Fade out oscillator", group=grp_Detail, tooltip="Fade out the oscillator leaving only the most recent periods prominent for a clearer chart.")
flipOsc = input.bool(false, title="Flip Oscillator", group=grp_Detail, tooltip="This will flip the oscillator upside down. The purpose is for use with the flip chart feature of Tradingview (Alt+i), which does not also flip the oscillator. This may help those with a particular long/short bias to see the other side of things. Divergence lines will not be drawn.")
grp_COND = "Conditional styles"
backgroundColor = input(color.new(color.white, 97), title = "", group=grp_COND, inline='clc')
showBackground = input(false, title="Background", group=grp_COND, inline='clc')
obosHighlightColor = input(color.new(red, 0), title = "", group=grp_COND, inline='obos')
obosHighlightEnabled= input.bool(false, title="Highlight overbought & oversold levels", group=grp_COND, inline="obos")
centerlineXBgColor = input(color.new(red, 90), title='', group=grp_COND, inline='clc1')
backgroundSignalOn = input(false, title="Centerline crossunder background color", group=grp_COND, tooltip="This will colour the background according to whether the RSI is above or below the 50 level.", inline='clc1')
centerlineXOscColor = input(color.new(red, 10), title='', group=grp_COND, inline='clc2')
oscSignalOn = input(false, title="Centerline crossunder oscillator color", group=grp_COND, tooltip="This will colour the oscillator according to whether the RSI is above or below the 50 level.", inline='clc2')
convertToHA = input(false, title="Enable Heikin Ashi mode for non HA charts", group="Heikin Ashi mode", tooltip="This will use Heikin Ashi formula Open and Close values. The purpose is for use on standard chart types, in order to produce a smoother less volatile line.\n\nEnabling this setting will also adjust the Range Band overbought and oversold levels to 35 and 65.")
haCheckHigh = convertToHA ? haH : high
haCheckLow = convertToHA ? haL : low
haCheckClose = convertToHA ? haC : close
//UO settings
grp_UOL = "UO settings"
oscLineColor = input.color(color.blue, title="Color", group=grp_UOL)
length1 = input.int(7, minval=1, title = "Fast Length", group=grp_UOL)
length2 = input.int(14, minval=1, title = "Middle Length", group=grp_UOL)
length3 = input.int(28, minval=1, title = "Slow Length", group=grp_UOL)
//Bands
centerlineupper = hline(50.3, color=color.new(#000000, 100), title="Alt centerline", linestyle=hline.style_solid, linewidth=1)
centerlinelower = hline(49.7, color=color.new(#000000, 100), title="Alt centerline", linestyle=hline.style_solid, linewidth=1)
bandHigh = hline(70, color=color.new(color.gray, 30), title="Band level", linestyle=hline.style_dotted, linewidth=1, display=(showBands and not (convertToHAbands or convertToHA) ? display.all : display.none))
bandHighHA = hline(65, color=color.new(color.gray, 30), title="HA Band level", linestyle=hline.style_dotted, linewidth=1, display=((showBands and convertToHAbands) or (showBands and convertToHA) ? display.all : display.none))
bandCenter = hline(50, color=(showCenterBand ? color.gray : color.new(#777777, 100)), title="Centerline", linestyle=hline.style_dotted, linewidth=1)
bandLowHA = hline(35, color=color.new(color.gray, 30), title="HA Band level", linestyle=hline.style_dotted, linewidth=1, display=((showBands and convertToHAbands) or (showBands and convertToHA) ? display.all : display.none))
bandLow = hline(30, color=color.new(color.gray, 30), title="Band level", linestyle=hline.style_dotted, linewidth=1, display=(showBands and not (convertToHAbands or convertToHA) ? display.all : display.none))
//UO calculations
average(bp, tr_, length) => math.sum(bp, length) / math.sum(tr_, length)
high_ = math.max(haCheckHigh, convertToHA ? haC[1] : close[1])
low_ = math.min(haCheckLow, convertToHA ? haC[1] : close[1])
bp = (haCheckClose) - low_
tr_ = high_ - low_
avg7 = average(bp, tr_, length1)
avg14 = average(bp, tr_, length2)
avg28 = average(bp, tr_, length3)
osc = flipOsc ? 100-(100 * (4*avg7 + 2*avg14 + avg28)/7) : (100 * (4*avg7 + 2*avg14 + avg28)/7)
//UO end
//Plot oscillator
distanceTransparency = (bar_index > (last_bar_index - 30) ? 10 : (bar_index > last_bar_index - 60 ? 20 : (bar_index > last_bar_index - 80 ? 30 : (bar_index > last_bar_index - 100 ? 40 : (bar_index > last_bar_index - 120 ? 50 : (bar_index > last_bar_index - 140 ? 60 : (bar_index > last_bar_index - 160 ? 70 : 80)))))))
ultimate_value = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, osc, barmerge.gaps_on)
flippedOsc = (ultimate_value * -1)
oscColorHA = ((obosHighlightEnabled and osc > 65) ? obosHighlightColor : ((obosHighlightEnabled and osc < 35) ? obosHighlightColor : (oscSignalOn and osc > 50 ? oscLineColor : (oscSignalOn and osc < 50 ? centerlineXOscColor : (fadeOutOsc ? color.new(oscLineColor, distanceTransparency) : oscLineColor)))))
oscColor = ((obosHighlightEnabled and osc > 70) ? obosHighlightColor : ((obosHighlightEnabled and osc < 30) ? obosHighlightColor : (oscSignalOn and osc > 50 ? oscLineColor : (oscSignalOn and osc < 50 ? centerlineXOscColor : (fadeOutOsc ? color.new(oscLineColor, distanceTransparency) : oscLineColor)))))
plot(ultimate_value, color=convertToHA ? oscColorHA : oscColor, linewidth=2, title="UO")
//background fill options
fill(bandHighHA, bandLowHA, backgroundSignalOn and ultimate_value > 50 ? na : backgroundSignalOn and ultimate_value < 50 ? centerlineXBgColor : na, title="Centerline crossover colors", editable=1)
fill(bandHighHA, bandLowHA, showBackground and (convertToHA or convertToHAbands) ? backgroundColor : na, title="HA Background", editable=1)
fill(bandHigh, bandLow, showBackground and not (convertToHA or convertToHAbands) ? backgroundColor : na, title="Background", editable=1)
//Pivot settings
grp_PPS = "Pivot Point Settings"
pp = input.int(defval = 12, title = "Pivot period", minval = 1, maxval = 50, group=grp_PPS)
maxpp = input.int(defval = 5, title = "Maximum Pivot periods to check for divs", minval = 1, maxval = 100, group=grp_PPS)
maxbars = input.int(defval = 100, title = "Maximum Bars to Check", minval = 1, maxval = 300, group=grp_PPS)
source = "Close"
prd = pp
//Styles
grp_STY = "Styles"
altCenterLineColor = input.color(color.new(color.orange, 100), title="Alt centerline color", group=grp_STY)
pos_reg_div_col = input(defval = green, title = "Positive Regular Divergence", group=grp_STY)
neg_reg_div_col = input(defval = red, title = "Negative Regular Divergence", group=grp_STY)
pos_hid_div_col = input(defval = green, title = "Positive Hidden Divergence", group=grp_STY)
neg_hid_div_col = input(defval = red, title = "Negative Hidden Divergence", group=grp_STY)
reg_div_l_style_= input.string(defval = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STY)
hid_div_l_style_= input.string(defval = "Dotted", title = "Hdden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STY)
reg_div_l_width = input.int(defval = 2, title = "Regular Divergence Line Width", minval = 1, maxval = 2, group=grp_STY)
hid_div_l_width = input.int(defval = 2, title = "Hidden Divergence Line Width", minval = 1, maxval = 2, group=grp_STY)
fill(centerlineupper, centerlinelower, altCenterLineColor, title="Alt centerline fill", display=display.all, editable=1)
// set line styles
var reg_div_l_style = reg_div_l_style_ == "Solid" ? line.style_solid :
reg_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
var hid_div_l_style = hid_div_l_style_ == "Solid" ? line.style_solid :
hid_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
// get indicators
uo = ultimate_value
// keep indicator colors in arrays
var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(haCheckClose, prd, prd)
float pl = ta.pivotlow(haCheckClose, prd, prd)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// functions to check Regular Divergences and Hidden Divergences
// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond)=>
divlen = 0
prsc = haCheckClose
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or haCheckClose > haCheckClose[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or
(cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (haCheckClose[startpoint] - haCheckClose[len]) / (len - startpoint)
virtual_line2 = haCheckClose[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] < virtual_line1 or nz(haCheckClose[y]) < virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond)=>
divlen = 0
prsc = haCheckClose
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or haCheckClose < haCheckClose[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x))) or
(cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (haCheckClose[startpoint] - nz(haCheckClose[len])) / (len - startpoint)
virtual_line2 = haCheckClose[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] > virtual_line1 or nz(haCheckClose[y]) > virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator)=>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 1) : 0)
array.set(divs, 1, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 1) : 0)
array.set(divs, 2, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 2) : 0)
array.set(divs, 3, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 2) : 0)
divs
// array to keep all divergences
var all_divergences = array.new_int(4) // 1 indicator * 4 divergence = 4 elements
// set related array elements
array_set_divs(div_pointer, index)=>
for x = 0 to 3
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
array_set_divs(calculate_divs(true, uo), 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines()=>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)
delete_old_neg_div_lines()=>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)
delete_old_pos_div_labels()=>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_neg_div_labels()=>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n)=>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n)=>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
// draw divergences lines and labels
divergence_text_top = ""
divergence_text_bottom = ""
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
for x = 0 to 0
div_type = -1
for y = 0 to 3
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if (y % 2) == 1
dnumdiv_top := dnumdiv_top + 1
top_label_col := array.get(div_colors, y)
if (y % 2) == 0
dnumdiv_bottom := dnumdiv_bottom + 1
bottom_label_col := array.get(div_colors, y)
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = (showlines and not flipOsc) ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? uo[array.get(all_divergences, x * 4 + y)] :
(y % 2) == 0 ? haCheckLow[array.get(all_divergences, x * 4 + y)] :
haCheckHigh[array.get(all_divergences, x * 4 + y)]),
x2 = bar_index - startpoint,
y2 = (source == "Close" ? uo[startpoint] :
(y % 2) == 0 ? haCheckLow[startpoint] :
haCheckHigh[startpoint]),
color = array.get(div_colors, y),
style = y < 2 ? reg_div_l_style : hid_div_l_style,
width = y < 2 ? reg_div_l_width : hid_div_l_width
)
: na
if (y % 2) == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
if showlast
delete_old_pos_div_lines()
array.push(pos_div_lines, new_line)
last_pos_div_lines := last_pos_div_lines + 1
remove_last_pos_divs := true
if (y % 2) == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
if showlast
delete_old_neg_div_lines()
array.push(neg_div_lines, new_line)
last_neg_div_lines := last_neg_div_lines + 1
remove_last_neg_divs := true
// set variables for alerts
if y == 0
pos_reg_div_detected := true
if y == 1
neg_reg_div_detected := true
if y == 2
pos_hid_div_detected := true
if y == 3
neg_hid_div_detected := true
alertcondition(pos_reg_div_detected and not pos_reg_div_detected[1], title='Regular Bullish Divergence in UO', message='Regular Bullish Divergence in UO')
alertcondition(neg_reg_div_detected and not neg_reg_div_detected[1], title='Regular Bearish Divergence in UO', message='Regular Bearish Divergence in UO')
alertcondition(pos_hid_div_detected and not pos_hid_div_detected[1], title='Hidden Bullish Divergence in UO', message='Hidden Bullish Divergence in UO')
alertcondition(neg_hid_div_detected and not neg_hid_div_detected[1], title='Hidden Bearish Divergence in UO', message='Hidden Bearish Divergence in UO')
alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]), title='Bullish Divergence in UO', message='Bullish Divergence in UO')
alertcondition((neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Bearish Divergence Detected in UO', message='Bearish Divergence Detected in UO')
alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]) or (neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Divergence Detected in UO', message='Divergence Detected in UO')
//Oscillator label
var table isFlippedLabel = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.black, 100), frame_width = 0, frame_color = color.new(#000000, 100))
if barstate.islast and flipOsc
// We only populate the table on the last bar.
table.cell(isFlippedLabel, 0, 0, text="Flipped", text_color=color.gray, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) |
LUNC Spot Index | https://www.tradingview.com/script/HJDcGl99-LUNC-Spot-Index/ | lysergik | https://www.tradingview.com/u/lysergik/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© lysergik
//@version=5
indicator("LUNC Spot Index", shorttitle="LUNC_INDEX", precision=8)
// Inputs
string style = input.string('Colorful', 'Style', ['Colorful','Lysergik','Classic'], group='Swag')
bool dark_mode = input.bool(true, 'Dark Mode', group='Swag')
int ma_length = input.int(50, 'EMA Length', 2, group='Configs')
// Data
binance_busd = request.security("BINANCE:LUNCBUSD",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
binance_usdt = request.security("BINANCE:LUNCUSDT",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
kucoin_usdt = request.security("KUCOIN:LUNCUSDT",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
bitget_usdt = request.security("BITGET:LUNCUSDT",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
bitget_usdc = request.security("BITGET:LUNCUSDC",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
bingx_usdt = request.security("BINGX:LUNCUSDT",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
okx_usdt = request.security("OKX:LUNCUSDT",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
gateio_usdt = request.security("GATEIO:LUNCUSDT",
timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
var table stats = table.new(position.bottom_right, 2, 5)
values = array.new<float>(16,binance_busd)
array.push(values, binance_usdt)
array.push(values, kucoin_usdt)
array.push(values, bitget_usdt)
array.push(values, bitget_usdc)
array.push(values, bingx_usdt)
array.push(values, okx_usdt)
array.push(values, gateio_usdt)
// Math
index = array.avg(values)
max = array.max(values)
min = array.min(values)
max_spread = max - min
ma = ta.ema(index, ma_length)
// Logic
bool above_ma = min > ma
bool below_ma = max < ma
bool index_up = index > index[1] and max > max[1]
bool index_down = index < index[1] and min < min[1]
color neutral_col = dark_mode ? color.white : color.black
color back_col = dark_mode ? color.black : color.white
color max_col = index_up ? color.aqua : neutral_col
color index_col = index_up ? color.lime : index_down ? color.yellow : neutral_col
color min_col = index_down ? color.purple : neutral_col
// 'Classic' colors:
color max_col_final = color.lime
color index_col_final = neutral_col
color min_col_final = color.red
if style == 'Colorful'
max_col_final := max_col
index_col_final := index_col
min_col_final := min_col
else if style == 'Lysergik'
max_col_final := color.aqua
index_col_final := neutral_col
min_col_final := color.purple
ma_col = above_ma ? color.aqua : below_ma ? color.purple : neutral_col
// Front-End
plot(ma, 'Moving Average', color=ma_col, style=plot.style_circles)
plot(max, 'Highest Price', color=max_col_final)
plot(index, 'Average Spot Price', color=index_col_final, trackprice=true)
plot(min, 'Lowest Price', color=min_col_final)
if barstate.islast
table.cell(stats, 0, 0, 'Max', text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 1, 0, str.tostring(max, '0.00000000'), text_color=max_col_final, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 0, 1, 'Index', text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 1, 1, str.tostring(index, '0.00000000'), text_color=index_col_final, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 0, 2, 'Min', text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 1, 2, str.tostring(min, '0.00000000'), text_color=min_col_final, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 0, 3, 'Spread', text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 1, 3, str.tostring(max_spread, '0.00000000'), text_color=back_col, text_size=size.auto, bgcolor=neutral_col)
table.cell(stats, 0, 4, 'How Terra', text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
table.cell(stats, 1, 4, 'Very Luna', text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
//hline(0)
//plot(max_spread, color=color.aqua)
|
True Strength Indicator + Realtime Divergences | https://www.tradingview.com/script/1fwE4x87-True-Strength-Indicator-Realtime-Divergences/ | tvenn | https://www.tradingview.com/u/tvenn/ | 165 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© tvenn
//@version=5
indicator("True Strength Indicator + Realtime Divergences", shorttitle="TSI+", overlay=false, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400, precision=3)
pulldatafromtimeframe = input.string("Chart", title="Select alternate timeframe in mins", options=["Chart", "1", "2", "3", "4", "5", "10", "15", "30", "45", "60", "120", "240"])
green = color.new(#95BD5F, 30)
red = color.new(#EA1889, 30)
haTicker = ticker.heikinashi(syminfo.tickerid)
[haO, haH, haL, haC] = request.security(haTicker, timeframe.period, [open, high, low, close])
//TSI settings
long = input(title="Long Length", defval=6, group="TSI settings")
short = input(title="Short Length", defval=13, group="TSI settings")
signal = input(title="Signal Length", defval=4, group="TSI settings")
//Divergence options
showlines = input(defval = true, title = "Show Divergence Lines", group="Divergence settings")
showlast = input(defval = true, title = "Show Only Last Divergence", group="Divergence settings")
dontconfirm = input(defval = true, title = "Don't Wait for Confirmation", group="Divergence settings")
//Bands
grp_Detail = "Details"
centerline = input(true, title="Centerline", group=grp_Detail, inline="1", tooltip="To add a solid centerline that stays behind the oscillator, simply adjust the color of the 'Alt centerline' within the styles tab and disable this centerline")
showBands = input(false, title="Range bands", group=grp_Detail, inline="3", tooltip="The color and style of the range bands can be further customised in the 'Style' tab of this settings menu.")
//Band crossover dots
crossoverDotsOn = input(true, title="Crossover dots", inline="4", group=grp_Detail, tooltip="The size and color of the dots can be altered in the 'Style' tab of this settings menu.")
fadeOutDotsOn = input(true, title="Fade out dots", inline="4", group=grp_Detail, tooltip="This will gradually fade out the historical crossover dots to minimise visual noise.")
crossoverLabel = input(false, title="Crossover label", group=grp_Detail, tooltip="A green label will show if the TSI band is above the signal band, a red label will show if the TSI band is below the signal band.\n\nThe crossover can be used to help time trade entries.")
CloudOn = input(title="TSI Cloud", defval=true, group=grp_Detail)
fadeOutOsc = input(false, title="Fade out oscillator", group=grp_Detail, tooltip="Face out the oscillator leaving only the most recent periods prominent for a clearer chart.")
flipOsc = input.bool(false, title="Flip Oscillator", group=grp_Detail, tooltip="This will flip the oscillator upside down. The purpose is for use with the flip chart feature of Tradingview (Alt+i), which does not also flip the oscillator. This may help those with a particular long/short bias to see the other side of things. Divergence lines will not be drawn.")
grp_BG = "Background styles"
backgroundColor = input(color.new(color.white, 97), title="", group=grp_BG, inline="bg")
showBackground = input(false, title="Background", group=grp_BG, inline="bg")
bandsDownColor = input.color(color.new(red, 90), title="", group=grp_BG, inline="crossunder")
BackgroundSignalOn = input(false, title="TSI signal band crossunder background color", group=grp_BG, tooltip="This will colour the background according to whether the TSI band is above or below the signal band.", inline="crossunder")
subZeroColor = input.color(color.new(red, 90), title="", group=grp_BG, inline="crossunder2")
BackgroundCenterSignalOn = input(false, title="TSI centerline crossunder background color", group=grp_BG, tooltip="This will colour the background according to whether the TSI line is above or below the centerline (0 level).\n\nThis can indicate bullishness above the centerline, and bearishness below the centerline.", inline="crossunder2")
centerlineupper = hline(1, color=color.new(#000000, 100), title="Alt centerline", linestyle=hline.style_solid, linewidth=1)
centerlinelower = hline(-1, color=color.new(#000000, 100), title="Alt centerline", linestyle=hline.style_solid, linewidth=1)
fill(centerlineupper, centerlinelower, color.new(color.orange, 100), title="Alt centerline", editable=1)
colorUpper = showBands ? color.new(color.gray, 30) : color.new(#777777, 100)
colorLower = showBands ? color.new(color.gray, 30) : color.new(#777777, 100)
band2 = hline(60, color=colorUpper, title="Overbought", linestyle=hline.style_dotted, linewidth=1)
band1 = hline(0, color=(centerline ? color.new(#777777, 0): na), title="Centerline", linestyle=hline.style_dotted, linewidth=1)
band0 = hline(-60, color=colorLower, title="Oversold", linestyle=hline.style_dotted, linewidth=1)
convertToHA = input(false, title="Enable Heikin Ashi mode on standard chart", group="Heikin Ashi mode", tooltip="This will use Heikin Ashi formula Open and Close values. The purpose is for use on standard chart types, as having this setting enabled on an actual Heikin Ashi chart will produce unrealistic Heikin Ahi average values.")
haCheckHigh = convertToHA ? haH : high
haCheckLow = convertToHA ? haL : low
haCheckClose = convertToHA ? haC : close
//TSI
double_smooth(src, long, short) =>
fist_smooth = ta.ema(src, long)
ta.ema(fist_smooth, short)
pc = ta.change(haCheckClose)
double_smoothed_pc = double_smooth(pc, long, short)
double_smoothed_abs_pc = double_smooth(math.abs(pc), long, short)
tsi_val = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
tsi_value_raw = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, tsi_val, barmerge.gaps_on)
tsi_value = (flipOsc ? tsi_value_raw*-1 : tsi_value_raw)
lagline=int(ta.ema(tsi_value, signal))
//Pivot settings
pp = input.int(defval = 12, title = "Pivot period", minval = 1, maxval = 50, group="Pivot point settings")
maxpp = input.int(defval = 5, title = "Maximum Pivot periods to check for divs", minval = 1, maxval = 100, group="Pivot point settings")
maxbars = input.int(defval = 100, title = "Maximum Bars to Check", minval = 1, maxval = 200, group="Pivot point settings")
source = "Close"
searchdiv = input.string(defval = "Regular/Hidden", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group="Divergence settings")
prd = pp
//Styles
grp_STYLE = "Styles"
primary_color = input(green, title="TSI color", group=grp_STYLE)
secondary_color = input(red, title="Lagline color", group=grp_STYLE)
pos_reg_div_col = input(defval = green, title = "Bullish Regular Divergence", group=grp_STYLE)
neg_reg_div_col = input(defval = red, title = "Bearish Regular Divergence", group=grp_STYLE)
pos_hid_div_col = input(defval = green, title = "Bullish Hidden Divergence", group=grp_STYLE)
neg_hid_div_col = input(defval = red, title = "Bearish Hidden Divergence", group=grp_STYLE)
reg_div_l_style_ = input.string(defval = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STYLE)
hid_div_l_style_ = input.string(defval = "Dotted", title = "Hdden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STYLE)
reg_div_l_width = input.int(defval = 2, title = "Regular Divergence Line Width", minval = 1, maxval = 2, group=grp_STYLE)
hid_div_l_width = input.int(defval = 2, title = "Hidden Divergence Line Width", minval = 1, maxval = 2, group=grp_STYLE)
distanceTransparency = (bar_index > (last_bar_index - 30) ? 10 : (bar_index > last_bar_index - 60 ? 20 : (bar_index > last_bar_index - 80 ? 30 : (bar_index > last_bar_index - 100 ? 40 : (bar_index > last_bar_index - 120 ? 50 : (bar_index > last_bar_index - 140 ? 60 : (bar_index > last_bar_index - 160 ? 70 : 80)))))))
dotDistanceTransparency = (bar_index > (last_bar_index - 10) ? 10 : (bar_index > last_bar_index - 20 ? 20 : (bar_index > last_bar_index - 30 ? 30 : (bar_index > last_bar_index - 40 ? 40 : (bar_index > last_bar_index - 50 ? 50 : (bar_index > last_bar_index - 60 ? 60 : (bar_index > last_bar_index - 70 ? 80 : 100)))))))
line1=plot(tsi_value, color=(fadeOutOsc ? color.new(primary_color, distanceTransparency) : primary_color), title="TSI")
line2=plot(ta.ema(tsi_value, signal), color=(fadeOutOsc ? color.new(secondary_color, distanceTransparency) : secondary_color), title="Lagline")
tsi_lagline_value=(ta.ema(tsi_value, signal))
tsi_bands_crossed_up = (tsi_value > tsi_lagline_value) ? 1 : 0
cloudDistanceTransparency = (bar_index > last_bar_index - 40 ? 50 : (bar_index > last_bar_index - 100 ? 75 : 100))
CloudColor = CloudOn and tsi_value > lagline ? (fadeOutOsc ? color.new(primary_color, cloudDistanceTransparency) : color.new(primary_color, 75)) : (CloudOn and tsi_value <= lagline ? (fadeOutOsc ? color.new(secondary_color, cloudDistanceTransparency) : color.new(secondary_color, 75)) : na)
fill(line1, line2, color=CloudColor)
//background fill options
fill(band2, band0, BackgroundSignalOn and tsi_bands_crossed_up ? na : BackgroundSignalOn and (tsi_bands_crossed_up == 0) ? bandsDownColor : na, title="Bands crossover background colors", editable=1)
fill(band2, band0, BackgroundCenterSignalOn and tsi_value > 0 ? na : BackgroundCenterSignalOn and tsi_value < 0 ? subZeroColor : na, title="Centerline crossover background colors", editable=1)
//=Crossover dots
plot((crossoverDotsOn and (not fadeOutDotsOn) and ta.cross(tsi_value, lagline)) ? tsi_value : na, style=plot.style_circles, color=ta.crossover(tsi_value, lagline) ? color.new(primary_color, 0) : ta.crossunder(tsi_value, lagline) ? color.new(secondary_color, 0) : na, title="Band crossover dots", linewidth=2)
plot((crossoverDotsOn and fadeOutDotsOn and ta.cross(tsi_value, lagline)) ? tsi_value : na, style=plot.style_circles, color=ta.crossover(tsi_value, lagline) ? color.new(primary_color, dotDistanceTransparency) : ta.crossunder(tsi_value, lagline) ? color.new(secondary_color, dotDistanceTransparency) : na, title="Band crossover fadeout dots", linewidth=2)
fill(band0, band2, showBackground ? backgroundColor : na)
// set line styles
var reg_div_l_style = reg_div_l_style_ == "Solid" ? line.style_solid :
reg_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
var hid_div_l_style = hid_div_l_style_ == "Solid" ? line.style_solid :
hid_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
// get indicators
tsi = tsi_value
// keep indicator colors in arrays
var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(haCheckClose, prd, prd)
float pl = ta.pivotlow(haCheckClose, prd, prd)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// functions to check Regular Divergences and Hidden Divergences
// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond)=>
divlen = 0
prsc = haCheckClose
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or haCheckClose > haCheckClose[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or
(cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (haCheckClose[startpoint] - haCheckClose[len]) / (len - startpoint)
virtual_line2 = haCheckClose[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] < virtual_line1 or nz(haCheckClose[y]) < virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond)=>
divlen = 0
prsc = haCheckClose
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or haCheckClose < haCheckClose[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x))) or
(cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (haCheckClose[startpoint] - nz(haCheckClose[len])) / (len - startpoint)
virtual_line2 = haCheckClose[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] > virtual_line1 or nz(haCheckClose[y]) > virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator)=>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 1) : 0)
array.set(divs, 1, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 1) : 0)
array.set(divs, 2, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 2) : 0)
array.set(divs, 3, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 2) : 0)
divs
// array to keep all divergences
var all_divergences = array.new_int(4) // 1 indicator * 4 divergence = 4 elements
// set related array elements
array_set_divs(div_pointer, index)=>
for x = 0 to 3
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
array_set_divs(calculate_divs(true, tsi), 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines()=>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)
delete_old_neg_div_lines()=>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)
delete_old_pos_div_labels()=>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_neg_div_labels()=>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n)=>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n)=>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
// draw divergences lines and labels
divergence_text_top = ""
divergence_text_bottom = ""
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
for x = 0 to 0
div_type = -1
for y = 0 to 3
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if (y % 2) == 1
dnumdiv_top := dnumdiv_top + 1
top_label_col := array.get(div_colors, y)
if (y % 2) == 0
dnumdiv_bottom := dnumdiv_bottom + 1
bottom_label_col := array.get(div_colors, y)
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = (showlines and not flipOsc) ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? tsi[array.get(all_divergences, x * 4 + y)] :
(y % 2) == 0 ? haCheckLow[array.get(all_divergences, x * 4 + y)] :
haCheckHigh[array.get(all_divergences, x * 4 + y)]),
x2 = bar_index - startpoint,
y2 = (source == "Close" ? tsi[startpoint] :
(y % 2) == 0 ? haCheckLow[startpoint] :
haCheckHigh[startpoint]),
color = array.get(div_colors, y),
style = y < 2 ? reg_div_l_style : hid_div_l_style,
width = y < 2 ? reg_div_l_width : hid_div_l_width
)
: na
if (y % 2) == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
if showlast
delete_old_pos_div_lines()
array.push(pos_div_lines, new_line)
last_pos_div_lines := last_pos_div_lines + 1
remove_last_pos_divs := true
if (y % 2) == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
if showlast
delete_old_neg_div_lines()
array.push(neg_div_lines, new_line)
last_neg_div_lines := last_neg_div_lines + 1
remove_last_neg_divs := true
// set variables for alerts
if y == 0
pos_reg_div_detected := true
if y == 1
neg_reg_div_detected := true
if y == 2
pos_hid_div_detected := true
if y == 3
neg_hid_div_detected := true
alertcondition(pos_reg_div_detected and not pos_reg_div_detected[1], title='Bullish Regular Divergence in TSI', message='Bullish Regular Divergence in TSI')
alertcondition(neg_reg_div_detected and not neg_reg_div_detected[1], title='Bearish Regular Divergence in TSI', message='Bearish Regular Divergence in TSI')
alertcondition(pos_hid_div_detected and not pos_hid_div_detected[1], title='Bullish Hidden Divergence in TSI', message='Bullish Hidden Divergence in TSI')
alertcondition(neg_hid_div_detected and not neg_hid_div_detected[1], title='Bearish Hidden Divergence in TSI', message='Bearish Hidden Divergence in TSI')
alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]), title='Bullish Divergence in TSI', message='Bullish Divergence in TSI')
alertcondition((neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Bearish Divergence in TSI', message='Bearish Divergence in TSI')
alertcondition((neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]) or (pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]), title='Divergence in TSI', message='Divergence in TSI')
alertcondition(crossoverDotsOn and (tsi_value > tsi_lagline_value) and not (tsi_value[1] > tsi_lagline_value[1]), title='TSI bands crossover bullish', message='TSI bands crossover bullish')
alertcondition(crossoverDotsOn and (tsi_value < tsi_lagline_value) and not (tsi_value[1] < tsi_lagline_value[1]), title='TSI bands crossover bearish', message='TSI bands crossover bearish')
//Oscillator name label
var table isFlippedLabel = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.black, 100), frame_width = 0, frame_color = color.new(#000000, 100))
var table bandState = table.new(position.middle_right, 1, 2, bgcolor = color.new(color.black, 100), frame_width = 0, frame_color = color.new(#000000, 100))
bandCrossedUp = tsi_val > tsi_lagline_value ? true : false
d = math.abs(tsi_val - tsi_lagline_value) > 14 ? color.white : na
if barstate.islast and flipOsc
// We only populate the table on the last bar.
table.cell(isFlippedLabel, 0, 0, text="Flipped", text_color=color.gray, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100))
if barstate.islast and crossoverLabel
table.cell(bandState, 0, 0, text="β", text_color=(math.abs(tsi_val - tsi_lagline_value) > 15 and bandCrossedUp ? color.orange : bandCrossedUp ? primary_color : color.new(color.gray, 90)), text_halign=text.align_left, text_size=size.large, bgcolor=color.new(#000000, 100))
table.cell(bandState, 0, 1, text="β", text_color=(math.abs(tsi_val - tsi_lagline_value) > 15 and not bandCrossedUp ? color.orange : not bandCrossedUp ? secondary_color : color.new(color.gray, 90)), text_halign=text.align_left, text_size=size.large, bgcolor=color.new(#000000, 100)) |
Candle Info by Monty | https://www.tradingview.com/script/MgDxyFkk-Candle-Info-by-Monty/ | MontyTheGuy | https://www.tradingview.com/u/MontyTheGuy/ | 40 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© MontyTheGuy
//@version=5
indicator("Candle Info by Monty", overlay=true)
int pLabel = input.int(20, 'Panel Index', minval=2)
var string lab = na
var string lText = na
var float infoLbText=na
bool cInfo=input.bool(false,"Show Candle OHLC",tooltip="OHLC: Open High Low Close")
string TTString="W2W - Wick to Wick \nCO2C - Candle Open to Current Price"
string Calc=input.string(title="% Calculation Mode",defval="Wick to Wick",options=["Wick to Wick","Candle Open To Current"],tooltip=TTString)
color cText=input.color(color.new(color.white,0),title="Label Text Color")
color cLabel=input.color(color.new(color.blue,10),title="Label Background Color")
label infoLabel = label.new(time, close, xloc=xloc.bar_time, color=cLabel, textcolor=cText, style=label.style_label_left, size=size.normal)
if Calc=="Wick to Wick"
lab :="W2W Move: "
infoLbText := math.round(math.abs(close > open ? ((high-low)/low)*100 : ((low-high)/high)*100),3)
else
lab := "CO2C Move: "
infoLbText := math.round(math.abs(close > open ? ((close-open)/open)*100 : ((open-close)/close)*100),3)
if cInfo
lText := str.tostring(lab) + str.tostring(infoLbText) + "%\n Open : " + str.tostring(math.round(math.abs(open))) + "\n Wick High : " + str.tostring(math.round(math.abs(close))) + "\n Wick Low : " + str.tostring(math.round(math.abs(low))) + "\n Close/Current : " + str.tostring(math.round(math.abs(close)))
else
lText := lab + str.tostring(infoLbText) + "%"
label.set_text(id=infoLabel, text= str.tostring(lText))
label.set_x(infoLabel, label.get_x(infoLabel) + math.round(ta.change(time) * pLabel))
label.delete(infoLabel[1])
|
Timeframe Bias Table | https://www.tradingview.com/script/zxKPSSlt-Timeframe-Bias-Table/ | MikeDelgado | https://www.tradingview.com/u/MikeDelgado/ | 173 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© MikeDelgado
//@version=5
indicator("Timeframe Bias Table", "TF Bias", overlay=true)
//input timeframes
inptf1 = input.string('W', '1. Timeframe', inline = '0')
inptf2 = input.string('D', '2. Timeframe', inline = '1')
inptf3 = input.string('4h', '3. Timeframe', inline = '2')
inptf4 = input.string('15m', '4. Timeframe', inline = '3')
inptf5 = input.string('1m', '5. Timeframe', inline = '4')
//input Bias
inp1 = input.string('-', 'Bias', options = ['α±', '-', 'α―',''],inline = '0')
inp2 = input.string('-', 'Bias', options = ['α±', '-', 'α―',''],inline = '1')
inp3 = input.string('-', 'Bias', options=['α±', '-', 'α―',''] , inline = '2')
inp4 = input.string('-', 'Bias', options=['α±', '-', 'α―',''] , inline = '3')
inp5 = input.string('-', 'Bias', options=['α±', '-', 'α―',''] , inline = '4')
inpColorTF = input.color(color.gray, "TF Color", inline = '5')
inpColorBull = input.color(color.gray, "α± Color", inline = '5')
inpColorBear = input.color(color.gray, "α― Color", inline = '5')
inpColorNeutral = input.color(color.gray, "- Color", inline = '5')
var tbl = table.new(position.top_right, 5, 5,
frame_color=color.new(#151715,100), border_width=1,
border_color=color.new(color.white, 100))
// Header
if barstate.islast
//TFs
table.cell(tbl, 0, 0, inptf1, text_color=inpColorTF)
table.cell(tbl, 1, 0, inptf2, text_color=inpColorTF)
table.cell(tbl, 2, 0, inptf3, text_color=inpColorTF)
table.cell(tbl, 3, 0, inptf4, text_color=inpColorTF)
table.cell(tbl, 4, 0, inptf5, text_color=inpColorTF)
//Bias
//W
if inp1=='α±'
table.cell(tbl, 0, 1, inp1, height=-1, text_color=inpColorBull)
else if inp1=='α―'
table.cell(tbl, 0, 1, inp1, text_color=inpColorBear)
else
table.cell(tbl, 0, 1, inp1, text_color=inpColorNeutral)
//D
if inp2=='α±'
table.cell(tbl, 1, 1, inp2, text_color=inpColorBull)
else if inp2=='α―'
table.cell(tbl, 1, 1, inp2, text_color=inpColorBear)
else
table.cell(tbl, 1, 1, inp2, text_color=inpColorNeutral)
//4h
if inp3=='α±'
table.cell(tbl, 2, 1, inp3, text_color=inpColorBull)
else if inp3=='α―'
table.cell(tbl, 2, 1, inp3, text_color=inpColorBear)
else
table.cell(tbl, 2, 1, inp3, text_color=inpColorNeutral)
//15m
if inp4=='α±'
table.cell(tbl, 3, 1, inp4, text_color=inpColorBull)
else if inp4=='α―'
table.cell(tbl, 3, 1, inp4, text_color=inpColorBear)
else
table.cell(tbl, 3, 1, inp4, text_color=inpColorNeutral)
//1m
if inp5=='α±'
table.cell(tbl, 4, 1, inp5, text_color=inpColorBull)
else if inp5=='α―'
table.cell(tbl, 4, 1, inp5, text_color=inpColorBear)
else
table.cell(tbl, 4, 1, inp5, text_color=inpColorNeutral)
|
Step-MA Filtered CCI [Loxx] | https://www.tradingview.com/script/aBf19325-Step-MA-Filtered-CCI-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 93 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Step-MA Filtered CCI [Loxx]",
shorttitle='SMAFCCI [Loxx]',
overlay=false,
timeframe="",
timeframe_gaps=true)
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Middle Crosses'
SM04 = 'Levels Crosses'
_stepma(float sense, float size, float stepMulti, phigh, plow, pprice)=>
float trend = 0.
float out = 0.
float sensitivity = sense == 0 ? 0.0001 : sense
float stepSize = size == 0 ? 0.0001 : size
float sizea = sensitivity * stepSize
float smax = phigh + 2.0 * sizea * stepMulti
float smin = plow - 2.0 * sizea * stepMulti
trend := nz(trend[1])
if (pprice > nz(smax[1]))
trend := 1
if (pprice < nz(smin[1]))
trend := -1
if (trend == 1)
if (smin < nz(smin[1]))
smin := nz(smin[1])
out := smin + sizea * stepMulti
if (trend == -1)
if (smax > nz(smax[1]))
smax := nz(smax[1])
out := smax - sizea * stepMulti
out
src = input(hlc3, title="Source", group = "Basic Settings")
per = input.int(50, "Period", minval=1, group = "Basic Settings")
Sensitivity = input.float(4, group = "Step MA Settings")
StepSize = input.float(5, group = "Step MA Settings")
StepMultiplier = input.float(5, group = "Step MA Settings")
lvlup = input.int(100, "Upper Level", group = "Levels Settings")
lvldn = input.int(-100, "Bottom Level", group = "Levels Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
cci = ta.cci(src, per)
out = _stepma(Sensitivity, StepSize, StepMultiplier, cci, cci, cci)
sig = out[1]
mid = 0
state = 0.
if sigtype == SM02
if (out < sig)
state :=-1
if (out > sig)
state := 1
else if sigtype == SM03
if (out < mid)
state :=-1
if (out > mid)
state := 1
else if sigtype == SM04
if (out < lvldn)
state := -1
if (out > lvlup)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(out, "Step CCI", color = colorout, linewidth = 2)
plot(lvlup, "Overbought", color = bar_index % 2 ? color.gray : na)
plot(lvldn, "Oversold", color = bar_index % 2 ? color.gray : na)
plot(mid, "Mid", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(out, sig) : sigtype == SM03 ? ta.crossover(out, mid) : ta.crossover(out, lvlup)
goShort = sigtype == SM02 ? ta.crossunder(out, sig) : sigtype == SM03 ? ta.crossunder(out, mid) : ta.crossunder(out, lvldn)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Step-MA Filtered CCI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Step-MA Filtered CCI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Step-MA Filtered Stochastic [Loxx] | https://www.tradingview.com/script/kVxhJsex-Step-MA-Filtered-Stochastic-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 300 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Step-MA Filtered Stochastic [Loxx]",
shorttitle='SMAFS [Loxx]',
overlay=false,
timeframe="",
timeframe_gaps=true)
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Signal'
SM03 = 'Middle Crosses'
SM04 = 'Levels Crosses'
_stepma(float sense, float size, float stepMulti, phigh, plow, pprice)=>
float trend = 0.
float out = 0.
float sensitivity = sense == 0 ? 0.000001 : sense
float stepSize = size == 0 ? 0.000001 : size
float sizea = sensitivity * stepSize
float smax = phigh + 2.0 * sizea * stepMulti
float smin = plow - 2.0 * sizea * stepMulti
trend := nz(trend[1])
if (pprice > nz(smax[1]))
trend := 1
if (pprice < nz(smin[1]))
trend := -1
if (trend == 1)
if (smin < nz(smin[1]))
smin := nz(smin[1])
out := smin + sizea * stepMulti
if (trend == -1)
if (smax > nz(smax[1]))
smax := nz(smax[1])
out := smax - sizea * stepMulti
out
per = input.int(32, "Period", minval=1, group = "Basic Settings")
periodD = input.int(3, title="%D Smoothing", minval=1, group = "Basic Settings")
Sensitivity = input.float(4, "Sensitivity", group = "Step MA Settings")
StepSize = input.float(5, "Step Size", group = "Step MA Settings")
StepMultiplier = input.float(.5, "Step Multiplier", step = 0.01, group = "Step MA Settings")
lvlup = input.int(80, "Upper Level", group = "Levels Settings")
lvldn = input.int(20, "Bottom Level", group = "Levels Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
out = ta.stoch(close, high, low, per)
sig = ta.sma(out, periodD)
out := _stepma(Sensitivity, StepSize, StepMultiplier, out, out, out)
sig := _stepma(Sensitivity, StepSize, StepMultiplier, sig, sig, sig)
mid = 50
state = 0.
if sigtype == SM02
if (out < sig)
state :=-1
if (out > sig)
state := 1
else if sigtype == SM03
if (out < mid)
state :=-1
if (out > mid)
state := 1
else if sigtype == SM04
if (out < lvldn)
state := -1
if (out > lvlup)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(out, "Step Stochastic", color = colorout, linewidth = 2)
plot(lvlup, "Overbought", color = bar_index % 2 ? color.gray : na)
plot(lvldn, "Oversold", color = bar_index % 2 ? color.gray : na)
plot(mid, "Mid", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(out, sig) : sigtype == SM03 ? ta.crossover(out, mid) : ta.crossover(out, lvlup)
goShort = sigtype == SM02 ? ta.crossunder(out, sig) : sigtype == SM03 ? ta.crossunder(out, mid) : ta.crossunder(out, lvldn)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Step-MA Filtered Stochastic [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Step-MA Filtered Stochastic [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Generalized Step Moving Average w/ Pips Filter [Loxx] | https://www.tradingview.com/script/gPyWrDWq-Generalized-Step-Moving-Average-w-Pips-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 81 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Generalized Step Moving Average w/ Pips Filter [Loxx]",
overlay = true,
shorttitle='GSMAPF [Loxx]',
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
_declen()=>
mtckstr = str.tostring(syminfo.mintick)
da = str.split(mtckstr, ".")
temp = array.size(da)
dlen = 0
if syminfo.mintick < 1
dstr = array.get(da, 1)
dlen := str.length(dstr)
dlen
_stepMaNew(float src, int length, float size, float mult)=>
float price0 = src
float price1 = nz(src[1])
float volty = 0.
float rng = 0.
float smax = 0.
float smin = 0.
float steptrend = 0.
float sum = 0.
for int i = 0 to length
rng := math.abs(src - nz(src[i]))
sum += rng
volty := math.max(size * syminfo.mintick, mult * sum / length)
smax := nz(smax[1])
smin := nz(smin[1])
steptrend := nz(steptrend[1])
if (price0 - nz(smax[1])) > 0
steptrend := 1
if (-price0 + nz(smin[1])) > 0
steptrend := -1
if steptrend > 0
smax := math.max(nz(smax[1]), math.max(price0, price1))
if smax < nz(smax[1])
smax := nz(smax[1])
smin := math.round(smax - volty, _declen())
if smin < nz(smin[1])
smin := nz(smin[1])
if smin > nz(smin[1]) and smax == nz(smax[1])
smin := nz(smin[1])
else if steptrend < 0
smin := math.min(nz(smin[1]), math.min(price0, price1))
if smin > nz(smin[1])
smin := smin[1]
smax := math.round(smin + volty, _declen())
if smax > nz(smax[1])
smax := nz(smax[1])
if smax < nz(smax[1]) and smin == nz(smin[1])
smax := nz(smax[1])
out = (smin + smax) / 2
out
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(5, "Period", group = "Basic Settings")
stsize = input.float(0, "Pips Step Size", step = 0.1, group = "Basic Settings")
stepmult = input.float(5, "Step Multiplier", step = 0.1, group = "Basic Settings")
MinStep = input.int(100, "Minimum Pips Multiplier", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = _stepMaNew(src, per, stsize, stepmult)
if math.abs(out - nz(out[1])) < MinStep * syminfo.mintick
out := nz(out[1])
sig = nz(out[1])
state = 0
if (out > sig)
state := 1
if (out < sig)
state := -1
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "Step MA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Generalized Step Moving Average w/ Pips Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Generalized Step Moving Average w/ Pips Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
SGX Nifty OHLC for Nifty 50 Index | https://www.tradingview.com/script/ejOwNPoa-SGX-Nifty-OHLC-for-Nifty-50-Index/ | Arun_K_Bhaskar | https://www.tradingview.com/u/Arun_K_Bhaskar/ | 175 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Arun_K_Bhaskar
//@version=5
indicator(title="SGX Nifty OHLC for Nifty 50 Index", shorttitle="SGX Nifty OHLC", overlay=true)
///////////////////////////////////////////////////////// Menu
symbol = input.symbol(defval="NSEIX:NIFTY1!", title='SGX NIFTY Symbol', tooltip='', inline='', group='') //SGX Nifty Futures
gpSGX = "SGX Nifty"
show_sgx_h = input.bool(true, title="High", group=gpSGX, inline="01")
show_sgx_l = input.bool(true, title="Low", group=gpSGX, inline="01")
show_sgx_o = input.bool(false, title="Open", group=gpSGX, inline="01")
show_sgx_c = input.bool(true, title="Close", group=gpSGX, inline="01")
gpNif = "NIFTY 50"
show_nifty_h = input.bool(false, title="High", group=gpNif, inline="01")
show_nifty_l = input.bool(false, title="Low", group=gpNif, inline="01")
show_nifty_o = input.bool(false, title="Open", group=gpNif, inline="01")
show_nifty_c = input.bool(false, title="Close", group=gpNif, inline="01")
i_past_levels = input.int(1, title="Previous", minval=0, group=gpNif, inline="02")
gpCol = "Colors"
o_col = input.color(#2962FF, title="Open", group=gpCol, inline="01")
c_col = input.color(#F59302, title="Close", group=gpCol, inline="01")
h_col = input.color(#EF5350, title="High", group=gpCol, inline="01")
l_col = input.color(#26A69A, title="Low", group=gpCol, inline="01")
gpSet = "Settings"
show_labels = input.bool(true, title="Labels", group=gpSet, inline="01")
show_warn = input.bool(true, title="Warn Label", group=gpSet, inline="01")
show_last = input.bool(true, title="Hide Historical", group=gpSet, inline="02")
islast = show_last ? request.security(syminfo.tickerid, "D", barstate.islast, lookahead=barmerge.lookahead_on) : true
///////////////////////////////////////////////////////// Warning
warn_txt = "Use 1 min timeframe for accurate OHLC.\n In other timeframes OHLC will have negligible difference, it won't be huge.\nThis indicator will appear only on NIFTY Index and Futures chart.\nTo hide this warning label go to the indicator Menu."
warn_label = label(na)
if (timeframe.period != "1") and show_warn
warn_label := label.new(bar_index-90, close, warn_txt, xloc.bar_index, textcolor=color.white, color=#EF5350, style=label.style_label_center, size=size.large)
label.delete(warn_label[1])
///////////////////////////////////////////////////////// SGX Nifty OHLC
open_time = time(timeframe.period, "1529-1530")
hlc_time = time(timeframe.period, "0915-0916")
// Open
_open = request.security(symbol, "D", open, barmerge.gaps_off, barmerge.lookahead_on)
// Close
_close = request.security(symbol, "1", close)
sgx_close = ta.valuewhen(hlc_time, _close, 0)
// High
_high = request.security(symbol, "1", ta.highest(high, 720))
sgx_high = ta.valuewhen(hlc_time, _high, 0)
// Low
_low = request.security(symbol, "1", ta.lowest(low, 720))
sgx_low = ta.valuewhen(hlc_time, _low, 0)
// Plot
nifty = syminfo.root == "NIFTY" or syminfo.root == "NIFTY1!" or syminfo.root == "NIFTY2!"
pivot_time = time(timeframe.period, "0916-1530")
plot(nifty and pivot_time and show_sgx_o and islast ? _open : na, "SGX Nifty Open", style=plot.style_linebr, color=o_col, linewidth=2)
plot(nifty and pivot_time and show_sgx_c and islast ? sgx_close : na, "SGX Nifty Close", style=plot.style_linebr, color=c_col, linewidth=2)
plot(nifty and pivot_time and show_sgx_h and islast ? sgx_high : na, "SGX Nifty High", style=plot.style_linebr, color=h_col, linewidth=2)
plot(nifty and pivot_time and show_sgx_l and islast ? sgx_low : na, "SGX Nifty Low", style=plot.style_linebr, color=l_col, linewidth=2)
// Today Start & End
day_start = timestamp(year, month, dayofmonth, 00, 00)
day_end = day_start + 86400000
// Lines & Labels
if show_sgx_o and nifty
sgx_open_line = line.new(day_start, _open, day_end, _open, xloc.bar_time, color=o_col, width=2)
line.delete(sgx_open_line[1])
sgx_open_label = label.new(day_end, _open, xloc=xloc.bar_time, text=str.tostring(_open, "#.##") + " (O SGX Nifty)", textcolor=o_col, color=color.new(color.white, 100), size=size.normal, style=label.style_label_left)
label.delete(sgx_open_label[1])
if show_sgx_c and nifty
sgx_close_line = line.new(day_start, sgx_close, day_end, sgx_close, xloc.bar_time, color=c_col, width=2)
line.delete(sgx_close_line[1])
sgx_close_label = label.new(day_end, sgx_close, xloc=xloc.bar_time, text=str.tostring(sgx_close, "#.##") + " (C SGX Nifty)", textcolor=c_col, color=color.new(color.white, 100), size=size.normal, style=label.style_label_left)
label.delete(sgx_close_label[1])
if show_sgx_h and nifty
sgx_high_line = line.new(day_start, sgx_high, day_end, sgx_high, xloc.bar_time, color=h_col, width=2)
line.delete(sgx_high_line[1])
sgx_high_label = label.new(day_end, sgx_high, xloc=xloc.bar_time, text=str.tostring(sgx_high, "#.##") + " (H SGX Nifty)", textcolor=h_col, color=color.new(color.white, 100), size=size.normal, style=label.style_label_left)
label.delete(sgx_high_label[1])
if show_sgx_l and nifty
sgx_low_line = line.new(day_start, sgx_low, day_end, sgx_low, xloc.bar_time, color=l_col, width=2)
line.delete(sgx_low_line[1])
sgx_low_label = label.new(day_end, sgx_low, xloc=xloc.bar_time, text=str.tostring(sgx_low, "#.##") + " (L SGX Nifty)", textcolor=l_col, color=color.new(color.white, 100), size=size.normal, style=label.style_label_left)
label.delete(sgx_low_label[1])
////////////////////////////////////////////////////////////////////// Nifty OHLC
// OHLC
nifty_o = request.security(syminfo.tickerid, "D", open[i_past_levels], barmerge.gaps_off, barmerge.lookahead_on)
nifty_h = request.security(syminfo.tickerid, "D", high[i_past_levels], barmerge.gaps_off, barmerge.lookahead_on)
nifty_l = request.security(syminfo.tickerid, "D", low[i_past_levels], barmerge.gaps_off, barmerge.lookahead_on)
nifty_c = request.security(syminfo.tickerid, "D", close[i_past_levels], barmerge.gaps_off, barmerge.lookahead_on)
// Plot Lines
plot(nifty and islast and show_nifty_o ? nifty_o : na, title="Nifty Open", style=plot.style_circles, color=color.new(o_col, 0), linewidth=1)
plot(nifty and islast and show_nifty_h ? nifty_h : na, title="Nifty High", style=plot.style_circles, color=color.new(h_col, 0), linewidth=1)
plot(nifty and islast and show_nifty_l ? nifty_l : na, title="Nifty Low", style=plot.style_circles, color=color.new(l_col, 0), linewidth=1)
plot(nifty and islast and show_nifty_c ? nifty_c : na, title="Nifty Close", style=plot.style_circles, color=color.new(c_col, 0), linewidth=1)
////////////////////////////////////////////////////////////////////// END |
Index Breadth Percent of Stocks above Key Moving Averages | https://www.tradingview.com/script/liD4ojmj-Index-Breadth-Percent-of-Stocks-above-Key-Moving-Averages/ | Esti0000 | https://www.tradingview.com/u/Esti0000/ | 323 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Esti0000
//@version=5
indicator("Index Breadth Percent of Stocks above Key Moving Averages", shorttitle = '% Breadth')
//User Inputs
market = input.string(defval="SP500", title="Select Market", options=["Overall", "SP500", "DJI", "Nasdaq", "Nasdaq100", "Russel2000", "Russel3000",
"SP500 Financials", "SP500 Materials", "SP500 Energy", "SP500 Staples", "SP500 Discretionary", "SP500 Industrials", "SP500 Real Estate",
"SP500 Utilities", "SP500 Technologies", "SP500 Heath Care"], group = 'Select Market')
dma = input.string(defval="20", title="Select DMA", options=["20", '50', "100", "150", "200"], group = 'Select Moving Average')
greed = input.int(defval = 80, title = 'Select Greed Level', group = 'Select Greed and Fear Zone')
fear = input.int(defval = 20, title = 'Select Fear Level', group = 'Select Greed and Fear Zone')
//Ticker Selection Criteria
ticker = ("Overall" == market) ? ("200" == dma) ? "MMTH" : ("150" == dma) ? "MMOF" : ("100" == dma) ? "MMOH" : ("50" == dma) ? "MMFI" : "MMTW" :
("SP500" == market) ? ("200" == dma) ? "S5TH" : ("150" == dma) ? "S5OF" : ("100" == dma) ? "S5OH" : ("50" == dma) ? "S5FI" : "S5TW" :
("DJI" == market) ? ("200" == dma) ? "DITH" : ("150" == dma) ? "DIOF" : ("100" == dma) ? "DIOH" : ("50" == dma) ? "DIFI" : "DITW" :
("Nasdaq" == market) ? ("200" == dma) ? "NCTH" : ("150" == dma) ? "NCOF" : ("100" == dma) ? "NCOH" : ("50" == dma) ? "NCFI" : "NCTW" :
("Nasdaq100" == market) ? ("200" == dma) ? "NDTH" : ("150" == dma) ? "NDOF" : ("100" == dma) ? "NDOH" : ("50" == dma) ? "NDFI" : "NDTW" :
("Russel2000" == market) ? ("200" == dma) ? "R2TH" : ("150" == dma) ? "R2OF" : ("100" == dma) ? "R2OH" : ("50" == dma) ? "R2FI" : "R2TW" :
("Russel3000" == market) ? ("200" == dma) ? "R3TH" : ("150" == dma) ? "R3OF" : ("100" == dma) ? "R3OH" : ("50" == dma) ? "R3FI" : "R3TW" :
("SP500 Financials" == market) ? ("200" == dma) ? "SFTH" : ("150" == dma) ? "SFOF" : ("100" == dma) ? "SFOH" : ("50" == dma) ? "SFFI" : "SFTW" :
("SP500 Materials" == market) ? ("200" == dma) ? "SBTH" : ("150" == dma) ? "SBOF" : ("100" == dma) ? "SBOH" : ("50" == dma) ? "SBFI" : "SBTW" :
("SP500 Energy" == market) ? ("200" == dma) ? "SETH" : ("150" == dma) ? "SEOF" : ("100" == dma) ? "SEOH" : ("50" == dma) ? "SEFI" : "SETW" :
("SP500 Staples" == market) ? ("200" == dma) ? "SPTH" : ("150" == dma) ? "SPOF" : ("100" == dma) ? "SPOH" : ("50" == dma) ? "SPFI" : "SPTW" :
("SP500 Discretionary" == market) ? ("200" == dma) ? "SYTH" : ("150" == dma) ? "SYOF" : ("100" == dma) ? "SYOH" : ("50" == dma) ? "SYFI" : "SYTW" :
("SP500 Industrials" == market) ? ("200" == dma) ? "SITH" : ("150" == dma) ? "SIOF" : ("100" == dma) ? "SIOH" : ("50" == dma) ? "SIFI" : "SITW" :
("SP500 Real Estate" == market) ? ("200" == dma) ? "SSTH" : ("150" == dma) ? "SSOF" : ("100" == dma) ? "SSOH" : ("50" == dma) ? "SSFI" : "SSTW" :
("SP500 Utilities" == market) ? ("200" == dma) ? "SUTH" : ("150" == dma) ? "SUOF" : ("100" == dma) ? "SUOH" : ("50" == dma) ? "SUFI" : "SUTW" :
("SP500 Technologies" == market) ? ("200" == dma) ? "SKTH" : ("150" == dma) ? "SKOF" : ("100" == dma) ? "SKOH" : ("50" == dma) ? "SKFI" : "SKTW" :
("SP500 Heath Care" == market) ? ("200" == dma) ? "SVTH" : ("150" == dma) ? "SVOF" : ("100" == dma) ? "SVOH" : ("50" == dma) ? "SVFI" : "SVTW" :
na
percentage_above_ma = request.security(ticker, timeframe.period, close)
//Plots
p_above = plot(percentage_above_ma)
greed_p = plot(greed, color = color.white)
fear_p = plot(fear, color = color.white)
//logic for painting above/below Key Moving Averages
fear_plot = plot(percentage_above_ma < fear ? fear : na, display = display.none)
greed_plot = plot(percentage_above_ma > greed ? greed : na, display = display.none)
fill(fear_plot, p_above, color = color.green)
fill(greed_plot, p_above, color = color.red) |
Wick-off Check Pattern [Misu] | https://www.tradingview.com/script/8Xc9ZwiK-Wick-off-Check-Pattern-Misu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 1,127 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author : @Fontiramisu
// @version=5
indicator("Wickoff Check Pattern [Misu]", shorttitle="Wickoff Check Pattern [Misu]", overlay=true)
// import Fontiramisu/fontLib/80 as fontilab
import Fontiramisu/fontilab/8 as fontilab
// -------- Find dev pivots ---------- [
// -- Var user input --
var devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
var depthTooltip = "The minimum number of bars that will be taken into account when analyzing pivots."
thresholdMultiplier = input.float(title="Deviation", defval=2.5, step=0.1, minval=0, tooltip=devTooltip, group="Pivot")
depth = input.int(title="Depth", defval=10, minval=1, tooltip=depthTooltip, group="Pivot")
// Prepare pivot variables
var line lineLast = na
var int iLast = 0 // Index last
var int iPrev = 0 // Index previous
var float pLast = 0 // Price last
var float pLastHigh = 0 // Price last
var float pLastLow = 0 // Price last
var isHighLast = false // If false then the last pivot was a pivot low
isPivotUpdate = false
// Get pivot information from dev pivot finding function
[dupLineLast, dupIsHighLast, dupIPrev, dupILast, dupPLast, dupPLastHigh, dupPLastLow] =
fontilab.getDeviationPivots(thresholdMultiplier, depth, lineLast, isHighLast, iLast, pLast, true, close, high, low)
if not na(dupIsHighLast)
lineLast := dupLineLast
isHighLast := dupIsHighLast
iPrev := dupIPrev
iLast := dupILast
pLast := dupPLast
pLastHigh := dupPLastHigh
pLastLow := dupPLastLow
isPivotUpdate := true
// Plot.
// Get last Pivots.
var highP = 0.0
var lowP = 0.0
var midP = 0.0
highP := isHighLast ? pLast : highP
lowP := not isHighLast ? pLast : lowP
midP := (highP + lowP)/2
// ] -------- Input Vars --------------- [.
wickoffMode = input.string("both", title="Wickoff Mode", options=["counter pattern", "breakout pattern", "both"], group="Wickoff Mode")
lenghtSizeAvgBody = input.int(9, title="Lenght Avg Body", group="Breakouts Settings")
firstBreakoutFactor = input.float(0.2, step=0.1, title="First Breakout Factor", tooltip="Factor used to validate the first breakout of the V pattern", group="Breakouts Settings")
lenghtWickValidation = input.int(10, title="Lenght Avg Wick Validation", group="Wickoff Settings")
factorWickValidation = input.float(1.5, step=0.1, title="Factor Avg Wick Validation", group="Wickoff Settings")
maxNbBarsValidWickoff = input.int(9, title="Max Bars Wickoff", group="Wickoff Settings")
// ] -------- Logical Vars ------------- [
// Confirm V pattern vars.
var biLastBreakHigh = 0
var biLastBreakLow = 0
var lastBreakHigh = 0.0
var lastBreakLow = 0.0
var hBreakInProgress = false
var lBreakInProgress = false
var indexPotWickoffH = 0
var indexPotWickoffL = 0
isWickoffHBull = false
isWickoffHBear = false
isWickoffLBull = false
isWickoffLBear = false
// ] -------- Util Functions ----------- [
// Cond Vars.
_bodyHi = math.max(close, open)
_bodyLo = math.min(close, open)
_body = _bodyHi - _bodyLo
_bodyAvg = ta.ema(_body, lenghtSizeAvgBody)
_longBody = _body > _bodyAvg
_upperWick = high - _bodyHi
_greenBody = open < close
_redBody = open > close
_highWick = high - _bodyHi
_lowWick = _bodyLo - low
_avgHighWick = ta.sma(_highWick, lenghtWickValidation)
_avgLowWick = ta.sma(_lowWick, lenghtWickValidation)
// COND: Potential Breakout pattern.
_breakUnderLowP = ta.crossunder(close, lowP) and _body > _bodyAvg * firstBreakoutFactor
_breakAboveHighP = ta.crossover(close, highP) and _body > _bodyAvg * firstBreakoutFactor
// @function detect wickoff.
isWickCrossPattern (src, isCrossUp, factor) =>
isCross = false
if isCrossUp
isCross := _bodyHi < src and src < high and _highWick > _avgHighWick * factor
else
isCross := low < src and src < _bodyLo and _lowWick > _avgLowWick * factor
isCross
// ] -------- Logical Script ----------- [
// Vars used to know current breaking levels.
lastBreakHigh := _breakAboveHighP ? highP : lastBreakHigh
lastBreakLow := _breakUnderLowP ? lowP : lastBreakLow
biLastBreakHigh := _breakAboveHighP ? bar_index : biLastBreakHigh
biLastBreakLow := _breakUnderLowP ? bar_index : biLastBreakLow
// Invalidate wickoff if max nb bars.
isMaxBarHigh = bar_index - biLastBreakHigh > maxNbBarsValidWickoff
isMaxBarLow = bar_index - biLastBreakLow > maxNbBarsValidWickoff
// Define break available.
hBreakInProgress := _breakAboveHighP or not isMaxBarHigh
lBreakInProgress := _breakUnderLowP or not isMaxBarLow
// Invalidate wickoff other conditions
isWickoffHBull := hBreakInProgress and isWickCrossPattern(lastBreakHigh, false, factorWickValidation)
isWickoffHBear := hBreakInProgress and isWickCrossPattern(lastBreakHigh, true, factorWickValidation)
isWickoffLBull := lBreakInProgress and isWickCrossPattern(lastBreakLow, false, factorWickValidation)
isWickoffLBear := lBreakInProgress and isWickCrossPattern(lastBreakLow, true, factorWickValidation)
// ] -------- Plot Part & Alerts ------- [
midPPlot = plot(midP, title='Mid Pivot', linewidth=1, color=color.yellow, display=display.none)
highPlot = plot(highP, title='High Pivot', linewidth=1, color=color.red, display=display.none)
lowPlot = plot(lowP, title='Low Pivot', linewidth=1, color=color.green, display=display.none)
if _breakUnderLowP
line.new(bar_index - 5, lowP, bar_index + maxNbBarsValidWickoff, lowP, xloc=xloc.bar_index, color=color.white, width=2)
if _breakAboveHighP
line.new(bar_index - 5, highP, bar_index + maxNbBarsValidWickoff, highP, xloc=xloc.bar_index, color=color.white, width=2)
if isWickoffHBull and wickoffMode != "counter pattern"
label.new(x = bar_index, y = low - (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "W", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center)
else if isWickoffLBull and wickoffMode != "breakout pattern"
label.new(x = bar_index, y = low - (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "W", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center)
else if isWickoffHBear and wickoffMode != "breakout pattern"
label.new(x = bar_index, y = high + (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "W", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center)
else if isWickoffLBear and wickoffMode != "counter pattern"
label.new(x = bar_index, y = high + (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "W", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center)
// ] |
energies_correlation_zscore | https://www.tradingview.com/script/6TtYPkbw-energies-correlation-zscore/ | voided | https://www.tradingview.com/u/voided/ | 11 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© voided
//@version=5
indicator("energies_correlation_zscore", overlay = true)
timeframe = input.timeframe("30")
window = input(48, "window")
type = input.string(title = "type", options = [ "zscore", "correlation" ], defval = "zscore")
ho = request.security("HO1!", timeframe, close)
rb = request.security("RB1!", timeframe, close)
cl = request.security("CL1!", timeframe, close)
ng = request.security("NG1!", timeframe, close)
var ho_rb_arr = array.new_float()
var ho_cl_arr = array.new_float()
var ho_ng_arr = array.new_float()
var rb_ho_arr = array.new_float()
var rb_cl_arr = array.new_float()
var rb_ng_arr = array.new_float()
var cl_ho_arr = array.new_float()
var cl_rb_arr = array.new_float()
var cl_ng_arr = array.new_float()
var ng_ho_arr = array.new_float()
var ng_rb_arr = array.new_float()
var ng_cl_arr = array.new_float()
ho_rb = ta.correlation(ho, rb, window)
ho_cl = ta.correlation(ho, cl, window)
ho_ng = ta.correlation(ho, ng, window)
array.push(ho_rb_arr, ho_rb)
array.push(ho_cl_arr, ho_cl)
array.push(ho_ng_arr, ho_ng)
rb_ho = ta.correlation(rb, ho, window)
rb_cl = ta.correlation(rb, cl, window)
rb_ng = ta.correlation(rb, ng, window)
array.push(rb_ho_arr, rb_ho)
array.push(rb_cl_arr, rb_cl)
array.push(rb_ng_arr, rb_ng)
cl_ho = ta.correlation(cl, ho, window)
cl_rb = ta.correlation(cl, rb, window)
cl_ng = ta.correlation(cl, ng, window)
array.push(cl_ho_arr, cl_ho)
array.push(cl_rb_arr, cl_rb)
array.push(cl_ng_arr, cl_ng)
ng_ho = ta.correlation(ng, ho, window)
ng_rb = ta.correlation(ng, rb, window)
ng_cl = ta.correlation(ng, cl, window)
array.push(ng_ho_arr, ng_ho)
array.push(ng_rb_arr, ng_rb)
array.push(ng_cl_arr, ng_cl)
if barstate.islast
fmt = "#.##"
t = table.new(position.bottom_right, 5, 5)
table.cell(t, 0, 0, type)
table.cell(t, 0, 1, "ho")
table.cell(t, 0, 2, "rb")
table.cell(t, 0, 3, "ng")
table.cell(t, 0, 4, "cl")
table.cell(t, 1, 0, "ho")
table.cell(t, 2, 0, "rb")
table.cell(t, 3, 0, "ng")
table.cell(t, 4, 0, "cl")
table.cell(t, 1, 1, "-")
table.cell(t, 2, 2, "-")
table.cell(t, 3, 3, "-")
table.cell(t, 4, 4, "-")
if type == "zscore"
table.cell(t, 1, 2, str.tostring((ho_rb - array.avg(ho_rb_arr)) / array.stdev(ho_rb_arr), fmt))
table.cell(t, 1, 3, str.tostring((ho_cl - array.avg(ho_cl_arr)) / array.stdev(ho_cl_arr), fmt))
table.cell(t, 1, 4, str.tostring((ho_ng - array.avg(ho_ng_arr)) / array.stdev(ho_ng_arr), fmt))
table.cell(t, 2, 1, str.tostring((rb_ho - array.avg(rb_ho_arr)) / array.stdev(rb_ho_arr), fmt))
table.cell(t, 2, 3, str.tostring((rb_cl - array.avg(rb_cl_arr)) / array.stdev(rb_cl_arr), fmt))
table.cell(t, 2, 4, str.tostring((rb_ng - array.avg(rb_ng_arr)) / array.stdev(rb_ng_arr), fmt))
table.cell(t, 3, 1, str.tostring((cl_ho - array.avg(cl_ho_arr)) / array.stdev(cl_ho_arr), fmt))
table.cell(t, 3, 2, str.tostring((cl_rb - array.avg(cl_rb_arr)) / array.stdev(cl_rb_arr), fmt))
table.cell(t, 3, 4, str.tostring((cl_ng - array.avg(cl_ng_arr)) / array.stdev(cl_ng_arr), fmt))
table.cell(t, 4, 1, str.tostring((ng_ho - array.avg(ng_ho_arr)) / array.stdev(ng_ho_arr), fmt))
table.cell(t, 4, 2, str.tostring((ng_rb - array.avg(ng_rb_arr)) / array.stdev(ng_rb_arr), fmt))
table.cell(t, 4, 3, str.tostring((ng_cl - array.avg(ng_cl_arr)) / array.stdev(ng_cl_arr), fmt))
else
table.cell(t, 1, 2, str.tostring(ho_rb, fmt))
table.cell(t, 1, 3, str.tostring(ho_cl, fmt))
table.cell(t, 1, 4, str.tostring(ho_ng, fmt))
table.cell(t, 2, 1, str.tostring(rb_ho, fmt))
table.cell(t, 2, 3, str.tostring(rb_cl, fmt))
table.cell(t, 2, 4, str.tostring(rb_ng, fmt))
table.cell(t, 3, 1, str.tostring(cl_ho, fmt))
table.cell(t, 3, 2, str.tostring(cl_rb, fmt))
table.cell(t, 3, 4, str.tostring(cl_ng, fmt))
table.cell(t, 4, 1, str.tostring(ng_ho, fmt))
table.cell(t, 4, 2, str.tostring(ng_rb, fmt))
table.cell(t, 4, 3, str.tostring(ng_cl, fmt))
|
two_leg_spread_returns_zscore | https://www.tradingview.com/script/kqELdHnr-two-leg-spread-returns-zscore/ | voided | https://www.tradingview.com/u/voided/ | 23 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© voided
//@version=5
indicator("two_leg_spread_returns_zscore")
timeframe = input.timeframe("5", "timeframe")
leg1_sym = input.symbol("RB1!", "leg1_sym")
leg2_sym = input.symbol("HO1!", "leg2_sym")
ma_length = input.int(48, "ma_length")
leg1 = request.security(leg1_sym, timeframe, close)
leg2 = request.security(leg2_sym, timeframe, close)
leg1_log_return = math.log(leg1 / leg1[1])
leg2_log_return = math.log(leg2 / leg2[1])
var leg1_returns = array.new_float()
var leg2_returns = array.new_float()
array.push(leg1_returns, leg1_log_return)
array.push(leg2_returns, leg2_log_return)
leg1_zscore = (leg1_log_return - array.avg(leg1_returns)) / array.stdev(leg1_returns)
leg2_zscore = (leg2_log_return - array.avg(leg2_returns)) / array.stdev(leg2_returns)
diff = ta.ema(leg1_zscore - leg2_zscore, ma_length)
bgcolor(leg1_zscore > 0 and leg2_zscore < 0 ? color.new(color.blue, 95) : leg1_zscore < 0 and leg2_zscore > 0 ? color.new(color.orange, 95) : color.new(color.white, 100))
plot(leg1_zscore, style = plot.style_histogram, color = color.new(color.blue, 50))
plot(leg2_zscore, style = plot.style_histogram, color = color.new(color.orange, 50))
plot(0, color = color.new(color.gray, 50))
plot(diff, color = diff > 0 ? color.blue : diff < 0 ? color.orange : color.gray) |
Clutter Fitler [Loxx] | https://www.tradingview.com/script/EKxb54qT-Clutter-Fitler-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 102 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Clutter Fitler [Loxx]",
shorttitle = "CF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
src = input.source(close, "Source", group = "Basic Settings")
sth = input.float(0.2, "Threshold", group = "Basic Settings", step = 0.01)
per = input.int(30, "Period", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
out = ta.ema(src, per)
filtTrend = clutterFilt(out, sth)
colorout = filtTrend ? (out > out[1] ? greencolor : out < out[1] ? redcolor : color.gray) : color.gray
plot(out, color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na) |
Adaptive-Lookback Stochastic [Loxx] | https://www.tradingview.com/script/0bppwdzK-Adaptive-Lookback-Stochastic-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 112 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Adaptive-Lookback Stochastic [Loxx]",
overlay = false,
shorttitle='ALBSTOCH [Loxx]',
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Middle Crosses'
SM04 = 'Levels Crosses'
_albper(swingCount, speed)=>
swing = 0.
if bar_index > 3
if (high > nz(high[1]) and
nz(high[1]) > nz(high[2]) and
nz(low[2]) < nz(low[3]) and
nz(low[3]) < nz(low[4]))
swing := -1
if (low < nz(low[1]) and
nz(low[1]) < nz(low[2]) and
nz(high[2]) > nz(high[3]) and
nz(high[3]) > nz(high[4]))
swing := 1
swingBuffer = swing
k = 0, n = 0
while (k < bar_index) and (n < swingCount)
if(swingBuffer[k] != 0)
n += 1
k += 1
albPeriod = math.max(math.round((speed != 0 and swingCount != 0) ? k/swingCount/speed : k/swingCount), 1)
albPeriod
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
inpSlowing = input.int(3, "Slowing Period", group = "Basic Settings")
swingCount = input.int(5, "ALB Swing Count", group = "Adaptive Lookback Settings")
speed = input.float(.1, "ALB Speed", minval = 0., step = 0.01, group = "Adaptive Lookback Settings")
lvlup = input.int(80, "Upper Level", group = "Levels Settings")
lvldn = input.int(20, "Bottom Level", group = "Levels Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
albper = _albper(swingCount, speed)
mi = ta.lowest(src, albper)
ma = ta.highest(src, albper)
sumlow = 0.
sumhigh = 0.
for k = 0 to inpSlowing - 1
sumlow += nz(src[k]) - nz(mi[k])
sumhigh += nz(ma[k]) - nz(mi[k])
stoch = 100.0 * sumlow/sumhigh
sigval = stoch[1]
mid = 50
state = 0.
if sigtype == SM02
if (stoch < sigval)
state :=-1
if (stoch > sigval)
state := 1
else if sigtype == SM03
if (stoch < mid)
state :=-1
if (stoch > mid)
state := 1
else if sigtype == SM04
if (stoch < lvldn)
state := -1
if (stoch > lvlup)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(stoch, "Stochastic", color = colorout, linewidth = 2)
plot(lvlup, "Overbought", color = bar_index % 2 ? color.gray : na)
plot(lvldn, "Oversold", color = bar_index % 2 ? color.gray : na)
plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(stoch, sigval) : sigtype == SM03 ? ta.crossover(stoch, mid) : ta.crossover(stoch, lvlup)
goShort = sigtype == SM02 ? ta.crossunder(stoch, sigval) : sigtype == SM03 ? ta.crossunder(stoch, mid) : ta.crossunder(stoch, lvldn)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Adaptive-Lookback Stochastic [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Adaptive-Lookback Stochastic [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Adaptive Deviation [Loxx] | https://www.tradingview.com/script/To2emkFR-Adaptive-Deviation-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 27 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Adaptive Deviation [Loxx]",
overlay = false,
shorttitle='AD [Loxx]',
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
adaptiveDeviation(float price, int per)=>
float m_per = (per > 1) ? per : 1
float m_fastEnd = math.max(m_per / 2.0, 1)
float m_slowEnd = m_per * 5
float m_perDiff = m_slowEnd - m_fastEnd
float difference = math.abs(ta.change(price))
float signal = 0.
float noise = 0.
if bar_index > m_per
signal := math.abs(price - nz(price[m_per]))
noise := nz(noise[1]) + difference - nz(difference[m_per])
else
for k = 0 to m_per - 1
noise += nz(difference[k])
float averageper = (signal /noise) * m_perDiff + m_fastEnd
float alpha = 2.0 / (1.0 + averageper)
float ema0 = 0., float ema1 = 0.
ema0 := nz(ema0[1]) + alpha * (price - nz(ema0[1]))
ema1 := nz(ema1[1]) + alpha * (price * price - nz(ema1[1]))
float out = math.sqrt(averageper * (ema1 - ema0 * ema0) / math.max(averageper - 1, 1))
out
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
inpper = input.int(20, "Period", group = "Basic Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = adaptiveDeviation(src, inpper)
rout = ta.stdev(src, inpper)
plot(out, "Adaptive Deviation", color = greencolor, linewidth = 2)
plot(rout, "Standard Deviation", color = color.white, linewidth = 1)
|
Shadow Compact Volume BETA | https://www.tradingview.com/script/2PKgyJZu/ | PaulVuMinh | https://www.tradingview.com/u/PaulVuMinh/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© PaulVM
//@version=5
indicator("Shadow Compact Volume BETA", shorttitle = "SCV - BETA", overlay = false)
lenght = input.int(minval = 5,defval = 24, title="Lenght")
upHidden = 0.0
dnHidden = 0.0
mainVol = 0.0
mainVol := (close - open) * 1000 / 3
candleDirection = open < close ? 1 : 0 // 1 up 0 down
upHidden := (candleDirection ? (open - low) : (close - low)) * 1000
dnHidden := (candleDirection ? (high - close) : (high - open)) * 1000
realPowerUp = upHidden/3 + (mainVol > 0 ? mainVol : 0)
realPowerDn = -1*dnHidden/3 + (mainVol < 0 ? mainVol : 0)
plot(mainVol, style=plot.style_columns, color=color.yellow)
plot(realPowerUp, style=plot.style_columns, color=color.green)
plot(realPowerDn, style=plot.style_columns, color=color.red)
|
vol_cone | https://www.tradingview.com/script/8UKvXuyX-vol-cone/ | voided | https://www.tradingview.com/u/voided/ | 82 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© voided
//@version=5
indicator("vol_cone", overlay = true, max_lines_count = 500)
stdevs = input.float(title = "stdevs", defval = 1.0)
stdevs_2 = input.float(title = "stdevs_2", defval = 2.0)
pp = input.int(title = "periods to project", defval = 1)
window = input.int(title = "window", defval = 21)
ppy = input.int(title = "periods per year", defval = 252)
history = input.bool(title = "show history", defval = false)
rate = input.float(title = "interest rate", defval = 3.0) / 100
lags = input.int(title = "lags", defval = 0)
show_stdevs_2 = input.bool(title = "show_stdevs_2", defval = true)
anchor = input.bool(title = "anchor_to_session_start", defval = false)
var rvs = array.new_float()
squared_returns = math.pow(math.log(close / close[1]), 2.0)
smoothed_returns = ta.ema(squared_returns, window)
rv = math.sqrt(smoothed_returns * ppy)
array.push(rvs, rv)
upper = close * (1 + rv * stdevs * math.sqrt(pp / ppy))
lower = close * (1 - rv * stdevs * math.sqrt(pp / ppy))
var fcst = array.new_int()
array.push(fcst, close <= upper[pp] and close >= lower[pp] ? 1 : 0)
hist_transp = history ? 0 : 100
hist_upper = close > upper[pp] ? color.new(color.red, hist_transp) : color.new(color.blue, hist_transp)
hist_lower = close < lower[pp] ? color.new(color.red, hist_transp) : color.new(color.blue, hist_transp)
plot(upper[pp], title = "upper bound", color = hist_upper, style = plot.style_stepline)
plot(lower[pp], title = "upper bound", color = hist_lower, style = plot.style_stepline)
one_year_ms = 252 * 24 * 60 * 60 * 1000
res = 100
var lns_up = array.new_line()
var lns_dn = array.new_line()
var lns_up_2 = array.new_line()
var lns_dn_2 = array.new_line()
while array.size(lns_up) < pp
for i = 0 to pp - 1
array.push(lns_up, line.new(x1 = 0, x2 = 0, y1 = 0, y2 = 0, xloc = xloc.bar_index))
array.push(lns_dn, line.new(x1 = 0, x2 = 0, y1 = 0, y2 = 0, xloc = xloc.bar_index))
array.push(lns_up_2, line.new(x1 = 0, x2 = 0, y1 = 0, y2 = 0, xloc = xloc.bar_index, color = color.red))
array.push(lns_dn_2, line.new(x1 = 0, x2 = 0, y1 = 0, y2 = 0, xloc = xloc.bar_index, color = color.red))
if barstate.islast
pct_rnk = array.percentrank(rvs, array.indexof(rvs, rv))
acc = array.avg(fcst) * 100
if anchor and timeframe.isintraday
for i = 0 to 5000
if time[i + 1] - time[i + 2] != time[i + 2] - time[i + 3]
lags := i + 2
break
x0 = bar_index[lags]
y0_up = close[lags]
y0_up_2 = close[lags]
y0_dn = close[lags]
y0_dn_2 = close[lags]
dy_up = 0.0
dy_up_2 = 0.0
dy_dn = 0.0
dy_dn_2 = 0.0
fp = 0.0
for i = 0 to pp - 1
fp := close[lags] * math.exp(rate * (i + 1) * 1 / ppy)
dy_up := fp * math.exp(rv * stdevs * math.sqrt((i + 1) * 1 / ppy)) - y0_up
dy_dn := y0_dn - fp / math.exp(rv * stdevs * math.sqrt((i + 1) * 1 / ppy))
dy_up_2 := fp * math.exp(rv * stdevs_2 * math.sqrt((i + 1) * 1 / ppy)) - y0_up_2
dy_dn_2 := y0_dn_2 - fp / math.exp(rv * stdevs_2 * math.sqrt((i + 1) * 1 / ppy))
up_ln = array.get(lns_up, i)
dn_ln = array.get(lns_dn, i)
line.set_x1(up_ln, x0)
line.set_x2(up_ln, x0 + 1)
line.set_y1(up_ln, y0_up)
line.set_y2(up_ln, y0_up + dy_up)
line.set_x1(dn_ln, x0)
line.set_x2(dn_ln, x0 + 1)
line.set_y1(dn_ln, y0_dn)
line.set_y2(dn_ln, y0_dn - dy_dn)
if show_stdevs_2
up_ln_2 = array.get(lns_up_2, i)
dn_ln_2 = array.get(lns_dn_2, i)
line.set_x1(up_ln_2, x0)
line.set_x2(up_ln_2, x0 + 1)
line.set_y1(up_ln_2, y0_up_2)
line.set_y2(up_ln_2, y0_up_2 + dy_up_2)
line.set_x1(dn_ln_2, x0)
line.set_x2(dn_ln_2, x0 + 1)
line.set_y1(dn_ln_2, y0_dn_2)
line.set_y2(dn_ln_2, y0_dn_2 - dy_dn_2)
x0 := x0 + 1
y0_up := y0_up + dy_up
y0_dn := y0_dn - dy_dn
y0_up_2 := y0_up_2 + dy_up_2
y0_dn_2 := y0_dn_2 - dy_dn_2
var t = table.new(position = position.top_right, columns = 2, rows = 7)
table.cell(t, 0, 0, text = "rv")
table.cell(t, 0, 1, text = "rnk")
table.cell(t, 0, 2, text = "acc")
table.cell(t, 0, 3, text = "up")
table.cell(t, 0, 4, text = "dn")
table.cell(t, 1, 0, text = str.format("{0, number, #.#}", rv * 100))
table.cell(t, 1, 1, text = str.format("{0, number, #.#}", pct_rnk))
table.cell(t, 1, 2, text = str.format("{0, number, #.#}", acc))
table.cell(t, 1, 3, text = str.format("{0, number, #.####}", y0_up + dy_up))
table.cell(t, 1, 4, text = str.format("{0, number, #.####}", y0_dn - dy_dn))
if show_stdevs_2
table.cell(t, 0, 5, text = "up_2")
table.cell(t, 0, 6, text = "dn_2")
table.cell(t, 1, 5, text = str.format("{0, number, #.####}", y0_up_2 + dy_up_2))
table.cell(t, 1, 6, text = str.format("{0, number, #.####}", y0_dn_2 - dy_dn_2))
|
Tallrye Alerts | https://www.tradingview.com/script/qUPxitTg-Tallrye-Alerts/ | tallrye | https://www.tradingview.com/u/tallrye/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© tallrye
//@version=5
indicator(title="Tallrye Exponential Moving Average", overlay=true)
//volumeFrom = volume
//volumeAverage = ta.ema(volumeFrom, 20)
//volumeCrossover = ta.crossover(volumeFrom, volumeAverage)
//signalOnVolume = if volumeCrossover == true
// input.int(1,title="signalOnVolumeTrue")
//else
// input.int(0,title="signalOnVolumeFalse")
// Input options
//renko_tickerid = ticker.renko(syminfo.tickerid, "ATR", 12)
//renko_close = request.security(renko_tickerid, timeframe.period, close)
averageData = input.source(close, title="Average Data Source")
fastLength = input.int(5, title="Fast Average Length")
slowLength = input.int(21, title="Slow Average Length")
// Calculate exponential moving averages
fastAverage = ta.ema(averageData, fastLength)
slowAverage = ta.ema(averageData, slowLength)
fastCrossover = ta.crossover(fastAverage, slowAverage)
reverseCrossover = ta.crossover(slowAverage, fastAverage)
//plot(fastAverage, color=color.navy, linewidth=2, title="Hizli EMA")
//plot(slowAverage, color=color.fuchsia, linewidth=2, title="Yavas EMA")
// Plot averages
signalOnFast = if fastCrossover == true
input.int(1,title="SignalOnFastTrue")
else
input.int(0,title="SignalOnFastFalse")
signalOnSlow = if reverseCrossover == true
input.int(1,title="SignalOnSlowTrue")
else
input.int(0,title="SignalOnSlowFalse")
//plot(signalOnVolume == 1 ? fastAverage : na, "Enough Volume", color=color.blue, linewidth=7)
//plotshape(signalOnVolume == 1 ? slowAverage : na, title="Enough Volume Begins", location=location.absolute, style=shape.circle, size=size.small, color=color.yellow)
//plot(signalOnFast == 1 ? fastAverage : na, "Buy Signal", color=color.blue, linewidth=7)
//plot(signalOnSlow == 1 ? slowAverage : na, "Sell Signal", color=color.red, linewidth=7)
plotshape(signalOnFast ? fastAverage : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.small, color=color.green)
plotshape(signalOnSlow ? slowAverage : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.small, color=color.red)
alertcondition(signalOnFast, title="Cagatay Buy", message="Cagatay Buy!")
alertcondition(signalOnSlow, title="Cagatay Sell", message="Cagatay Sell!")
// Show the moving average trend with a coloured background
backgroundColor = if fastCrossover == true
color.new(color.fuchsia, 85)
else if reverseCrossover == true
color.new(color.red, 80)
bgcolor(backgroundColor, title="EMA Background")
|
Relative Strength/Zero Line/UP/DOWN | https://www.tradingview.com/script/35FSQjeK-Relative-Strength-Zero-Line-UP-DOWN/ | amandeepjha8 | https://www.tradingview.com/u/amandeepjha8/ | 19 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Inspired from Β© bharatTrader
//@version=4
study("Dynamic Relative Strength", shorttitle="Dynamic Relative Strength")
//Input
source = input(title="Source", type=input.source, defval=close)
comparativeTickerId = input("NSE:CNXSMALLCAP", type=input.symbol, title="Comparative Symbol")
length = input(123, type=input.integer, minval=1, title="Daily Period")
inpLen2 = input(52, title= 'Weekly Period')
length := timeframe.isweekly ? inpLen2 : length
Monthly = input(10, title='Monthly Period')
length := timeframe.ismonthly ? Monthly : length
// Other Settings
showZeroLine = input(defval=true, type=input.bool, title="Show Zero Line")
showRefDateLbl = input(defval=false, type=input.bool, title="Show Reference Label")
toggleRSColor = input(defval=true, type=input.bool, title="Toggle RS color on crossovers")
showRSTrend = input(defval=false, type=input.bool, title="RS Trend,", group="RS Trend", inline="RS Trend")
base = input(title="Range", minval=1, defval=5, group="RS Trend", inline="RS Trend")
showMA = input(defval=false, type=input.bool, title="Show Moving Average,", group="RS Mean", inline="RS Mean")
lengthMA = input(61, type=input.integer, minval=1, title="Period", group="RS Mean", inline="RS Mean")
//Set up
baseSymbol = security(syminfo.tickerid, timeframe.period, source)
comparativeSymbol = security(comparativeTickerId, timeframe.period, source)
//Calculations
res = ((baseSymbol/baseSymbol[length])/(comparativeSymbol/comparativeSymbol[length]) - 1)
resColor = toggleRSColor ? res > 0 ? color.green : color.red : color.blue
refDay = showRefDateLbl and barstate.islast ? dayofmonth(time[length]) : na
refMonth = showRefDateLbl and barstate.islast ? month(time[length]) : na
refYear = showRefDateLbl and barstate.islast ? year(time[length]) : na
refLabelStyle = res[length] > 0 ? label.style_label_up : label.style_label_down
refDateLabel = showRefDateLbl and barstate.islast ? label.new(bar_index - length, 0, text="RS-" + tostring(length) + " reference, " + tostring(refDay) + "-" + tostring(refMonth) + "-" + tostring(refYear), color=color.blue, style=refLabelStyle, yloc=yloc.price) : na
y0 = res - res[base]
angle0 = atan(y0/base) // radians
zeroLineColor = iff(showRSTrend, angle0 > 0.0 ? color.green : color.maroon, color.maroon)
//Plot
plot(showZeroLine ? 0 : na, linewidth=2, color=zeroLineColor, title="Zero Line / RS Trend")
plot(res, title="RS", linewidth=2, color= resColor)
plot(showMA ? sma(res, lengthMA) : na, color=color.gray, title="MA") |
Mulitiple time frame Slow Stochastic Jamila | https://www.tradingview.com/script/jUT2hA4l-Mulitiple-time-frame-Slow-Stochastic-Jamila/ | Cape1303 | https://www.tradingview.com/u/Cape1303/ | 22 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Cape1303
//@version=4
study(title="Slow Stochastic 3 time frame", shorttitle="SlowStochDWM")
smoothK = input(14, minval=1), smoothD = input(3, minval=1)
k = sma(stoch(close, high, low, smoothK), 3)
d = sma(k, smoothD)
plot(d, color=color.white, title="daily")
//plot(d, color=color.red)
plot(security(syminfo.tickerid, "D", d), color=color.white, title="1Day")
plot(security(syminfo.tickerid, "3D", d), color=color.blue, title="3Day")
plot(security(syminfo.tickerid, "W", d), color=color.green, title="1week")
//plot(security(syminfo.tickerid, "2W",d), color=color.aqua, title="2weeks")
plot(security(syminfo.tickerid, "M", d), color=color.yellow, title="Month")
h0 = hline(80)
h1 = hline(20)
h2 = hline(50)
fill(h0, h1, color=color.purple, transp=95) |
Katusabe Double MA | https://www.tradingview.com/script/f6n1iPFO-Katusabe-Double-MA/ | Isaac_katusabe | https://www.tradingview.com/u/Isaac_katusabe/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Isaac_katusabe
//@version=5
indicator("Katusabe Double MA", overlay=true )
float a = 5
ema20 = ta.ema(close, 20)
ema50 = ta.ema(close, 50)
plot(ema20, title="20", color=#D8860E, linewidth=1)
plot(ema50, title="50", color=#5034A2, linewidth=1)
|
Heiken Ashi smoothed | https://www.tradingview.com/script/LbqgHYDP/ | nomnol | https://www.tradingview.com/u/nomnol/ | 52 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© nomnol
//@version=5
indicator(title = "Heiken Ashi smoothed", shorttitle="HA smoothed", overlay=true)
// === Input ===
ma1_len = input(6, title="MA 01")
ma1_type = input.string("SMMA", "ma1_type", options=["SMA", "EMA", "SMMA", "LWMA", "ALMA", "HMA"])
ma2_len = input(2, title="MA 02")
ma2_type = input.string("LWMA", "ma2_type", options=["SMA", "EMA", "SMMA", "LWMA", "ALMA", "HMA"])
// === MA 01 Filter ===
ma1_o = 0.0
ma1_h = 0.0
ma1_l = 0.0
ma1_c = 0.0
if ma1_type == "SMA"
ma1_o := ta.sma(open, ma1_len)
ma1_h := ta.sma(high, ma1_len)
ma1_l := ta.sma(low, ma1_len)
ma1_c := ta.sma(close, ma1_len)
else if ma1_type == "EMA"
ma1_o := ta.ema(open, ma1_len)
ma1_h := ta.ema(high, ma1_len)
ma1_l := ta.ema(low, ma1_len)
ma1_c := ta.ema(close, ma1_len)
else if ma1_type == "SMMA"
ma1_o := ta.rma(open, ma1_len)
ma1_h := ta.rma(high, ma1_len)
ma1_l := ta.rma(low, ma1_len)
ma1_c := ta.rma(close, ma1_len)
else if ma1_type == "LWMA"
ma1_o := ta.wma(open, ma1_len)
ma1_h := ta.wma(high, ma1_len)
ma1_l := ta.wma(low, ma1_len)
ma1_c := ta.wma(close, ma1_len)
else if ma1_type == "ALMA"
alma1_offset = 0.85 * (ma1_len - 1)
alma1_sigma = ma1_len / 6
ma1_o := ta.alma(open, ma1_len, alma1_offset, alma1_sigma)
ma1_h := ta.alma(high, ma1_len, alma1_offset, alma1_sigma)
ma1_l := ta.alma(low, ma1_len, alma1_offset, alma1_sigma)
ma1_c := ta.alma(close, ma1_len, alma1_offset, alma1_sigma)
else if ma1_type == "HMA"
ma1_o := ta.hma(open, ma1_len)
ma1_h := ta.hma(high, ma1_len)
ma1_l := ta.hma(low, ma1_len)
ma1_c := ta.hma(close, ma1_len)
// else if ma1_type == "SMMA"
// ma1_o := na(ma1_o[1]) ? ta.sma(open, ma1_len) : (ma1_o[1] * (ma1_len - 1) + open) / ma1_len
// ma1_h := na(ma1_h[1]) ? ta.sma(high, ma1_len) : (ma1_h[1] * (ma1_len - 1) + high) / ma1_len
// ma1_l := na(ma1_l[1]) ? ta.sma(low, ma1_len) : (ma1_l[1] * (ma1_len - 1) + low) / ma1_len
// ma1_c := na(ma1_c[1]) ? ta.sma(close, ma1_len) : (ma1_c[1] * (ma1_len - 1) + close) / ma1_len
// === PLOTITING===
// ma1_col=ma1_o>ma1_c ? color.red : color.green
// plotcandle(ma1_o, ma1_h, ma1_l, ma1_c, title="MA1", color=ma1_col)
// === HA calculator ===
ha_o = 0.0
ha_c = 0.0
ha_o := na(ha_o[1]) ? (ma1_o[1] + ma1_h[1] + ma1_l[1] + ma1_c[1]) / 4 : (ha_o[1] + ha_c[1]) / 2
ha_h = ma1_h
ha_l = ma1_l
ha_c := (ma1_o + ma1_h + ma1_l + ma1_c) / 4
// === PLOTITING===
// ha_col=ha_o>ha_c ? color.red : color.green
// plotcandle(ha_o, ha_h, ha_l, ha_c, title="HA", color=ha_col)
// === MA 02 Filter ===
ma2_o = 0.0
ma2_h = 0.0
ma2_l = 0.0
ma2_c = 0.0
if ma2_type == "SMA"
ma2_o := ta.sma(ha_o, ma2_len)
ma2_h := ta.sma(ha_h, ma2_len)
ma2_l := ta.sma(ha_l, ma2_len)
ma2_c := ta.sma(ha_c, ma2_len)
else if ma2_type == "EMA"
ma2_o := ta.ema(ha_o, ma2_len)
ma2_h := ta.ema(ha_h, ma2_len)
ma2_l := ta.ema(ha_l, ma2_len)
ma2_c := ta.ema(ha_c, ma2_len)
else if ma2_type == "SMMA"
ma2_o := ta.rma(ha_o, ma2_len)
ma2_h := ta.rma(ha_h, ma2_len)
ma2_l := ta.rma(ha_l, ma2_len)
ma2_c := ta.rma(ha_c, ma2_len)
else if ma2_type == "LWMA"
ma2_o := ta.wma(ha_o, ma2_len)
ma2_h := ta.wma(ha_h, ma2_len)
ma2_l := ta.wma(ha_l, ma2_len)
ma2_c := ta.wma(ha_c, ma2_len)
else if ma2_type == "ALMA"
alma2_offset = 0.85 * (ma2_len - 1)
alma2_sigma = ma2_len / 6
ma2_o := ta.alma(ha_o, ma2_len, alma2_offset, alma2_sigma)
ma2_h := ta.alma(ha_h, ma2_len, alma2_offset, alma2_sigma)
ma2_l := ta.alma(ha_l, ma2_len, alma2_offset, alma2_sigma)
ma2_c := ta.alma(ha_c, ma2_len, alma2_offset, alma2_sigma)
else if ma2_type == "HMA"
ma2_o := ta.hma(ha_o, ma2_len)
ma2_h := ta.hma(ha_h, ma2_len)
ma2_l := ta.hma(ha_l, ma2_len)
ma2_c := ta.hma(ha_c, ma2_len)
// === PLOTITING===
ma2_col=ma2_o>ma2_c ? color.red : color.green
plotcandle(ma2_o, ma2_h, ma2_l, ma2_c, title="HA Smoothed", color=ma2_col)
// === HA calculator ===
// ha_t = ticker.heikinashi(syminfo.tickerid)
// ha_p = timeframe.period
// ha_o = request.security(ha_t, ha_p, ma1_o)
// ha_h = request.security(ha_t, ha_p, ma1_h)
// ha_l = request.security(ha_t, ha_p, ma1_l)
// ha_c = request.security(ha_t, ha_p, ma1_c) |
Itakura-Saito Autoregressive Extrapolation of Price [Loxx] | https://www.tradingview.com/script/jqKfdXMa-Itakura-Saito-Autoregressive-Extrapolation-of-Price-Loxx/ | FilipDvoran | https://www.tradingview.com/u/FilipDvoran/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Itakura-Saito Autoregressive Extrapolation of Price [Loxx]",
shorttitle = "ISAGEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
bluecolor = #042dd2
_Geom(float[] x, int p)=>
int n = array.size(x)
float[] df = array.new<float>(n, 0.)
float[] db = array.new<float>(n, 0.)
float[] result = array.new<float>(n, 0.)
int kh = 0
int ki = 0
float tmp = 0.
float num = 0.
float denf = 0.
float denb = 0.
float r = 0.
for i = 0 to n - 1
array.set(df, i, array.get(x, i))
array.set(db, i, array.get(x, i))
//Main loop
for k = 1 to p
num := 0.
denf := 0.
denb := 0.
for i = k to n - 1
num += array.get(df, i) * array.get(db, i - 1)
denf += math.pow(array.get(df, i), 2)
denb += math.pow(array.get(db, i - 1), 2)
r := -num / math.sqrt(denf) / math.sqrt(denb)
//Calculate prediction coefficients
array.set(result, k, r)
kh := k / 2
for i = 1 to kh
ki := k - i
tmp := array.get(result, i)
array.set(result, i, array.get(result, i) + r * array.get(result, ki))
if (i != ki)
array.set(result, ki, array.get(result, ki) + r * tmp)
if (k < p)
for i = n - 1 to k
tmp1 = array.get(df, i)
array.set(df, i, array.get(df, i) + r * array.get(db, i - 1))
array.set(db, i, array.get(db, i - 1) + r * tmp1)
result
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Open", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
LastBar = input.int(30, "Last Bar", group = "Basic Settings", tooltip = "Bar from where to start prediction")
PastBars = input.int(300, "Past Bars", group = "Basic Settings", maxval = 2000)
LPOrder = input.float(0.6, "Order of Linear Prediction", group = "Basic Settings", minval = 0, maxval = 1, step = 0.01)
FutBars = input.int(100, "Future Bars", group = "Basic Settings", maxval = 500)
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
barcolor(colorbars ? color.gray : na)
int lb = LastBar
int np = PastBars
int no = math.ceil(LPOrder * PastBars)
int nf = np - no - 1
float[] x = array.new<float>(np, 0.)
float[] pv = array.new<float>(np, 0.)
float[] fv = array.new<float>(nf + 1, 0.)
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
cnp = np >= 250 ? 250 : np
cnf = nf >= 250 ? 250 : nf
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
//Prepare data
float av = 0.
avar = array.new<float>(np, 0.)
for i = 0 to np - 1
array.set(avar, i, nz(src[i + lb]))
av := array.avg(avar)
for i = 0 to np - 1
array.set(x, np - 1 - i, nz(src[i + lb]) - av)
//Use linear prediction _Geom
float[] result = _Geom(x, no)
//Calculate linear predictions
//Calculate linear predictions
for n = no to np + nf - 1
float sum = 0.
for i = 1 to no
if (n - i < np)
sum -= array.get(result, i) * array.get(x, n - i)
else
sum -= array.get(result, i) * array.get(fv, n - i - np + 1)
if (n < np)
array.set(pv, np - 1 - n, sum)
else
array.set(fv, n - np + 1, sum)
array.set(fv, 0, array.get(pv, 0))
for i = 0 to np - no - 1
array.set(pv, i, array.get(pv, i) + av)
array.set(fv, i, array.get(fv, i) + av)
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < np - no - 1 - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(pv, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
skipperfv = array.size(fv) >= 2000 ? 8 : array.size(fv) >= 1000 ? 4 : array.size(fv) >= 500 ? 2 : 1
i := 0
j := 0
outer = math.min(np - no - 1, FutBars)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(fv, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(fv, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1 |
Step Generalized Double DEMA (ATR based) [Loxx] | https://www.tradingview.com/script/s1ZjIZmo-Step-Generalized-Double-DEMA-ATR-based-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 569 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Step Generalized Double DEMA (ATR based) [Loxx]",
shorttitle="SGDDEMAATRB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
gdema(float price, float period, float volumeFactor)=>
float vol = (volumeFactor > 0) ? (volumeFactor > 1) ? 1 : volumeFactor : 0.01
float volpl = vol + 1
float alpha = 2.0 / (1.0 + (period > 1 ? period : 1))
float winst1 = 0., float winst2 = 0., float winst3 = 0., float winst4 = 0.
winst1 := nz(winst1[1]) + alpha * (price - nz(winst1[1]))
winst2 := nz(winst2[1]) + alpha * (winst1 - nz(winst2[1]))
winst3 := nz(winst3[1]) + alpha * ((winst1 * volpl - winst2 * vol) - nz(winst3[1]))
winst4 := nz(winst4[1]) + alpha * (winst3 - nz(winst4[1]))
winst = winst3 * volpl - winst4 * vol
winst
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Double DEMA period", group = "Basic Settings")
vf = input.float(.7, "Double DEMA volume factor", step = 0.1, minval = 0.1, group = "Basic Settings")
mult = input.float(20, "Step Size in % of ATR", group = "Basic Settings")
atrper = input.int(50, "ATR Period", group = "Basic Settings")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
multout = mult/100.0
atr = ta.atr(atrper)
val = gdema(src, per, vf)
stepSize = multout * atr
_diff = val - nz(val[1])
val := nz(val[1]) + ((_diff < stepSize and _diff > -stepSize) ? 0 : (_diff / stepSize) * stepSize)
goLong_pre = ta.crossover(val, val[1])
goShort_pre = ta.crossunder(val, val[1])
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plot(val,"SGDDEMA", color = contSwitch == 1 ? greencolor : redcolor, linewidth = 3)
barcolor(colorbars ? contSwitch == 1 ? greencolor : redcolor : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "Long", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "Short", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Step Generalized Double DEMA (ATR based) [Loxx]: Uptrend\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Step Generalized Double DEMA (ATR based) [Loxx]]: Downtrend\nSymbol: {{ticker}}\nPrice: {{close}}")
|
TSL_adch | https://www.tradingview.com/script/LGx7RQLG-TSL-adch/ | adch-1 | https://www.tradingview.com/u/adch-1/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© adch-1
//@version=5
indicator("TSL_adch", overlay=true)
a=math.max(high[1],high[2])
b=math.min(low[1],low[2])
c=close[1]
d=open[2]
e=math.avg(a,b,c,d)
//e=(a+b+c+d)/4
//e=high[1]
plot(e)
|
Black Scholes Option Pricing Model w/ Greeks [Loxx] | https://www.tradingview.com/script/WobQqSxF-Black-Scholes-Option-Pricing-Model-w-Greeks-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 521 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Black Scholes Option Pricing Model w/ Greeks [Loxx]",
shorttitle ="BSOPMG",
overlay = true,
max_lines_count = 500)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
//constants
color darkGreenColor = #1B7E02
string callString = "Call"
string putString = "Put"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
float[] sarr = array.new_float(0)
for i = 0 to per - 1
array.push(sarr, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
f_tickFormat() =>
_s = str.tostring(syminfo.mintick)
_s := str.replace_all(_s, '25', '00')
_s := str.replace_all(_s, '5', '0')
_s := str.replace_all(_s, '1', '0')
_s
// N(0,1) density
f(float x)=>
float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
out
// Boole's Rule
Boole(float StartPoint, float EndPoint, int n)=>
float[] X = array.new<float>(n + 1 , 0)
float[] Y = array.new<float>(n + 1 , 0)
float delta_x = (EndPoint - StartPoint) / n
for i = 0 to n
array.set(X, i, StartPoint + i * delta_x)
array.set(Y, i, f(array.get(X, i)))
float sum = 0
for t = 0 to (n - 1) / 4
int ind = 4 * t
sum += (1 / 45.0) *
(14 * array.get(Y, ind)
+ 64 * array.get(Y, ind + 1)
+ 24 * array.get(Y, ind + 2)
+ 64 * array.get(Y, ind + 3)
+ 14 * array.get(Y, ind + 4))
* delta_x
sum
// alternate function not used
// Waissi and Rossin normal cdf approximation
normCDF(float z)=>
float b1 = -0.0004406
float b2 = 0.0418198
float b3 = 0.9
out = 1.0 / (1.0 + math.exp(-math.sqrt(math.pi) * (b1 * math.pow(z, 5) + b2 * math.pow(z, 3) + b3 * z)))
out
// N(0,1) cdf by Boole's Rule
N(float x)=>
float out = Boole(-10.0, x, 240)
out
d1(float S, float K, float r, float q, float v, float T)=>
float d1 = (math.log(S / K) + T * (r - q + 0.5 * v * v)) / (v * math.sqrt(T))
d1
d2(float S, float K, float r, float q, float v, float T)=>
float d1 = (math.log(S / K) + T * (r - q + 0.5 * v * v)) / (v * math.sqrt(T))
d2 = d1 - v * math.sqrt(T)
d2
// Black-Scholes Option Price
BSPrice(float S, float K, float r, float T, float q, float v, string PutCall)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float call = S * math.exp(-q * T) * N(d1) - math.exp(-r * T) * K * N(d2)
float out = 0
out := PutCall == callString ? call : call - S * math.exp(-q * T) + K * math.exp(-r * T)
out
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 1Β° Order Greeks
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// Black-Scholes Delta or Spot Delta
BSDelta(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float out = OpType == callString ? math.exp(-q * T) * N(d1) : math.exp(-q * T) * (N(d1) - 1)
out
// Black-Scholes Vega or Zeta
BSVega(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float out = S * math.exp(-q * T) * f(d1) * math.sqrt(T)
out
// Black-Scholes Theta
BSTheta(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float b = r - q
float num = S * math.exp((b - r) * T) * f(d1) * v
float dom = 2 * math.sqrt(T)
float mult1 = 0
float mult2 = 0
float out = 0
if (OpType == callString)
mult1 := (b - r) * S * math.exp((b - r) * T) * N(d1)
mult2 := r * K * math.exp(-r * T) * N(d2)
out := -num / dom - mult1 - mult2
else
mult1 := (b - r) * S * math.exp((b - r) * T) * N(-d1)
mult2 := r * K * math.exp(-r * T) * N(-d2)
out := -num / dom + mult1 + mult2
out
// Black-Scholes Rho or Rho Call Futures Option
BSRho(float S, float K, float T, float r, float q, float v, string OpType)=>
float d2 = d2(S, K, r, q, v, T)
float price = BSPrice(S, K, r, T, q, v, OpType)
float out = 0
if OpType == callString
out := syminfo.type == "futures" ? - T * price : T * K * math.exp(-r * T) * N(d2)
else
out := syminfo.type == "futures" ? - T * price : -T * K * math.exp(-r * T) * N(-d2)
out
// Black-Scholes Lambda, omega, or elasticity
BSLambda(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float price = BSPrice(S, K, T, r, q, v, OpType)
float delta = OpType == callString ? math.exp(-q * T) * N(d1) : math.exp(-q * T) * (N(d1) - 1)
float out = delta * S / price
out
// Black-Scholes Epsilon
BSEpsilon(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float out = OpType == callString ? -S * T * math.exp(-q * T) * N(d2) : S * T * math.exp(-q * T) * N(d1)
out
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 2nd Order Greeks
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// Black-Scholes Gamma or Convexity
BSGamma(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float out = (f(d1) * math.exp(-q * T)) / (S * v * math.sqrt(T))
out
// Black-Scholes Vanna, DdeltaDvol, or DVegaDSpot
BSVanna(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float out = ((-math.exp(-q * T) * d2) / v) * f(d1)
out
// Black-Scholes Charm, Delta Bleed, or DDeltaDTime
BSCharm(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float b = r - q
float out = 0
if OpType == callString
out := -math.exp((b - r) * T) * (f(d1) * (b / (v * math.sqrt(T)) - d2 / (2 * T)) + (b - r) * N(d1))
else
out := -math.exp((b - r) * T) * (f(d1) * (b / (v * math.sqrt(T)) - d2 / (2 * T)) - (b - r) * N(-d1))
out
// Black-Scholes Vomma, DvegaDvol, or volga
BSVomma(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float vega = BSVega(S, K, T, r, q, v)
float out = vega * ((d1 * d2) / v)
out
// Black-Scholes Veta
BSVeta(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float out = -S * math.exp(-q * T) * f(d1) * math.sqrt(T) * (q + ((r - q) * d1)/ (v * math.sqrt(T)) - ((1 + d1 * d2) / (2 * T)))
out
// Black-Scholes Vera or rhova
BSVera(float S, float K, float T, float r, float q, float v, string OpType)=>
float v2 = math.pow(v, 2)
float out = math.exp(-r * T) * (1 / K) * (1 / math.sqrt(2 * math.pi * v2 * T)) * math.exp((-1 / (2 * v2 * T)) * math.pow(math.log(K / S) - ((r - q) - 0.5 * v2) * T, 2))
out
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 3rd Order Greeks
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// Black-Scholes Speed or DGammaDSpot
BSSpeed(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float gamma = BSGamma(S, K, r, q, v, T)
float dv = 1 + d1 / (v * math.sqrt(T))
float out = -gamma * (dv / S)
out
// Black-Scholes Zomma
BSZomma(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float gamma = BSGamma(S, K, r, q, v, T)
float d1d2 = (d1 * d2) - 1
float out = gamma * (d1d2 / v)
out
// Black-Scholes Color, Gamma Bleed
BSColor(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float b = (r - q)
float gamma = BSGamma(S, K, r, q, v, T)
float out = gamma * ((r - b) + (b * d1) / (v * math.sqrt(T)) + (1 - d1 * d2) / (2 * T))
out
// Black-Scholes Ultima or DVommaDVol
BSUltima(float S, float K, float T, float r, float q, float v)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float vomma = BSVomma(S, K, T, r, q, v)
float out = vomma * (1 / v) * (d1 * d2 + d1 / d2 - d2 / d1 - 1)
out
// Black-Scholes Dual Delta or Strike Delta
BSDualDelta(float S, float K, float T, float r, float q, float v, string OpType)=>
float d2 = d2(S, K, r, q, v, T)
float out = OpType == callString ? -math.exp(-r * T) * N(d2) : math.exp(-r * T) * N(-d2)
out
// Black-Scholes Dual Gamma or Strike Gamma
BSDualGamma(float S, float K, float T, float r, float q, float v, string OpType)=>
float d1 = d1(S, K, r, q, v, T)
float d2 = d2(S, K, r, q, v, T)
float out = math.exp(-r * T) * (f(d2) / (K * v * math.sqrt(T)))
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Spot Price Settings")
srcin = input.string("Close", "Spot Price", group= "Spot Price Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(275, "Strike Price", group = "Basic Settings")
string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings")
string greeksshow = input.string("First-order", title = "Greeks to Show", options =["First-order", "Second-order", "Third-order"], group = "Basic Settings")
float v = input.float(25.6, "% Implied Volatility", group = "Implied Volatility Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Historical Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Historical Volatility Settings")
string rfrtype = input.string("USD", "Option Base Currency", options = ['USD', 'GBP', 'JPY', 'CAD', 'CNH', 'SGD', 'INR', 'AUD', 'SEK', 'NOK', 'DKK'], group = "Risk-free Rate Settings", tooltip = "Automatically pulls 10-year bond yield from corresponding currency")
float rfrman = input.float(3.97, "% Manual Risk-free Rate", group = "Risk-free Rate Settings") / 100
bool usdrsrman = input.bool(false, "Use manual input for Risk-free Rate?", group = "Risk-free Rate Settings")
float divsman = input.float(7.5, "% Manual Yearly Dividend Yield", group = "Dividend Settings") / 100
bool usediv = input.bool(false, "Adjust for Dividends?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
bool autodiv = input.bool(true, "Automatically Calculate Yearly Dividend Yield?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
float q = usediv ? (autodiv ? request.dividends(syminfo.tickerid) / close * 4 : divsman) : 0
string byield = switch rfrtype
"USD"=> 'US10Y'
"GBP"=> 'GB10Y'
"JPY"=> 'US10Y'
"CAD"=> 'CA10Y'
"CNH"=> 'CN10Y'
"SGD"=> 'SG10Y'
"INR"=> 'IN10Y'
"AUD"=> 'AU10Y'
"USEKSD"=> 'SE10Y'
"NOK"=> 'NO10Y'
"DKK"=> 'DK10Y'
=> 'US10Y'
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float r = usdrsrman ? rfrman : request.security(byield, timeframe.period, close) / 100
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
float tempr = syminfo.type == "futures" ? 0 : r
price = BSPrice(spot, K, r, T, q, v, OpType)
// 1rst order
delta = BSDelta(spot, K, T, r, q, v, OpType)
vega = BSVega(spot, K, T, r, q, v)
theta = BSTheta(spot, K, T, r, q, v, OpType)
rho = BSRho(spot, K, T, r, q, v, OpType)
lambda = BSLambda(spot, K, T, r, q, v, OpType)
epsilon = BSEpsilon(spot, K, T, r, q, v, OpType)
// 2nd order
gamma = BSGamma(spot, K, T, r, q, v)
vanna = BSVanna(spot, K, T, r, q, v)
charm = BSCharm(spot, K, T, r, q, v, OpType)
vomma = BSVomma(spot, K, T, r, q, v)
veta = BSVeta(spot, K, T, r, q, v, OpType)
vera = BSVera(spot, K, T, r, q, v, OpType)
// 3rd order
speed = BSSpeed(spot, K, T, r, q, v)
zomma = BSZomma(spot, K, T, r, q, v)
colorz = BSColor(spot, K, T, r, q, v)
ultima = BSUltima(spot, K, T, r, q, v)
dualdelta = BSDualDelta(spot, K, T, r, q, v, OpType)
dualgamma = BSDualGamma(spot, K, T, r, q, v, OpType)
var testTable = table.new(position = position.middle_right, columns = 1, rows = 22, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = " Inputs for European " + OpType + " Option", bgcolor=color.yellow, text_color = color.black, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 1, text = " Spot Price: " + str.tostring(spot, f_tickFormat()) , bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 2, text = " Strike Price: " + str.tostring(K, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 3, text = " Volatility (annual): " + str.tostring(v * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 4, text = " Risk-free Rate Type: " + rfrtype , bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 5, text = " Risk-free Rate: " + str.tostring(tempr * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 6, text = " Dividend Yield (annual): " + str.tostring(q * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 7, text = " Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow) + " ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 8, text = " Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish) + " ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 9, text = " Output ", bgcolor=color.yellow, text_color = color.black, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 10, text = " Price: " + str.tostring(price, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 11, text = " Calculated Values ", bgcolor=color.yellow, text_color = color.black, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 12, text = " Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 13, text = " Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 14, text = " Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
if greeksshow == "First-order"
table.cell(table_id = testTable, column = 0, row = 15, text = " First-order Greeks ", bgcolor=color.yellow, text_color = color.black, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 16, text = " Delta: " + str.tostring(delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 17, text = " Vega: " + str.tostring(vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 18, text = " Theta: " + str.tostring(theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 19, text = " Rho: " + str.tostring(rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 20, text = " Lambda: " + str.tostring(lambda, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 21, text = " Epsilon: " + str.tostring(epsilon, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
if greeksshow == "Second-order"
table.cell(table_id = testTable, column = 0, row = 15, text = " Second-order Greeks ", bgcolor=color.yellow, text_color = color.black, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 16, text = " Gamma: " + str.tostring(gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 17, text = " Vanna: " + str.tostring(vanna, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 18, text = " Charm: " + str.tostring(charm, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 19, text = " Vomma: " + str.tostring(vomma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 20, text = " Veta: " + str.tostring(veta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 21, text = " Vera: " + str.tostring(vera, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
if greeksshow == "Third-order"
table.cell(table_id = testTable, column = 0, row = 15, text = " Third-order Greeks ", bgcolor=color.yellow, text_color = color.black, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 16, text = " Speed: " + str.tostring(zomma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 17, text = " Color: " + str.tostring(colorz, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 18, text = " Ultima: " + str.tostring(ultima, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 19, text = " Dual Delta: " + str.tostring(dualdelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
table.cell(table_id = testTable, column = 0, row = 20, text = " Dual Gamma: " + str.tostring(dualgamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal)
|
Choppy Market EMA Identification | https://www.tradingview.com/script/bnpFXFAP-Choppy-Market-EMA-Identification/ | Fraggl | https://www.tradingview.com/u/Fraggl/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Fraggl
//@version=5
indicator("Choppy Market EMA Identification", overlay=true)
src = input(close, 'Source', group="Strategy Config")
ema_len = input.int(200, minval=1, title='EMA Length', group="Strategy Config")
max_cross = input.int(1, title='EMA Crosses to invalidate')
lookback = input.int(6, minval=1, title='EMA Touch Lookback', group="Strategy Config")
ema_col = input.color(color.white, group="Strategy Config")
fun_numbersOfEmaCross(numbers, ema) =>
int crosses = 0
cr = ta.cross(close,ema)
for candleNo = 1 to numbers+1
if cr[candleNo]
crosses := crosses+1
[crosses]
ema = ta.ema(src, ema_len)
[C] = fun_numbersOfEmaCross(lookback, ema)
maColor = if C < max_cross
ema_col
else
color.new(color.white, 100)
plot(ema, title='TR EMA', color=maColor, linewidth=2)
|
RSI + MA, LinReg, ZZ (HH HL LH LL), Div, Ichi, MACD and TSI Hist | https://www.tradingview.com/script/KR0Yh23Q-RSI-MA-LinReg-ZZ-HH-HL-LH-LL-Div-Ichi-MACD-and-TSI-Hist/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 515 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("RSI β’ Yata",
overlay = false,
precision = 3,
max_bars_back = 500)
// ---------------------------------
groupRSI = "Relative Strength Index"
// ---------------------------------
len = input.int (14, minval=1 , title="Length", inline="RSI0", group=groupRSI)
src = input (close , title="Source", inline="RSI0", group=groupRSI)
up = ta.rma(math.max(ta.change(src), 0), len)
dn = ta.rma(-math.min(ta.change(src), 0), len)
rsi0 = dn == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / dn)
show_smooth = input.bool(false , title="Smoothed RSI", inline="RSI0.5", group=groupRSI)
ema_smooth = input.int (3 , title="| Smooth Length", inline="RSI0.5", group=groupRSI)
rsi_smooth = ta.ema (rsi0 , ema_smooth)
rsi = show_smooth ? rsi_smooth : rsi0
// ---------------------------------
show_bar = input.bool(false, title="Show Bars Colors", inline="RSI1", group=groupRSI)
color_rsi_30 = input.color(color.new(#0B54FE, 0), title="Colors:" , inline="RSI2", group=groupRSI)
color_rsi_40 = input.color(color.new(#3348f4, 0), title="" , inline="RSI2", group=groupRSI)
color_rsi_49 = input.color(color.new(#4743EE, 0), title="" , inline="RSI2", group=groupRSI)
color_rsi_51 = input.color(color.new(#8431DF, 0), title="" , inline="RSI2", group=groupRSI)
color_rsi_60 = input.color(color.new(#AC26D5, 0), title="" , inline="RSI2", group=groupRSI)
color_rsi_70 = input.color(color.new(#FC0FC0, 0), title="" , inline="RSI2", group=groupRSI)
color_rsi_no = input.color(color.new(#7e57c2, 0), title="|" , inline="RSI2", group=groupRSI)
rsi_color = rsi < 30 ? color_rsi_30 :
rsi < 40 ? color_rsi_40 :
rsi < 50 ? color_rsi_49 :
rsi > 70 ? color_rsi_70 :
rsi > 60 ? color_rsi_60 :
rsi > 50 ? color_rsi_51 :
na
barcolor(show_bar ? rsi_color : na)
// ---------------------------------
show_rsiF = input.bool(false, title="Show RSI Background Fill", inline="RSI3", group=groupRSI)
rsiF = rsi //ta.rsi(src, len)
rsi_plot = plot(rsiF, title="RSI Fill" , color=na)
middle_plot = plot(50, title="Middle Fill", color=na)
color_f20 = input.color(color.new(#0B54FE, 85) ,title="|", inline="RSI3", group=groupRSI)
color_f49 = input.color(color.new(#4743EE, 95) ,title="", inline="RSI3", group=groupRSI)
color_f51 = input.color(color.new(#8431DF, 95) ,title="", inline="RSI3", group=groupRSI)
color_f80 = input.color(color.new(#FC0FC0, 85) ,title="", inline="RSI3", group=groupRSI)
color_up = show_rsiF and rsiF > 50 ? color_f80 : show_rsiF ? color_f49 : na
color_dn = show_rsiF and rsiF > 50 ? color_f51 : show_rsiF ? color_f20 : na
fill(rsi_plot, middle_plot, rsiF > 50 ? 80 : 50, rsiF > 50 ? 50 : 20, color_up, color_dn)
// ---------------------------------
show_candles = input.bool(false, title="Show RSI Candles", inline="RSI4", group=groupRSI)
ad = true // Advanced RSI
u = math.max(src - src[1], 0)
dm = math.max(src[1] - src, 0)
b = 1 / len
ruh = b * math.max(high - close[1], 0) + (1 - b) * ta.rma(u, len)[1]
rdh = (1 - b) * ta.rma(dm, len)[1]
rul = (1 - b) * ta.rma(u, len)[1]
rdl = b * math.max(close[1] - low, 0) + (1 - b) * ta.rma(dm, len)[1]
function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced
rsiha = 100 - 100 / (1 + ruh / rdh)
rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(src, len)
rsih = if ad
function(rsiha, len)
else
rsiha
rsil = if ad
function(rsila, len)
else
rsila
uc = input.color(color.new(color.green , 50) , title="|", inline="RSI4", group=groupRSI)
dc = input.color(color.new(color.red , 50) , title="", inline="RSI4", group=groupRSI)
bordercolor = input.color(color.new(color.gray , 75) , title="", inline="RSI4", group=groupRSI)
wickcolor = input.color(color.new(color.gray , 75) , title="", inline="RSI4", group=groupRSI)
plotcandle(show_candles ? rsia[1] : na, rsih, rsil, rsia, title="RSI Candles", color=ta.change(rsia) > 0 ? uc : dc, wickcolor=wickcolor, bordercolor=bordercolor)
// ---------------------------------
showDots = input.bool(true, title="Show OB/OS Dots", inline="RSI5", group=groupRSI)
color_Dos = input.color(color.new(color.green , 25), title="|", inline="RSI5", group=groupRSI)
color_Dob = input.color(color.new(color.red , 25), title="", inline="RSI5", group=groupRSI)
ob = ta.cross(rsi, 70) == 1 and rsi >= 70
os = ta.cross(rsi, 30) == 1 and rsi <= 30
plot(ob and showDots ? rsi : na , linewidth=4, style=plot.style_circles, color=color_Dob, title="Overbought")
plot(os and showDots ? rsi : na , linewidth=4, style=plot.style_circles, color=color_Dos, title="Oversold")
// ---------------------------------
color_OB = input.color(color.new(color.green , 65) ,title="Background Lines Colors:" , inline="RSI6", group=groupRSI)
color_NT = input.color(color.new(color.silver , 65) ,title="" , inline="RSI6", group=groupRSI)
color_OS = input.color(color.new(color.red , 65) ,title="" , inline="RSI6", group=groupRSI)
//color_fOB = input.color(color.new(color.green , 97) ,title="|" , inline="RSI6", group=groupRSI)
//color_fOS = input.color(color.new(color.red , 97) ,title="" , inline="RSI6", group=groupRSI)
band0 = hline(80, title="80", linewidth=1, linestyle=hline.style_dotted , color=color_OB)
band1 = hline(70, title="70", linewidth=1, linestyle=hline.style_solid , color=color_OB)
band2 = hline(60, title="60", linewidth=1, linestyle=hline.style_dotted , color=color_NT)
band3 = hline(50, title="50", linewidth=1, linestyle=hline.style_solid , color=color_NT)
band4 = hline(40, title="40", linewidth=1, linestyle=hline.style_dotted , color=color_NT)
band5 = hline(30, title="30", linewidth=1, linestyle=hline.style_solid , color=color_OS)
band6 = hline(20, title="20", linewidth=1, linestyle=hline.style_dotted , color=color_OS)
fill(band1, band0, color=color.new(color.green , 97), title="Background OB")
fill(band5, band6, color=color.new(color.red , 97), title="Background OS")
// ---------------------------------
showLRSI = input.bool(true, title="RSI Label", inline="RSI0", group=groupRSI)
var label Label_RSI = na
Label_RSI := label.new(bar_index + 1, rsi, str.tostring(math.round(rsi, 2), "##"), style=label.style_label_left, color= showLRSI ? color.new(color.silver, 95) : na, textcolor= showLRSI ? color.new(color.silver, 15) : na)
label.delete(Label_RSI[1])
// -----------------------
groupMA = "Moving Average"
// -----------------------
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"BB (Bollinger)" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
"VWAP" => ta.vwap(source)
"LSMA" => ta.linreg(source, length, offset=0)
"HMA" => ta.hma(source, length)
"ALMA" => ta.alma(source, length, offset=0.85, sigma=6.0)
// -----------------------
show_ma = input.bool (false , title="Show RSI MA" , inline="MA3", group=groupMA)
bull_ma_color = input.color (color.new(#7E9BDE, 50) , title="| Bullish" , inline="MA3", group=groupMA)
bear_ma_color = input.color (color.new(#FF8B00, 50) , title="Bearish" , inline="MA3", group=groupMA)
ma_length = input.int (21 , title="Length" , inline="MA1", group=groupMA)
ma_type = input.string ("SMA" , title="Type", options=["SMA", "BB (Bollinger)", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP", "LSMA", "HMA", "ALMA"], inline="MA1", group=groupMA)
bb_mult = input.float (2.0 , title="Bollinger Bands Standard Dev." , inline="MA2", group=groupMA)
rsi_ma = ma(rsi, ma_length, ma_type)
ma_color = rsi_ma > rsi_ma[1] ? bull_ma_color : bear_ma_color
ma_plot = plot(show_ma ? rsi_ma : na, color=ma_color, title="Moving Average")
bb_color = input.color(color.new(#000000, 75), title="| Fill", inline="MA2", group=groupMA)
bb_check = ma_type == "BB (Bollinger)"
bb_uband = plot(show_ma and bb_check ? rsi_ma + ta.stdev(rsi, ma_length) * bb_mult : na, color=bb_color, title="Upper Bollinger Band")
bb_lband = plot(show_ma and bb_check ? rsi_ma - ta.stdev(rsi, ma_length) * bb_mult : na, color=bb_color, title="Lower Bollinger Band")
fill(bb_uband, bb_lband, color= bb_check ? bb_color : na, title="BB Background")
basis = rsi_ma //ta.sma(rsi, ma_length)
dev = bb_mult * ta.stdev(rsi, ma_length)
upper_bb = basis + dev
lower_bb = basis - dev
over_bb = rsi > upper_bb
under_bb = rsi < lower_bb
// -----------------------
rsiR_input = input.string("None", options=["None", "RSI Levels", "Middle Line", "Moving Average", "Bollinger Bands"], title="| RSI Line Color Ref.", inline="RSI1", group=groupRSI)
rsi_bb = over_bb ? color_rsi_70 : under_bb ? color_rsi_30 : color_rsi_no
rsiR1 = rsi ? color_rsi_no : na
rsiR2 = rsi > 50 ? color_rsi_70 : rsi < 50 ? color_rsi_30 : na
rsiR3 = rsi > 70 ? color_rsi_70 :
rsi < 30 ? color_rsi_30 :
rsi > rsi_ma and rsi > 50 ? color_rsi_60 :
rsi > rsi_ma and rsi < 50 ? color_rsi_51 :
rsi < rsi_ma and rsi > 50 ? color_rsi_49 :
rsi < rsi_ma and rsi < 50 ? color_rsi_40 :
na
rsiR0 = rsiR_input == "None" ? rsiR1 :
rsiR_input == "RSI Levels" ? rsi_color :
rsiR_input == "Middle Line" ? rsiR2 :
rsiR_input == "Moving Average" ? rsiR3 :
rsiR_input == "Bollinger Bands" ? rsi_bb :
na
plot(rsi, title="RSI", color=rsiR0)
// ------------------
groupH = "Histograms"
// ------------------
Color_Grow_Above = input(#2B4B46, title="Histograms Colors:", inline="H0", group=groupH)
Color_Fall_Above = input(#8CA18D, title="" , inline="H0", group=groupH)
Color_Grow_Below = input(#B49C79, title="" , inline="H0", group=groupH)
Color_Fall_Below = input(#8B3D44, title="" , inline="H0", group=groupH)
// ------------------
sHist_RSI = input(false, title="Show RSI Histogram |" , inline="HRSI0", group=groupH)
AbsHistogram = input(false, title="Zero Line" , inline="HRSI0", group=groupH)
HistogramStyle = input(false, title="Columns Style" , inline="HRSI0", group=groupH)
rsiCustom = input(false, title="Use Custom RSI and MA Settings:" , inline="RSI0A", group=groupH)
len_h = input.int (14, minval=1 , title="RSI Length", inline="HRSI1", group=groupH)
src_h = input (close , title="RSI Source", inline="HRSI1", group=groupH)
rsi_h = ta.rsi(src_h, len_h)
ma_length_h = input.int (21 , title="MA Length", inline="HRSI2", group=groupH)
ma_type_h = input.string ("SMA" , title="MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP", "LSMA", "HMA", "ALMA"], inline="HRSI2", group=groupH)
rsi_ma_h = ma(rsi_h, ma_length_h, ma_type_h)
custom_rsi = rsiCustom ? rsi_h - rsi_ma_h : rsi - rsi_ma
absRSI = math.abs(custom_rsi)
RSIz = AbsHistogram ? custom_rsi : absRSI
hColor = custom_rsi >= 0 ? (custom_rsi[1] < custom_rsi ? Color_Grow_Above : Color_Fall_Above) : (custom_rsi[1] < custom_rsi ? Color_Grow_Below : Color_Fall_Below)
pStyle = HistogramStyle ? plot.style_columns : plot.style_histogram
plot(sHist_RSI ? RSIz : na, style=pStyle, color=hColor, title="RSI Histogram")
// ------------------
//sHist_TSI = input(false , title="Show TSI Histogram", inline="HTSI1", group=groupH)
//Short_Len = input(5 , title="Short Period" , inline="HTSI2", group=groupH)
//Long_Len = input(20 , title="Long Period" , inline="HTSI2", group=groupH)
//TSI_Signal_Len = input(5 , title="| Signal Period" , inline="HTSI1", group=groupH)
//
//TSI = ta.tsi(close, Short_Len, Long_Len)
//TSI_Signal = ta.ema(TSI, TSI_Signal_Len)
//Histogram_TSI = TSI - TSI_Signal
//
//TSIcolor = Histogram_TSI >= 0 ? (Histogram_TSI[1] < Histogram_TSI ? Color_Grow_Above : Color_Fall_Above) : (Histogram_TSI[1] < Histogram_TSI ? Color_Grow_Below : Color_Fall_Below)
//plotshape(Histogram_TSI and sHist_TSI ? 5 : na, style=shape.square, color=TSIcolor, location=location.top, size=size.tiny, title="TSI Histogram")
// ------------------
sHist_MACD = input(true, title="Show MACD Histogram", group=groupH)
Fast_Len = input(12 , title="Fast Length", inline="HMACD1", group=groupH)
Slow_Len = input(26 , title="Slow Length", inline="HMACD1", group=groupH)
MACD_Source = input.source(close , title="MACD Source" , inline="HMACD2", group=groupH)
MACD_Signal_Len = input.int(9, minval=1 , title="Smoothing" , inline="HMACD2", group=groupH)
MA_Source = input.string("EMA" , title="Oscillator Type" , options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP", "LSMA", "HMA", "ALMA"], inline="HMACD3", group=groupH)
MA_Signal = input.string("EMA" , title="Signal Line" , options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP", "LSMA", "HMA", "ALMA"], inline="HMACD3", group=groupH)
Fast_MA = ma(MACD_Source, Fast_Len, MA_Source)
Slow_MA = ma(MACD_Source, Slow_Len, MA_Source)
MACD = Fast_MA - Slow_MA
MACD_Signal = ma(MACD, MACD_Signal_Len, MA_Signal)
Histogram_MACD = MACD - MACD_Signal
MACDcolor = Histogram_MACD >= 0 ? (Histogram_MACD[1] < Histogram_MACD ? Color_Grow_Above : Color_Fall_Above) : (Histogram_MACD[1] < Histogram_MACD ? Color_Grow_Below : Color_Fall_Below)
plotshape(Histogram_MACD and sHist_MACD ? 5 : na, style=shape.square, color=MACDcolor, location=location.bottom, size=size.tiny, title="MACD Histogram")
// ------------------
showMACDf = input.bool(false, title="Show MACD (Full) |" , inline="MACD0", group=groupH)
mHistogramStyle = input(false, title="Columns Style" , inline="MACD0", group=groupH)
mStyle = mHistogramStyle ? plot.style_columns : plot.style_histogram
Color_MACD = input(#0094ff, title="|" , inline="MACD0", group=groupH)
Color_Signal = input(#ff6a00, title="" , inline="MACD0", group=groupH)
fast_length = input.int(12 , title="Fast Length" , inline="MACD1", group=groupH)
slow_length = input.int(26 , title="Slow Length" , inline="MACD1", group=groupH)
macd_src = input.source(close , title="MACD Source" , inline="MACD2", group=groupH)
signal_length = input.int(9 , title="Smoothing" , inline="MACD2", group=groupH)
ma_source = input.string("EMA" , title="Oscillator Type" , inline="MACD3", group=groupH, options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP", "LSMA", "HMA", "ALMA"])
ma_signal = input.string("EMA" , title="Signal Line" , inline="MACD3", group=groupH, options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP", "LSMA", "HMA", "ALMA"])
SetScale = input.int(20 , title="Scaling" , inline="MACD4", group=groupH, minval=1, maxval=100, step=5)
HisLen = input.int(500 , title="Length" , inline="MACD4", group=groupH, minval=1, step=20)
ScaleCol = input.bool(true , title="Colors" , inline="MACD4", group=groupH, tooltip="Scaling: Set Top of Range. 0 will be bottom. \nLength: StdDev period, causes distortion, avoid lowering. Must be >= highest MACD value. \nColors: Uses corrected center for coloring. Otherwise colors will retain original MACD colors.")
// ------------------
shortMA = ma(macd_src, fast_length, ma_source)
longMA = ma(macd_src, slow_length, ma_source)
macdLine = shortMA - longMA
signalLine = ma(macdLine, signal_length, ma_signal)
hist = macdLine - signalLine
// ------------------
midline = SetScale / 2
sd_hist = ta.stdev(hist, HisLen)
basis_hist = ta.ema(hist, HisLen)
up_hist = basis_hist + sd_hist * 2
dn_hist = basis_hist - sd_hist * 2
re_hist = (hist - dn_hist) / (up_hist - dn_hist) * SetScale
sd_sig = ta.stdev(signalLine, HisLen)
basis_sig = ta.ema(signalLine, HisLen)
up_sig = basis_sig + sd_sig * 2
dn_sig = basis_sig - sd_sig * 2
rescaled_sig = (signalLine - dn_sig) / (up_sig - dn_sig) * SetScale
sd_mac = ta.stdev(macdLine, HisLen)
basis_mac = ta.ema(macdLine, HisLen)
up_mac = basis_mac + sd_mac * 2
dn_mac = basis_mac - sd_mac * 2
rescaled_mac = (macdLine - dn_mac) / (up_mac - dn_mac) * SetScale
// ------------------
histLineCol = hist >= 0 ? hist[1] < hist ? Color_Grow_Above : Color_Fall_Above : hist[1] < hist ? Color_Grow_Below : Color_Fall_Below
re_histLineCol = re_hist >= midline ? re_hist[1] < re_hist ? Color_Grow_Above : Color_Fall_Above : re_hist[1] < re_hist ? Color_Grow_Below : Color_Fall_Below
//midCol = ScaleCol ? re_hist >= midline ? Color_Grow_Above : Color_Grow_Below : hist >= 0 ? Color_Grow_Above : Color_Grow_Below
// ------------------
//plot(midline, title="Center (Color)", color=midCol, style=plot.style_line, linewidth=2, display=display.none)
//hline(midline, title="Center", color=color.gray, linestyle=hline.style_solid, linewidth=1)
//hline(SetScale, title="Top Range", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
//hline(0, title="Low Range", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
plot(showMACDf ? rescaled_mac : na , title="MACD" , color=Color_MACD, style=plot.style_line, linewidth=1, histbase=midline)
plot(showMACDf ? rescaled_sig : na , title="Signal" , color=Color_Signal, style=plot.style_line, linewidth=1, histbase=midline)
plot(showMACDf ? re_hist : na , title="Histogram" , color=ScaleCol ? re_histLineCol : histLineCol, style=mStyle, linewidth=1, histbase=midline)
// --------------------------
groupI = "Ichimoku Kinko Hyo"
// --------------------------
ichi_sw = input (true , title="Show Ichimoku Cloud" , inline="ICHI0", group=groupI)
conversionPeriods = input.int (13, minval=1 , title="Tenkan-Sen" , inline="ICHI1", group=groupI)
basePeriods = input.int (33, minval=1 , title="Kijun-Sen" , inline="ICHI1", group=groupI)
laggingSpan2Periods = input.int (84, minval=1 , title="Chikou Span" , inline="ICHI2", group=groupI)
displacement = input.int (33, minval=1 , title="Displacement" , inline="ICHI2", group=groupI)
donchian(len) => math.avg(ta.lowest(rsi, len), ta.highest(rsi, len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
colorI1 = input(color.new(#1B5E20, 65), title="Senkou: Span A" , inline="ICHI3", group=groupI)
colorI2 = input(color.new(#801922, 65), title="Span B" , inline="ICHI3", group=groupI)
colorI3 = input(color.new(#1B5E20, 90), title="Fill A" , inline="ICHI3", group=groupI)
colorI4 = input(color.new(#801922, 90), title="Fill B" , inline="ICHI3", group=groupI)
ichiLwidth = input.int(1, minval=0, title="| Lines Width", inline="ICHI0", group=groupI)
pI1 = plot(ichi_sw ? leadLine1 : na, offset = displacement - 1, linewidth=ichiLwidth, color=colorI1, title="LeadLine A")
pI2 = plot(ichi_sw ? leadLine2 : na, offset = displacement - 1, linewidth=ichiLwidth, color=colorI2, title="LeadLine B")
fill(pI1, pI2, color = leadLine1 > leadLine2 ? colorI3 : colorI4, title="Ichimoku Cloud")
// ----------------------
groupS = "Stochastic RSI"
// ----------------------
show_stoch = input.bool(false, title="Show Stochastic RSI |", inline="STOCH1", group=groupS)
smoothK = input.int(21, minval=1 , title="K" , inline="STOCH2", group=groupS)
smoothD = input.int(5, minval=1 , title="D" , inline="STOCH3", group=groupS)
lengthRSI = input.int(21, minval=1 , title="RSI Length" , inline="STOCH2", group=groupS)
lengthStoch = input.int(50, minval=1 , title="Stoch. Length" , inline="STOCH3", group=groupS)
src_stoch = input(close, title="Source", inline="STOCH4", group=groupS)
colorS1 = input(color.new(color.green, 85) , title="| Bullish" , inline="STOCH4", group=groupS)
colorS2 = input(color.new(color.red, 85) , title="Bearish" , inline="STOCH4", group=groupS)
showSRSI_l = input.bool(false , title="Lines" , inline="STOCH1", group=groupS)
showSRSI_f = input.bool(true , title="Fill" , inline="STOCH1", group=groupS)
showSRSI_lc = showSRSI_l ? display.all : display.none
showSRSI_fc = showSRSI_f ? display.all : display.none
SRSI = ta.rsi(src_stoch, lengthRSI)
kS = ta.sma(ta.stoch(SRSI, SRSI, SRSI, lengthStoch), smoothK)
dS = ta.sma(kS, smoothD)
pkS = plot(show_stoch ? kS : na, linewidth=1, color=colorS1, display=showSRSI_lc, title="Stochastic K")
pdS = plot(show_stoch ? dS : na, linewidth=1, color=colorS2, display=showSRSI_lc, title="Stochastic D")
fill(plot1 = pkS, plot2 = pdS, color = kS >= dS ? colorS1 : colorS2, display=showSRSI_fc, title="Stochastic RSI")
// -----------------
groupT = "RSI Trend"
// -----------------
//show_trend = input.bool(false, title="Show RSI Trend |", inline="T1", group=groupT)
//rsiLengthInput = input.int (14, minval=1 , title="Fast Length" , inline="T1A", group=groupT)
//rsiLengthInput2 = input.int (28, minval=1 , title="Slow Length" , inline="T1A", group=groupT)
show_baseline = input.bool(false , title="Show Hull Trend |" , inline="T2", group=groupT)
trendlen = input (30 , title="Length" , inline="T2A", group=groupT)
//showT_l = input.bool(false, title="Lines", inline="T1", group=groupT)
//showT_f = input.bool(true, title="Fill", inline="T1", group=groupT)
//showT_lc = showT_l ? display.all : display.none
//showT_fc = showT_f ? display.all : display.none
showHl = input.bool(false, title="Lines", inline="T2", group=groupT)
showHf = input.bool(true, title="Fill", inline="T2", group=groupT)
showHlC = showHl ? display.all : display.none
showHfC = showHf ? display.all : display.none
colorR1 = input(color.new(#0B54FE, 90), title="| Bullish" , inline="T2A", group=groupT)
colorR2 = input(color.new(#FC0FC0, 90), title="Bearish" , inline="T2A", group=groupT)
BBMC = ta.hma(close, trendlen)
MHULL = BBMC[0]
SHULL = BBMC[2]
hmac = MHULL > SHULL ? colorR1 : colorR2
//frsi = ta.hma(ta.rsi(close, rsiLengthInput), 10)
//srsi = ta.hma(ta.rsi(close, rsiLengthInput2), 10)
hullrsi1 = ta.rsi(MHULL, len)
hullrsi2 = ta.rsi(SHULL, len)
//RSItrend = frsi > srsi ? colorR1 : colorR2
//trend1 = plot(show_trend ? frsi : na, linewidth=1, color=colorR1, display=showT_lc, title="RSI Trend 1")
//trend2 = plot(show_trend ? srsi : na, linewidth=1, color=colorR2, display=showT_lc, title="RSI Trend 2")
hull1 = plot(show_baseline ? hullrsi1 : na, linewidth=1, color=colorR1, display=showHlC, title="HMA 1")
hull2 = plot(show_baseline ? hullrsi2 : na, linewidth=1, color=colorR2, display=showHlC, title="HMA 2")
//fill(trend1, trend2, color=show_trend ? RSItrend : na, display=showT_fc, title="RSI Trend")
fill(hull1, hull2, color=show_baseline ? hmac : na, display=showHfC, title="RSI Hull Trend")
// -----------------
show_tstate = input.bool(false, title="Show Trend State |", inline="T3", group=groupT)
var state = 0
if ta.crossover(rsi, 66.67)
state := 1
state
if ta.crossunder(rsi, 33.33)
state := 2
state
if state == 1 and ta.crossunder(rsi, 40)
state := 3
state
if state == 2 and ta.crossover(rsi, 60)
state := 3
state
state := state
colorST1 = input(color.new(#0B54FE , 75), title="Bull." , inline="T3", group=groupT)
colorST3 = input(color.new(color.silver , 75), title="N." , inline="T3", group=groupT)
colorST2 = input(color.new(#FC0FC0 , 75), title="Bear." , inline="T3", group=groupT)
state_col = state == 1 ? colorST1 : state == 2 ? colorST2 : state == 3 ? colorST3 : na
state_col2 = state == 1 ? colorST1 : state == 2 ? colorST2 : state == 3 ? colorST3 : na
mh = plot(show_tstate ? 60 : na, title="Mid-High Band", color=state == 2 or state == 3 ? state_col2 : na, style=plot.style_circles, linewidth=1)
ml = plot(show_tstate ? 40 : na, title="Mid-Low Band", color=state == 1 or state == 3 ? state_col2 : na, style=plot.style_circles, linewidth=1)
// --------------------------
groupLR = "Linear Regression"
// --------------------------
linreg = input (true , title="Show Linear Regression |" , inline="LR1", group=groupLR)
periodTrend = input.int (89, minval=4 , title="Trend Period" , inline="LR2", group=groupLR)
deviationsAmnt = input.float (1.618, step=0.1, title="Deviation" , inline="LR2", group=groupLR)
//estimatorType = input.string ("Unbiased" , title="Estimator" , options=["Biased", "Unbiased"], inline="LR3", group=groupLR)
estimatorType = "Unbiased"
var extendType = input.string ("Segment" , title="Lines: Extension" , options=["Right", "Segment"], inline="LR3", group=groupLR) == "Right" ? extend.right : extend.none
lrLwidth = input.int (2, minval=0 , title="Width" , inline="LR3", group=groupLR)
UPlr = input(color.new(color.green, 65), title="Lines Colors: Upper", inline="LR4", group=groupLR)
MIDlr = input(color.new(color.silver, 65), title="Middle" , inline="LR4", group=groupLR)
LOWlr = input(color.new(color.red, 65), title="Lower" , inline="LR4", group=groupLR)
i_line0 = "Solid"
i_line1 = "Dotted"
i_line2 = "Dashed"
f_getLineStyle(_inputStyle) =>
_return = _inputStyle == i_line1 ? line.style_dotted : _inputStyle == i_line2 ? line.style_dashed : line.style_solid
_return
ulLRstyle = input.string(i_line0, title="Style: Upper/Lower", options=[i_line0, i_line1, i_line2], inline="LR5", group=groupLR)
miLRstyle = input.string(i_line2, title="Middle", options=[i_line0, i_line1, i_line2], inline="LR5", group=groupLR)
// --------------------------
rsdcr2(PeriodMinusOne, Deviations, Estimate) =>
var period = PeriodMinusOne + 1
var devDenominator = Estimate == "Unbiased" ? PeriodMinusOne : period
Ex = 0.0
Ex2 = 0.0
Exy = 0.0
Ey = 0.0
for i = 0 to PeriodMinusOne by 1
closeI = nz(rsi[i])
Ex := Ex + i
Ex2 := Ex2 + i * i
Exy := Exy + closeI * i
Ey := Ey + closeI
Ey
ExEx = Ex * Ex
slope = Ex2 == ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0
for i = 0 to PeriodMinusOne by 1
deviation := deviation + math.pow(nz(rsi[i]) - (intercept - bar_index[i] * slope), 2.0)
deviation
deviation := Deviations * math.sqrt(deviation / devDenominator)
correlate = ta.correlation(rsi, bar_index, period)
r2 = math.pow(correlate, 2.0)
[linearRegression, slope, deviation, correlate, r2]
// --------------------------
drawLine(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := linreg ? line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, width=lrLwidth) : na
line.delete(Line[1])
periodMinusOne = periodTrend - 1
[linReg, slope, deviation, correlate, r2] = rsdcr2(periodMinusOne, deviationsAmnt, estimatorType)
endPointBar = bar_index - periodTrend + 1
endPointY = linReg + slope * periodMinusOne
drawLine(endPointBar, endPointY + deviation, bar_index, linReg + deviation, extendType, UPlr, f_getLineStyle(ulLRstyle))
drawLine(endPointBar, endPointY, bar_index, linReg, extendType, MIDlr, f_getLineStyle(miLRstyle))
drawLine(endPointBar, endPointY - deviation, bar_index, linReg - deviation, extendType, LOWlr, f_getLineStyle(ulLRstyle))
// --------------------------
showCor = input(false, title="Correlation", inline="LR1", group=groupLR)
var label Label = na
Label := label.new(math.max(0, endPointBar - 1), endPointY, text=str.tostring(correlate, "#.##"), style=label.style_label_right, color= showCor ? color.new(color.silver, 95) : na, textcolor= showCor ? color.new(color.silver, 15) : na)
label.delete(Label[1])
// ----------------------
groupZ = "Highs & Lows"
// ----------------------
showDiv = input.bool(true , title="Show Divergences" , inline="Z1", group=groupZ)
length = input (21 , title="| Pivot Length" , inline="Z1", group=groupZ)
r = rsi[length]
l = rsi[14]
ph = ta.pivothigh(rsi,length,length)
pl = ta.pivotlow(rsi,length,length)
valH = ta.valuewhen(ph,r,0)
valL = ta.valuewhen(pl,r,0)
valpH = ta.valuewhen(ph,r,1)
valpL = ta.valuewhen(pl,r,1)
d = math.abs(r)
n = bar_index
label lbl = na
HIH = valH > valpH ? "HH" : na
HIL = valH < valpH ? "LH" : na
LOL = valL < valpL ? "LL" : na
LOH = valL > valpL ? "HL" : na
// ----------------------
zL1style = input.string (i_line1 , title="Lines" , options=[i_line0, i_line1, i_line2], inline="Z2", group=groupZ)
showHL = input.bool (true , title="Show H/L |" , inline="Z3", group=groupZ)
showHLlines = input.bool (true , title="Li." , inline="Z3", group=groupZ)
zL2style = input.string (i_line2 , title="" , options=[i_line0, i_line1, i_line2], inline="Z3", group=groupZ)
styleZ1 = f_getLineStyle(zL1style)
styleZ2 = f_getLineStyle(zL2style)
zL1width = input.int(1, minval=0, title="Width", inline="Z2", group=groupZ)
zL2width = input.int(1, minval=0, title="Wi.", inline="Z3", group=groupZ)
colorZUP = input(color.new(color.green, 25), title="", inline="Z2", group=groupZ)
colorZDN = input(color.new(color.red, 25), title="", inline="Z2", group=groupZ)
colorHIH = input(color.new(color.red, 75) , title="H/L Colors: HH", inline="Z4", group=groupZ)
colorHIL = input(color.new(color.orange, 75), title="LH" , inline="Z4", group=groupZ)
colorLOL = input(color.new(color.green, 75) , title="LL" , inline="Z4", group=groupZ)
colorLOH = input(color.new(#2196F3, 75) , title="HL" , inline="Z4", group=groupZ)
// ----------------------
if ph and valH > valpH and showHL
lbl := label.new(n[length], math.max(r,l), HIH, color=colorHIH,
style=label.style_label_down, textcolor=color.new(color.white, 15), size=size.small)
label.delete(lbl[1])
linehh = showHLlines ? line.new(n[length], math.max(r,l), bar_index, math.max(r,l), extend=extend.right, style=styleZ2, color=colorHIH, width=zL2width) : na
line.delete(linehh[1])
else if ph and valH < valpH and showHL
lbl := label.new(n[length], math.max(r,l), HIL, color=colorHIL,
style=label.style_label_down, textcolor=color.new(color.white, 15), size=size.small)
label.delete(lbl[1])
linehl = showHLlines ? line.new(n[length], math.max(r,l), bar_index, math.max(r,l), extend=extend.right, style=styleZ2, color=colorHIL, width=zL2width) : na
line.delete(linehl[1])
else if pl and valL < valpL and showHL
lbl := label.new(n[length], math.min(r,l), LOL, color=colorLOL,
style=label.style_label_up, textcolor=color.new(color.white, 15), size=size.small)
label.delete(lbl[1])
linell = showHLlines ? line.new(n[length], math.min(r,l), bar_index, math.min(r,l), extend=extend.right, style=styleZ2, color=colorLOL, width=zL2width) : na
line.delete(linell[1])
else if pl and valL > valpL and showHL
lbl := label.new(n[length], math.min(r,l), LOH, color=colorLOH,
style=label.style_label_up, textcolor=color.new(color.white, 15), size=size.small)
label.delete(lbl[1])
linelh = showHLlines ? line.new(n[length], math.min(r,l), bar_index, math.min(r,l), extend=extend.right, style=styleZ2, color=colorLOH, width=zL2width) : na
line.delete(linelh[1])
label.delete(lbl[250])
// ----------------------
showBG = input.bool(true, title="OB/OS Bkg.", inline="LR1", group=groupLR)
bgcolor(rsi > linReg + deviation and ta.pivothigh(rsi, length, 0) and rsi >= 65 and showBG ? color.new(color.red, 95) : rsi < linReg - deviation and ta.pivotlow(rsi, length, 1) and rsi <= 35 and showBG ? color.new(color.green, 95) : na)
// ----------------------
extendOptionUp = input.string("None", title="Upper Line Ext.", options=["None", "Left", "Right", "Both"], inline="ZUP", group=groupZ)
extendOptionLow = input.string("None", title="Lower Line Ext.", options=["None", "Left", "Right", "Both"], inline="ZLOW", group=groupZ)
lengthdiv = input.int(21 , minval=0, title="Leftbars Len." , inline="ZUP", group=groupZ)
lengthright = input.int(0 , minval=0, title="Rightbars Le." , inline="ZLOW", group=groupZ)
lengthwg = lengthright
length2wg = lengthright
astart = input.int(1 , minval=0, title="Draw Upper Line from Pivot" , inline="ZP1", group=groupZ)
aend = input.int(0 , minval=0, title=">" , inline="ZP1" , group=groupZ)
bstart = input.int(1 , minval=0, title="Draw Lower Line from Pivot" , inline="ZP2", group=groupZ)
bend = input.int(0 , minval=0, title=">" , inline="ZP2", group=groupZ)
upwg = ta.pivothigh(rsi, lengthdiv, lengthright)
dnwg = ta.pivotlow(rsi, lengthdiv, lengthright)
upchart = ta.pivothigh(close, lengthdiv, lengthright)
dnchart = ta.pivotlow(close, lengthdiv, lengthright)
nw = bar_index
a1 = ta.valuewhen(not na(upwg), nw, astart)
b1 = ta.valuewhen(not na(dnwg), nw, bstart)
a2 = ta.valuewhen(not na(upwg), nw, aend)
b2 = ta.valuewhen(not na(dnwg), nw, bend)
ach1 = ta.valuewhen(not na(upchart), nw, astart)
bch1 = ta.valuewhen(not na(dnchart), nw, bstart)
ach2 = ta.valuewhen(not na(upchart), nw, aend)
bch2 = ta.valuewhen(not na(dnchart), nw, bend)
// ----------------------
lineExtendUp = extendOptionUp == "Left" ? extend.left :
extendOptionUp == "Right" ? extend.right :
extendOptionUp == "Both" ? extend.both :
extend.none
lineExtendLow = extendOptionLow == "Left" ? extend.left :
extendOptionLow == "Right" ? extend.right :
extendOptionLow == "Both" ? extend.both :
extend.none
//line upper = line.new(nw[nw - a1 + lengthwg], upwg[nw - a1 + lengthwg], nw[nw - a2 + lengthwg], upwg[nw - a2 + lengthwg], extend=lineExtendUp, color=colorZDN, width=zL1width, style=styleZ1)
//line.delete(upper[1])
//line lower = line.new(nw[nw - b1 + length2wg], dnwg[nw - b1 + length2wg], nw[nw - b2 + length2wg], dnwg[nw - b2] , extend=lineExtendLow, color=colorZUP, width=zL1width, style=styleZ1)
//line.delete(lower[1])
// ----------------------
div1 = upwg[nw - a2] < upwg[nw - a1] and upchart[nw - ach2] > upchart[nw - ach1] and upchart > high[nw - ach1] // and ta.pivotlow(rsi,length,0)
div2 = dnwg[nw - b2] > dnwg[nw - b1] and dnchart[nw - bch2] < dnchart[nw - bch1] and dnchart < low[nw - bch1] // and ta.pivothigh(rsi,length,0)
if div1 and showDiv
line.new(nw[nw - a1 + lengthwg], upwg[nw - a1], nw[nw - a2 + lengthwg], upwg[nw - a2], extend=lineExtendUp, color=colorZDN, width=zL1width, style=styleZ1)
label1 = label.new(nw[nw - a2 + lengthwg], 70 , text="div.", style=label.style_label_up, color=color.new(color.red, 100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.new(color.red, 15))
if div2 and showDiv
line.new(nw[nw - b1 + length2wg], dnwg[nw - b1], nw[nw - b2 + length2wg], dnwg[nw - b2], extend=lineExtendLow, color=colorZUP, width=zL1width, style=styleZ1)
label2 = label.new(nw[nw - b2 + length2wg], 30, text="div.", style=label.style_label_down, color=color.new(color.green, 100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.new(color.green, 15))
// ----------------------
enterShort = div1
enterLong = div2
enterPos = div1 or div2
alertcondition(enterLong , title="Divergence Alert (Long)" , message="Go Long β²\n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(enterShort , title="Divergence Alert (Short)" , message="Go Short βΌ\n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(enterPos , title="Divergences Alert" , message="Ticker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}") |
Choppy Market EMA Identification | https://www.tradingview.com/script/KdIgRm3v-Choppy-Market-EMA-Identification/ | Fraggl | https://www.tradingview.com/u/Fraggl/ | 37 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Fraggl
//@version=5
indicator("Choppy Market EMA Identification", overlay=true)
src = input(close, 'Source', group="Strategy Config")
ema_len = input.int(200, minval=1, title='EMA Length', group="Strategy Config")
max_cross = input.int(1, title='EMA Crosses to invalidate')
lookback = input.int(6, minval=1, title='EMA Touch Lookback', group="Strategy Config")
ema_col = input.color(color.white, group="Strategy Config")
fun_numbersOfEmaCross(numbers, ema) =>
int crosses = 0
cr = ta.cross(close,ema)
for candleNo = 1 to numbers+1
if cr[candleNo]
crosses := crosses+1
[crosses]
ema = ta.ema(src, ema_len)
[C] = fun_numbersOfEmaCross(lookback, ema)
maColor = if C < max_cross
ema_col
else
color.new(color.white, 100)
plot(ema, title='TR EMA', color=maColor, linewidth=2)
|
R2-Adaptive Regression | https://www.tradingview.com/script/cgCHhXpJ-R2-Adaptive-Regression/ | bjr117 | https://www.tradingview.com/u/bjr117/ | 23 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© bjr117, alexgrover
//@version=5
indicator(title = "R2-Adaptive Regression", shorttitle = "R2AR", overlay = true)
//==============================================================================
// Inputs
//==============================================================================
r2ar_length = input.int(title = "R2AR Length", defval = 100, minval = 1)
r2ar_src = input.source(title = "R2AR Source", defval = close)
//==============================================================================
//==============================================================================
// Mathematical Functions
//==============================================================================
a(x) => ta.stdev(r2ar_src, r2ar_length) * ta.correlation(r2ar_src, x, r2ar_length) / ta.stdev(x, r2ar_length)
b(x) => ta.sma(r2ar_src, r2ar_length) - a(x)*ta.sma(x, r2ar_length)
r(x) => math.pow(ta.correlation(r2ar_src, x, r2ar_length), 2)
//==============================================================================
//==============================================================================
// Calculating the R2-Adaptive Regression line
//==============================================================================
out = float(0.0)
x2 = nz(out[1], r2ar_src)
y1 = ta.linreg(r2ar_src, r2ar_length, 0)
y2 = a(x2)*x2 + b(x2)
out := r(y1)*y1 + r(y2)*y2 + (1 - (r(y1) + r(y2)))*x2
//==============================================================================
//==============================================================================
// Plotting the R2-Adaptive Regression line
//==============================================================================
plot(out, title = "R2AR", color = color.new(#000000, 0))
//============================================================================== |
Choppy Market EMA Identification | https://www.tradingview.com/script/8HQvXISz-Choppy-Market-EMA-Identification/ | Fraggl | https://www.tradingview.com/u/Fraggl/ | 13 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Fraggl
//@version=5
indicator("Choppy Market EMA Identification", overlay=true)
src = input(close, 'Source', group="Strategy Config")
ema_len = input.int(200, minval=1, title='EMA Length', group="Strategy Config")
max_cross = input.int(1, title='EMA Crosses to invalidate')
lookback = input.int(6, minval=1, title='EMA Touch Lookback', group="Strategy Config")
ema_col = input.color(color.white, group="Strategy Config")
fun_numbersOfEmaCross(numbers, ema) =>
int crosses = 0
cr = ta.cross(close,ema)
for candleNo = 1 to numbers+1
if cr[candleNo]
crosses := crosses+1
[crosses]
ema = ta.ema(src, ema_len)
[C] = fun_numbersOfEmaCross(lookback, ema)
maColor = if C < max_cross
ema_col
else
color.new(color.white, 100)
plot(ema, title='TR EMA', color=maColor, linewidth=2)
|
Psychological levels (Bank levels) by tartigradia | https://www.tradingview.com/script/hLhvmcSX-Psychological-levels-Bank-levels-by-tartigradia/ | tartigradia | https://www.tradingview.com/u/tartigradia/ | 40 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© tartigradia
//
// Description:
// Psychological levels (Bank levels) plots the price levels by truncating after the nth leftmost digits, as it appears the humain brain tends to intuitively calculate in log/zipf.
// Contrary to other similar scripts, this one uses a mathematical calculation that extracts the 1, 2 or 3 leftmost digits and calculate the previous and next level by incrementing/decrementing these digits. This means it works for any asset at any price range.
// For example, if price is at 0.0421, the next major price level is 0.05 and medium one is 0.043. For another asset currently priced at 19354, the next and previous major price levels are 20000 and 10000 respectively, and the next/previous medium levels are 20000 and 19000, and the next/previous weak levels are 19400 and 19300.
// By default, strong upper level is in green, strong lower level is in red, medium upper level is in blue, medium lower level is in yellow, and weak levels aren't displayed but can be. Strong levels are increments of the first leftmost digit (eg, 10000 to 20000), medium levels are increments of the second leftmost digit (eg, 19000 to 20000), and weak levels of the third leftmost digit (eg, 19100 to 19200). Instead of plotting all the psychological levels all at once as a grid, which makes the chart unintelligible, here the levels adapt dynamically around the current price, so that they show the upper/lower levels relatively to the current price.
// A simple moving average is implemented, so that "half-levels" are also displayed when relevant (eg, medium level can also display 19500 instead of only 19000 or 20000). This can be disabled by setting smoothing to 1.
// I made this script mainly to train with PineScript, but I guess it can be useful for new traders, as it's easy to forget that psychological levels can often be as strong if not stronger than technical levels.
//@version=5
indicator(title='Psychological levels (Bank levels) by tartigradia', shorttitle='PsychoLevels', format=format.price, timeframe="D", timeframe_gaps=false, overlay=true)
//
// Aux functions
// Detect the n left-most digits
f_nleftmostdigits(_num, _n, _increment) =>
// If input price number is smaller than 1.0, then we add 1 to n because 0 counts as a significant number, eg, 0.0456 with n=2 would return 0.04 instead of 0.045
_n2 = (_num < 1.0) ? _n + 1 : _n
// Get the n leftmost digits, by using log10 to remove lower order digits
nleftmostdigits_nb = int(_num / math.pow(10, (int(math.log10(_num)) - _n2 + 1)))
// Get the smallest unit at exact the n leftmost digit, this eases calculation of next or previous value
nleftmostdigits_unit = math.pow(10, (int(math.log10(_num)) - _n2 + 1))
// Truncate input price after the n leftmost digits
nleftmostdigits_truncated = nleftmostdigits_nb * nleftmostdigits_unit
// Return the next or previous (above or below) truncated price at the n leftmost digits
nleftmostdigits_truncated + nleftmostdigits_unit * _increment
// Rounding function, from TradingView PineScript v5 manual, deprecated, not used
f_round(_val, _decimals) =>
// Rounds _val to _decimals places.
_p = math.pow(10, _decimals)
math.round(math.abs(_val) * _p) / _p * math.sign(_val)
//
// Inputs
src = input(close, title='Data source')
smooth = input.int(2, 'Smoothing (SMA)', minval=1, tooltip='Smooth out transitions by calculating the average between the previous and next psychological level, this allows to display "half-levels" (eg, medium levels can display 19500 instead of only 19000 or 20000). Set smoothing to 1 to disable. Values above 2 are disadvised as the levels will not be psychologically meaningful anymore (eg, 19667).')
cgr = color.green
cre = color.red
cbl = color.teal
cye = color.yellow
//
// Plot
plot(ta.sma(f_nleftmostdigits(src, 3, 1), smooth), 'Weak level above', color=color.new(cbl, 30), linewidth=1, style=plot.style_circles, display=display.none)
plot(ta.sma(f_nleftmostdigits(src, 3, 0), smooth), 'Weak level below', color=color.new(cye, 30), linewidth=1, style=plot.style_circles, display=display.none)
plot(ta.sma(f_nleftmostdigits(src, 2, 1), smooth), 'Medium level above', color=color.new(cbl, 30), linewidth=2, style=plot.style_circles)
plot(ta.sma(f_nleftmostdigits(src, 2, 0), smooth), 'Medium level below', color=color.new(cye, 30), linewidth=2, style=plot.style_circles)
// Plot strongest last so that it overlaps lower strength levels
plot(ta.sma(f_nleftmostdigits(src, 1, 1), smooth), 'Strong level above', color=color.new(cgr, 30), linewidth=3, style=plot.style_circles)
plot(ta.sma(f_nleftmostdigits(src, 1, 0), smooth), 'Strong level below', color=color.new(cre, 30), linewidth=3, style=plot.style_circles)
|
Adaptive Rebound Line (ARL) | https://www.tradingview.com/script/gMzPJzOS-Adaptive-Rebound-Line-ARL/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© More-Than-Enough
//@version=5
indicator(title = "Adaptive Rebound Line", shorttitle = "ARL", overlay = true, precision = 3, timeframe = "", timeframe_gaps = true)
Length = input(14, "Length")
Exponent = input.int(0, "Exponent", step = 10)
Primary_Source = input(hlc3, "Primary Source")
Secondary_Source = input(low, "Secondary Source")
Deviation = input.float(0.0, "Deviation", step = 0.1)
ARL = (ta.ema(Secondary_Source, Length)[1] + (Primary_Source - ta.ema(Secondary_Source, Length)[1]) / (Length * math.pow(Primary_Source / ta.ema(close, Length)[1], Exponent))) * (1.00 + (Deviation * 0.01))
plot(ARL, title = "ARL", color = color.rgb(91, 156, 246), linewidth = 2) |
Tide Finder (TiFi) | https://www.tradingview.com/script/gpD7ciTV-Tide-Finder-TiFi/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© More-Than-Enough
//@version=5
indicator(title = "Tide Finder", shorttitle = "TiFi", overlay = true, precision = 2)
/// Settings ///
Magnetic_Waves_On = input.bool(title = "Magnetic Waves", defval = true)
Water_Level_On = input.bool(title = "Water Level", defval = true)
Lines_On = input.bool(title = "Lines", defval = false)
Compass_On = input.bool(title = "Compass", defval = false)
Compass_Record_On = input.bool(title = "Compass Record", defval = false)
Cycle_On = input.bool(title = "Day & Night Cycle", defval = false)
Ship_Path_On = input.bool(title = "Ship Path", defval = false)
/// Calculations ///
/// Day & Night Cycle ///
AM = ta.ema(close, 55)
PM = ta.ema(close, 200)
Day = ta.crossunder(PM, AM)
Night = ta.crossover(PM, AM)
/// Compass (Magnetic Polarity) ///
North_Polarity_Source = ta.ema(hlc3, 8)
North_Polarity = (North_Polarity_Source[1] * (7) + hlc3) / 8
South_Polarity_Source = ta.ema(hlc3, 24)
South_Polarity = (South_Polarity_Source[1] * (23) + hlc3) / 24
/// Water Level ///
Water_Level = ta.rsi(close, 14)
High_Water_Level = (Water_Level >= 68.5)
Low_Water_Level = (Water_Level <= 31.5)
/// Lines ///
// Slow Middle Line Calculations
Source_Sum = math.sum(math.abs(hlc3 - hlc3[1]), 5)
Change_Ratio = if Source_Sum != 0
math.abs(hlc3 - hlc3[5]) / Source_Sum
Ratio_Smoothing = math.pow(Change_Ratio * ((2 / (2.5 + 1)) - (2 / (20 + 1))) + (2 / (20 + 1)), 2)
Previous_Ratio = 0.0
Previous_Ratio := nz(Previous_Ratio[1]) + Ratio_Smoothing * (hlc3 - nz(Previous_Ratio[1]))
Ratio_Close = Previous_Ratio
HAshi_Close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, Ratio_Close)
//
Line_Deviation = ta.stdev(close, 20)
Line_Split = ta.sma(close, 20)
Top_Line = Line_Split + (Line_Deviation * 3)
High_Line = Line_Split + (Line_Deviation * 2)
Slow_Middle_Line = ta.ema(HAshi_Close, 20) // Slow Middle Line (Kaufman Adaptive Moving Average)
Fast_Middle_Line = ta.ema(low, 14)[1] + (hlc3 - ta.ema(low, 14)[1]) / (14 * math.pow(hlc3 / ta.ema(close, 14)[1], 4)) // Fast Middle Line (Adaptive Rebound Line)
Low_Line = Line_Split - (Line_Deviation * 2)
Bottom_Line = Line_Split - (Line_Deviation * 3)
Dip_Line_Calculation = low - (ta.atr(20) * 5.0)
Dip_Line = ta.sma(Dip_Line_Calculation, 75)
/// Magnetic Waves ///
Wave_Length = 75
Magnetic_Source = hlc3
Wave_Current = ta.ema(Magnetic_Source, Wave_Length)
North_Pole = ((Wave_Current[1] * (Wave_Length - 1) + Magnetic_Source) / Wave_Length) * (104 * 0.01) // Alt: (105 * 0.01)
Northern_Hemisphere = ((Wave_Current[1] * (Wave_Length - 1) + Magnetic_Source) / Wave_Length) * (102 * 0.01) // Alt: (102.5 * 0.01)
Equator = ((Wave_Current[1] * (Wave_Length - 1) + Magnetic_Source) / Wave_Length) * (100 * 0.01)
Southern_Hemisphere = ((Wave_Current[1] * (Wave_Length - 1) + Magnetic_Source) / Wave_Length) * (98 * 0.01) // Alt: (97.5 * 0.01)
South_Pole = ((Wave_Current[1] * (Wave_Length - 1) + Magnetic_Source) / Wave_Length) * (96 * 0.01) // Alt: (95 * 0.01)
/// Plots /// "β" "β" "β’"
/// Day & Time Cycle ///
plot(Cycle_On ? PM : na, title = "Night Time", color = color.blue, linewidth = 4)
plot(Cycle_On ? AM : na, title = "Day Time", color = color.yellow, linewidth = 4)
plotshape(Cycle_On ? Night : na, title = "Moon", style = shape.circle, location = location.top, color = color.blue, size = size.normal)
plotshape(Cycle_On ? Day : na, title = "Sun", style = shape.circle, location = location.top, color = color.yellow, size = size.normal)
/// Magnetic Waves ///
plot(Magnetic_Waves_On ? North_Pole : na, title = "North Pole", color = color.rgb(129, 199, 132, 50), style = plot.style_circles) // North Pole
plot(Magnetic_Waves_On ? Northern_Hemisphere : na, title = "Northern Hemisphere", color = color.rgb(129, 199, 132, 75), style = plot.style_circles) // Northern Hemisphere
plot(Magnetic_Waves_On ? Equator : na, title = "Equator", color = color.rgb(144, 191, 249, 50), style = plot.style_circles) // Equator
plot(Magnetic_Waves_On ? Southern_Hemisphere : na, title = "Southern Hemisphere", color = color.rgb(247, 124, 128, 75), style = plot.style_circles) // Southern Hemisphere
plot(Magnetic_Waves_On ? South_Pole : na, title = "South Pole", color = color.rgb(247, 124, 128, 50), style = plot.style_circles) // South Pole
/// Ship Path ///
plot(Ship_Path_On ? ta.sar(0.02, 0.02, 0.2) : na, title = "Wave Shape", color = color.orange, style = plot.style_stepline_diamond)
plot(Ship_Path_On ? high : na, title = "High Point", color = color.rgb(0, 230, 118, 50), style = plot.style_stepline)
plot(Ship_Path_On ? close : na, title = "Close Point", color = color.white, linewidth = 2)
plot(Ship_Path_On ? low : na, title = "Low Point", color = color.rgb(255, 82, 82, 50), style = plot.style_stepline)
/// Water Level ///
plotshape(Water_Level_On ? High_Water_Level : na, title = "High Water Level", style = shape.circle, location = location.abovebar, color = color.red, size = size.tiny)
plotshape(Water_Level_On ? Low_Water_Level : na, title = "Low Water Level", style = shape.circle, location = location.belowbar, color = color.lime, size = size.tiny)
/// Lines ///
plot(Lines_On ? Top_Line : na, title = "Top Line", color = color.rgb(165, 214, 167, 50))
plot(Lines_On ? High_Line : na, title = "High Line", color = color.rgb(165, 214, 167))
plot(Lines_On ? Slow_Middle_Line : na, title = "Slow Middle Line (KAMA)", color = color.rgb(144, 191, 249))
plot(Lines_On ? Fast_Middle_Line : na, title = "Fast Middle Line (ARL)", color = color.rgb(144, 191, 249))
plot(Lines_On ? Low_Line : na, title = "Low Line", color = color.rgb(250, 161, 164))
plot(Lines_On ? Bottom_Line : na, title = "Bottom Line", color = color.rgb(250, 161, 164, 50))
plot(Lines_On ? Dip_Line : na, title = "Dip Line", color = color.yellow)
/// Compass ///
plot(Compass_On ? South_Polarity : na, title = "South Magnetic Polarity", color = color.red, linewidth = 3, offset = 8, show_last = Compass_Record_On ? na : 25) // South Polarity
plot(Compass_On ? North_Polarity : na, title = "North Magnetic Polarity", color = color.rgb(0, 188, 212), linewidth = 3, offset = 3, show_last = Compass_Record_On ? na : 20) // North Polarity
|
Realtime Cumulative Delta | https://www.tradingview.com/script/SrwsemQt-Realtime-Cumulative-Delta/ | StalinTrading | https://www.tradingview.com/u/StalinTrading/ | 170 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© StalinTrading
//@version=5
indicator("Realtime CVD")
linestyle = input.string(defval='Candle', title='Style', options=['Candle', 'Line'])
varip buyvol = 0.0
varip sellvol = 0.0
varip lastprice = 0.0
varip lastvolume = 0.0
varip cumdelta = 0.0
varip o_ = 0.0
varip c_ = 0.0
varip h_ = 0.0
varip l_ = 0.0
if barstate.isrealtime and lastvolume != volume
buyvol += close > lastprice ? (volume-lastvolume) : close == lastprice ? (volume-lastvolume)*0.5 : 0
sellvol += close < lastprice ? (volume-lastvolume) : close == lastprice ? (volume-lastvolume)*0.5 : 0
lastprice := close
lastvolume := volume
c_ := buyvol-sellvol + nz(c_[1])
o_ := c_[1]
h_ := buyvol-sellvol > 0 ? o_ + sellvol : c_ + sellvol
l_ := buyvol-sellvol > 0 ? c_ - buyvol : o_ - buyvol
if barstate.isnew
lastprice := close
lastvolume := volume
buyvol := 0
sellvol := 0
plot(buyvol, color=color.new(color.teal, 30), style=plot.style_columns, title="β§ Buyvol", display = display.none)
plot(-sellvol, color=color.new(color.red, 30), style=plot.style_columns, title="β© Sellvol", display = display.none)
plot(buyvol-sellvol, color=color.new(color.white, 20), style=plot.style_columns, title="Delta", display = display.none)
plot(c_, title="Cum Ξ", color=color.new(color.yellow, 0), display = display.none)
colo = buyvol-sellvol > 0 ? color.new(color.teal, 30) : color.new(color.red, 30)
plotcandle(o_, h_, l_, c_, color=colo, title="Cum Ξ candle", wickcolor = color.new(color.white, 100)) |
Indicator Cheat Mode | https://www.tradingview.com/script/1TnFGnNg-Indicator-Cheat-Mode/ | ExoPlanetaryEdu | https://www.tradingview.com/u/ExoPlanetaryEdu/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© ExoPlanetaryEdu
//@version=5
indicator("Cheat Mode Enabled", overlay = true)
//MACD Variables
fastLength = input.int( defval=12, title="Fast Length")
slowLength = input.int( defval=26, title="Slow Length")
MACDLength = input.int( defval=9, title="MACD Length")
//Stochastic Variables
KPeriod = input.int( defval=14, title="Stochastic K Period")
DPeriod = input.int( defval=3, title="Stochastic D Period")
smoothK = input.int(1, title="%K Smoothing", minval=1)
//RSI Variable
RSILength = input.int( defval=9, title="RSI Length")
Midpt = 0.00
// MACD histogram change
//Get the MACD
[macdLine, signalLine, histLine] = ta.macd(close, fastLength, slowLength, MACDLength)
//Set Buy to be when the the hist is lower than previous candle but that previous candle is higher than it's previous (Previous candle is a peak)
MACDBuy = histLine > histLine [1] and histLine[1] < histLine [2]
//Set Sell to be opposite (Negative Peak)
MACDSell = histLine < histLine [1] and histLine[1] > histLine [2]
//plotshape(MACDBuy, title="MACD", location=location.belowbar, color=color.green, style=shape.triangleup, text="MACDBuy", textcolor=color.green)
//plotshape(MACDSell, title="MACD", location=location.abovebar, color=color.red, style=shape.triangledown, text="MACDSell", textcolor=color.red)
//Stochastic slowK14 SlowD3
k = ta.sma(ta.stoch(close, high, low, KPeriod), smoothK)
d = ta.sma(k, DPeriod)
//Set Buy to be when K is greater than D but between 80 and 30, Do not want to buy with K having no up side room, or buy when in a low state
StochBuy = k > k[1] and k[1] > k[2] and k > 30
//Set sell to be when k is less than D
StochSell =k < k[1] and k[1] < k[2]
//plotshape(StochBuy, title="Stoch", location=location.belowbar, color=color.green, style=shape.triangleup, text="StochBuy", textcolor=color.green)
//plotshape(StochSell, title="Stoch", location=location.abovebar, color=color.red, style=shape.triangledown, text="StochSell", textcolor=color.red)
//Get RSI
RSIValue = ta.rsi(close, RSILength)
//set buy to be RSI rising for 2 periods but still less than overbought (70)
RSIBuy = (RSIValue > RSIValue[1]) and (RSIValue > RSIValue[2]) and RSIValue < 70
//Set sell to be RSI falling for 2 periods but still not oversold
RSISell = (RSIValue < RSIValue[1]) and (RSIValue < RSIValue[2]) and RSIValue > 30
//RSI troubleshooting
//plotshape(RSIBuy, title="RSI", location=location.belowbar, color=color.green, style=shape.triangleup, text="RSIBuy", textcolor=color.green)
//plotshape(RSISell, title="RSI", location=location.abovebar, color=color.red, style=shape.triangledown, text="RSISell", textcolor=color.red)
//Buy-sell stock definitions
BuyStock = (StochBuy and RSIBuy and (MACDBuy or MACDBuy[1]))
SellStock = (StochSell and RSISell and (MACDSell or MACDSell[1]))
//Plot Shapes
plotshape(SellStock, title="Sell", location=location.abovebar, color=color.red, style=shape.triangledown, text="Sell", textcolor=color.red)
plotshape(BuyStock, title="Buy", location=location.belowbar, color=color.green, style=shape.triangleup, text="Buy", textcolor=color.green)
//if (open > close)
// Midpt := low
//if (close > open)
// Midpt := high
//if (open == close)
// Midpt := open
//if ((Midpt > Midpt[1]) and (Midpt[1] >= Midpt[2]))
// Midpt[1] == (Midpt + Midpt[2])/2
//plot(Midpt, color=color.red, linewidth=2)
|
STD-Filtered, ATR-Adaptive Laguerre Filter [Loxx] | https://www.tradingview.com/script/ANHAenmR-STD-Filtered-ATR-Adaptive-Laguerre-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 139 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD-Filtered, ATR-Adaptive Laguerre Filter [Loxx]",
shorttitle = "STDFATRALF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
_lagfiltosc(float src, float per) =>
float _gamma = 1.0 - 10.0 / (per + 9.0)
float L0 = 0.0, float L1 = 0.0, float L2 = 0.0, float L3 = 0.0
L0 := (1 - _gamma) * src + _gamma * nz(L0[1])
L1 := -_gamma * L0 + nz(L0[1]) + _gamma * nz(L1[1])
L2 := -_gamma * L1 + nz(L1[1]) + _gamma * nz(L2[1])
L3 := -_gamma * L2 + nz(L2[1]) + _gamma * nz(L3[1])
float out = (L0 + 2.0 * L1 + 2.0 * L2 + L3)/6.0
out
//std filter
_filt(float src, simple int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - price[1]) < filtdev ? price[1] : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(20, "Laguerre/ATR Period", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "Laguerre Filter", "Both", "None"], group= "Filter Settings")
filter = input.float(2, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(10, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
//first source
src := filterop == "Both" or filterop == "Price" and filter > 0 ? _filt(src, filterperiod, filter) : src
//apply ATR adaptivity
atr = ta.atr(per)
fmax = ta.highest(atr, per)
fmin = ta.lowest(atr, per)
coeff = (fmin != fmax) ? 1 - (atr - fmin)/(fmax - fmin) : 0.5
val = _lagfiltosc(src, per * (coeff + 1.0) / 2.0)
//apply standard devaition filter
out = val
out := filterop == "Both" or filterop == "Laguerre Filter" and filter > 0 ? _filt(out, filterperiod, filter) : out
sig = nz(out[1])
state = 0
if (out > sig)
state := 1
if (out < sig)
state := -1
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "N-Pole GF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD-Filtered, ATR-Adaptive Laguerre Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD-Filtered, ATR-Adaptive Laguerre Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
VIX Implied range | https://www.tradingview.com/script/fDV8T7Qf-VIX-Implied-range/ | VolTrader005 | https://www.tradingview.com/u/VolTrader005/ | 64 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© twdsje
//@version=4
study("VIX Range Estimate", overlay=true)
volatilityindex = input(title="Index", type=input.string, defval="CBOE:VIX")
vix = security(volatilityindex, timeframe.period, open)
highTimeFrame = input("D", type=input.resolution)
sessSpec = input("0830-1500", type=input.session)
is_newbar(res, sess) =>
t = time(res, sess)
na(t[1]) and not na(t) or t[1] < t
newbar = is_newbar("1440", sessSpec)
float s1 = na
s1 := newbar ? open : nz(s1[1])
float vixopen = na
vixopen := newbar ? vix : nz(vixopen[1])
float vixpercent = (vixopen / 19) * .01
float highestimate = s1 * (1 + vixpercent)
float high50estimate = s1 * (1 + (vixpercent *.5))
float lowestimate = s1 * (1 - vixpercent)
float low50estimate = s1 * (1 - (vixpercent * .5))
plot(s1, style=plot.style_circles, linewidth=1, color=color.gray)
//plot(vixopen, style=plot.style_circles, linewidth=3, color=color.red)
plot(highestimate, style=plot.style_circles, linewidth=1, color=color.red)
plot(lowestimate, style=plot.style_circles, linewidth=1, color=color.red)
plot(high50estimate, style=plot.style_circles, linewidth=1, color=color.red)
plot(low50estimate, style=plot.style_circles, linewidth=1, color=color.red) |
Tickers Info Extension | https://www.tradingview.com/script/8wJZQ9YH-Tickers-Info-Extension/ | HALDRO | https://www.tradingview.com/u/HALDRO/ | 124 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© HALDRO
opt01 = 'XAU'
opt02 = 'DXY'
opt03 = 'BTC'
opt04 = 'ETH'
opt05 = 'SPX'
opt06 = 'NASDAQ'
opt07 = 'AVG STABLE.D'
opt08 = 'AVG STOCK Price'
opt09 = 'Alt Cap(TOTAL3)'
opt10 = 'Custom'
MA(source, length, type) =>
switch type
'SMA' => ta.sma(source, length)
'EMA' => ta.ema(source, length)
'RMA' => ta.rma(source, length)
'WMA' => ta.wma(source, length)
'VWMA'=> ta.vwma(source, length)
'HMA' => ta.hma(source, length)
//@version=5
indicator('Tickers Info Extension')
// Chart Inputs
mod = input.session (opt01, 'Mode', group='Chart', inline='mode', options=[opt01, opt02, opt03, opt04, opt05, opt06, opt07, opt08, opt09, opt10])
custom = input.symbol ('', 'Custom', group='Chart', inline='mode', tooltip='If you want to select a different ticker, then select the Custom in Mode option')
compare = input.bool (true, 'Compare ?', group='Chart', inline='comp', tooltip='If Compare ON, the current ticker is divided by the selection in Mode')
typesym = input.session ('Candles', 'Type Symbol', group='Chart', inline='symb', options=['Candles', 'Open', 'High', 'Close', 'Low'])
// MA Settings
usema = input.bool (true, 'Use MA ?', group='MA Settings')
length = input.int (0050, 'Length', group='MA Settings', inline='ma')
maType = input.string ('EMA', 'MA Type', group='MA Settings', inline='ma', options=['SMA', 'EMA', 'RMA', 'WMA', 'VWMA', 'HMA'])
// Color
upColor = input.color (#00ff6d, 'UP Col', group='Color', inline='color')
dnColor = input.color (#ff0056, 'DN Col', group='Color', inline='color')
wickColor = input.color (#ffffff, 'Wick Col', group='Color', inline='color')
tablefont = input.color (#ffa726, 'Panel Font', group='Color', inline='table')
tablebg = input.color (#363A45, 'Panel BG', group='Color', inline='table')
// Ticker List
TF = timeframe.period
ANY = syminfo.tickerid
CST = custom
BTC = 'BITSTAMP:BTCUSD'
DJI = 'TVC:DJI'
DXY = 'TVC:DXY'
ETH = 'BINANCE:ETHUSDT'
NDX = 'NASDAQ:NDX'
SPX = 'TVC:SPX'
WM2NS = 'FRED:WM2NS'
XAU = 'OANDA:XAUUSD'
USDT_D = 'CRYPTOCAP:USDT.D'
USDC_D = 'CRYPTOCAP:USDC.D'
DDAI_D = 'CRYPTOCAP:DAI.D'
TOTAL3 = 'TOTAL3'
// Request OHLC
[O_ANY, H_ANY, L_ANY, C_ANY] = request.security(ANY, TF, [open, high, low, close])
[O_BTC, H_BTC, L_BTC, C_BTC] = request.security(BTC, TF, [open, high, low, close])
[O_CST, H_CST, L_CST, C_CST] = request.security(CST, TF, [open, high, low, close])
[O_DJI, H_DJI, L_DJI, C_DJI] = request.security(DJI, TF, [open, high, low, close])
[O_DXY, H_DXY, L_DXY, C_DXY] = request.security(DXY, TF, [open, high, low, close])
[O_ETH, H_ETH, L_ETH, C_ETH] = request.security(ETH, TF, [open, high, low, close])
[O_NDX, H_NDX, L_NDX, C_NDX] = request.security(NDX, TF, [open, high, low, close])
[O_SPX, H_SPX, L_SPX, C_SPX] = request.security(SPX, TF, [open, high, low, close])
[O_XAU, H_XAU, L_XAU, C_XAU] = request.security(XAU, TF, [open, high, low, close])
[O_USDT_D, H_USDT_D, L_USDT_D, C_USDT_D] = request.security(USDT_D, TF, [open, high, low, close])
[O_USDC_D, H_USDC_D, L_USDC_D, C_USDC_D] = request.security(USDC_D, TF, [open, high, low, close])
[O_DDAI_D, H_DDAI_D, L_DDAI_D, C_DDAI_D] = request.security(DDAI_D, TF, [open, high, low, close])
[O_TOTAL3, H_TOTAL3, L_TOTAL3, C_TOTAL3] = request.security(TOTAL3, TF, [open, high, low, close])
// Calculation
// STOCK MARKET PRICE
O_STOCKAVG = (O_DJI + O_SPX + O_NDX) / 3
H_STOCKAVG = (H_DJI + H_SPX + H_NDX) / 3
L_STOCKAVG = (L_DJI + L_SPX + L_NDX) / 3
C_STOCKAVG = (C_DJI + C_SPX + C_NDX) / 3
// AVG STABLE COIN DOMINACE
O_AVGDOM = (O_USDT_D + O_USDC_D + O_DDAI_D)
H_AVGDOM = (H_USDT_D + H_USDC_D + H_DDAI_D)
L_AVGDOM = (L_USDT_D + L_USDC_D + L_DDAI_D)
C_AVGDOM = (C_USDT_D + C_USDC_D + C_DDAI_D)
// Get OHLC Selected Ticker
tickerMod(Type) =>
ticker_Open = switch Type
opt01 => O_XAU
opt02 => O_DXY
opt03 => O_BTC
opt04 => O_ETH
opt05 => O_SPX
opt06 => O_NDX
opt07 => O_AVGDOM
opt08 => O_STOCKAVG
opt09 => O_TOTAL3
opt10 => O_CST
ticker_High = switch Type
opt01 => H_XAU
opt02 => H_DXY
opt03 => H_BTC
opt04 => H_ETH
opt05 => H_SPX
opt06 => H_NDX
opt07 => H_AVGDOM
opt08 => H_STOCKAVG
opt09 => H_TOTAL3
opt10 => H_CST
ticker_Low = switch Type
opt01 => L_XAU
opt02 => L_DXY
opt03 => L_BTC
opt04 => L_ETH
opt05 => L_SPX
opt06 => L_NDX
opt07 => L_AVGDOM
opt08 => L_STOCKAVG
opt09 => L_TOTAL3
opt10 => L_CST
ticker_Close = switch Type
opt01 => C_XAU
opt02 => C_DXY
opt03 => C_BTC
opt04 => C_ETH
opt05 => C_SPX
opt06 => C_NDX
opt07 => C_AVGDOM
opt08 => C_STOCKAVG
opt09 => C_TOTAL3
opt10 => C_CST
if compare == true
ticker_Open := O_ANY / ticker_Open
ticker_High := H_ANY / ticker_High
ticker_Low := L_ANY / ticker_Low
ticker_Close := C_ANY / ticker_Close
[ticker_Open, ticker_High, ticker_Low, ticker_Close]
[O,H,L,C] = tickerMod(mod)
stype = switch typesym
'Open' => O
'High' => H
'Low' => L
'Close' => C
=> na
// Plots
colorCandle = C > O ? upColor : dnColor, wickcolor=wickColor, Bordercolor=colorCandle
plotcandle(O,H,L,C, color=colorCandle, wickcolor=wickColor, bordercolor=Bordercolor, editable=false, display=typesym != 'Candles' ? display.none : display.all)
plot(usema ? MA(C, length, maType) : na, 'MA')
plot(stype, title = 'Price')
// Panel Symbol Info
string symbolOnly = str.substring(CST, str.pos(CST, ':') + 1)
msg = ' / '
cond = compare and mod != opt10 ? syminfo.ticker + msg + mod : mod==opt10 and compare != true ? symbolOnly : mod==opt10 and compare ? syminfo.ticker + msg + symbolOnly : mod
var table panel = table.new(position = position.bottom_right, columns = 2, rows = 1, bgcolor = tablebg, border_width = 1)
if barstate.islast
table.cell(panel, 1, 0, text=str.tostring(cond), text_color = tablefont, bgcolor = tablebg)
|
Pro Trading Art - Broadening Wedges | https://www.tradingview.com/script/undnWhCB-Pro-Trading-Art-Broadening-Wedges/ | protradingart | https://www.tradingview.com/u/protradingart/ | 242 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© protradingart
//@version=5
indicator("Pro Trading Art - Broadening Wedges", "PTA- Broadening Wedges",
overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
pivotLeg = input.int(10, "Pivot Length")
var High = 0.0
var Low = 0.0
///////////////////// PH ////////////////////////////////////////////
var broadeningTop = array.new_float(na)
var broadeningTopIndex = array.new_int(na)
var line btLineRight = na
ph = ta.pivothigh(pivotLeg, pivotLeg)
if not na(ph)
array.push(broadeningTop, ph)
array.push(broadeningTopIndex, bar_index-pivotLeg)
if array.size(broadeningTop) > 2
array.shift(broadeningTop)
array.shift(broadeningTopIndex)
if array.size(broadeningTop) >= 2
btX1 = array.get(broadeningTopIndex, 0)
btY1 = array.get(broadeningTop, 0)
btX2 = array.get(broadeningTopIndex, 1)
btY2 = array.get(broadeningTop, 1)
line btLine = na
if btY2 > btY1
High := btY2
btLine := line.new(x1=btX1, y1=btY1, x2=btX2, y2=btY2, width=2, color=color.lime)
btLineRight := line.new(x1=btX2, y1=btY2, x2=bar_index, y2=btY2,
width=2, color=color.lime, style=line.style_dotted)
else
line.set_x2(btLineRight, bar_index)
///////////////////// PL ////////////////////////////////////////////
var broadeningBottom = array.new_float(na)
var broadeningBottomIndex = array.new_int(na)
var line bbLineRight = na
pl = ta.pivotlow(pivotLeg, pivotLeg)
if not na(pl)
array.push(broadeningBottom, pl)
array.push(broadeningBottomIndex, bar_index-pivotLeg)
if array.size(broadeningBottom) > 2
array.shift(broadeningBottom)
array.shift(broadeningBottomIndex)
if array.size(broadeningBottom) >= 2
bbX1 = array.get(broadeningBottomIndex, 0)
bbY1 = array.get(broadeningBottom, 0)
bbX2 = array.get(broadeningBottomIndex, 1)
bbY2 = array.get(broadeningBottom, 1)
line bbLine = na
if bbY2 > bbY1
Low := bbY2
bbLine := line.new(x1=bbX1, y1=bbY1, x2=bbX2, y2=bbY2, width=2, color=color.red)
bbLineRight := line.new(x1=bbX2, y1=bbY2, x2=bar_index, y2=bbY2,
width=2, color=color.red, style=line.style_dotted)
else
line.set_x2(bbLineRight, bar_index)
longCondition = ta.crossover(close, High)
shortCondition = ta.crossunder(close, Low)
plotshape(longCondition ? low : na, style=shape.labelup, location = location.absolute, size=size.normal, color=color.rgb(6, 245, 14), text = "Long", textcolor = color.black)
plotshape(shortCondition ? high : na, style=shape.labeldown, location = location.absolute, size=size.small, color=color.rgb(250, 1, 1), text="Short", textcolor = color.white)
if longCondition
alert("Upper Wedges Breakout In : "+ syminfo.ticker, alert.freq_once_per_bar_close)
if shortCondition
alert("Lower Wedges Breakout In : "+ syminfo.ticker, alert.freq_once_per_bar_close) |
Candlestick Channels [LuxAlgo] | https://www.tradingview.com/script/pzUpBSIm-Candlestick-Channels-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,759 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// Β© LuxAlgo
//@version=5
indicator("Candlestick Channels [LuxAlgo]", overlay = true, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(14, 'Trend Length'
, minval = 0)
alpha = input.float(50, 'Convergence'
, minval = 0
, maxval = 100)
smooth = input.int(7, 'Smooth'
, minval = 1)
//Patterns
enable_hammer = input(true, 'Hammer'
, group = 'patterns')
enable_ihammer = input(true, 'Inverted Hammer'
, group = 'patterns')
enable_shooting = input(true, 'Shooting Star'
, group = 'patterns')
enable_hanging = input(true, 'Hanging Man'
, group = 'patterns')
enable_bulleng = input(false, 'Bullish Engulfing'
, group = 'patterns')
enable_beareng = input(false, 'Bearish Engulfing'
, group = 'patterns')
enable_wm = input(true, 'White Marubozu'
, group = 'patterns')
enable_bm = input(true, 'Black Marubozu'
, group = 'patterns')
//Style
bull_css = input(#0cb51a, 'Bullish Color'
, group = 'Style')
avg_css = input(#ff5d00, 'Average Color'
, group = 'Style')
bear_css = input(#ff1100, 'Bearish Color'
, group = 'Style')
fade = input.int(200, 'Fading Period'
, minval = 1)
//-----------------------------------------------------------------------------}
//Variables/Functions
//-----------------------------------------------------------------------------{
n = bar_index
o = open,h = high,l = low,c = close
atr = ta.atr(20) / 2
st = ta.stoch(c, c, c, length)
downtrend = st < 50
uptrend = st > 50
d = math.abs(c - o)
//Label
lbl(y, txt, direction, tlt)=>
label.new(n, y, txt
, size = size.tiny
, style = direction == 1 ? label.style_label_up : label.style_label_down
, color = direction == 1 ? bull_css : bear_css
, textcolor = color.white
, tooltip = tlt)
//-----------------------------------------------------------------------------}
//Tooltips
//-----------------------------------------------------------------------------{
var hammer_tlt = "The hammer candlestick pattern is formed of a short body with a long lower wick, and is found at the bottom of a downward trend."
+ "\n" + "\nA hammer shows that although there were selling pressures during the day, ultimately a strong buying pressure drove the price back up."
var ihammer_tlt = "The inverted hammer is a similar pattern than the hammer pattern. The only difference being that the upper wick is long, while the lower wick is short."
+ "\n" + "\nIt indicates a buying pressure, followed by a selling pressure that was not strong enough to drive the market price down. The inverse hammer suggests that buyers will soon have control of the market."
var bulleng_tlt = "The bullish engulfing pattern is formed of two candlesticks. The first candle is a short red body that is completely engulfed by a larger green candle"
+ "\n" + "\nThough the second day opens lower than the first, the bullish market pushes the price up, culminating in an obvious win for buyers"
var wm_tlt = "The white marubozu is a single candles formation formed after a downtrend and indicating a bullish reversal."
+ "\n" + "\nThis candlestick has a long bullish body with no upper or lower shadows, reflecting a strong buying pressure."
var shooting_tlt = "The shooting star is the same shape as the inverted hammer, but is formed in an uptrend: it has a small lower body, and a long upper wick."
+ "\n" + "\nUsually, the market will gap slightly higher on opening and rally to an intra-day high before closing at a price just above the open β like a star falling to the ground."
var hanging_tlt = "The hanging man is the bearish equivalent of a hammer; it has the same shape but forms at the end of an uptrend."
+ "\n" + "\nIt indicates that there was a significant sell-off during the day, but that buyers were able to push the price up again. The large sell-off is often seen as an indication that the bulls are losing control of the market."
var beareng_tlt = "A bearish engulfing pattern occurs at the end of an uptrend. The first candle has a small green body that is engulfed by a subsequent long red candle."
+ "\n" + "\nIt signifies a peak or slowdown of price movement, and is a sign of an impending market downturn. The lower the second candle goes, the more significant the trend is likely to be."
var bm_tlt = "The black marubozu is a single candles formation formed after an uptrend and indicating a bearish reversal."
+ "\n" + "\nThis candlestick has a long bearish body with no upper or lower shadows, reflecting a strong selling pressure."
//-----------------------------------------------------------------------------}
//Pattern Rules
//-----------------------------------------------------------------------------{
hammer = downtrend and math.min(o, c) - l > 2 * d and h - math.max(c, o) < d / 4
ihammer = downtrend and h - math.max(o, c) > 2 * d and math.min(c, o) - l < d / 4
shooting = uptrend and h - math.max(o, c) > 2 * d and math.min(c, o) - l < d / 4
hanging = uptrend and math.min(o, c) - l > 2 * d and h - math.max(c, o) < d / 4
bulleng = downtrend and c > o and c[1] < o[1] and c > o[1] and d > atr
beareng = uptrend and c < o and c[1] > o[1] and c < o[1] and d > atr
wm = c > o and h - math.max(o, c) + math.min(o, c) - l < d / 10 and d > atr and downtrend[1]
bm = c < o and h - math.max(o, c) + math.min(o, c) - l < d / 10 and d > atr and uptrend[1]
//-----------------------------------------------------------------------------}
//Channel
//-----------------------------------------------------------------------------{
var max = h
var min = l
//Bullish Patterns
if hammer and enable_hammer
max += alpha / 100 * (c - max)
lbl(low, 'H', 1, hammer_tlt)
if ihammer and enable_ihammer
max += alpha / 100 * (c - max)
lbl(low, 'IH', 1, ihammer_tlt)
if bulleng and enable_bulleng
max += alpha / 100 * (c - max)
lbl(low, 'BE', 1, bulleng_tlt)
if wm and enable_wm
max += alpha / 100 * (c - max)
lbl(low, 'WM', 1, wm_tlt)
//Bearish Patterns
if shooting and enable_shooting
min += alpha / 100 * (c - min)
lbl(high, 'SS', 0, shooting_tlt)
if hanging and enable_hanging
min += alpha / 100 * (c - min)
lbl(high, 'HM', 0, hanging_tlt)
if beareng and enable_beareng
min += alpha / 100 * (c - min)
lbl(high, 'BE', 0, beareng_tlt)
if bm and enable_bm
min += alpha / 100 * (c - min)
lbl(high, 'BM', 0, bm_tlt)
max := math.max(c, max)
min := math.min(c, min)
smooth_max = ta.ema(max, smooth)
smooth_min = ta.ema(min, smooth)
avg = math.avg(smooth_max, smooth_min)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
var os = 0
os := c > smooth_max ? 1 : c < smooth_min ? 0 : os
var fade_max = 0
fade_max := os == 0 ? fade_max + 1 : 0
var fade_min = 0
fade_min := os == 1 ? fade_min + 1 : 0
plot_0 = plot(smooth_max, 'Upper', bull_css)
plot_1 = plot(avg, 'Average', avg_css)
plot_2 = plot(smooth_min, 'Lower', bear_css)
css1 = color.from_gradient(fade_max, 0, fade, color.new(bull_css, 80), color.new(bull_css, 100))
fill(plot_0, plot_1, css1)
css2 = color.from_gradient(fade_min, 0, fade, color.new(bear_css, 80), color.new(bear_css, 100))
fill(plot_1, plot_2, css2)
//-----------------------------------------------------------------------------} |
Jelle RSI DIV | https://www.tradingview.com/script/swBpY4d5-Jelle-RSI-DIV/ | Dionj1991 | https://www.tradingview.com/u/Dionj1991/ | 48 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© K-zax
//@version=5
indicator('Jelle RSI DIV')
// INDICATOR INPUT
//--------------------------------------------------------------------------------------------------------------------------
rsiLen = input.int(14, title='RSI Length', minval=1, group='RSI')
// OVERSELL / OVERBUY LEVEL INPUT
//--------------------------------------------------------------------------------------------------------------------------
overbuy = input.float(70, title='Overbuy', minval=0, maxval=100, group='Overbuy - Oversell')
oversell = input.float(30, title='Oversell', minval=0, maxval=100, group='Overbuy - Oversell')
useFillObOs = input.bool(true, 'Fill overbuy / oversell area', group='Overbuy - Oversell')
useBgObOs = input.bool(true, 'Plot background on overbuy / oversell', group='Overbuy - Oversell')
// DIVERGENCE INPUT
//--------------------------------------------------------------------------------------------------------------------------
priceTopBotSource = input.string('close', options=['High / Low', 'close'], title='Price top / bot source', group='Input')
loopback = input.int(defval=2, minval=1, title='Loopback', group='Divergence')
confirmation = input.int(defval=2, minval=1, title='Confirmation', group='Divergence')
topLimit = input.float(60, title='Top Detection Limit', minval=0, maxval=100, group='Divergence')
botLimit = input.float(40, title='Bottom Detection Limit', minval=0, maxval=100, group='Divergence')
maxLoopback = input.int(defval=50, minval=1, title='Max Divergence Loopback', group='Divergence')
showToBotDiv = input.bool(true, 'Highlight Div Top / Bot', group='Divergence')
// COLOR
//--------------------------------------------------------------------------------------------------------------------------
rsiLineColor = input(title='RSI line', defval=#0b9ebf)
obOsLineColor = input(title='Overbuy / oversell line', defval=color.gray)
fillObColor = input(title='Fill overbuy', defval=#2caa83)
fillOsColor = input(title='Fill oversell', defval=#cc141e)
bgObColor = input(title='Background overbuy', defval=#2caa83)
bgOsColor = input(title='Background oversell', defval=#cc141e)
divLineColor = input(title='Divergence line', defval=color.yellow)
topColor = input(title='Divergence top', defval=#2caa83)
botColor = input(title='Divergence bot', defval=#cc141e)
// INDICATEUR
//--------------------------------------------------------------------------------------------------------------------------
_rsi = ta.rsi(close, rsiLen)
// PLOT INDICATOR
//--------------------------------------------------------------------------------------------------------------------------
hline(overbuy, linestyle=hline.style_dotted, color=obOsLineColor)
hline(oversell, linestyle=hline.style_dotted, color=obOsLineColor)
rsiPlot = plot(_rsi, color=rsiLineColor)
upperLine = plot(overbuy, color=color.new(color.black, 100))
lowerLine = plot(oversell, color=color.new(color.black, 100))
fill(rsiPlot, upperLine, color=useFillObOs and _rsi > overbuy ? color.new(fillObColor, 50) : na, transp=90)
fill(rsiPlot, lowerLine, color=useFillObOs and _rsi < oversell ? color.new(fillOsColor, 50) : na, transp=90)
bgcolor(useBgObOs and _rsi > overbuy ? color.new(bgObColor, 70) : na, transp=90)
bgcolor(useBgObOs and _rsi < oversell ? color.new(bgOsColor, 70) : na, transp=90)
// TOP / BOT FINDER
//-----------------------------
current = nz(_rsi[confirmation])
// FIND TOP / BOT
//-----------------------------
isTop = true
isBot = true
for i = 0 to loopback + confirmation by 1
if _rsi[i] > current or current < 50
isTop := false
isTop
if _rsi[i] < current or current > 50
isBot := false
isBot
// IS TOP
//-----------------------------
var top1 = 0.0
var top2 = 0.0
var top3 = 0.0
var priceTop1 = 0.0
var priceTop2 = 0.0
var priceTop3 = 0.0
var top1Time = 0
var top2Time = 0
var top3Time = 0
var top1BarIndex = 0
var top2BarIndex = 0
var top3BarIndex = 0
var masterTopTime = 0
var masterTopBarIndex = 0
var masterTopRsiValue = 0.0
var masterTopPriceValue = 0.0
if isTop
top3 := top2
top2 := top1
top1 := current
priceTop3 := priceTop2
priceTop2 := priceTop1
priceTop1 := priceTopBotSource == 'close' ? close[confirmation] : high[confirmation]
top3Time := top2Time
top2Time := top1Time
top1Time := time[confirmation]
top3BarIndex := top2BarIndex
top2BarIndex := top1BarIndex
top1BarIndex := bar_index[confirmation]
top1BarIndex
isMasterTop = top3 < top2 and top2 > top1 and top2 > overbuy
if isMasterTop
masterTopTime := top2Time
masterTopBarIndex := top2BarIndex
masterTopRsiValue := top2
masterTopPriceValue := priceTop2
masterTopPriceValue
if top1BarIndex - masterTopBarIndex > maxLoopback
masterTopTime := 0
masterTopBarIndex := 0
masterTopRsiValue := 0.0
masterTopPriceValue := 0.0
masterTopPriceValue
isBearDiv = isTop and not isMasterTop and top1 > topLimit and top1 < masterTopRsiValue and priceTop1 > masterTopPriceValue and top1BarIndex - masterTopBarIndex <= maxLoopback
var line bearDivLine = na
if isBearDiv
bearDivLine := line.new(x1=masterTopTime, y1=masterTopRsiValue, x2=top1Time, y2=top1, color=color.new(divLineColor, 0), xloc=xloc.bar_time, style=line.style_solid, width=1)
bearDivLine
plotshape(isBearDiv and showToBotDiv ? current + 10 : na, style=shape.diamond, location=location.absolute, color=topColor, offset=-confirmation, size=size.tiny)
// IS BOT
//-----------------------------
var bot1 = 0.0
var bot2 = 0.0
var bot3 = 0.0
var priceBot1 = 0.0
var priceBot2 = 0.0
var priceBot3 = 0.0
var bot1Time = 0
var bot2Time = 0
var bot3Time = 0
var bot1BarIndex = 0
var bot2BarIndex = 0
var bot3BarIndex = 0
var masterBotTime = 0
var masterBotBarIndex = 0
var masterBotRsiValue = 0.0
var masterBotPriceValue = 0.0
if isBot
bot3 := bot2
bot2 := bot1
bot1 := current
priceBot3 := priceBot2
priceBot2 := priceBot1
priceBot1 := priceTopBotSource == 'close' ? close[confirmation] : low[confirmation]
bot3Time := bot2Time
bot2Time := bot1Time
bot1Time := time[confirmation]
bot3BarIndex := bot2BarIndex
bot2BarIndex := bot1BarIndex
bot1BarIndex := bar_index[confirmation]
bot1BarIndex
isMasterBot = bot3 > bot2 and bot2 < bot1 and bot2 < oversell
if isMasterBot
masterBotTime := bot2Time
masterBotBarIndex := bot2BarIndex
masterBotRsiValue := bot2
masterBotPriceValue := priceBot2
masterBotPriceValue
if bot1BarIndex - masterBotBarIndex > maxLoopback
masterBotTime := 0
masterBotBarIndex := 0
masterBotRsiValue := 0.0
masterBotPriceValue := 0.0
masterBotPriceValue
isBullDiv = isBot and not isMasterBot and bot1 < botLimit and bot1 > masterBotRsiValue and priceBot1 < masterBotPriceValue and bot1BarIndex - masterBotBarIndex <= maxLoopback
var line bullDivLine = na
if isBullDiv
bullDivLine := line.new(x1=masterBotTime, y1=masterBotRsiValue, x2=bot1Time, y2=bot1, color=color.new(divLineColor, 0), xloc=xloc.bar_time, style=line.style_solid, width=1)
bullDivLine
alertcondition(isBullDiv,title="Buy",message="Buy")
alertcondition(isBearDiv,title="Sell",message="Sell")
plotshape(isBullDiv and showToBotDiv ? current - 10 : na, style=shape.diamond, location=location.absolute, color=botColor, offset=-confirmation, size=size.tiny)
|
Mackrani RSI Trend WITH COLORS | https://www.tradingview.com/script/zo3hpai4-Mackrani-RSI-Trend-WITH-COLORS/ | raashidmackrani | https://www.tradingview.com/u/raashidmackrani/ | 55 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© raashidmackrani
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© traderharikrishna
//@version=5
indicator("Mackrani RSI Trend WITH COLORS")
showbarcolor=input.bool(true,'Apply Barcolor')
show_Baseline=input.bool(true,'Show Hull Trend')
rsiLengthInput = input.int(14, minval=1, title="RSI Length1", group="RSI Settings")
rsiLengthInput2 = input.int(28, minval=1, title="RSI Length2", group="RSI Settings")
trendlen= input(title='Hull Trend Length', defval=30,group='Hull Trend')
oversold=input.int(30, minval=1, title="Over Sold", group="RSI Settings")
overbought=input.int(70, minval=1, title="Over Bought", group="RSI Settings")
BBMC=ta.hma(close,trendlen)
MHULL = BBMC[0]
SHULL = BBMC[2]
hmac=MHULL > SHULL ?color.new(#00c3ff , 0):color.new(#ff0062, 0)
buysignal=MHULL > SHULL
sellsignal=MHULL < SHULL
frsi=ta.hma(ta.rsi(close,rsiLengthInput),10)
srsi=ta.hma(ta.rsi(close,rsiLengthInput2),10)
hullrsi1=ta.rsi(MHULL,rsiLengthInput)
hullrsi2=ta.rsi(SHULL,rsiLengthInput)
rsic=frsi>srsi?color.new(#00c3ff , 0):color.new(#ff0062, 0)
barcolor(showbarcolor?hmac:na)
hu1=plot(show_Baseline?hullrsi1:frsi,title='HMA1',color=color.gray,linewidth=1,display=display.none)
hu2=plot(show_Baseline?hullrsi2:srsi,title='HMA2',color=color.gray,linewidth=1,display=display.none)
fill(hu1,hu2,title='HULL RSI TREND',color=show_Baseline?hmac:rsic)
rsiUpperBand2 = hline(90, "RSI Upper Band(90)", color=color.red,linestyle=hline.style_dotted,display=display.none)
rsiUpperBand = hline(overbought, "RSI Upper Band", color=color.red,linestyle=hline.style_dotted,display=display.none)
fill(rsiUpperBand2,rsiUpperBand,title='Buy Zone',color=color.red,transp=80)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50),linestyle=hline.style_solid)
rsiLowerBand = hline(oversold, "RSI Lower Band", color=color.green,linestyle=hline.style_dotted,display=display.none)
rsiLowerBand2 = hline(10, "RSI Lower Band(10)", color=color.green,linestyle=hline.style_dotted,display=display.none)
fill(rsiLowerBand,rsiLowerBand2,title='Sell Zone',color=color.green,transp=80)
plotshape(buysignal and sellsignal[1] ?hullrsi1 :na, title='Buy', style=shape.triangleup, location=location.absolute, color=color.new(color.yellow, 0), size=size.tiny, offset=0)
plotshape(sellsignal and buysignal[1] ?hullrsi1 :na, title='Sell', style=shape.triangledown, location=location.absolute, color=color.new(color.red, 0), size=size.tiny, offset=0)
alertcondition(buysignal and sellsignal[1] ,title='RSI TREND:Buy Signal',message='RSI TREND: Buy Signal')
alertcondition(sellsignal and buysignal[1],title='RSI TREND:Sell Signal',message='RSI TREND: Sell Signal') |
Fed Liquidity | https://www.tradingview.com/script/I2d5n9Il-Fed-Liquidity/ | Forklift5909 | https://www.tradingview.com/u/Forklift5909/ | 394 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Forklift5909
//@version=5
indicator("Fed Liquidity")
BalanceSheet = request.security("FRED:WALCL", "W", close)
RRP = request.security("FRED:RRPONTSYD", "W", close)
TGA = request.security("FRED:WTREGEN", "W", close)
Liquidity = (BalanceSheet)-(TGA + RRP)
plot(Liquidity + RRP + TGA, color=color.red, offset=2, style=plot.style_columns)
plot(Liquidity + RRP, color=color.yellow, offset=2, style=plot.style_columns)
plot(Liquidity, color=color.green, offset=2, style=plot.style_columns)
plot(BalanceSheet, color=color.purple, offset=2, linewidth=3) |
Emirindicator | https://www.tradingview.com/script/lloZiYLY/ | EmirhanDuzgun | https://www.tradingview.com/u/EmirhanDuzgun/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© EmirhanDuzgun
//@version=5
indicator(title = "StopLossCal",overlay = true)
Kalinlik = input.int(defval= 1,title = "KalΔ±nlΔ±k")
atrstop = open - (ta.atr(14)*1.7)
atrenk = input.color(defval=color.red,title="Stop Rengi",group="Renkler")
plot(atrstop,color=atrenk,title="Stop Loss",linewidth=Kalinlik)
atr1 = open + (ta.atr(14)*1.96)
atrenk1 = input.color(defval=color.blue,title="Stopu GiriΕe Γek",group="Renkler")
rr1 = plot(atr1,color=atrenk1,title="Stopu GiriΕe Γek",linewidth=Kalinlik)
atr2 = open + (ta.atr(14)*2.97)
atrenk2 = input.color(defval=color.white,title="Take Profit",group="Renkler")
rr2 = plot(atr2,color=atrenk2,title="Take Profit",linewidth=Kalinlik)
fill(rr1,rr2,color=color.new(color.green,70))
|
Dollar Index (DXY) Candles [Loxx] | https://www.tradingview.com/script/uFeR0nFq-Dollar-Index-DXY-Candles-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 78 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Dollar Index (DXY) Candles [Loxx]",
shorttitle="DXYC [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
eurc = request.security("EURUSD", "", close)
euro = request.security("EURUSD", "", open)
eurh = request.security("EURUSD", "", high)
eurl = request.security("EURUSD", "", low)
jpyc = request.security("JPYUSD", "", close)
jpyo = request.security("JPYUSD", "", open)
jpyh = request.security("JPYUSD", "", high)
jpyl = request.security("JPYUSD", "", low)
gbpc = request.security("GBPUSD", "", close)
gbpo = request.security("GBPUSD", "", open)
gbph = request.security("GBPUSD", "", high)
gbpl = request.security("GBPUSD", "", low)
cadc = request.security("CADUSD", "", close)
cado = request.security("CADUSD", "", open)
cadh = request.security("CADUSD", "", high)
cadl = request.security("CADUSD", "", low)
sekc = request.security("SEKUSD", "", close)
seko = request.security("SEKUSD", "", open)
sekh = request.security("SEKUSD", "", high)
sekl = request.security("SEKUSD", "", low)
chfc = request.security("CHFUSD", "", close)
chfo = request.security("CHFUSD", "", open)
chfh = request.security("CHFUSD", "", high)
chfl = request.security("CHFUSD", "", low)
dxyClose = 50.14348112 * math.pow(eurc, -0.576) * math.pow(jpyc, 0.136) * math.pow(gbpc, -0.119) * math.pow(cadc, 0.091) * math.pow(sekc, 0.042) * math.pow(chfc, 0.036)
dxyOpen = 50.14348112 * math.pow(euro, -0.576) * math.pow(jpyo, 0.136) * math.pow(gbpo, -0.119) * math.pow(cado, 0.091) * math.pow(seko, 0.042) * math.pow(chfo, 0.036)
dxyHigh = 50.14348112 * math.pow(eurh, -0.576) * math.pow(jpyh, 0.136) * math.pow(gbph, -0.119) * math.pow(cadh, 0.091) * math.pow(sekh, 0.042) * math.pow(chfh, 0.036)
dxyLow = 50.14348112 * math.pow(eurl, -0.576) * math.pow(jpyl, 0.136) * math.pow(gbpl, -0.119) * math.pow(cadl, 0.091) * math.pow(sekl, 0.042) * math.pow(chfl, 0.036)
plotcandle(dxyOpen, dxyHigh, dxyLow, dxyClose, title='Title', color = dxyOpen < dxyClose ? greencolor : redcolor, wickcolor=color.black) |
Diver RSI | https://www.tradingview.com/script/9ifY0IPh/ | UnknownUnicorn29393911 | https://www.tradingview.com/u/UnknownUnicorn29393911/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© justdoit7772
//@version=5
indicator(title="Diver RSI", format=format.price, timeframe="", timeframe_gaps=true)
// rsi ꡬνκΈ°
rsi = ta.rsi(close, 14)
plot(rsi)
hline(30)
hline(70)
// pivot_low ꡬνκΈ°
pivot_low = ta.pivotlow(rsi, 5, 5)
bgcolor(pivot_low ? color.new(color.green, 85) : na, offset = -5)
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [1] νΌλ΄λ‘μ°κ° λ°κ²¬ λμλκ°?
plFound = na(pivot_low) ? false : true
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [2] 2κ°μ νΌλ΄λ‘μ°μμ rsiκ° μ¦κ° νμλκ°?
is_pl_higher = rsi[5] > ta.valuewhen(plFound, rsi[5], 1)
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [3] νΌλ΄λ‘μ° 2κ°μμμ μ κ°λ κ°μ νμλκ°?
is_price_lower = low[5] < ta.valuewhen(plFound, low[5], 1)
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [4] 2κ°μ νΌλ΄κ° range μ ν
_inRange(cond) =>
bars = ta.barssince(cond == true)
5 <= bars and bars <= 50
bullCond = plFound and is_pl_higher and is_price_lower and _inRange(plFound[1])
plot(
plFound ? rsi[5] : na,
offset=-5,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? color.green : na)
)
// pivot_high ꡬνκΈ°
pivot_high = ta.pivothigh(rsi, 5, 5)
bgcolor(pivot_high ? color.new(color.red, 85) : na, offset = -5)
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [1] νΌλ΄νμ΄κ° λ°κ²¬ λμλκ°?
phFound = na(pivot_high) ? false : true
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [2] 2κ°μ νΌλ΄νμ΄μμ rsiκ° κ°μ νμλκ°?
is_ph_lower = rsi[5] < ta.valuewhen(phFound, rsi[5], 1)
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [3] νΌλ΄λ‘μ° 2κ°μμμ κ³ κ°λ μ¦κ° νμλκ°?
is_price_higher = high[5] > ta.valuewhen(phFound, high[5], 1)
// μμΉ λ€μ΄λ²μ μ€ νλ¨κΈ°μ€ [4] 2κ°μ νΌλ΄κ° range μ ν (μ΄λ―Έ μμμ ꡬνν¨)
// _inRange(cond) =>
// bars = ta.barssince(cond == true)
// 5 <= bars and bars <= 50
bearCond = phFound and is_ph_lower and is_price_higher and _inRange(phFound[1])
plot(
phFound ? rsi[5] : na,
offset=-5,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? color.red : na)
)
/////**** Divergence Indicator μλ³Έμμ€ ****/////
// len = input.int(title="RSI Period", minval=1, defval=14)
// src = input(title="RSI Source", defval=close)
// lbR = input(title="Pivot Lookback Right", defval=5)
// lbL = input(title="Pivot Lookback Left", defval=5)
// rangeUpper = input(title="Max of Lookback Range", defval=60)
// rangeLower = input(title="Min of Lookback Range", defval=5)
// plotBull = input(title="Plot Bullish", defval=true)
// plotHiddenBull = input(title="Plot Hidden Bullish", defval=false)
// plotBear = input(title="Plot Bearish", defval=true)
// plotHiddenBear = input(title="Plot Hidden Bearish", defval=false)
// bearColor = color.red
// bullColor = color.green
// hiddenBullColor = color.new(color.green, 80)
// hiddenBearColor = color.new(color.red, 80)
// textColor = color.white
// noneColor = color.new(color.white, 100)
// osc = ta.rsi(src, len)
// plot(osc, title="RSI", linewidth=2, color=#2962FF)
// hline(50, title="Middle Line", color=#787B86, linestyle=hline.style_dotted)
// obLevel = hline(70, title="Overbought", color=#787B86, linestyle=hline.style_dotted)
// osLevel = hline(30, title="Oversold", color=#787B86, linestyle=hline.style_dotted)
// fill(obLevel, osLevel, title="Background", color=color.rgb(33, 150, 243, 90))
// plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
// phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
// _inRange(cond) =>
// bars = ta.barssince(cond == true)
// rangeLower <= bars and bars <= rangeUpper
// //------------------------------------------------------------------------------
// // Regular Bullish
// // Osc: Higher Low
// oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// // Price: Lower Low
// priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
// bullCond = plotBull and priceLL and oscHL and plFound
// plot(
// plFound ? osc[lbR] : na,
// offset=-lbR,
// title="Regular Bullish",
// linewidth=2,
// color=(bullCond ? bullColor : noneColor)
// )
// plotshape(
// bullCond ? osc[lbR] : na,
// offset=-lbR,
// title="Regular Bullish Label",
// text=" Bull ",
// style=shape.labelup,
// location=location.absolute,
// color=bullColor,
// textcolor=textColor
// )
// //------------------------------------------------------------------------------
// // Hidden Bullish
// // Osc: Lower Low
// oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// // Price: Higher Low
// priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
// hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
// plot(
// plFound ? osc[lbR] : na,
// offset=-lbR,
// title="Hidden Bullish",
// linewidth=2,
// color=(hiddenBullCond ? hiddenBullColor : noneColor)
// )
// plotshape(
// hiddenBullCond ? osc[lbR] : na,
// offset=-lbR,
// title="Hidden Bullish Label",
// text=" H Bull ",
// style=shape.labelup,
// location=location.absolute,
// color=bullColor,
// textcolor=textColor
// )
// //------------------------------------------------------------------------------
// // Regular Bearish
// // Osc: Lower High
// oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// // Price: Higher High
// priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
// bearCond = plotBear and priceHH and oscLH and phFound
// plot(
// phFound ? osc[lbR] : na,
// offset=-lbR,
// title="Regular Bearish",
// linewidth=2,
// color=(bearCond ? bearColor : noneColor)
// )
// plotshape(
// bearCond ? osc[lbR] : na,
// offset=-lbR,
// title="Regular Bearish Label",
// text=" Bear ",
// style=shape.labeldown,
// location=location.absolute,
// color=bearColor,
// textcolor=textColor
// )
// //------------------------------------------------------------------------------
// // Hidden Bearish
// // Osc: Higher High
// oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// // Price: Lower High
// priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
// hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
// plot(
// phFound ? osc[lbR] : na,
// offset=-lbR,
// title="Hidden Bearish",
// linewidth=2,
// color=(hiddenBearCond ? hiddenBearColor : noneColor)
// )
// plotshape(
// hiddenBearCond ? osc[lbR] : na,
// offset=-lbR,
// title="Hidden Bearish Label",
// text=" H Bear ",
// style=shape.labeldown,
// location=location.absolute,
// color=bearColor,
// textcolor=textColor
// ) |
SBS Algo | https://www.tradingview.com/script/h9tb8oIk-SBS-Algo/ | a_guy_from_wall_street | https://www.tradingview.com/u/a_guy_from_wall_street/ | 668 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© hiimannshu
//@version=5
indicator(title="SBS Algo", shorttitle="SBS Algo",overlay=true)
//------------ADX---------//
adxfilter = input.bool(true,"ADX filter",group = "Filter Signals")
lvl = input.int(15,"ADX level",group = "Inputs")
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"],group = "Inputs")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"],group = "Inputs")
TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - nz(SmoothedTrueRange[1]) / 14 + TrueRange
SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - nz(SmoothedDirectionalMovementPlus[1]) / 14 + DirectionalMovementPlus
SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - nz(SmoothedDirectionalMovementMinus[1]) / 14 + DirectionalMovementMinus
DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
ADX = ta.sma(DX, 14)
adxabove_Lvl = ADX>lvl
adx_buy = DIMinus<DIPlus and adxabove_Lvl
adx_sell= DIMinus>DIPlus and adxabove_Lvl
//----
length = input.int(defval = 20,title = "Pivot Length",group = "Inputs")
tl_Slope = input.float(defval = 1.9,title = 'Degree of Slope',minval=0,step=0.1,group = "Inputs")
//---------EMA----------//
emafilter = input.bool(true,"EMA filter",group = "Filter Signals")
showEma = input.bool(false,"",inline="ema")
emalength = input.int(title="EMA", minval = 1, maxval = 500, defval = 200,inline="ema")
emacol = input.color(color.black,"",inline="ema")
ema = ta.ema(close,emalength)
above_ema = ema<close
below_ema = ema>close
plot(showEma?ema:na,color=emacol)
showLtSig = input(defval = false,title = 'Show Latest Signals only')
showWS = input.bool(false,"Show Weak confluence")
showSS = input.bool(true,"Show Strong Confluence")
//-------
color buyCol = input.color(defval = color.green,title = "Buy Lable",group = "Lable Colors")
color sellCol = input.color(defval = color.red,title = "Sell Lable",group = "Lable Colors")
color txtCol = input.color(defval = color.white,title = "Text",group = "Lable Colors")
color trans = color.new(color.white,100)
showLines = input(defval = false,title = 'Show Trend Lines')
showCrLines = input(defval = false,title = 'Show Latest trend Lines')
highVal = 0.0
lowVal = 0.0
phSlope = 0.0
plSlope = 0.0
src = close
barIndex = bar_index
ph = ta.pivothigh(length,length)
pl = ta.pivotlow(length,length)
slope = math.abs(ta.sma(src*barIndex,length)-ta.sma(src,length)*ta.sma(barIndex,length))/ta.variance(barIndex,length)/2*tl_Slope
phSlope := ph ? slope : phSlope[1]
plSlope := pl ? slope : plSlope[1]
highVal := ph ? ph : highVal[1] - phSlope
lowVal := pl ? pl : lowVal[1] + plSlope
up_sig = 0
dn_sig = 0
up_sig := src[length] > highVal ? 0 : ph ? 1 : up_sig[1]
dn_sig := src[length] < lowVal ? 0 : pl ? 1 : dn_sig[1]
upper_breakout = up_sig[1] and src[length] > highVal and ( src > src[length] )
lower_breakout = dn_sig[1] and src[length] < lowVal and ( src < src[length] )
//---------MACD---------//
fast_ma = sma_source == "SMA" ? ta.sma(close, 12) : ta.ema(close, 12)
slow_ma = sma_source == "SMA" ? ta.sma(close, 26) : ta.ema(close, 26)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, 9) : ta.ema(macd, 9)
below_buy = macd<0 and signal<0 and ta.crossover(macd,signal) and (emafilter?above_ema:true)
below_sell = macd<0 and signal<0 and ta.crossunder(macd,signal) and (emafilter?below_ema:true)
above_sell = macd>0 and signal>0 and ta.crossunder(macd,signal) and (emafilter?below_ema:true)
above_buy = macd>0 and signal>0 and ta.crossover(macd,signal) and (emafilter?above_ema:true)
arrow_buy = showSS and below_buy and adx_buy
arrow_sell = showSS and above_sell and adx_sell
plotshape(showWS and above_buy and adx_buy,"Above Buy",shape.circle,location.belowbar,buyCol,offset=1,size=size.tiny)
plotshape(showWS and below_sell and adx_sell,"Below Sell",shape.circle,location.abovebar,sellCol,offset=1,size=size.tiny)
plotshape(arrow_buy,"Below Buy",shape.triangleup,location.belowbar,buyCol,size=size.small)
plotshape(arrow_sell,"Above Sell",shape.triangledown,location.abovebar,sellCol,size=size.small)
//----
var line up_l = na
var line dn_l = na
var label rub = na
var label rdb = na
bool phtl_break = ta.crossover(src,highVal-phSlope*length)
bool pltl_break = ta.crossunder(src,lowVal+plSlope*length)
if ph[1]
line.delete(up_l[1])
label.delete(rub[1])
up_l := line.new(barIndex-length-1,ph[1],barIndex-length,highVal,color=showCrLines?buyCol:trans, extend=extend.right,style=line.style_dotted)
if pl[1]
line.delete(dn_l[1])
label.delete(rdb[1])
dn_l := line.new(barIndex-length-1,pl[1],barIndex-length,lowVal,color=showCrLines?sellCol:trans,extend=extend.right,style=line.style_dotted)
if phtl_break
label.delete(rub[1])
rub := label.new(barIndex,low,"πππ",color=showLtSig? buyCol:trans,textcolor=showLtSig? txtCol: trans,style=label.style_label_up,size=size.small)
if pltl_break
label.delete(rdb[1])
rdb := label.new(barIndex,high,"ππππ",color=showLtSig ? sellCol: trans,textcolor= showLtSig? txtCol: trans,style=label.style_label_down,size=size.small)
//----
plotshape(upper_breakout and (emafilter?above_ema:true) and (adxfilter?adx_buy:true) and not(showLtSig)? low[length] : na,"Buy",shape.labelup,location.absolute,buyCol,-length,text="πππ",textcolor=txtCol,size=size.tiny)
plotshape(lower_breakout and (emafilter?below_ema:true) and (adxfilter?adx_sell:true) and not(showLtSig)? high[length] : na,"Sell",shape.labeldown,location.absolute,sellCol,-length,text="ππππ",textcolor=txtCol,size=size.tiny)
plot(showLines ?highVal:na,'Upper Trend Line',color = ph ? na : buyCol,offset=-length)
plot(showLines ?lowVal:na,'Lower Trend Line',color = pl ? na : sellCol,offset=-length)
buy_cond = phtl_break and (emafilter?above_ema:true) and (adxfilter?adx_buy:true)
sell_cond = pltl_break and (emafilter?below_ema:true) and (adxfilter?adx_sell:true)
if buy_cond
alert("Buy " + str.tostring(syminfo.ticker)+" @ "+ str.tostring(close),alert.freq_once_per_bar_close)
if sell_cond
alert("Sell " + str.tostring(syminfo.ticker)+" @ "+ str.tostring(close),alert.freq_once_per_bar_close)
if arrow_buy
alert("Bullish arrow on " + str.tostring(syminfo.ticker),alert.freq_once_per_bar_close)
if arrow_sell
alert("Bearish arrow on " + str.tostring(syminfo.ticker),alert.freq_once_per_bar_close)
|
MA package | https://www.tradingview.com/script/CrHEdss8-MA-package/ | OldGrumpyCat | https://www.tradingview.com/u/OldGrumpyCat/ | 647 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© OldGrumpyCat
//@version=4
study(title="εη·ηΎ€γθη«γ", overlay=true)
longsmoothing = input(title="εη·ι‘ε", defval="EMA", options=["RMA", "SMA", "EMA", "WMA", "ALMA"])
ma_fun(s, length) =>
if s == "RMA"
rma(close, length)
else
if s == "SMA"
sma(close, length)
else
if s == "EMA"
ema(close, length)
else
if s == "ALMA"
alma(close, length, 0.85, 6)
else
wma(close, length)
ma1 = input(5, minval = 1, title = "MA1")
ma2 = input(8, minval = 1, title = "MA2")
ma3 = input(13, minval = 1, title = "MA3")
ma4 = input(50, minval = 1, title = "MA4")
ma5 = input(55, minval = 1, title = "MA5")
ma6 = input(60, minval = 1, title = "MA6")
ma7 = input(100, minval = 1, title = "MA7")
ma8 = input(150, minval = 1, title = "MA8")
ma9 = input(200, minval = 1, title = "MA9")
e1 = ma_fun(longsmoothing, ma1)
e2 = ma_fun(longsmoothing, ma2)
e3 = ma_fun(longsmoothing, ma3)
e4 = ma_fun(longsmoothing, ma4)
e5 = ma_fun(longsmoothing, ma5)
e6 = ma_fun(longsmoothing, ma6)
e7 = ma_fun(longsmoothing, ma7)
e8 = ma_fun(longsmoothing, ma8)
e9 = ma_fun(longsmoothing, ma9)
plot(e1, color = #2196f3)
plot(e2, color = #00bcd4)
plot(e3, color = #4caf50)
plot(e4, color = #ffeb3b)
plot(e5, color = #ff9800)
plot(e6, color = #f44336)
plot(e7, color = #444444)
plot(e8, color = #040404)
plot(e9, color = #000000) |
MA Trend Bar [vnhilton] | https://www.tradingview.com/script/Ua7uvcw4-MA-Trend-Bar-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 11 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© vnhilton
//@version=5
indicator("MA Trend Bar [vnhilton]", "MA Trend Bar", false, timeframe="", timeframe_gaps=true)
//Moving Average Configuration
src = input(close, title="Source")
shortLen = input.int(9, "Short MA Length", 1)
longLen = input.int(21, "Long MA Length", 2)
maType = input.string("EMA", "MA Type", ["ALMA", "EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"])
//Moving Average Selection
ma(src, len, type) =>
switch type
"EMA" => ta.ema(src, len)
"HMA" => ta.hma(src, len)
"RMA" => ta.rma(src, len)
"SMA" => ta.sma(src, len)
"VWMA" => ta.vwma(src, len)
"WMA" => ta.wma(src, len)
//Moving Average Assignments
shortMA = ma(src, shortLen, maType)
longMA = ma(src, longLen, maType)
//Trend Color Based On Short Term Moving Average Relative to Longer Term Moving Average
trendColor = shortMA >= longMA ? color.rgb(0, 165, 49, 0) : color.rgb(255, 109, 90, 0)
plot(1, "MA Trend Bar", trendColor, 10, plot.style_line, histbase=0) |
Visible Range High Low [vnhilton] | https://www.tradingview.com/script/QC1y2mvF-Visible-Range-High-Low-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 84 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© vnhilton
//Inspired by PineCoders' "VisibleChart" library & "Chart VWAP" by TradingView
//@version=5
indicator("Visible Range High Low [vnhilton]", "VRHL", true)
//Getting access to functions from PineCoders' "VisibleChart" library
import PineCoders/VisibleChart/4 as PCVC
//Label parameters
highLabelColor = input.color(color.rgb(0, 165, 49, 80), "High Label Color")
highTextColor = input.color(color.rgb(0, 165, 49, 0), "High Text Color")
lowLabelColor = input.color(color.rgb(255, 109, 90, 80), "Low Label Color")
lowTextColor = input.color(color.rgb(255, 109, 90, 0), "Low Text Color")
//Getting OHLCV values
[chartOpen, chartHigh, chartLow, chartClose, chartVolume] = PCVC.ohlcv()
//Getting HL time
int highTime = PCVC.highBarTime()
int lowTime = PCVC.lowBarTime()
//Plotting labels
var label highLabel = label.new(na, na, na, xloc.bar_time, yloc.price, highLabelColor, label.style_label_down, highTextColor)
var label lowLabel = label.new(na, na, na, xloc.bar_time, yloc.price, lowLabelColor, label.style_label_up, lowTextColor)
label.set_xy(highLabel, highTime, chartHigh)
label.set_xy(lowLabel, lowTime, chartLow)
label.set_text(highLabel, str.tostring(chartHigh, format.mintick))
label.set_text(lowLabel, str.tostring(chartLow, format.mintick)) |
BTC Hashrate with smoothing | https://www.tradingview.com/script/TwrrJMwz-BTC-Hashrate-with-smoothing/ | Powerscooter | https://www.tradingview.com/u/Powerscooter/ | 21 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Powerscooter
// Since IntoTheBlock only provides daily hashrate data, this chart might look chunky on lower timeframes, even with smoothing.
//@version=5
indicator("BTC Hashrate", overlay = true, scale = scale.none)
smoothing = input.string(title="Smoothing", defval="SMA", options=["SMA", "RMA", "EMA", "WMA"], group="Hashrate Settings")
ma_function(source, length) =>
switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
SmoothLength = input(30, 'MA Length', group="Hashrate Settings")
Source = input.string(title="Data Source", defval="IntoTheBlock", options=["Glassnode", "IntoTheBlock"], group="Source Settings")
SourceE = switch Source
"Glassnode" => "GLASSNODE:BTC_HASHRATE"
"IntoTheBlock" => "INTOTHEBLOCK:BTC_HASHRATE"
HashRate = request.security(SourceE, "D", close)
plot(ma_function(HashRate, SmoothLength), "Hashrate", color=color.blue) |
Bar Bodies [vnhilton] | https://www.tradingview.com/script/XBUXOfQu-Bar-Bodies-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 41 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© vnhilton
//@version=5
//This script uses the low wick to represent the candlestick body (high wick isn't used)
indicator('Bar Bodies [vnhilton]', overlay=true)
//The low wick's created from the low to the open/close for green/red candle respectively
l = close >= open ? open : close
//Candle body will start from high always, so needs to be closed at the close/open for green/red candle respectively
c = close >= open ? close : open
//Low wick color based on green/red candle
barColor = close >= open ? color.lime : color.red
//Plot low wick
plotcandle(high, high, l, c, color=na, wickcolor=barColor, bordercolor=na) |
Variety N-Tuple Moving Averages [Loxx] | https://www.tradingview.com/script/IM2KIi2P-Variety-N-Tuple-Moving-Averages-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 172 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("Variety N-Tuple Moving Averages [Loxx]",
shorttitle="VNTMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
_iT3(src, per, hot, clean)=>
a = hot
_c1 = -a * a * a
_c2 = 3 * a * a + 3 * a * a * a
_c3 = -6 * a * a - 3 * a - 3 * a * a * a
_c4 = 1 + 3 * a + a * a * a + 3 * a * a
alpha = 0.
if (clean == "T3 New")
alpha := 2.0 / (2.0 + (per - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + per)
_t30 = src, _t31 = src
_t32 = src, _t33 = src
_t34 = src, _t35 = src
_t30 := nz(_t30[1]) + alpha * (src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
fact(int n)=>
float a = 1
for i = 1 to n
a *= i
a
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14,"Period", group = "Basic Settings")
nemadepth = input.int(3, "Depth", maxval = 35, minval = 1, group = "Basic Settings")
type = input.string("EMA", "Variety Moving Average Type", options = ["EMA", "WMA", "SMA", "RMA", "T3"], group = "Basic Settings")
t3hot = input.float(0.7, "T3 Hot", group= "T3 Settings")
t3swt = input.string("T3 New", "T3 Type", options = ["T3 New", "T3 Original"], group = "T3 Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len)=>
out = 0.0
if type == "EMA"
out := ta.ema(src, len)
else if type == "WMA"
out := ta.wma(src, len)
else if type == "SMA"
out := ta.sma(src, len)
else if type == "RMA"
out := ta.rma(src, len)
else if type == "T3"
out := _iT3(src, len, t3hot, t3swt)
out
_gsmth(string type, float src, simple int per, simple int depth, float[] coeff)=>
float out = 0.
if depth == 1
ma1 = variant(type, src, per)
out := ma1
if depth == 2
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
out :=
array.get(coeff, 1) * ma1
- ma2
if depth == 3
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ ma3
if depth == 4
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- ma4
if depth == 5
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ ma5
if depth == 6
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- ma6
if depth == 7
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ ma7
if depth == 8
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- ma8
if depth == 9
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ ma9
if depth == 10
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- ma10
if depth == 11
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ ma11
if depth == 12
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- ma12
if depth == 13
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ ma13
if depth == 14
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- ma14
if depth == 15
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ ma15
if depth == 16
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- ma16
if depth == 17
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ ma17
if depth == 18
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- ma18
if depth == 19
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ ma19
if depth == 20
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- ma20
if depth == 21
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ ma21
if depth == 22
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- ma22
if depth == 23
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ ma23
if depth == 24
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- ma24
if depth == 25
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
ma25 = variant(type, ma24, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- array.get(coeff, 24) * ma24
+ ma25
if depth == 26
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
ma25 = variant(type, ma24, per)
ma26 = variant(type, ma25, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- array.get(coeff, 24) * ma24
+ array.get(coeff, 25) * ma25
- ma26
if depth == 27
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
ma25 = variant(type, ma24, per)
ma26 = variant(type, ma25, per)
ma27 = variant(type, ma26, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- array.get(coeff, 24) * ma24
+ array.get(coeff, 25) * ma25
- array.get(coeff, 26) * ma26
+ ma27
if depth == 28
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
ma25 = variant(type, ma24, per)
ma26 = variant(type, ma25, per)
ma27 = variant(type, ma26, per)
ma28 = variant(type, ma27, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- array.get(coeff, 24) * ma24
+ array.get(coeff, 25) * ma25
- array.get(coeff, 26) * ma26
+ array.get(coeff, 27) * ma27
- ma28
if depth == 29
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
ma25 = variant(type, ma24, per)
ma26 = variant(type, ma25, per)
ma27 = variant(type, ma26, per)
ma28 = variant(type, ma27, per)
ma29 = variant(type, ma28, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- array.get(coeff, 24) * ma24
+ array.get(coeff, 25) * ma25
- array.get(coeff, 26) * ma26
+ array.get(coeff, 27) * ma27
- array.get(coeff, 28) * ma28
+ ma29
if depth == 30
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
ma16 = variant(type, ma15, per)
ma17 = variant(type, ma16, per)
ma18 = variant(type, ma17, per)
ma19 = variant(type, ma18, per)
ma20 = variant(type, ma19, per)
ma21 = variant(type, ma20, per)
ma22 = variant(type, ma21, per)
ma23 = variant(type, ma22, per)
ma24 = variant(type, ma23, per)
ma25 = variant(type, ma24, per)
ma26 = variant(type, ma25, per)
ma27 = variant(type, ma26, per)
ma28 = variant(type, ma27, per)
ma29 = variant(type, ma28, per)
ma30 = variant(type, ma29, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ array.get(coeff, 15) * ma15
- array.get(coeff, 16) * ma16
+ array.get(coeff, 17) * ma17
- array.get(coeff, 18) * ma18
+ array.get(coeff, 19) * ma19
- array.get(coeff, 20) * ma20
+ array.get(coeff, 21) * ma21
- array.get(coeff, 22) * ma22
+ array.get(coeff, 23) * ma23
- array.get(coeff, 24) * ma24
+ array.get(coeff, 25) * ma25
- array.get(coeff, 26) * ma26
+ array.get(coeff, 27) * ma27
- array.get(coeff, 28) * ma28
+ array.get(coeff, 29) * ma29
- ma30
out
nemadepth := math.max(math.min(nemadepth, 49), 1)
coeff = array.new<float>(50, 0.)
for k = 0 to nemadepth
array.set(coeff, k, nz(fact(nemadepth) / (fact(nemadepth - k) * fact(k)), 1))
depth = array.size(coeff) - 1
out = _gsmth(type, src, per, nemadepth, coeff)
sig = nz(out[1])
colorout = out > sig ? greencolor : out < sig ? redcolor : color.gray
plot(out, "Variety NEMA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
alertcondition(goLong, title = "Long", message = "Variety N-Tuple Moving Averages [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Variety N-Tuple Moving Averages [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
ETS Price Deviation Reversal Areas | https://www.tradingview.com/script/8aJu3qLJ-ETS-Price-Deviation-Reversal-Areas/ | EasyTradingSignals | https://www.tradingview.com/u/EasyTradingSignals/ | 96 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© EasyTradingSignals
// This indicator tracks the degree to which price moves away from an average and triggers potential direction changes based on standard deviation levels
// It also tries to avoid giving signals when prices are in a very small range
// Change this code as you want to, but please let the community know and send me a message if you found something to share! Thanks!
//@version=5
indicator(title='ETS Price Deviation Reversal Areas', shorttitle='Price Deviation Reversals', overlay=false)
source = close
windowsize = input(title='Window Size', defval=20)
// Reversals
delen = input.int(6, minval=1, title="EMA Length") //5
delend = input.int(7, minval=1, title="EMA of Primary Length") //6
amp = 1.5 //input(type=input.float, defval=1.5, minval=-9.00, maxval=9, step=0.1, title="Amplify")
dedo = (100 - ta.ema(close, delen) / close * 100) * amp // This is a percentage of the position of the current price in relation to the moving average
ded = ta.ema(dedo, delend)
delength = input.int(13, minval=1) //14
demult = input.float(0.5, minval=0.001, maxval=50, step=0.05, title="Level 1")
debasis = ta.sma(ded, delength)
dedev = demult * ta.stdev(ded, delength) // This is a standard deviation from the moving average with a multiplier
deupper = debasis + dedev
delower = debasis - dedev
demult2 = input.float(1.2, minval=0.001, maxval=50, step=0.05, title="Level 2") //1.5
debasis2 = ta.sma(ded, delength)
dedev2 = demult2 * ta.stdev(ded, delength) // This is a standard deviation from the moving average with a multiplier
deupper2 = debasis2 + dedev2
delower2 = debasis2 - dedev2
demultb = input.float(1.6, minval=0.001, maxval=50, step=0.05, title="Level 3")
debasisb = ta.sma(ded, delength)
dedevb = demultb * ta.stdev(ded, delength) // This is a standard deviation from the moving average with a multiplier
deupperb = debasisb + dedevb
delowerb = debasisb - dedevb
plot(deupper, color=color.blue)
plot(deupperb, color=color.navy)
plot(debasis, color=color.black)
plot(ded, color=color.green, linewidth=2)
plot(delower, color=color.orange)
plot(delowerb, color=color.red)
plot(deupper2, color=color.aqua)
plot(debasis2, color=color.black)
plot(delower2, color=color.purple)
//////////////////////////////////////////
per = input.int(title="Period", defval=13)
demax = high > high[1] ? high - high[1] : 0
demin = low < low[1] ? low[1] - low : 0
demax_av = ta.sma(demax, per)
demin_av = ta.sma(demin, per)
dmark = ta.ema(demax_av / (demax_av + demin_av) * 100, 3)
//////////////////////////////////////////
sp = input.int(8, minval=1, title='Min Span')
span = (math.abs(delowerb) + deupperb) * 100 > sp ? true : false // span tracks the size of the price changes
co = (ded <= delower and ded[1] >= delower[1]) and span ? ded : (ded <= delowerb and ded[1] >= delowerb[1]) ? ded : na
cu = (ded >= deupper and ded[1] <= deupper[1]) and span ? ded : (ded >= deupperb and ded[1] <= deupperb[1]) ? ded : na
plot(cu, title="Cross", color=color.green, linewidth=5, style=plot.style_circles)
plot(co, title="Cross", color=color.orange, linewidth=5, style=plot.style_circles)
cu2 = (ded >= delower2 and ded[1] <= delower2[1]) and span ? ded : na
co2 = (ded <= deupper2 and ded[1] >= deupper2[1]) and span ? ded : na
plot(cu2, title="Cross", color=color.blue, linewidth=3, style=plot.style_circles)
plot(co2, title="Cross", color=color.red, linewidth=3, style=plot.style_circles)
//// Alerts
alertcondition(cu, title='PDR Outer Up', message='Potential reversal upwards')
alertcondition(co, title='PDR Outer Down', message='Potential reversal downwards')
alertcondition(cu2, title='PDR Early Up', message='Potential early reversal upwards')
alertcondition(co2, title='PDR Early Down', message='Potential early reversal downwards')
|
NNFX Exposure Utility | https://www.tradingview.com/script/LVNrfnkR-NNFX-Exposure-Utility/ | bjr117 | https://www.tradingview.com/u/bjr117/ | 31 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© bjr117
//@version=5
indicator(title = "NNFX Exposure Utility", shorttitle = "NNFXEXP", overlay = true)
//==============================================================================
// Exposure Settings (User Input)
//==============================================================================
// AUD Input Settings
aud_is_long = input.bool(title = "AUD", defval = false, group = "LONG", inline = "AUDLONG")
aud_is_short = input.bool(title = "AUD", defval = false, group = "SHORT", inline = "AUDSHORT")
aud_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "AUDLONG")
aud_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "AUDSHORT")
// CAD Input Settings
cad_is_long = input.bool(title = "CAD", defval = false, group = "LONG", inline = "CADLONG")
cad_is_short = input.bool(title = "CAD", defval = false, group = "SHORT", inline = "CADSHORT")
cad_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "CADLONG")
cad_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "CADSHORT")
// CHF Input Settings
chf_is_long = input.bool(title = "CHF", defval = false, group = "LONG", inline = "CHFLONG")
chf_is_short = input.bool(title = "CHF", defval = false, group = "SHORT", inline = "CHFSHORT")
chf_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "CHFLONG")
chf_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "CHFSHORT")
// JPY Input Settings
jpy_is_long = input.bool(title = "JPY", defval = false, group = "LONG", inline = "JPYLONG")
jpy_is_short = input.bool(title = "JPY", defval = false, group = "SHORT", inline = "JPYSHORT")
jpy_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "JPYLONG")
jpy_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "JPYSHORT")
// EUR Input Settings
eur_is_long = input.bool(title = "EUR", defval = false, group = "LONG", inline = "EURLONG")
eur_is_short = input.bool(title = "EUR", defval = false, group = "SHORT", inline = "EURSHORT")
eur_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "EURLONG")
eur_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "EURSHORT")
// GBP Input Settings
gbp_is_long = input.bool(title = "GBP", defval = false, group = "LONG", inline = "GBPLONG")
gbp_is_short = input.bool(title = "GBP", defval = false, group = "SHORT", inline = "GBPSHORT")
gbp_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "GBPLONG")
gbp_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "GBPSHORT")
// NZD Input Settings
nzd_is_long = input.bool(title = "NZD", defval = false, group = "LONG", inline = "NZDLONG")
nzd_is_short = input.bool(title = "NZD", defval = false, group = "SHORT", inline = "NZDSHORT")
nzd_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "NZDLONG")
nzd_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "NZDSHORT")
// SGD Input Settings
sgd_is_long = input.bool(title = "SGD", defval = false, group = "LONG", inline = "SGDLONG")
sgd_is_short = input.bool(title = "SGD", defval = false, group = "SHORT", inline = "SGDSHORT")
sgd_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "SGDLONG")
sgd_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "SGDSHORT")
// USD Input Settings
usd_is_long = input.bool(title = "USD", defval = false, group = "LONG", inline = "USDLONG")
usd_is_short = input.bool(title = "USD", defval = false, group = "SHORT", inline = "USDSHORT")
usd_long_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "LONG", inline = "USDLONG")
usd_short_exp = input.float(title = "| Exposure (%)", defval = 2.0, minval = 0, step = 0.005, group = "SHORT", inline = "USDSHORT")
//==============================================================================
// Table Settings (User Input)
//==============================================================================
// These options control where the table appears on the chart
table_y_pos = input.string(title = "GUI position", defval = "top", options = ["top", "middle", "bottom"], group = "GUI Settings", inline = "GUI Pos")
table_x_pos = input.string(title = "", defval = "right", options = ["left", "center", "right"], group = "GUI Settings", inline = "GUI Pos")
// Table colors
text_color = input.color(title = "Text", defval = color.new(color.black, 0), group = "GUI Settings", inline = "GUI Colors")
long_exp_color = input.color(title = "Long", defval = color.new(color.green, 30), group = "GUI Settings", inline = "GUI Colors")
short_exp_color = input.color(title = "Short", defval = color.new(color.red, 30), group = "GUI Settings", inline = "GUI Colors")
background_color = input.color(title = "Background", defval = color.new(color.gray, 100), group = "GUI Settings", inline = "GUI Colors")
//==============================================================================
//==============================================================================
// Helper Function: Calculate the total exposure given the current exposure inputs
//==============================================================================
get_total_exposure() =>
// Set initial total exposure to 0%
var float total_exposure = 0.0
// Iterate through the user inputs and see if there is >0% exposure on any currency
// Add that to exposure
if aud_is_long
total_exposure += aud_long_exp
if aud_is_short
total_exposure += aud_short_exp
if cad_is_long
total_exposure += cad_long_exp
if cad_is_short
total_exposure += cad_short_exp
if chf_is_long
total_exposure += chf_long_exp
if chf_is_short
total_exposure += chf_short_exp
if jpy_is_long
total_exposure += jpy_long_exp
if jpy_is_short
total_exposure += jpy_short_exp
if eur_is_long
total_exposure += eur_long_exp
if eur_is_short
total_exposure += eur_short_exp
if gbp_is_long
total_exposure += gbp_long_exp
if gbp_is_short
total_exposure += gbp_short_exp
if nzd_is_long
total_exposure += nzd_long_exp
if nzd_is_short
total_exposure += nzd_short_exp
if sgd_is_long
total_exposure += sgd_long_exp
if sgd_is_short
total_exposure += sgd_short_exp
if usd_is_long
total_exposure += usd_long_exp
if usd_is_short
total_exposure += usd_short_exp
// Return total exposure
total_exposure / 2.0
//==============================================================================
//==============================================================================
// Create table
//==============================================================================
// Creates the table
var table exp_table = table.new(table_y_pos + "_" + table_x_pos, 3, 10)
// Lists the contents of the Pair column
var string[] pairs_traded = array.from("AUD", "CAD", "CHF", "JPY", "EUR", "GBP", "NZD", "SGD", "USD")
// Populates table
if barstate.islast
// Populate table header
table.cell(exp_table, 0, 0, "Currency", bgcolor = background_color, text_color = text_color, text_size = size.small)
table.cell(exp_table, 1, 0, "Long %", bgcolor = background_color, text_color = text_color, text_size = size.small)
table.cell(exp_table, 2, 0, "Short %", bgcolor = background_color, text_color = text_color, text_size = size.small)
// Populate the Currency column with pairs_traded, and the Long %, Short % columns with 0%
for row_index = 1 to array.size(pairs_traded)
table.cell(exp_table, 0, row_index, array.get(pairs_traded, row_index - 1), bgcolor = background_color, text_color = text_color, text_size = size.tiny)
table.cell(exp_table, 1, row_index, "0%", bgcolor = background_color, text_color = text_color, text_size = size.tiny)
table.cell(exp_table, 2, row_index, "0%", bgcolor = background_color, text_color = text_color, text_size = size.tiny)
// Populate the Long %, Short % columns with any exposure values > 0%
for row_index = 1 to array.size(pairs_traded)
// Iterate through the Currency row
current_pair = array.get(pairs_traded, row_index - 1)
// Set the current pair's exposure on the Long % and Short % cells
if current_pair == "AUD"
// Check to see if there is any >0% exposure
if aud_is_long
table.cell(exp_table, 1, row_index, str.tostring(aud_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if aud_is_short
table.cell(exp_table, 2, row_index, str.tostring(aud_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "CAD"
// Check to see if there is any >0% exposure
if cad_is_long
table.cell(exp_table, 1, row_index, str.tostring(cad_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if cad_is_short
table.cell(exp_table, 2, row_index, str.tostring(cad_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "CHF"
// Check to see if there is any >0% exposure
if chf_is_long
table.cell(exp_table, 1, row_index, str.tostring(chf_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if chf_is_short
table.cell(exp_table, 2, row_index, str.tostring(chf_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "JPY"
// Check to see if there is any >0% exposure
if jpy_is_long
table.cell(exp_table, 1, row_index, str.tostring(jpy_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if jpy_is_short
table.cell(exp_table, 2, row_index, str.tostring(jpy_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "EUR"
// Check to see if there is any >0% exposure
if eur_is_long
table.cell(exp_table, 1, row_index, str.tostring(eur_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if eur_is_short
table.cell(exp_table, 2, row_index, str.tostring(eur_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "GBP"
// Check to see if there is any >0% exposure
if gbp_is_long
table.cell(exp_table, 1, row_index, str.tostring(gbp_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if gbp_is_short
table.cell(exp_table, 2, row_index, str.tostring(gbp_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "NZD"
// Check to see if there is any >0% exposure
if nzd_is_long
table.cell(exp_table, 1, row_index, str.tostring(nzd_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if nzd_is_short
table.cell(exp_table, 2, row_index, str.tostring(nzd_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "SGD"
// Check to see if there is any >0% exposure
if sgd_is_long
table.cell(exp_table, 1, row_index, str.tostring(sgd_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if sgd_is_short
table.cell(exp_table, 2, row_index, str.tostring(sgd_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
else if current_pair == "USD"
// Check to see if there is any >0% exposure
if usd_is_long
table.cell(exp_table, 1, row_index, str.tostring(usd_long_exp) + "%", bgcolor = long_exp_color, text_color = text_color, text_size = size.tiny)
if usd_is_short
table.cell(exp_table, 2, row_index, str.tostring(usd_short_exp) + "%", bgcolor = short_exp_color, text_color = text_color, text_size = size.tiny)
// Merge the columns in the last row of the table to make the Total Exposure row take up the space of all 3 columns
//table.merge_cells(exp_table, 0, array.size(pairs_traded) + 1, 2, array.size(pairs_traded) + 1)
// Populate the Total Exposure % row
//table.cell(exp_table, 1, array.size(pairs_traded) + 1, "Total Exposure: " + str.tostring(get_total_exposure()) + "%", bgcolor = background_color, text_color = text_color, text_size = size.small, text_halign = text.align_center)
//============================================================================== |
STD-Stepped, Variety N-Tuple Moving Averages [Loxx] | https://www.tradingview.com/script/EiNUBmCm-STD-Stepped-Variety-N-Tuple-Moving-Averages-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 214 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© loxx
//@version=5
indicator("STD-Stepped, Variety N-Tuple Moving Averages [Loxx]",
shorttitle="STDSVNTMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
_iT3(src, per, hot, clean)=>
a = hot
_c1 = -a * a * a
_c2 = 3 * a * a + 3 * a * a * a
_c3 = -6 * a * a - 3 * a - 3 * a * a * a
_c4 = 1 + 3 * a + a * a * a + 3 * a * a
alpha = 0.
if (clean == "T3 New")
alpha := 2.0 / (2.0 + (per - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + per)
_t30 = src, _t31 = src
_t32 = src, _t33 = src
_t34 = src, _t35 = src
_t30 := nz(_t30[1]) + alpha * (src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
fact(int n)=>
float a = 1
for i = 1 to n
a *= i
a
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(15,"Period", group = "Basic Settings")
nemadepth = input.int(5, "Depth", maxval = 15, minval = 1, group = "Basic Settings")
type = input.string("EMA", "Variety Moving Average Type", options = ["EMA", "WMA", "SMA", "RMA", "T3"], group = "Basic Settings")
t3hot = input.float(0.7, "T3 Hot", group= "T3 Settings")
t3swt = input.string("T3 New", "T3 Type", options = ["T3 New", "T3 Original"], group = "T3 Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "NTMA", "Both", "None"], group= "Filter Settings")
filter = input.float(2, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(10, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len)=>
out = 0.0
if type == "EMA"
out := ta.ema(src, len)
else if type == "WMA"
out := ta.wma(src, len)
else if type == "SMA"
out := ta.sma(src, len)
else if type == "RMA"
out := ta.rma(src, len)
else if type == "T3"
out := _iT3(src, len, t3hot, t3swt)
out
_gsmth(string type, float src, simple int per, simple int depth, float[] coeff)=>
float out = 0.
if depth == 1
ma1 = variant(type, src, per)
out := ma1
if depth == 2
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
out :=
array.get(coeff, 1) * ma1
- ma2
if depth == 3
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ ma3
if depth == 4
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- ma4
if depth == 5
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ ma5
if depth == 6
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- ma6
if depth == 7
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ ma7
if depth == 8
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- ma8
if depth == 9
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ ma9
if depth == 10
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- ma10
if depth == 11
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ ma11
if depth == 12
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- ma12
if depth == 13
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ ma13
if depth == 14
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- ma14
if depth == 15
ma1 = variant(type, src, per)
ma2 = variant(type, ma1, per)
ma3 = variant(type, ma2, per)
ma4 = variant(type, ma3, per)
ma5 = variant(type, ma4, per)
ma6 = variant(type, ma5, per)
ma7 = variant(type, ma6, per)
ma8 = variant(type, ma7, per)
ma9 = variant(type, ma8, per)
ma10 = variant(type, ma9, per)
ma11 = variant(type, ma10, per)
ma12 = variant(type, ma11, per)
ma13 = variant(type, ma12, per)
ma14 = variant(type, ma13, per)
ma15 = variant(type, ma14, per)
out :=
array.get(coeff, 1) * ma1
- array.get(coeff, 2) * ma2
+ array.get(coeff, 3) * ma3
- array.get(coeff, 4) * ma4
+ array.get(coeff, 5) * ma5
- array.get(coeff, 6) * ma6
+ array.get(coeff, 7) * ma7
- array.get(coeff, 8) * ma8
+ array.get(coeff, 9) * ma9
- array.get(coeff, 10) * ma10
+ array.get(coeff, 11) * ma11
- array.get(coeff, 12) * ma12
+ array.get(coeff, 13) * ma13
- array.get(coeff, 14) * ma14
+ ma15
out
//std filter
_filt(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - price[1]) < filtdev ? price[1] : price
price
nemadepth := math.max(math.min(nemadepth, 49), 1)
coeff = array.new<float>(50, 0.)
for k = 0 to nemadepth
array.set(coeff, k, nz(fact(nemadepth) / (fact(nemadepth - k) * fact(k)), 1))
depth = array.size(coeff) - 1
src := filterop == "Both" or filterop == "Price" and filter > 0 ? _filt(src, filterperiod, filter) : src
out = _gsmth(type, src, per, nemadepth, coeff)
out := filterop == "Both" or filterop == "NTMA" and filter > 0 ? _filt(out, filterperiod, filter) : out
sig = nz(out[1])
state = 0
if (out > sig)
state := 1
if (out < sig)
state := -1
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "NTMA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD-Stepped, Variety N-Tuple Moving Averages [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD-Stepped, Variety N-Tuple Moving Averages [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
AMC Dividend Shift Variance [Joshlo] | https://www.tradingview.com/script/15ZlFL4w-AMC-Dividend-Shift-Variance-Joshlo/ | Joshlo | https://www.tradingview.com/u/Joshlo/ | 8 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Joshlo
//@version=5
indicator("AMC Dividend Shift Variance", shorttitle="AMC Div Shift", overlay=true)
//PRE SHIFT AMC in TV
tvShift = input.float(1.62779, title="TradingView Shift", group="TradingView Shift")
tvCol = input.color(color.purple, title="Pre Dividend Split Price", group="TradingView Shift")
//AMC DIVIDEND DATE
showDate = input.bool(true, "Show Dividend Date on Chart", group="AMC Dividend Date")
i_startTime = input.time(title="Div Date Open", defval=timestamp("22 Aug 2022 13:30:00"), tooltip="Adjust according to your timezone", group="AMC Dividend Date")
i_endTime = input.time(title="Div Date Open +5mins", defval=timestamp("22 Aug 2022 13:35:00"), tooltip="Adjust according to your timezone", group="AMC Dividend Date")
f_dateFilter = time >= i_startTime and time <= i_endTime
f_preSplit = time < i_startTime
f_postSplit = time > i_endTime
//Alternative Charts Shift
i_wb = input.bool(true, "WeBull Shift", group="Alternative Shifts")
webullShift = input.float(1.49917, title="Webull Shift", group="Alternative Shifts")
wbCol = input.color(color.blue, title="Webull Shift Colour", group="Alternative Shifts")
i_futu = input.bool(true, "Futu Shift", group="Alternative Shifts")
futuShift = input.float(1.61342, title="Futu Shift", group="Alternative Shifts")
futuCol = input.color(color.aqua, title="Futu Shift Colour", group="Alternative Shifts")
i_hood = input.bool(true, "Robinhood Shift", group="Alternative Shifts")
hoodShift = input.float(1.57357, title="Robinhood Shift", group="Alternative Shifts")
hoodCol = input.color(color.lime, title="Robinhood Shift Colour", group="Alternative Shifts")
tv1=plot(f_preSplit ? high*tvShift : na, color=color.new(tvCol, 100), title="AMC Pre Shift High")
tv2=plot(f_preSplit ? low*tvShift : na, color=color.new(tvCol, 100), title="AMC Pre Shift Low")
fill(tv1, tv2, color=color.new(tvCol, 80), title="AMC Pre Shift Range")
plotbar(showDate ? f_dateFilter ? 27.49 : na : na, showDate ? f_dateFilter ? 27.49 : na : na, showDate ? f_dateFilter ? 8.49 : na : na, showDate ? f_dateFilter ? 8.49 : na : na, color=color.new(color.blue,0), title="AMC Dividend Split Date")
wb1=plot(i_wb ? f_preSplit ? (high*tvShift)/webullShift : na : na, color=color.new(wbCol, 100), title="WeBull Pre High")
wb2=plot(f_preSplit ? (low*tvShift)/webullShift : na, color=color.new(wbCol, 100), title="WeBull Shift Low")
fill(wb1, wb2, color=color.new(wbCol, 80), title="WeBull Shift Range")
futu1=plot(i_futu ? f_preSplit ? (high*tvShift)/futuShift : na : na, color=color.new(futuCol, 100), title="Futu Shift High")
futu2=plot(i_futu ? f_preSplit ? (low*tvShift)/futuShift : na : na, color=color.new(futuCol, 100), title="Futu Shift Low")
fill(futu1, futu2, color=color.new(futuCol, 80), title="Futu Shift Range")
hood1=plot(i_hood ? f_preSplit ? (high*tvShift)/hoodShift : na : na, color=color.new(hoodCol, 100), title="Robinhood Shift High")
hood2=plot(i_hood ? f_preSplit ? (low*tvShift)/hoodShift : na : na, color=color.new(hoodCol, 100), title="Robinhood Shift Low")
fill(hood1, hood2, color=color.new(hoodCol, 80), title="Robinhood Shift Range") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.