ATRStopLossFinderLibrary "ATRStopLossFinder"
Average True Range Stop Loss Finder
credits to www.tradingview.com for the initial version
stopLossFinder(length, smoothing, multiplier, refHigh, refLow, refClose) Returns the stop losses for an entry on this candle, depending on the ATR
Parameters:
length : simple int optional to select the lookback amount of candles
smoothing : string optional to select the averaging method, options=
multiplier : simple float optional if you want to tweak the speed the trend changes.
refHigh : series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
refLow : series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
refClose : series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
Returns: series float stopLossLong, series float stopLossShort, series float atr
Indicators and strategies
AbdulLibraryLibrary "AbdulLibrary"
The library consists of three sections:
Technical Analysis Functions - A collection of tools commonly used by day traders
Trading Setup Filters Functions - A number of filters that help day traders to screen trading signals
Candlestick Pattern Detection Functions - To detect different candlestick patterns that are used in day trading setups
Note that this would have been possible without the help of @ZenAndTheArtOfTrading as I build-up this library after completing his pine script mastery course so big thanks to him
The content of the library are:-
fibLevels(preDayClose, preDayHigh, preDayLow) Calculates Daily Pivot Point and Fibonacci Key Levels
Parameters:
preDayClose : The previous day candle close
preDayHigh : The previous day candle high
preDayLow : The previous day candle low
Returns: Returns Daily Pivot Point and Fibonacci Key Levels as a tuple
bullishFib(canHigh, canLow, fibLevel) Calculates Fibonacci Levels in Bullish move
Parameters:
canHigh : The high of the move
canLow : The low of the move
fibLevel : The Fib level as % you want to calculate
Returns: Returns The Fib level for the Bullish move
bearishFib(canHigh, canLow, fibLevel) Calculates Fibonacci Levels in Bearish move
Parameters:
canHigh : The high of the move
canLow : The low of the move
fibLevel : The Fib level as % you want to calculate
Returns: Returns The Fib level for the Bearish move
getCandleSize() Calculates the size of candle (high - low) in points
Returns: Returns candle size in points
getCandleBodySize() Calculates the size of candle (close - open) in points
Returns: Returns candle body size in points
getHighWickSize() Calculates the high wick size of candle in points
Returns: Returns The high wick size of candle in points
getLowWickSize() Calculates the low wick size of candle in points
Returns: Returns The low wick size of candle in points
getBodyPercentage() Calculates the candle body size as % of overall candle size
Returns: Returns The candle body size as % of overall candle size
isSwingHigh(period) Checks if the price has created new swing high over a period of time
Parameters:
period : The lookback time we want to check for swing high
Returns: Returns True if the current candle or the previous candle is a swing high
isSwingLow(period) Checks if the price has created new swing low over a period of time
Parameters:
period : The lookback time we want to check for swing low
Returns: Returns True if the current candle or the previous candle is a swing low
isDojiSwingHigh(period) Checks if a doji is a swing high over a period of time
Parameters:
period : The lookback time we want to check for swing high
Returns: Returns True if the doji is a swing high
isDojiSwingLow(period) Checks if a doji is a swing low over a period of time
Parameters:
period : The lookback time we want to check for swing low
Returns: Returns True if the doji is a swing low
isBigBody(atrFilter, atr, candleBodySize, multiplier) Checks if a candle has big body compared to ATR
Parameters:
atrFilter : Check if user wants to use ATR to filter candle-setup signals
atr : The ATR value to be used to compare candle body size
candleBodySize : The candle body size
multiplier : The multiplier to be used to compare candle body size
Returns: Returns Boolean true if the candle setup is big
isSmallBody(atrFilter, atr, candleBodySize, multiplier) Checks if a candle has small body compared to ATR
Parameters:
atrFilter : Check if user wants to use ATR to filter candle-setup signals
atr : The ATR value to be used to compare candle body size
candleBodySize : The candle body size
multiplier : The multiplier to be used to compare candle body size
Returns: Returns Boolean true if the candle setup is small
isHammer(fibLevel, colorMatch) Checks if a candle is a hammer based on user input parameters and candle conditions
Parameters:
fibLevel : Fib level to base candle body on
colorMatch : Checks if user needs for the candel to be green
Returns: Returns Boolean - True if the candle setup is hammer
isShootingStar(fibLevel, colorMatch) Checks if a candle is a shooting star based on user input parameters and candle conditions
Parameters:
fibLevel : Fib level to base candle body on
colorMatch : Checks if user needs for the candel to be red
Returns: Returns Boolean - True if the candle setup is star
isBullEngCan(allowance, period) Check if a candle is a bullish engulfing candle
Parameters:
allowance : How many points the candle open is allowed to be off (To allow for gaps)
period : The lookback period for swing low check
Returns: Boolean - True only if the candle is a bullish engulfing candle
isBearEngCan(allowance, period) Check if a candle is a bearish engulfing candle
Parameters:
allowance : How many points the candle open is allowed to be off (To allow for gaps)
period : The lookback period for swing high check
Returns: Boolean - True only if the candle is a bearish engulfing candle
isBullDoji(maxSize, wickLimit, colorFilter) Check if a candle is a bullish doji candle
Parameters:
maxSize : Maximum candle body size as % of total candle size to be considered as doji
wickLimit : Maximum wick size of one wick compared to the other wick
colorFilter : Checks if the doji is green
Returns: Boolean - True if the candle is a bullish doji
isBearDoji(maxSize, wickLimit, colorFilter) Check if a candle is a bearish doji candle
Parameters:
maxSize : Maximum candle body size as % of total candle size to be considered as doji
wickLimit : Maximum wick size of one wick compared to the other wick
colorFilter : Checks if the doji is red
Returns: Boolean - True if the candle is a bearish doji
isBullOutBar() Check if a candle is a bullish outside bar
Returns: Boolean - True if the candle is a bullish outside bar
isInsideBar() Check if a candle is an inside bar
Returns: Returns Boolean - True if a candle is an inside bar
InitialiseArraysLibrary "InitialiseArrays"
@description: Efficiently create arrays, populating them with an arbitrary number of elements and setting their starting values. Works with a mix of typed and na values.
A limitation of the built-in functions to create arrays is that while you can create and populate arrays with a single command, you can only set all elements to the same value in this way.
Or, you can create an array from a set of values or variables, but you can't include any na values.
Now, it's easy enough to work around this, but I wanted to make something more efficient (because I want to use lots of arrays), hence this library.
Calling a function from here is more efficient because you only do it once (assuming it's a var) and don't evaluate an if condition each run, and don't create unnecessary variables.
It's also easier to read and takes less space.
f_initialiseBoolArray()
@function f_initialiseBoolArray(string _values) Creates a boolean array, populated with the values that you specify in the input string.
@param _values is a string that contains a comma-separated list of the values that you want to initialise the boolean array with. Values other than true, false, and na are disregarded. Spaces are disregarded.
@returns Returns a boolean array of arbitrary length.
f_initialiseFloatArray()
@function f_initialiseFloatArray(string _values) Creates a float array, populated with the values that you specify in the input string.
@param _values is a string that contains a comma-separated list of the values that you want to initialise the float array with. Non-numerical entries are converted to NaN values. Spaces are disregarded.
@returns Returns a float array of arbitrary length.
f_initialiseIntArray()
@function f_initialiseIntArray(string _values) Creates an int array, populated with the values that you specify in the input string.
@param _values is a string that contains a comma-separated list of the values that you want to initialise the int array with. Floating-point numbers are rounded down to the nearest integer. Any na values are preserved. Spaces are disregarded.
@returns Returns a float array of arbitrary length.
V1 includes functions for bools, floats, and ints. I might extend it if people want.
drawingutilsLibrary "drawingutils"
Private methods used in my scripts for some basic and customized drawings. No documentation provided as these are meant for private use only.
draw_line()
draw_label()
draw_linefill()
draw_labelled_line()
draw_labelled_box()
runTimer()
okhan_commonThis is a draft version of a library intended to clean up my other indicators, thats why probably it won't be heplful for others, and I won't focus on documenting it at the moment.
However, if by any chance you plan to use this library, let me know if you need me to document anything.
PivotsLibrary "Pivots"
This Library focuses in functions related to pivot highs and lows and some of their applications (i.e. divergences, zigzag, harmonics, support and resistance...)
pivots(srcH, srcL, length) Delivers series of pivot highs, lows and zigzag.
Parameters:
srcH : Source series to look for pivot highs. Stricter applications might source from 'close' prices. Oscillators are also another possible source to look for pivot highs and lows. By default 'high'
srcL : Source series to look for pivot lows. By default 'low'
length : This value represents the minimum number of candles between pivots. The lower the number, the more detailed the pivot profile. The higher the number, the more relevant the pivots. By default 10
Returns:
zigzagArray(pivotHigh, pivotLow) Delivers a Zigzag series based on alternating pivots. Ocasionally this line could paint a few consecutive lows or highs without alternating. That happens because it's finding a few consecutive Higher Highs or Lower Lows. If to use lines entities instead of series, that could be easily avoided. But in this one, I'm more interested outputting series rather than painting/deleting line entities.
Parameters:
pivotHigh : Pivot high series
pivotLow : Pivot low series
Returns:
zigzagLine(srcH, srcL, colorLine, widthLine) Delivers a Zigzag based on line entities.
Parameters:
srcH : Source series to look for pivot highs. Stricter applications might source from 'close' prices. Oscillators are also another possible source to look for pivot highs and lows. By default 'high'
srcL : Source series to look for pivot lows. By default 'low'
colorLine : Color of the Zigzag Line. By default Fuchsia
widthLine : Width of the Zigzag Line. By default 4
Returns: Zigzag printed on screen
divergence(h2, l2, h1, l1, length) Calculates divergences between 2 series
Parameters:
h2 : Series in which to locate divs: Highs
l2 : Series in which to locate divs: Lows
h1 : Series in which to locate pivots: Highs. By default high
l1 : Series in which to locate pivots: Lows. By default low
length : Length used to calculate Pivots: By default 10
Returns:
Common FunctionsLibrary "CommonFunctions"
This Library provides some handy functions commonly used in Pine Script.
crosses(source1, offset1, source2, offset2) Checks the existance of crosses between the series
Parameters:
source1 : First series
offset1 : (Optional) Offset of First series. By default 0
source2 : (Optional) Second series. By default 'close' price
offset2 : (Optional) Offset of Second series. By default 0
Returns:
marketState(source1, offset1, source2, offset2) Determines Bullish/Bearish state according to the relative position between the series.
Parameters:
source1 : Active series used to determine bullish/bearish states.
offset1 : (Optional) Offset of First series. By default 0.
source2 : (Optional) Second series. By default 'close' price.
offset2 : (Optional) Offset of Second series. By default 0.
Returns:
histProfile(source) Histogram profiling
Parameters:
source : Histogram series
Returns:
srcSelect(showSrc1, src1, showSrc2, src2) Selects the appropiate source. If multiple sources are activated simultaneously, the order within the switch clause prevails. The first one activated is the one being output.
Parameters:
showSrc1 : Boolean controlling the activation of Source #1.
src1 : Source #1.
showSrc2 : Boolean controlling the activation of Sources #2-10. By default 'false'.
src2 : Sources #2-10. By default 'number'.
Returns: Selected source.
MakeLoveNotWarLibrary "MakeLoveNotWar"
Make Love Not War, place a flag of support on your chart!
flag(pos, text_size) Make Love Not War function.
Parameters:
pos : string, position.
text_size : string, text size.
Returns: table.
Cayoshi_LibraryLibrary "Cayoshi_Library"
fungtion show win loss and Netprofit Show
Library สำหรับเรียกใช้
1.Win_Loss_Show() การแสดง แพ้ ชนะ
2.NetProfit_Show() การแสดงผล Backtest
3.Count_Bar_Back_Test() กำหนดระยะเวลา หรือ แท่งบาร์ในการ Backtest
math_utilsLibrary "math_utils"
Collection of math functions that are not part of the standard math library
num_of_non_decimal_digits(number) num_of_non_decimal_digits - The number of the most significant digits on the left of the dot
Parameters:
number : - The floating point number
Returns: number of non digits
num_of_decimal_digits(number) num_of_decimal_digits - The number of the most significant digits on the right of the dot
Parameters:
number : - The floating point number
Returns: number of decimal digits
floor(number, precision) floor - floor with precision to the given most significant decimal point
Parameters:
number : - The floating point number
precision : - The number of decimal places a.k.a the most significant decimal digit - e.g precision 2 will produce 0.01 minimum change
Returns: number floored to the decimal digits defined by the precision
ceil(number, precision) floor - ceil with precision to the given most significant decimal point
Parameters:
number : - The floating point number
precision : - The number of decimal places a.k.a the most significant decimal digit - e.g precision 2 will produce 0.01 minimum change
Returns: number ceiled to the decimal digits defined by the precision
clamp(number, lower, higher, precision) clamp - clamp with precision to the given most significant decimal point
Parameters:
number : - The floating point number
lower : - The lowerst number limit to return
higher : - The highest number limit to return
precision : - The number of decimal places a.k.a the most significant decimal digit - e.g precision 2 will produce 0.01 minimum change
Returns: number clamped to the decimal digits defined by the precision
ConditionalAverages█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing functions that average values selectively.
█ CONCEPTS
Averaging can be useful to smooth out unstable readings in the data set, provide a benchmark to see the underlying trend of the data, or to provide a general expectancy of values in establishing a central tendency. Conventional averaging techniques tend to apply indiscriminately to all values in a fixed window, but it can sometimes be useful to average values only when a specific condition is met. As conditional averaging works on specific elements of a dataset, it can help us derive more context-specific conclusions. This library offers a collection of averaging methods that not only accomplish these tasks, but also exploit the efficiencies of the Pine Script™ runtime by foregoing unnecessary and resource-intensive for loops.
█ NOTES
To Loop or Not to Loop
Though for and while loops are essential programming tools, they are often unnecessary in Pine Script™. This is because the Pine Script™ runtime already runs your scripts in a loop where it executes your code on each bar of the dataset. Pine Script™ programmers who understand how their code executes on charts can use this to their advantage by designing loop-less code that will run orders of magnitude faster than functionally identical code using loops. Most of this library's function illustrate how you can achieve loop-less code to process past values. See the User Manual page on loops for more information. If you are looking for ways to measure execution time for you scripts, have a look at our LibraryStopwatch library .
Our `avgForTimeWhen()` and `totalForTimeWhen()` are exceptions in the library, as they use a while structure. Only a few iterations of the loop are executed on each bar, however, as its only job is to remove the few elements in the array that are outside the moving window defined by a time boundary.
Cumulating and Summing Conditionally
The ta.cum() or math.sum() built-in functions can be used with ternaries that select only certain values. In our `avgWhen(src, cond)` function, for example, we use this technique to cumulate only the occurrences of `src` when `cond` is true:
float cumTotal = ta.cum(cond ? src : 0) We then use:
float cumCount = ta.cum(cond ? 1 : 0) to calculate the number of occurrences where `cond` is true, which corresponds to the quantity of values cumulated in `cumTotal`.
Building Custom Series With Arrays
The advent of arrays in Pine has enabled us to build our custom data series. Many of this library's functions use arrays for this purpose, saving newer values that come in when a condition is met, and discarding the older ones, implementing a queue .
`avgForTimeWhen()` and `totalForTimeWhen()`
These two functions warrant a few explanations. They operate on a number of values included in a moving window defined by a timeframe expressed in milliseconds. We use a 1D timeframe in our example code. The number of bars included in the moving window is unknown to the programmer, who only specifies the period of time defining the moving window. You can thus use `avgForTimeWhen()` to calculate a rolling moving average for the last 24 hours, for example, that will work whether the chart is using a 1min or 1H timeframe. A 24-hour moving window will typically contain many more values on a 1min chart that on a 1H chart, but their calculated average will be very close.
Problems will arise on non-24x7 markets when large time gaps occur between chart bars, as will be the case across holidays or trading sessions. For example, if you were using a 24H timeframe and there is a two-day gap between two bars, then no chart bars would fit in the moving window after the gap. The `minBars` parameter mitigates this by guaranteeing that a minimum number of bars are always included in the calculation, even if including those bars requires reaching outside the prescribed timeframe. We use a minimum value of 10 bars in the example code.
Using var in Constant Declarations
In the past, we have been using var when initializing so-called constants in our scripts, which as per the Style Guide 's recommendations, we identify using UPPER_SNAKE_CASE. It turns out that var variables incur slightly superior maintenance overhead in the Pine Script™ runtime, when compared to variables initialized on each bar. We thus no longer use var to declare our "int/float/bool" constants, but still use it when an initialization on each bar would require too much time, such as when initializing a string or with a heavy function call.
Look first. Then leap.
█ FUNCTIONS
avgWhen(src, cond)
Gathers values of the source when a condition is true and averages them over the total number of occurrences of the condition.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
Returns: (float) A cumulative average of values when a condition is met.
avgWhenLast(src, cond, cnt)
Gathers values of the source when a condition is true and averages them over a defined number of occurrences of the condition.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
cnt : (simple int) The quantity of last occurrences of the condition for which to average values.
Returns: (float) The average of `src` for the last `x` occurrences where `cond` is true.
avgWhenInLast(src, cond, cnt)
Gathers values of the source when a condition is true and averages them over the total number of occurrences during a defined number of bars back.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
cnt : (simple int) The quantity of bars back to evaluate.
Returns: (float) The average of `src` in last `cnt` bars, but only when `cond` is true.
avgSince(src, cond)
Averages values of the source since a condition was true.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when the average is reset.
Returns: (float) The average of `src` since `cond` was true.
avgForTimeWhen(src, ms, cond, minBars)
Averages values of `src` when `cond` is true, over a moving window of length `ms` milliseconds.
Parameters:
src : (series int/float) The source of the values to be averaged.
ms : (simple int) The time duration in milliseconds defining the size of the moving window.
cond : (series bool) The condition determining which values are included. Optional.
minBars : (simple int) The minimum number of values to keep in the moving window. Optional.
Returns: (float) The average of `src` when `cond` is true in the moving window.
totalForTimeWhen(src, ms, cond, minBars)
Sums values of `src` when `cond` is true, over a moving window of length `ms` milliseconds.
Parameters:
src : (series int/float) The source of the values to be summed.
ms : (simple int) The time duration in milliseconds defining the size of the moving window.
cond : (series bool) The condition determining which values are included. Optional.
minBars : (simple int) The minimum number of values to keep in the moving window. Optional.
Returns: (float) The sum of `src` when `cond` is true in the moving window.
HighTimeframeTimingLibrary "HighTimeframeTiming"
@description Library for sampling high timeframe (HTF) historical data at an arbitrary number of HTF bars back, using a single security() call.
The data is fixed and does not alter over the course of the HTF bar. It also behaves consistently on historical and elapsed realtime bars.
‼ LIMITATIONS: This library function depends on there being a consistent number of chart timeframe bars within the HTF bar. This is almost always true in 24/7 markets like crypto.
This might not be true if the chart doesn't produce an update when expected, for example because the asset is thinly traded and there is no volume or price update from the feed at that time.
To mitigate this risk, use this function on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
The consistent ratio of bars might also break down in markets with irregular sessions and hours. I'm not sure if or how one could mitigate this.
Another limitation is that because we're accessing a multiplied number of chart bars, you will run out of chart bars faster than you would HTF bars. This is only a problem if you use a large historical operator.
If you call a function from this library, you should probably reproduce these limitations in your script description.
However, all of this doesn't mean that this function might not still be the best available solution, depending what your needs are.
If a single chart bar is skipped, for example, the calculation will be off by 1 until the next HTF bar opens. This is certainly inconsistent, but potentially still usable.
@function f_offset_synch(float _HTF_X, int _HTF_H, int _openChartBarsIn, bool _updateEarly)
Returns the number of chart bars that you need to go back in order to get a stable HTF value from a given number of HTF bars ago.
@param float _HTF_X is the timeframe multiplier, i.e. how much bigger the selected timeframe is than the chart timeframe. The script shows a way to calculate this using another of my libraries without using up a security() call.
@param int _HTF_H is the historical operator on the HTF, i.e. how many bars back you want to go on the higher timeframe. If omitted, defaults to zero.
@param int _openChartBarsIn is how many chart bars have been opened within the current HTF bar. An example of calculating this is given below.
@param bool _updateEarly defines whether you want to update the value at the closing calculation of the last chart bar in the HTF bar or at the open of the first one.
@returns an integer that you can use as a historical operator to retrieve the value for the appropriate HTF bar.
🙏 Credits: This library is an attempt at a solution of the problems in using HTF data that were laid out by Pinecoders in "security() revisited" -
Thanks are due to the authors of that work for an understanding of HTF issues. In addition, the current script also includes some of its code.
Specifically, this script reuses the main function recommended in "security() revisited", for the purposes of comparison. And it extends that function to access historical data, again just for comparison.
All the rest of the code, and in particular all of the code in the exported function, is my own.
Special thanks to LucF for pointing out the limitations of my approach.
~~~~~~~~~~~~~~~~|
EXPLANATION
~~~~~~~~~~~~~~~~|
Problems with live HTF data: Many problems with using live HTF data from security() have been clearly explained by Pinecoders in "security() revisited"
In short, its behaviour is inconsistent between historical and elapsed realtime bars, and it changes in realtime, which can cause calculations and alerts to misbehave.
Various unsatisfactory solutions are discussed in "security() revisited", and understanding that script is a prerequisite to understanding this library.
PineCoders give their own solution, which is to fix the data by essentially using the previous HTF bar's data. Importantly, that solution is consistent between historical and realtime bars.
This library is an attempt to provide an alternative to that solution.
Problems with historical HTF data: In addition to the problems with live HTF data, there are different issues when trying to access historical HTF data.
Why use historical HTF data? Maybe you want to do custom calculations that involve previous HTF bars. Or to use HTF data in a function that has mutable variables and so can't be done in a security() call.
Most obviously, using the historical operator (in this description, represented using { } because the square brackets don't render) on variables already retrieved from a security() call, e.g. HTF_Close{1}, is not very useful:
it retrieves the value from the previous *chart* bar, not the previous HTF bar.
Using {1} directly in the security() call instead does get data from the previous HTF bar, but it behaves inconsistently, as we shall see.
This library addresses these concerns as well.
Housekeeping: To follow what's going on with the example and comparisons, turn line labels on: Settings > Scales > Indicator Name Label.
The following explanation assumes "close" as the source, but you can change it if you want.
To quickly see the difference between historical and realtime bars, set the HTF to something like 3 minutes on a 15s chart.
The bars at the top of the screen show the status. Historical bars are grey, elapsed realtime bars are red, and the realtime bar is green. A white vertical line shows the open of a HTF bar.
A: This library function f_offset_synch(): When supplied with an input offset of 0, it plots a stable value of the close of the *previous* HTF bar. This value is thus safe to use for calculations and alerts.
For a historical operator of {1}, it gives the close of the *last-but-one* bar. Sounds simple enough. Let's look at the other options to see its advantages.
B: Live HTF data: Represented on the line label as "security(){0}". Note: this is the source that f_offset_synch() samples.
The raw HTF data is very different on historical and realtime bars:
+ On historical bars, it uses a flat value from the end of the previous HTF bar. It updates at the close of the HTF bar.
+ On realtime bars, it varies between and within each chart bar.
There might be occasions where you want to use live data, in full knowledge of its drawbacks described above. For example, to show simple live conditions that are reversible after a chart bar close.
This library transforms live data to get the fixed data, thus giving you access to both live and fixed data with only one security() call.
C: Historical data using security(){H}: To see how this behaves, set the {H} value in the settings to 1 and show options A, B, and C.
+ On historical bars, this option matches option A, this library function, exactly. It behaves just like security(){0} but one HTF bar behind, as you would expect.
+ On realtime bars, this option takes the value of security(){0} at the end of a HTF bar, but it takes it from the previous *chart* bar, and then persists that.
The easiest way to see this inconsistency is on the first realtime bar (marked red at the top of the screen). This option suddenly jumps, even if it's in the middle of a HTF bar.
Contrast this with option A, which is always constant, until it updates, once per HTF bar.
D: PineCoders' original function: To see how this behaves, show options A, B, and D. Set the {H} value in the settings to 0, then 1.
The PineCoders' original function (D) and extended function (E) do not have the same limitations as this library, described in the Limitations section.
This option has all of the same advantages that this library function, option A, does, with the following differences:
+ It cannot access historical data. The {H} setting makes no difference.
+ It always updates at the open of the first chart bar in a new HTF bar.
By contrast, this library function, option A, is configured by default to update at the close of the last chart bar in a HTF bar.
This little frontrunning is only a few seconds but could be significant in trading. E.g. on a 1D HTF with a 4H chart, an alert that involves a HTF change set to trigger ON CLOSE would trigger 4 hours later using this method -
but use exactly the same value. It depends on the market and timeframe as to whether you could actually trade this. E.g. at the very end of a tradfi day your order won't get executed.
This behaviour mimics how security() itself updates, as is easy to see on the chart. If you don't want it, just set in_updateEarly to false. Then it matches option D exactly.
E: PineCoders' function, extended to get history: To see how this behaves, show options A and E. Set the {H} value in the settings to 0, then 1.
I modified the original function to be able to get historical values. In all other respects it is the same.
Apart from not having the option to update earlier, the only disadvantage of this method vs this library function is that it requires one security() call for each historical operator.
For example, if you wanted live data, and fixed data, and fixed data one bar back, you would need 3 security() calls. My library function requires just one.
This is the essential tradeoff: extra complexity and less robustness in certain circumstances (the PineCoders function is simple and universal by comparison) for more flexibility with fewer security() calls.
harmonicpatternsarraysLibrary "harmonicpatternsarrays"
Library provides an alternative method to scan harmonic patterns and contains utility functions using arrays.
These are mostly customized for personal use. Hence, will not add documentation for arrays. All credit to @HeWhoMustNotBeNamed
getLabel()
delete()
delete()
delete()
delete()
delete()
pop()
pop()
pop()
pop()
pop()
shift()
shift()
shift()
shift()
shift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
clear()
clear()
clear()
clear()
clear()
push()
push()
push()
push()
push()
push()
push()
push()
push()
push()
get_trend_series()
getrange()
getSupportedPatterns()
scan_xab()
scan_abc_axc()
scan_bcd()
scan_xad_xcd()
get_prz_range()
isHarmonicPattern()
MovingAveragesLibraryLibrary "MovingAveragesLibrary"
This is a library allowing one to select between many different Moving Average formulas to smooth out any float variable.
You can use this library to apply a Moving Average function to any series of data as long as your source is a float.
The default application would be for applying Moving Averages onto your chart. However, the scope of this library is beyond that. Any indicator or strategy you are building can benefit from this library.
You can apply different types of smoothing and moving average functions to your indicators, momentum oscillators, average true range calculations, support and resistance zones, envelope bands, channels, and anything you can think of to attempt to smooth out noise while finding a delicate balance against lag.
If you are developing an indicator, you can use the 'ave_func' to allow your users to select any Moving Average for any function or variable by creating an input string with the following structure:
var_name = input.string(, , )
Where the types of Moving Average you would like to be provided would be included in options.
Example:
i_ma_type = input.string(title = "Moving Average Type", defval = "Hull Moving Average", options = )
Where you would add after options the strings I have included for you at the top of the PineScript for your convenience.
Then for the output you desire, simply call 'ave_func' like so:
ma = ave_func(source, length, i_ma_type)
Now the plotted Moving Average will be the same as what you or your users select from the Input.
ema(src, len) Exponential Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: Float value.
sma(src, len) Simple Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: Float value.
rma(src, len) Relative Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: Float value.
wma(src, len) Weighted Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: Float value.
dv2(len) Donchian V2 function.
Parameters:
len : Lookback length to use.
Returns: Open + Close / 2 for the selected length.
ModFilt(src, len) Modular Filter smoothing function.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: Float value.
EDSMA(src, len) Ehlers Dynamic Smoothed Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: EDSMA smoothing.
dema(x, t) Double Exponential Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: DEMA smoothing.
tema(src, len) Triple Exponential Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: TEMA smoothing.
smma(x, t) Smoothed Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: SMMA smoothing.
vwma(x, t) Volume Weighted Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: VWMA smoothing.
hullma(x, t) Hull Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: Hull smoothing.
covwma(x, t) Coefficient of Variation Weighted Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: COVWMA smoothing.
frama(x, t) Fractal Reactive Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: FRAMA smoothing.
kama(x, t) Kaufman's Adaptive Moving Average.
Parameters:
x : Series to use ('close' is used if no argument is supplied).
t : Lookback length to use.
Returns: KAMA smoothing.
donchian(len) Donchian Calculation.
Parameters:
len : Lookback length to use.
Returns: Average of the highest price and the lowest price for the specified look-back period.
tma(src, len) Triangular Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: TMA smoothing.
VAMA(src, len) Volatility Adjusted Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: VAMA smoothing.
Jurik(src, len) Jurik Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: JMA smoothing.
MCG(src, len) McGinley smoothing.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: McGinley smoothing.
zlema(series, length) Zero Lag Exponential Moving Average.
Parameters:
series : Series to use ('close' is used if no argument is supplied).
length : Lookback length to use.
Returns: ZLEMA smoothing.
xema(src, len) Optimized Exponential Moving Average.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
len : Lookback length to use.
Returns: XEMA smoothing.
EhlersSuperSmoother(src, lower) Ehlers Super Smoother.
Parameters:
src : Series to use ('close' is used if no argument is supplied).
lower : Smoothing value to use.
Returns: Ehlers Super smoothing.
EhlersEmaSmoother(sig, smoothK, smoothP) Ehlers EMA Smoother.
Parameters:
sig : Series to use ('close' is used if no argument is supplied).
smoothK : Lookback length to use.
smoothP : Smothing value to use.
Returns: Ehlers EMA smoothing.
ave_func(in_src, in_len, in_type) Returns the source after running it through a Moving Average function.
Parameters:
in_src : Series to use ('close' is used if no argument is supplied).
in_len : Lookback period to be used for the Moving Average function.
in_type : Type of Moving Average function to use. Must have a string input to select the options from that MUST match the type-casing in the function below.
Returns: The source as a float after running it through the Moving Average function.
Strategy█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing a variety of strategy-related functions to assist in calculations like profit and loss, stop losses and limits. It also includes several useful functions one can use to convert between units in ticks, price, currency or a percentage of the position's size.
█ CONCEPTS
The library contains three types of functions:
1 — Functions beginning with `percent` take either a portion of a price, or the current position's entry price and convert it to the value outlined in the function's documentation.
Example: Converting a percent of the current position entry price to ticks, or calculating a percent profit at a given level for the position.
2 — Functions beginning with `tick` convert a tick value to another form.
These are useful for calculating a price or currency value from a specified number of ticks.
3 — Functions containing `Level` are used to calculate a stop or take profit level using an offset in ticks from the current entry price.
These functions can be used to plot stop or take profit levels on the chart, or as arguments to the `limit` and `stop` parameters in strategy.exit() function calls.
Note that these calculated levels flip automatically with the position's bias.
For example, using `ticksToStopLevel()` will calculate a stop level under the entry price for a long position, and above the entry price for a short position.
There are also two functions to assist in calculating a position size using the entry's stop and a fixed risk expressed as a percentage of the current account's equity. By varying the position size this way, you ensure that entries with different stop levels risk the same proportion of equity.
█ NOTES
Example code using some of the library's functions is included at the end of the library. To see it in action, copy the library's code to a new script in the Pine Editor, and “Add to chart”.
For each trade, the code displays:
• The entry level in orange.
• The stop level in fuchsia.
• The take profit level in green.
The stop and take profit levels automatically flip sides based on whether the current position is long or short.
Labels near the last trade's levels display the percentages used to calculate them, which can be changed in the script's inputs.
We plot markers for entries and exits because strategy code in libraries does not display the usual markers for them.
Look first. Then leap.
█ FUNCTIONS
percentToTicks(percent) Converts a percentage of the average entry price to ticks.
Parameters:
percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to ticks. 50 is 50% of the entry price.
Returns: (float) A value in ticks.
percentToPrice(percent) Converts a percentage of the average entry price to a price.
Parameters:
percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to price. 50 is 50% of the entry price.
Returns: (float) A value in the symbol's quote currency (USD for BTCUSD).
percentToCurrency(price, percent) Converts the percentage of a price to money.
Parameters:
price : (series int/float) The symbol's price.
percent : (series int/float) The percentage of `price` to calculate.
Returns: (float) A value in the symbol's currency.
percentProfit(exitPrice) Calculates the profit (as a percentage of the position's `strategy.position_avg_price` entry price) if the trade is closed at `exitPrice`.
Parameters:
exitPrice : (series int/float) The potential price to close the position.
Returns: (float) Percentage profit for the current position if closed at the `exitPrice`.
priceToTicks(price) Converts a price to ticks.
Parameters:
price : (series int/float) Price to convert to ticks.
Returns: (float) A quantity of ticks.
ticksToPrice(price) Converts ticks to a price offset from the average entry price.
Parameters:
price : (series int/float) Ticks to convert to a price.
Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.
ticksToCurrency(ticks) Converts ticks to money.
Parameters:
ticks : (series int/float) Number of ticks.
Returns: (float) Money amount in the symbol's currency.
ticksToStopLevel(ticks) Calculates a stop loss level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `stop` parameter of a `strategy.exit()` call. NOTE: The stop level automatically flips based on whether the position is long or short.
Parameters:
ticks : (series int/float) The distance in ticks from the entry price to the stop loss level.
Returns: (float) A stop loss level for the current position.
ticksToTpLevel(ticks) Calculates a take profit level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `limit` parameter of a `strategy.exit()` call. NOTE: The take profit level automatically flips based on whether the position is long or short.
Parameters:
ticks : (series int/float) The distance in ticks from the entry price to the take profit level.
Returns: (float) A take profit level for the current position.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent) Calculates the position size needed to implement a given stop loss (in ticks) corresponding to `riskPercent` of equity.
Parameters:
stopLossTicks : (series int) The stop loss (in ticks) that will be used to protect the position.
riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
Returns: (int) A quantity of contracts.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice) Calculates the position size needed to implement a given stop loss (%) corresponding to `riskPercent` of equity.
Parameters:
stopLossPercent : (series int/float) The stop loss in percent that will be used to protect the position.
riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
entryPrice : (series int/float) The entry price of the position.
Returns: (int) A quantity of contracts.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, when, alertMessage) A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit in as a value in percent. NOTE: this function may work incorrectly with pyramiding turned on due to the use of `strategy.position_avg_price` in its calculations of stop loss and take profit offsets.
Parameters:
id : (series string) The order identifier of the `strategy.exit()` call.
lossPercent : (series int/float) Stop loss as a percent of the entry price.
profitPercent : (series int/float) Take profit as a percent of the entry price.
qty : (series int/float) Number of contracts/shares/lots/units to exit a trade with. The default value is `na`.
qtyPercent : (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
comment : (series string) Optional. Additional notes on the order.
when : (series bool) Condition of the order. The order is placed if it is true.
alertMessage : (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
adx: Configurable ADX (library) Library "adx"
Calculate ADX (and its constituent parts +DI, -DI, ATR),
using different moving averages and periods.
adx(atrMA, diMA, adxMA, atrLen, diLen, adxLen, h, l, c)
Parameters:
atrMA : Moving Average used for calculating the Average True Range.
Traditionally RMA, but using SMA here and in adxMA gives good results too.
diMA : Moving Average used for calculating the Directional Index.
Traditionally, RMA.
adxMA : Moving Average used for calculating the Average Directional
Index. Traditionally RMA, but using SMA here and in atrMA gives good results
too.
atrLen : Length of the Average True Range.
diLen : Length of the Directional Index.
adxLen : Length (smoothing) of the Average Directional Index.
h : Candle's high.
l : Candle's low.
c : Candle's close.
Returns:
ColorsLibrary "Colors"
This Library delivers Hex Codes of Colors frequently used in indicators and strategies.
v3(colorName) Collection: Pinescript v3 Colors.
Parameters:
colorName : Color Name.
Returns: Hex code of the inquired color.
v4(colorName) Collection: Pinescript v4 Colors.
Parameters:
colorName : Color Name.
Returns: Hex code of the inquired color.
lib_MilitzerLibrary "lib_Militzer"
// This is a collection of functions either found on the internet, or made by me.
// This is only public so my other scripts that reference this can also be public.
// But if you find anything useful here, be my guest.
print()
strToInt()
timeframeToMinutes()
eHarmonicpatternsExtendedLibrary "eHarmonicpatternsExtended"
Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations. Republishing as new library instead of existing eHarmonicpatterns because I need that copy for existing scripts.
scan_xab(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : AB/XA ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) Checks if abc or axc ratio is in range of any harmonic pattern
Parameters:
abcRatio : BC/AB ratio
axcRatio : XC/AX ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_bcd(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : CD/BC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) Checks if xad or xcd ratio is in range of any harmonic pattern
Parameters:
xadRatio : AD/XA ratio
xcdRatio : CD/XC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
isHarmonicPattern(x, a, b, c, d, flags, errorPercent) Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, b, c, flags, errorPercent) Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
get_prz_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj) Provides PRZ range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
Returns: Start and end of consolidated PRZ range
get_prz_range_xad(x, a, b, c, patternArray, errorPercent, start_adj, end_adj) Provides PRZ range based on XAD range only
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
Returns: Start and end of consolidated PRZ range
MathProbabilityDistributionLibrary "MathProbabilityDistribution"
Probability Distribution Functions.
name(idx) Indexed names helper function.
Parameters:
idx : int, position in the range (0, 6).
Returns: string, distribution name.
usage:
.name(1)
Notes:
(0) => 'StdNormal'
(1) => 'Normal'
(2) => 'Skew Normal'
(3) => 'Student T'
(4) => 'Skew Student T'
(5) => 'GED'
(6) => 'Skew GED'
zscore(position, mean, deviation) Z-score helper function for x calculation.
Parameters:
position : float, position.
mean : float, mean.
deviation : float, standard deviation.
Returns: float, z-score.
usage:
.zscore(1.5, 2.0, 1.0)
std_normal(position) Standard Normal Distribution.
Parameters:
position : float, position.
Returns: float, probability density.
usage:
.std_normal(0.6)
normal(position, mean, scale) Normal Distribution.
Parameters:
position : float, position in the distribution.
mean : float, mean of the distribution, default=0.0 for standard distribution.
scale : float, scale of the distribution, default=1.0 for standard distribution.
Returns: float, probability density.
usage:
.normal(0.6)
skew_normal(position, skew, mean, scale) Skew Normal Distribution.
Parameters:
position : float, position in the distribution.
skew : float, skewness of the distribution.
mean : float, mean of the distribution, default=0.0 for standard distribution.
scale : float, scale of the distribution, default=1.0 for standard distribution.
Returns: float, probability density.
usage:
.skew_normal(0.8, -2.0)
ged(position, shape, mean, scale) Generalized Error Distribution.
Parameters:
position : float, position.
shape : float, shape.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.ged(0.8, -2.0)
skew_ged(position, shape, skew, mean, scale) Skew Generalized Error Distribution.
Parameters:
position : float, position.
shape : float, shape.
skew : float, skew.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.skew_ged(0.8, 2.0, 1.0)
student_t(position, shape, mean, scale) Student-T Distribution.
Parameters:
position : float, position.
shape : float, shape.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.student_t(0.8, 2.0, 1.0)
skew_student_t(position, shape, skew, mean, scale) Skew Student-T Distribution.
Parameters:
position : float, position.
shape : float, shape.
skew : float, skew.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.skew_student_t(0.8, 2.0, 1.0)
select(distribution, position, mean, scale, shape, skew, log) Conditional Distribution.
Parameters:
distribution : string, distribution name.
position : float, position.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
shape : float, shape.
skew : float, skew.
log : bool, if true apply log() to the result.
Returns: float, probability.
usage:
.select('StdNormal', __CYCLE4F__, log=true)
Adaptive_LengthLibrary "Adaptive_Length"
This library contains functions to calculate Adaptive dynamic length which can be used in Moving Averages and other indicators.
Two Exponential Moving Averages (EMA) are plotted. Coloring in plot is derived from Chikou filter and Dynamic length of MA1 is adapted using Signal output from Chikou library.
dynamic(para, adapt_Pct, minLength, maxLength) Adaptive dynamic length based on boolean parameter
Parameters:
para : Boolean parameter; if true then length would decrease and would increase if its false
adapt_Pct : Percentage adaption based on parameter
minLength : Minimum allowable length
maxLength : Maximum allowable length
Returns: Adaptive Dynamic Length based on Boolean Parameter
auto_alpha(src, a) Adaptive length based on automatic alpha calculations from source input
Parameters:
src : Price source for alpha calculations
a : Input Alpha value
Returns: Adaptive Length calculated from input price Source and Alpha
MovingAveragesLibrary "MovingAverages"
Contains utilities for generating moving average values including getting a moving average by name and a function for generating a Volume-Adjusted WMA.
sma(_D, _len) Simple Moving Avereage
Parameters:
_D : The series to measure from.
_len : The number of bars to measure with.
ema(_D, _len) Exponential Moving Avereage
Parameters:
_D : The series to measure from.
_len : The number of bars to measure with.
rma(_D, _len) RSI Moving Avereage
Parameters:
_D : The series to measure from.
_len : The number of bars to measure with.
wma(_D, _len) Weighted Moving Avereage
Parameters:
_D : The series to measure from.
_len : The number of bars to measure with.
vwma(_D, _len) volume-weighted Moving Avereage
Parameters:
_D : The series to measure from. Default is 'close'.
_len : The number of bars to measure with.
alma(_D, _len) Arnaud Legoux Moving Avereage
Parameters:
_D : The series to measure from. Default is 'close'.
_len : The number of bars to measure with.
cma(_D, _len, C, compound) Coefficient Moving Avereage (CMA) is a variation of a moving average that can simulate SMA or WMA with the advantage of previous data.
Parameters:
_D : The series to measure from. Default is 'close'.
_len : The number of bars to measure with.
C : The coefficient to use when averaging. 0 behaves like SMA, 1 behaves like WMA.
compound : When true (default is false) will use a compounding method for weighting the average.
dema(_D, _len) Double Exponential Moving Avereage
Parameters:
_D : The series to measure from. Default is 'close'.
_len : The number of bars to measure with.
zlsma(_D, _len) Arnaud Legoux Moving Avereage
Parameters:
_D : The series to measure from. Default is 'close'.
_len : The number of bars to measure with.
zlema(_D, _len) Arnaud Legoux Moving Avereage
Parameters:
_D : The series to measure from. Default is 'close'.
_len : The number of bars to measure with.
get(type, len, src) Generates a moving average based upon a 'type'.
Parameters:
type : The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
len : The number of bars to measure with.
src : The series to measure from. Default is 'close'.
Returns: The moving average series requested.
ChikouLibrary "Chikou"
This library contains Chikou Filter function to enhances functionality of Chikou-Span from Ichimoku Cloud using a simple trend filter.
Chikou is basically close value of ticker offset to close and it is a good for indicating if close value has crossed potential Support/Resistance zone from past. Chikou is usually used with 26 period.
Chikou filter uses a lookback length calculated from provided lookback percentage and checks if trend was bullish or bearish within that lookback period.
Bullish : Trend is bullish if Chikou span is above high values of all candles within defined lookback period. Bull color shows bullish trend .
Bearish : Trend is bearish if Chikou span is below low values of all candles within defined lookback period. This is indicated by Bearish color.
Reversal / Choppiness : Reversal color indicates that Chikou are swinging around candles within defined lookback period which is an indication of consolidation or trend reversal.
chikou(src, len, perc, _high, _low, bull_col, bear_col, r_col) Chikou Filter for Ichimoku Cloud with Color and Signal Output
Parameters:
src : Price Source (better to use (OHLC4+high+low/3 instead of default close value)
len : Chikou Legth (displaced source value)
perc : Percentage lookback period for Chikou Filter with defined how much candels of total length should be considered for backward filteration
_high : Ticker High Value
_low : Ticker Low Value
bull_col : Color to be returned if source value is greater than all candels within provided lookback percentage.
bear_col : Color to be returned if source value is lower than all candels within provided lookback percentage.
r_col : Color to be returned if source value is swinging around candles within defined lookback period which is an indication of consolidation or trend reversal.
Returns: Color based on trend. 'bull_col' if trend is bullish, 'bear_col' if trend is bearish. 'r_col' if no prominent trend. Integer Signal is also returned as 1 for Bullish, -1 for Bearish and 0 for no prominent trend.