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.
Göstergeler ve stratejiler
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.
HA_CandlesLibrary "HA_Candles"
Heikin Ashi Candles
HA_Close() Heikin Ashi Modified Close
Returns: Heikin Ashi Modified Close
HA_Open() Heikin Ashi Modified Open
Returns: Heikin Ashi Modified Open
HA_High() Heikin Ashi Modified High
Returns: Heikin Ashi Modified High
HA_Low() Heikin Ashi Modified Low
Returns: Heikin Ashi Modified Low
HA_Delta(Heikin) Heikin Ashi Delta
Parameters:
Heikin : Ashi Close, Heikin Ashi Open
Returns: Heikin Ashi Delta
easytableLibrary "easytable"
Create tables easily, with minimal code
▦ FEATURES ▦
█ Create tables █ JSON To Table █ Change Colors █ Array to Rows/Columns █ Pre-Styles █ Change Text Size █ Delete Rows/Columns █ Blink Cells
indentify_table_id() Identifies all tables ID number in each cell(0,0).
get_table_by_id(id_number) Get table object by ID number.
Parameters:
id_number : (int) ID number of the table to fetch.
Returns: table.
change_cells_color(table_object, cells_color, start_column, end_column, start_row, end_row) Change cells background colors.
Parameters:
table_object : (table) table object to be changed.
cells_color : (color) Cells color.
start_column : (int) Start column.
end_column : (int) End column.
start_row : (int) Start Row.
end_row : (int) End Row to change.
Returns: Void.
change_cells_text_color(table_object, text_color, start_column, end_column, start_row, end_row) Change cells text colors.
Parameters:
table_object : (table) table object to be changed.
text_color : (color) Text color.
start_column : (int) Start column.
end_column : (int) End column.
start_row : (int) Start Row.
end_row : (int) End Row.
Returns: Void.
change_all_table_text_color(table_object, text_color, table_column_size, table_row_size) Change All table text color.
Parameters:
table_object : (table) table object to be changed.
text_color : (color) Text color.
table_column_size : (int) Size of the table columns.
table_row_size : (int) Size of the table rows.
Returns: Void.
change_table_size(table_object, n_of_columns, n_of_rows, tbl_size) Change table size.
Parameters:
table_object : (table) table object to be changed.
n_of_columns : (int) Size of the table columns.
n_of_rows : (int) Size of the table rows.
tbl_size : (string) size of the table.
Returns: Void.
change_cells_text_size(text_size, start_column, end_column, start_row, end_row, table_id) Change table cells text size .
Parameters:
text_size : (string) Text size.
start_column : (int) Start column.
end_column : (int)(optional) End column.
start_row : (int)(optional) Start Row.
end_row : (int)(optional) End Row.
table_id : (int)(optional) Number of the ID of the table.
Returns: Void.
table_delete_row(table_object, table_column_size, start_row, end_row) Delete specified rows from table.
Parameters:
table_object : (table) table object to be changed.
table_column_size : (int) Table columns max size.
start_row : (int) Start row to delete.
end_row : (int)(optional) End row to delete (optional — Assumes start_row value).
Returns: Void.
table_delete_column(table_object, table_row_size, start_column, end_column) Delete specified columns from table.
Parameters:
table_object : (table) table object to be changed.
table_row_size : (int) Table rows max size.
start_column : (int) Start column to delete.
end_column : (int)(optional) End column to delete (optional — Assumes start_column value).
Returns: Void.
array_to_table_column_auto(column_to_insert, array_to_insert, table_id) Insert string array to table column without passing table object.
Parameters:
column_to_insert : (int) Column to be inserted.
array_to_insert : (string array) Start column to delete.
table_id : (int)(optional) Number of the ID of the table.
Returns: Void.
array_to_table_row_auto(row_to_insert, array_to_insert, table_id) Insert string array to table row without passing table object.
Parameters:
row_to_insert : (int) Column to be inserted.
array_to_insert : (string array) Start column to delete.
table_id : (int)(optional) Number of the ID of the table.
Returns: Void.
array_to_table_row(table_object, row_to_insert, array_to_insert) Insert string array to table row by passing table object.
Parameters:
table_object : (table) table object to be changed.
row_to_insert : (int) Row to be inserted.
array_to_insert : (string array) Start column to delete.
Returns: Void.
array_to_table_column(table_object, column_to_insert, array_to_insert) Insert string array to table column by passing table object.
Parameters:
table_object : (table) table object to be changed.
column_to_insert : (int) Column to be inserted.
array_to_insert : (string array) Start column to delete.
Returns: Void.
blink_cell(cell_column, cell_row, c_color, blink_interval_ms, table_id) Changes cell color at set intervals (blink).
Parameters:
cell_column : (int) Cell column position.
cell_row : (int) Cell row position.
c_color : (color) Color to blink.
blink_interval_ms : (int)(opt) Interval in milliseconds.
table_id : (int)(opt) Table ID number.
change_table_style(table_object, number_of_columns, number_of_rows, color) Changes table pre-style by selecting a pre-style number.
Parameters:
table_object : (table) table object to be changed.
number_of_columns : (int) Table column size.
number_of_rows : (int) Table row size.
color : 1 (color) Color of .
Returns: Void.
create_table_clean(n_of_columns, n_of_rows, position) Create a simple(blank) table without any styling.
Parameters:
n_of_columns : (int) Numbers of columns in the table.
n_of_rows : (int) Number of rows in the table.
position : (string) table position.
Returns: table object.
create_table_with_style(n_of_columns, n_of_rows, style_number, position) Create table with a pre-set style.
Parameters:
n_of_columns : (int) Numbers of columns in the table.
n_of_rows : (int) Number of rows in the table.
style_number : (int) Style number.
position : (string) table position.
Returns: table object.
json_to_table(raw_json) Create table based on input raw json string.
Parameters:
raw_json : (int) Raw json string.
Returns: table object.
json_example() Example function that display a table based on a json
example_create_table()
jsonLibrary "json"
Convert JSON strings to tradingview
▦ FEATURES ▦
█ Json to array █ Get json key names █ Get json key values █ Size of json
get_json_keys_names(raw_json) Returns string array with all key names
Parameters:
raw_json : (string) Raw JSON string
Returns: (string array) Array with all key names
get_values_by_id_name(raw_json, key_name) Returns string array with values of the input key name
Parameters:
raw_json : (string) Raw JSON string
key_name : (string) Name of the key to be fetched
Returns: (string array) Array with values of the input key name
size_of_json_string(raw_json) Returns size of raw JSON string
Parameters:
raw_json : (string) Raw JSON string
Returns: Size of n_of_values, size of n_of_keys_names
timeUtilsLibrary "timeUtils"
Utils for time series
tradingDaysTillEndOfMonth() Calculates how many full trading days left until the end of the current month. (It doesn't take into account market holidays)
Returns: int series of the remaining trading days until the end of the month.
insideRange()
utilsLibrary "utils"
ma_smooth(alg, src, len) Calculates various moving averages
Parameters:
alg : Smoothing algorithm to use
src : Source data
len : Length of moving average
RVSILibrary "RVSI"
This Library contains functions that calculate all types of " Relative Volume Strength Index (MZ RVSI ) " depending upon unique volume oscillator. Achieved RVSI value can be used for divergence detection in volume or to adapt dynamic length in Moving Averages or other functions.
rvsi_tfs(vol_src, vol_Len, rvsiLen, _open, _close) Relative Volume Strength Index based on TFS Volume Oscillator
Parameters:
vol_src : Volume Source
vol_Len : Volume Legth for TFS Volume Oscillato
rvsiLen : Period of Relative Volume Strength Index
_open : Ticker Open Value
_close : Ticker Close Value
Returns: Relative Volume Strength Index value based on TFS Volume Oscillator
rvsi_obv(vol_src, rvsiLen, _close) Relative Volume Strength Index based on On Balance Volume
Parameters:
vol_src : Volume Source to Calculate On Balance Volume
rvsiLen : Period of Relative Volume Strength Index
_close : Ticker Close Value
Returns: Relative Volume Strength Index value based on On Balance Volume
rvsi_kvo(vol_src, FastX, SlowX, rvsiLen, _close) Relative Volume Strength Index based on Klinger Volume Oscillator
Parameters:
vol_src : Volume Source
FastX : Volume Fast Length
SlowX : Volume Slow Length
rvsiLen : Period of Relative Volume Strength Index
_close : Ticker Close Value
Returns: Relative Volume Strength Index value based on Klinger Volume Oscillator
rvsi_vzo(vol_src, zLen, rvsiLen, _close) Relative Volume Strength Index based on Volume Zone Oscillator
Parameters:
vol_src : Volume Source
zLen : Volume Legth for Volume Zone Oscillator
rvsiLen : Period of Relative Volume Strength Index
_close : Ticker Close Value
Returns: Relative Volume Strength Index value based on Volume Zone Oscillator
rvsi_cvo_obv(vol_src, ema1len, ema2len, rvsiLen) Relative Volume Strength Index based on Cumulative Volume Oscillator with On Balance Volume as Calculations Source
Parameters:
vol_src : Volume Source
ema1len : EMA Fast Length
ema2len : EMA Slow Length
rvsiLen : Period of Relative Volume Strength Index
Returns: Relative Volume Strength Index value based on Cumulative Volume Oscillator with On Balance Volume as Calculations Source
rvsi_cvo_pvt(vol_src, FastX, SlowX, rvsiLen) Relative Volume Strength Index based on Cumulative Volume Oscillator with Price Volume Trend as Calculations Source
Parameters:
vol_src : Volume Source
FastX : EMA Fast Length
SlowX : EMA Slow Length
rvsiLen : Period of Relative Volume Strength Index
Returns: Relative Volume Strength Index value based on Cumulative Volume Oscillator with Price Volume Trend as Calculations Source
rvsi_cvo_cvd(vol_src, FastX, SlowX, rvsiLen, _open, _close, _high, _low) Relative Volume Strength Index based on Cumulative Volume Oscillator with Cumulative Volume Delta as Calculations Source
Parameters:
vol_src : Volume Source
FastX : EMA Fast Length
SlowX : EMA Slow Length
rvsiLen : Period of Relative Volume Strength Index
_open : Ticker Open Value
_close : Ticker Close Value
_high : Ticker High Value
_low : Ticker Low Value
Returns: Relative Volume Strength Index value based on Cumulative Volume Oscillator with Cumulative Volume Delta as Calculations Source
eStrategyLibrary "eStrategy"
Library contains methods which can help build custom strategy for continuous investment plans and also compare it with systematic buy and hold.
sip(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice) Depicts systematic buy and hold over period of time
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalEquity - Present equity
customStrategy(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice, sellPrice, initialInvestmentPercent, recurringInvestmentPercent, signal, tradePercent) Allows users to define custom strategy and enhance systematic buy and hold by adding take profit and reloads
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
sellPrice : Indicatinve sell price. Use low to be conservative. high, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
initialInvestmentPercent : percent of amount to invest from the initial depost. Keep rest of them as cash
recurringInvestmentPercent : percent of amount to invest from recurring deposit. Keep rest of them as cash
signal : can be 1, -1 or 0. 1 means buy/reload. -1 means take profit and 0 means neither.
tradePercent : percent of amount to trade when signal is not 0. If taking profit, it will sell the percent from existing position. If reloading, it will buy with percent from cash reserve
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalCash = Amount of cash held
totalEquity - Overall equity = totalQty*close + totalCash