TableBuilderLibrary "TableBuilder"
A helper library to make it simpler to create tables in pinescript
This is a simple table building library that I created because I personally feel that the built-in table building method is too verbose. It features chaining methods and variable arguments.
There are many features that are lacking because the implementation is early, and there may be antipatterns because I am not familiar with the runtime behavior like pinescript. If you have any comments on code improvements or features you want, please comment :D
Statistics
SILLibrary "SIL"
mean_src(x, y)
calculates moving average : x is the source of price (OHLC) & y = the lookback period
Parameters:
x
y
stan_dev(x, y, z)
calculates standard deviation, x = source of price (OHLC), y = the average lookback, z = average given prior two float and intger inputs, call the f_avg_src() function in f_stan_dev()
Parameters:
x
y
z
vawma(x, y)
calculates volume weighted moving average, x = source of price (OHLC), y = loookback period
Parameters:
x
y
gethurst(x, y, z)
calculates the Hurst Exponent and Hurst Exponent average, x = source of price (OHLC), y = lookback period for Hurst Exponent Calculation, z = lookback period for average Hurst Exponent
Parameters:
x
y
z
libKageMiscLibrary "libKageMisc"
Kage's Miscelaneous library
print(_value)
Print a numerical value in a label at last historical bar.
Parameters:
_value : (float) The value to be printed.
Returns: Nothing.
barsBackToDate(_year, _month, _day)
Get the number of bars we have to go back to get data from a specific date.
Parameters:
_year : (int) Year of the specific date.
_month : (int) Month of the specific date. Optional. Default = 1.
_day : (int) Day of the specific date. Optional. Default = 1.
Returns: (int) Number of bars to go back until reach the specific date.
bodySize(_index)
Calculates the size of the bar's body.
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.
Returns: (float) The size of the bar's body in price units.
shadowSize(_direction)
Size of the current bar shadow. Either "top" or "bottom".
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) The size of the chosen bar's shadow in price units.
shadowBodyRatio(_direction)
Proportion of current bar shadow to the bar size
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) Ratio of the shadow size per body size.
bodyCloseRatio(_index)
Proportion of chosen bar body size to the close price
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.()
Returns: (float) Ratio of the body size per close price.
lastDayOfMonth(_month)
Returns the last day of a month.
Parameters:
_month : (int) Month number.
Returns: (int) The number (28, 30 or 31) of the last day of a given month.
nameOfMonth(_month)
Return the short name of a month.
Parameters:
_month : (int) Month number.
Returns: (string) The short name ("Jan", "Feb"...) of a given month.
pl(_initialValue, _finalValue)
Calculate Profit/Loss between two values.
Parameters:
_initialValue : (float) Initial value.
_finalValue : (float) Final value = Initial value + delta.
Returns: (float) Profit/Loss as a percentual change.
gma(_Type, _Source, _Length)
Generalist Moving Average (GMA).
Parameters:
_Type : (string) Type of average to be used. Either "EMA", "HMA", "RMA", "SMA", "SWMA", "WMA" or "VWMA".
_Source : (series float) Series of values to process.
_Length : (simple int) Number of bars (length).
Returns: (float) The value of the chosen moving average.
xFormat(_percentValue, _minXFactor)
Transform a percentual value in a X Factor value.
Parameters:
_percentValue : (float) Percentual value to be transformed.
_minXFactor : (float) Minimum X Factor to that the conversion occurs. Optional. Default = 10.
Returns: (string) A formated string.
isLong()
Check if the open trade direction is long.
Returns: (bool) True if the open position is long.
isShort()
Check if the open trade direction is short.
Returns: (bool) True if the open position is short.
lastPrice()
Returns the entry price of the last openned trade.
Returns: (float) The last entry price.
barsSinceLastEntry()
Returns the number of bars since last trade was oppened.
Returns: (series int)
getBotNameFrosty()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getBotNameZig()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getTicksValue(_currencyValue)
Converts currency value to ticks
Parameters:
_currencyValue : (float) Value to be converted.
Returns: (float) Value converted to minticks.
getSymbol(_botName, _botCustomSymbol)
Formats the symbol string to be used with a bot
Parameters:
_botName : (string) Bot name constant. Either BOT_NAME_FROSTY or BOT_NAME_ZIG. Optional. Default is empty string.
_botCustomSymbol : (string) Custom string. Optional. Default is empy string.
Returns: (string) A string containing the symbol for the bot. If all arguments are empty, the current symbol is returned in Binance format.
showProfitLossBoard()
Calculates and shows a board of Profit/Loss through the years.
Returns: Nothing.
Liquidation_linesLibrary "Liquidationline"
f_calculateLeverage(_leverage, _maintainance, _value, _direction)
Parameters:
_leverage
_maintainance
_value
_direction
f_liqline_update(_Liqui_Line, _killonlowhigh)
Parameters:
_Liqui_Line
_killonlowhigh
f_liqline_draw(_Liqui_Line, _priceorliq)
Parameters:
_Liqui_Line
_priceorliq
f_liqline_add(_Liqui_Line, linetoadd, _limit)
Parameters:
_Liqui_Line
linetoadd
_limit
Liquidationline
Fields:
creationtime
stoptime
price
leverage
maintainance
line_active
line_color
line_thickness
line_style
line_direction
line_finished
text_active
text_size
text_color
this library can draw typical liquidation lines, which can be called e.g. by indicator signals
You can see the default implementation in the lower part of the code, starting with RUNTIME
Don't forget to increase max lines to 500 in your script.
It can look like this screenshot here, with only minor changes to your executing script.
The base is the same
DistributionsLibrary "Distributions"
Library with price distribution zones calculation helpers.
Based on research from "Trading Systems and Methods, 5th Edition" by Perry J. Kaufman
getZones(h, l, c, window)
Returns price distribution zones based on HLC and for some period
Parameters:
h : high price
l : low price
c : close price
window : period to calculate distributions
Returns: tuple of 5 price zones in descent order, from highest to lowest
PerformanceTableLibrary "PerformanceTable"
TODO: add library description here
This library was created as a library because adding a performance table to an existing strategy script made the strategy script lengthy and inconvenient to manage.
The monthly table script referenced @QuantNomad's code.
The performance table script referenced @myncrypto's code.
To use, copy and paste the code below at the bottom of the strategy script you are using, and the table for strategy performance will be displayed on a chart.
//------------Copy & Paste --------------------------------------//
import Cube_Lee/PerformanceTable/1 as PT
PT = input.bool(true, "Show Performance Table", tooltip = "전략의 성과를 우측상단에 테이블로 표시합니다.", group = "Performance Table")
MT = input.bool(true, "Show Monthly Table", tooltip = "전략의 월별 수익률을 우측하단에 테이블로 표시합니다.", group = "Performance Table")
if PT
PT.PerformanceTable()
if MT
PT.MonthlyTable()
//------------Copy & Paste---------------------------------------//
PerformanceTable()
MonthlyTable()
MLExtensionsLibrary "MLExtensions"
normalizeDeriv(src, quadraticMeanLength)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the first-order derivative for price).
quadraticMeanLength : The length of the quadratic mean (RMS).
Returns: nDeriv The normalized derivative of the input series.
normalize(src, min, max)
Rescales a source value with an unbounded range to a target range.
Parameters:
src : The input series
min : The minimum value of the unbounded range
max : The maximum value of the unbounded range
Returns: The normalized series
rescale(src, oldMin, oldMax, newMin, newMax)
Rescales a source value with a bounded range to anther bounded range
Parameters:
src : The input series
oldMin : The minimum value of the range to rescale from
oldMax : The maximum value of the range to rescale from
newMin : The minimum value of the range to rescale to
newMax : The maximum value of the range to rescale to
Returns: The rescaled series
color_green(prediction)
Assigns varying shades of the color green based on the KNN classification
Parameters:
prediction : Value (int|float) of the prediction
Returns: color
color_red(prediction)
Assigns varying shades of the color red based on the KNN classification
Parameters:
prediction : Value of the prediction
Returns: color
tanh(src)
Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
Parameters:
src : The input series (i.e., the normalized derivative).
Returns: tanh The hyperbolic tangent of the input series.
dualPoleFilter(src, lookback)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the hyperbolic tangent).
lookback : The lookback window for the smoothing.
Returns: filter The smoothed hyperbolic tangent of the input series.
tanhTransform(src, smoothingFrequency, quadraticMeanLength)
Returns the tanh transform of the input series.
Parameters:
src : The input series (i.e., the result of the tanh calculation).
smoothingFrequency
quadraticMeanLength
Returns: signal The smoothed hyperbolic tangent transform of the input series.
n_rsi(src, n1, n2)
Returns the normalized RSI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the RSI calculation).
n1 : The length of the RSI.
n2 : The smoothing length of the RSI.
Returns: signal The normalized RSI.
n_cci(src, n1, n2)
Returns the normalized CCI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the CCI calculation).
n1 : The length of the CCI.
n2 : The smoothing length of the CCI.
Returns: signal The normalized CCI.
n_wt(src, n1, n2)
Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the WaveTrend Classic calculation).
n1
n2
Returns: signal The normalized WaveTrend Classic series.
n_adx(highSrc, lowSrc, closeSrc, n1)
Returns the normalized ADX ideal for use in ML algorithms.
Parameters:
highSrc : The input series for the high price.
lowSrc : The input series for the low price.
closeSrc : The input series for the close price.
n1 : The length of the ADX.
regime_filter(src, threshold, useRegimeFilter)
Parameters:
src
threshold
useRegimeFilter
filter_adx(src, length, adxThreshold, useAdxFilter)
filter_adx
Parameters:
src : The source series.
length : The length of the ADX.
adxThreshold : The ADX threshold.
useAdxFilter : Whether to use the ADX filter.
Returns: The ADX.
filter_volatility(minLength, maxLength, useVolatilityFilter)
filter_volatility
Parameters:
minLength : The minimum length of the ATR.
maxLength : The maximum length of the ATR.
useVolatilityFilter : Whether to use the volatility filter.
Returns: Boolean indicating whether or not to let the signal pass through the filter.
backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isStopLossHit, maxBarsBackIndex, thisBarIndex)
Performs a basic backtest using the specified parameters and conditions.
Parameters:
high : The input series for the high price.
low : The input series for the low price.
open : The input series for the open price.
startLongTrade : The series of conditions that indicate the start of a long trade.`
endLongTrade : The series of conditions that indicate the end of a long trade.
startShortTrade : The series of conditions that indicate the start of a short trade.
endShortTrade : The series of conditions that indicate the end of a short trade.
isStopLossHit : The stop loss hit indicator.
maxBarsBackIndex : The maximum number of bars to go back in the backtest.
thisBarIndex : The current bar index.
Returns: A tuple containing backtest values
init_table()
init_table()
Returns: tbl The backtest results.
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winrate, stopLosses)
update_table(tbl, tradeStats)
Parameters:
tbl : The backtest results table.
tradeStatsHeader : The trade stats header.
totalTrades : The total number of trades.
totalWins : The total number of wins.
totalLosses : The total number of losses.
winLossRatio : The win loss ratio.
winrate : The winrate.
stopLosses : The total number of stop losses.
Returns: Updated backtest results table.
DataCorrelationLibrary "DataCorrelation"
Implementation of functions related to data correlation calculations. Formulas have been transformed in such a way that we avoid running loops and instead make use of time series to gradually build the data we need to perform calculation. This allows the calculations to run on unbound series, and/or higher number of samples
🎲 Simplifying Covariance
Original Formula
//For Sample
Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / (n-1)
//For Population
Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / n
Now, if we look at numerator, this can be simplified as follows
∑ ((xᵢ-x̄)(yᵢ-ȳ))
=> (x₁-x̄)(y₁-ȳ) + (x₂-x̄)(y₂-ȳ) + (x₃-x̄)(y₃-ȳ) ... + (xₙ-x̄)(yₙ-ȳ)
=> (x₁y₁ + x̄ȳ - x₁ȳ - y₁x̄) + (x₂y₂ + x̄ȳ - x₂ȳ - y₂x̄) + (x₃y₃ + x̄ȳ - x₃ȳ - y₃x̄) ... + (xₙyₙ + x̄ȳ - xₙȳ - yₙx̄)
=> (x₁y₁ + x₂y₂ + x₃y₃ ... + xₙyₙ) + (x̄ȳ + x̄ȳ + x̄ȳ ... + x̄ȳ) - (x₁ȳ + x₂ȳ + x₃ȳ ... xₙȳ) - (y₁x̄ + y₂x̄ + y₃x̄ + yₙx̄)
=> ∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ
So, overall formula can be simplified to be used in pine as
//For Sample
Covₓᵧ = (∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ) / (n-1)
//For Population
Covₓᵧ = (∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ) / n
🎲 Simplifying Standard Deviation
Original Formula
//For Sample
σ = √(∑(xᵢ-x̄)² / (n-1))
//For Population
σ = √(∑(xᵢ-x̄)² / n)
Now, if we look at numerator within square root
∑(xᵢ-x̄)²
=> (x₁² + x̄² - 2x₁x̄) + (x₂² + x̄² - 2x₂x̄) + (x₃² + x̄² - 2x₃x̄) ... + (xₙ² + x̄² - 2xₙx̄)
=> (x₁² + x₂² + x₃² ... + xₙ²) + (x̄² + x̄² + x̄² ... + x̄²) - (2x₁x̄ + 2x₂x̄ + 2x₃x̄ ... + 2xₙx̄)
=> ∑xᵢ² + nx̄² - 2x̄∑xᵢ
=> ∑xᵢ² + x̄(nx̄ - 2∑xᵢ)
So, overall formula can be simplified to be used in pine as
//For Sample
σ = √(∑xᵢ² + x̄(nx̄ - 2∑xᵢ) / (n-1))
//For Population
σ = √(∑xᵢ² + x̄(nx̄ - 2∑xᵢ) / n)
🎲 Using BinaryInsertionSort library
Chatterjee Correlation and Spearman Correlation functions make use of BinaryInsertionSort library to speed up sorting. The library in turn implements mechanism to insert values into sorted order so that load on sorting is reduced by higher extent allowing the functions to work on higher sample size.
🎲 Function Documentation
chatterjeeCorrelation(x, y, sampleSize, plotSize)
Calculates chatterjee correlation between two series. Formula is - ξnₓᵧ = 1 - (3 * ∑ |rᵢ₊₁ - rᵢ|)/ (n²-1)
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
sampleSize : number of samples to be considered for calculattion of correlation. Default is 20000
plotSize : How many historical values need to be plotted on chart.
Returns: float correlation - Chatterjee correlation value if falls within plotSize, else returns na
spearmanCorrelation(x, y, sampleSize, plotSize)
Calculates spearman correlation between two series. Formula is - ρ = 1 - (6∑dᵢ²/n(n²-1))
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
sampleSize : number of samples to be considered for calculattion of correlation. Default is 20000
plotSize : How many historical values need to be plotted on chart.
Returns: float correlation - Spearman correlation value if falls within plotSize, else returns na
covariance(x, y, include, biased)
Calculates covariance between two series of unbound length. Formula is Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / (n-1) for sample and Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / n for population
Parameters:
x : First series for which covariance need to be calculated
y : Second series for which covariance need to be calculated
include : boolean flag used for selectively including sample
biased : boolean flag representing population covariance instead of sample covariance
Returns: float covariance - covariance of selective samples of two series x, y
stddev(x, include, biased)
Calculates Standard Deviation of a series. Formula is σ = √( ∑(xᵢ-x̄)² / n ) for sample and σ = √( ∑(xᵢ-x̄)² / (n-1) ) for population
Parameters:
x : Series for which Standard Deviation need to be calculated
include : boolean flag used for selectively including sample
biased : boolean flag representing population covariance instead of sample covariance
Returns: float stddev - standard deviation of selective samples of series x
correlation(x, y, include)
Calculates pearson correlation between two series of unbound length. Formula is r = Covₓᵧ / σₓσᵧ
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
include : boolean flag used for selectively including sample
Returns: float correlation - correlation between selective samples of two series x, y
JeeSauceScriptsLibrary "JeeSauceScripts"
getupdnvol()
GetTotalUpVolume(upvolume)
Parameters:
upvolume
GetTotalDnVolume(downvolume)
Parameters:
downvolume
GetDelta(totalupvolume, totaldownvolume)
Parameters:
totalupvolume
totaldownvolume
GetMaxUpVolume(upvolume)
Parameters:
upvolume
GetMaxDnVolume(downvolume)
Parameters:
downvolume
Getcvd()
Getcvdopen(cvd)
Parameters:
cvd
Getcvdhigh(cvd, maxvolumeup)
Parameters:
cvd
maxvolumeup
Getcvdlow(cvd, maxvolumedown)
Parameters:
cvd
maxvolumedown
Getcvdclose(cvd, delta)
Parameters:
cvd
delta
CombineData(data1, data2, data3, data4, data5, data6)
Parameters:
data1
data2
data3
data4
data5
data6
FindData(data, find)
Parameters:
data
find
Replica of TradingView's Backtesting Engine with ArraysHello everyone,
Here is a perfectly replicated TradingView backtesting engine condensed into a single library function calculated with arrays. It includes TradingView's calculations for Net profit, Total Trades, Percent of Trades Profitable, Profit Factor, Max Drawdown (absolute and percent), and Average Trade (absolute and percent). Here's how TradingView defines each aspect of its backtesting system:
Net Profit: The overall profit or loss achieved.
Total Trades: The total number of closed trades, winning and losing.
Percent Profitable: The percentage of winning trades, the number of winning trades divided by the total number of closed trades.
Profit Factor: The amount of money the strategy made for every unit of money it lost, gross profits divided by gross losses.
Max Drawdown: The greatest loss drawdown, i.e., the greatest possible loss the strategy had compared to its highest profits.
Average Trade: The sum of money gained or lost by the average trade, Net Profit divided by the overall number of closed trades.
Here's how each variable is defined in the library function:
_backtest(bool _enter, bool _exit, float _startQty, float _tradeQty)
bool _enter: When the strategy should enter a trade (entry condition)
bool _exit: When the strategy should exit a trade (exit condition)
float _startQty: The starting capital in the account (for BTCUSD, it is the amount of USD the account starts with)
float _tradeQty: The amount of capital traded (if set to 1000 on BTCUSD, it will trade 1000 USD on each trade)
Currently, this library only works with long strategies, and I've included a commented out section under DEMO STRATEGY where you can replicate my results with TradingView's backtesting engine. There's tons I could do with this beyond what is shown, but this was a project I worked on back in June of 2022 before getting burned out. Feel free to comment with any suggestions or bugs, and I'll try to add or fix them all soon. Here's my list of thing to add to the library currently (may not all be added):
Add commission calculations.
Add support for shorting
Add a graph that resembles TradingView's overview graph.
Clean and optimize code.
Clean up in a way that makes it easy to add other TradingView calculations (such as Sharpe and Sortino ratio).
Separate all variables, so they become accessible outside of calculations (such as gross profit, gross loss, number of winning trades, number of losing trades, etc.).
Thanks for reading,
OztheWoz
TechnicalRating█ OVERVIEW
This library is a Pine Script™ programmer’s tool for incorporating TradingView's well-known technical ratings within their scripts. The ratings produced by this library are the same as those from the speedometers in the technical analysis summary and the "Rating" indicator in the Screener , which use the aggregate biases of 26 technical indicators to calculate their results.
█ CONCEPTS
Ensemble analysis
Ensemble analysis uses multiple weaker models to produce a potentially stronger one. A common form of ensemble analysis in technical analysis is the usage of aggregate indicators together in hopes of gaining further market insight and reinforcing trading decisions.
Technical ratings
Technical ratings provide a simplified way to analyze financial markets by combining signals from an ensemble of indicators into a singular value, allowing traders to assess market sentiment more quickly and conveniently than analyzing each constituent separately. By consolidating the signals from multiple indicators into a single rating, traders can more intuitively and easily interpret the "technical health" of the market.
Calculating the rating value
Using a variety of built-in TA functions and functions from our ta library, this script calculates technical ratings for moving averages, oscillators, and their overall result within the `calcRatingAll()` function.
The function uses the script's `calcRatingMA()` function to calculate the moving average technical rating from an ensemble of 15 moving averages and filters:
• Six Simple Moving Averages and six Exponential Moving Averages with periods of 10, 20, 30, 50, 100, and 200
• A Hull Moving Average with a period of 9
• A Volume-Weighted Moving Average with a period of 20
• An Ichimoku Cloud with a conversion line length of 9, base length of 26, and leading span B length of 52
The function uses the script's `calcRating()` function to calculate the oscillator technical rating from an ensemble of 11 oscillators:
• RSI with a period of 14
• Stochastic with a %K period of 14, a smoothing period of 3, and a %D period of 3
• CCI with a period of 20
• ADX with a DI length of 14 and an ADX smoothing period of 14
• Awesome Oscillator
• Momentum with a period of 10
• MACD with fast, slow, and signal periods of 12, 26, and 9
• Stochastic RSI with an RSI period of 14, a %K period of 14, a smoothing period of 3, and a %D period of 3
• Williams %R with a period of 14
• Bull Bear Power with a period of 50
• Ultimate Oscillator with fast, middle, and slow lengths of 7, 14, and 28
Each indicator is assigned a value of +1, 0, or -1, representing a bullish, neutral, or bearish rating. The moving average rating is the mean of all ratings that use the `calcRatingMA()` function, and the oscillator rating is the mean of all ratings that use the `calcRating()` function. The overall rating is the mean of the moving average and oscillator ratings, which ranges between +1 and -1. This overall rating, along with the separate MA and oscillator ratings, can be used to gain insight into the technical strength of the market. For a more detailed breakdown of the signals and conditions used to calculate the indicators' ratings, consult our Help Center explanation.
Determining rating status
The `ratingStatus()` function produces a string representing the status of a series of ratings. The `strongBound` and `weakBound` parameters, with respective default values of 0.5 and 0.1, define the bounds for "strong" and "weak" ratings.
The rating status is determined as follows:
Rating Value Rating Status
< -strongBound Strong Sell
< -weakBound Sell
-weakBound to weakBound Neutral
> weakBound Buy
> strongBound Strong Buy
By customizing the `strongBound` and `weakBound` values, traders can tailor the `ratingStatus()` function to fit their trading style or strategy, leading to a more personalized approach to evaluating ratings.
Look first. Then leap.
█ FUNCTIONS
This library contains the following functions:
calcRatingAll()
Calculates 3 ratings (ratings total, MA ratings, indicator ratings) using the aggregate biases of 26 different technical indicators.
Returns: A 3-element tuple: ( [(float) ratingTotal, (float) ratingOther, (float) ratingMA ].
countRising(plot)
Calculates the number of times the values in the given series increase in value up to a maximum count of 5.
Parameters:
plot : (series float) The series of values to check for rising values.
Returns: (int) The number of times the values in the series increased in value.
ratingStatus(ratingValue, strongBound, weakBound)
Determines the rating status of a given series based on its values and defined bounds.
Parameters:
ratingValue : (series float) The series of values to determine the rating status for.
strongBound : (series float) The upper bound for a "strong" rating.
weakBound : (series float) The upper bound for a "weak" rating.
Returns: (string) The rating status of the given series ("Strong Buy", "Buy", "Neutral", "Sell", or "Strong Sell").
Signal AnalyzerThis library contains functions that try to analyze trading signals performance.
Like the % of average returns after a long or short signal is provided or the number of times that signal was correct, in the inmediate 2 candles after the signal.
Hurst Exponent (Dubuc's variation method)Library "Hurst"
hurst(length, samples, hi, lo)
Estimate the Hurst Exponent using Dubuc's variation method
Parameters:
length : The length of the history window to use. Large values do not cause lag.
samples : The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
hi : The high value of the series to analyze.
lo : The low value of the series to analyze.
The Hurst Exponent is a measure of fractal dimension, and in the context of time series it may be interpreted as indicating a mean-reverting market if the value is below 0.5 or a trending market if the value is above 0.5. A value of exactly 0.5 corresponds to a random walk.
There are many definitions of fractal dimension and many methods for its estimation. Approaches relying on calculation of an area, such as the Box Counting Method, are inappropriate for time series data, because the units of the x-axis (time) do match the units of the y-axis (price). Other approaches such as Detrended Fluctuation Analysis are useful for nonstationary time series but are not exactly equivalent to the Hurst Exponent.
This library implements Dubuc's variation method for estimating the Hurst Exponent. The technique is insensitive to x-axis units and is therefore useful for time series. It will give slightly different results to DFA, and the two methods should be compared to see which estimator fits your trading objectives best.
Original Paper:
Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
Review of various Hurst Exponent estimators for time-series data, including Dubuc's method:
www.intechopen.com
NetLiquidityLibraryLibrary "NetLiquidityLibrary"
The Net Liquidity Library provides daily values for net liquidity. Net liquidity is measured as Fed Balance Sheet - Treasury General Account - Reverse Repo. Time series for each individual component included too.
get_net_liquidity_for_date(t)
Function takes date in timestamp form and returns the Net Liquidity value for that date. If date is not present, 0 is returned.
Parameters:
t : The timestamp of the date you are requesting the Net Liquidity value for.
Returns: The Net Liquidity value for the specified date.
get_net_liquidity()
Gets the Net Liquidity time series from Dec. 2021 to current. Dates that are not present are represented as 0.
Returns: The Net Liquidity time series.
ReduceSecurityCallsLibrary "ReduceSecurityCalls"
This library allows you to reduce the number of request.security calls to 1 per symbol per timeframe. Script provides example how to use it with request.security and possible optimisation applied to htf data call.
This data can be used to calculate everything you need and more than that (for example you can calculate 4 emas with one function call on mat_out).
ParseSource(mat_outs, o)
Should be used inside request.security call. Optimise your calls using timeframe.change when htf data parsing! Supports up to 5 expressions (results of expressions must be float or int)
Parameters:
mat_outs : Matrix to be used as outputs, first value is newest
o : Please use parametres in the order they specified (o should be 1st, h should be 2nd etc..)
Returns: outs array, due to weird limitations do not try this :matrix_out = matrix.copy(ParseSource)
kNNLibrary "kNN"
Collection of experimental kNN functions. This is a work in progress, an improvement upon my original kNN script:
The script can be recreated with this library. Unlike the original script, that used multiple arrays, this has been reworked with the new Pine Script matrix features.
To make a kNN prediction, the following data should be supplied to the wrapper:
kNN : filter type. Right now either Binary or Percent . Binary works like in the original script: the system stores whether the price has increased (+1) or decreased (-1) since the previous knnStore event (called when either long or short condition is supplied). Percent works the same, but the values stored are the difference of prices in percents. That way larger differences in prices would give higher scores.
k : number k. This is how many nearest neighbors are to be selected (and summed up to get the result).
skew : kNN minimum difference. Normally, the prediction is done with a simple majority of the neighbor votes. If skew is given, then more than a simple majority is needed for a prediction. This also means that there are inputs for which no prediction would be given (if the majority votes are between -skew and +skew). Note that in Percent mode more profitable trades will have higher voting power.
depth : kNN matrix size limit. Originally, the whole available history of trades was used to make a prediction. This not only requires more computational power, but also neglects the fact that the market conditions are changing. This setting restricts the memory matrix to a finite number of past trades.
price : price series
long : long condition. True if the long conditions are met, but filters are not yet applied. For example, in my original script, trades are only made on crossings of fast and slow MAs. So, whenever it is possible to go long, this value is set true. False otherwise.
short : short condition. Same as long , but for short condition.
store : whether the inputs should be stored. Additional filters may be applied to prevent bad trades (for example, trend-based filters), so if you only need to consult kNN without storing the trade, this should be set to false.
feature1 : current value of feature 1. A feature in this case is some kind of data derived from the price. Different features may be used to analyse the price series. For example, oscillator values. Not all of them may be used for kNN prediction. As the current kNN implementation is 2-dimensional, only two features can be used.
feature2 : current value of feature 2.
The wrapper returns a tuple: [ longOK, shortOK ]. This is a pair of filters. When longOK is true, then kNN predicts a long trade may be taken. When shortOK is true, then kNN predicts a short trade may be taken. The kNN filters are returned whenever long or short conditions are met. The trade is supposed to happen when long or short conditions are met and when the kNN filter for the desired direction is true.
Exported functions :
knnStore(knn, p1, p2, src, maxrows)
Store the previous trade; buffer the current one until results are in. Results are binary: up/down
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
src : current price
maxrows : limit the matrix size to this number of rows (0 of no limit)
Returns: modified knn matrix
knnStorePercent(knn, p1, p2, src, maxrows)
Store the previous trade; buffer the current one until results are in. Results are in percents
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
src : current price
maxrows : limit the matrix size to this number of rows (0 of no limit)
Returns: modified knn matrix
knnGet(distance, result)
Get neighbours by getting k results with the smallest distances
Parameters:
distance : distance array
result : result array
Returns: array slice of k results
knnDistance(knn, p1, p2)
Create a distance array from the two given parameters
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
Returns: distance array
knnSum(knn, p1, p2, k)
Make a prediction, finding k nearest neighbours and summing them up
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
k : sum k nearest neighbors
Returns: sum of k nearest neighbors
doKNN(kNN, k, skew, depth, price, long, short, store, feature1, feature2)
execute kNN filter
Parameters:
kNN : filter type
k : number k
skew : kNN minimum difference
depth : kNN matrix size limit
price : series
long : long condition
short : short condition
store : store the supplied features (if false, only checks the results without storage)
feature1 : feature 1 value
feature2 : feature 2 value
Returns: filter output
LibIndicadoresUteisLibrary "LibIndicadoresUteis"
Collection of useful indicators. This collection does not do any type of plotting on the graph, as the methods implemented can and should be used to get the return of mathematical formulas, in a way that speeds up the development of new scripts. The current version contains methods for stochastic return, slow stochastic, IFR, leverage calculation for B3 futures market, leverage calculation for B3 stock market, bollinger bands and the range of change.
estocastico(PeriodoEstocastico)
Returns the value of stochastic
Parameters:
PeriodoEstocastico : Period for calculation basis
Returns: Float with the stochastic value of the period
estocasticoLento(PeriodoEstocastico, PeriodoMedia)
Returns the value of slow stochastic
Parameters:
PeriodoEstocastico : Stochastic period for calculation basis
PeriodoMedia : Average period for calculation basis
Returns: Float with the value of the slow stochastic of the period
ifrInvenenado(PeriodoIFR, OrigemIFR)
Returns the value of the RSI/IFR Poisoned of Guima
Parameters:
PeriodoIFR : RSI/IFR period for calculation basis
OrigemIFR : Source of RSI/IFR for calculation basis
Returns: Float with the RSI/IFR value for the period
calculoAlavancagemFuturos(margem, alavancagemMaxima)
Returns the number of contracts to work based on margin
Parameters:
margem : Margin for contract unit
alavancagemMaxima : Maximum number of contracts to work
Returns: Integer with the number of contracts suggested for trading
calculoAlavancagemAcoes(alavancagemMaxima)
Returns the number of batches to work based on the margin
Parameters:
alavancagemMaxima : Maximum number of batches to work
Returns: Integer with the amount of lots suggested for trading
bandasBollinger(periodoBB, origemBB, desvioPadrao)
Returns the value of bollinger bands
Parameters:
periodoBB : Period of bollinger bands for calculation basis
origemBB : Origin of bollinger bands for calculation basis
desvioPadrao : Standard Deviation of bollinger bands for calculation basis
Returns: Two-position array with upper and lower band values respectively
theRoc(periodoROC, origemROC)
Returns the value of Rate Of Change
Parameters:
periodoROC : Period for calculation basis
origemROC : Source of calculation basis
Returns: Float with the value of Rate Of Change
BpaLibrary "Bpa"
TODO: library of Brooks Price Action concepts
isBreakoutBar(atr, high, low, close, open, tail, size)
TODO: check if the bar is a breakout based on the specified conditions
Parameters:
atr : TODO: atr value
high : TODO: high price
low : TODO: low price
close : TODO: close price
open : TODO: open price
tail : TODO: decimal value for a percent that represent the size of the tail of the bar that cant be preceeded to be considered strong close
size : TODO: decimal value for a percent that represents by how much the breakout bar should be bigger than others to be considered one
Returns: TODO: boolean value, true if breakout bar, false otherwise
LibraryCOTLibrary "LibraryCOT"
This library provides tools to help Pine programmers fetch Commitment of Traders (COT) data for futures.
rootToCFTCCode(root)
Accepts a futures root and returns the relevant CFTC code.
Parameters:
root : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
Returns: The part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
currencyToCFTCCode(curr)
Converts a currency string to its corresponding CFTC code.
Parameters:
curr : Currency code, e.g., "USD" for US Dollar.
Returns: The corresponding to the currency, if one exists.
optionsToTicker(includeOptions)
Returns the part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
Parameters:
includeOptions : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
Returns: The part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
metricNameAndDirectionToTicker(metricName, metricDirection)
Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
Parameters:
metricName : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
metricDirection : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Valid values vary with metrics. Invalid values will cause a runtime error.
Returns: The part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", or "TC_L" for "Traders Commercial" and "Long".
typeToTicker(metricType)
Converts a metric type into one component required to build a valid COT ticker ID. See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
Parameters:
metricType : Metric type. Accepted values are: "All", "Old", "Other".
Returns: The part of a COT ticker.
convertRootToCOTCode(mode, convertToCOT)
Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
Parameters:
mode : A string determining how the function will work. Valid values are:
"Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
"Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
"Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
"Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
convertToCOT : "bool" value that, when `true`, causes the function to return a CFTC code. Otherwise, the root or currency information is returned. Optional. The default is `true`.
Returns: If `convertToCOT` is `true`, the part of a COT ticker ID string. If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
COTTickerid(COTType, CTFCCode, includeOptions, metricName, metricDirection, metricType)
Returns a valid TradingView ticker for the COT symbol with specified parameters.
Parameters:
COTType : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
CTFCCode : The for the asset, e.g., wheat futures (root "ZW") have the code "001602".
includeOptions : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
metricName : One of the metric names listed in this library's chart.
metricDirection : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction".
metricType : Type of the metric. Possible values: "All", "Old", and "Other".
Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
TradingWolfLibaryLibrary "TradingWolfLibary"
getMA(int, string)
Gets a Moving Average based on type
Parameters:
int : length The MA period
string : maType The type of MA
Returns: A moving average with the given parameters
minStop(float, simple, float, string)
Calculates and returns Minimum stop loss
Parameters:
float : entry price (Close if calculating on the entry candle)
simple : int Calculate how many bars back to look at swings
float : Minimum Stop Loss allowed (Should be x 0.01) if input
string : Direciton of trade either "Long" or "Short"
Returns: Stop Loss Value
KernelFunctionsLibrary "KernelFunctions"
This library provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substitution/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels. Compared to Moving Averages (which are really just simple kernels themselves), these kernel functions are more adaptive and afford the user an unprecedented degree of customization and flexibility.
rationalQuadratic(_src, _lookback, _relativeWeight, _startAtBar)
Rational Quadratic Kernel - An infinite sum of Gaussian Kernels of different length scales.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_relativeWeight : Relative weighting of time frames. Smaller values result in a more stretched-out curve, and larger values will result in a more wiggly curve. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Rational Quadratic Kernel.
gaussian(_src, _lookback, _startAtBar)
Gaussian Kernel - A weighted average of the source series. The weights are determined by the Radial Basis Function (RBF).
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Gaussian Kernel.
periodic(_src, _lookback, _period, _startAtBar)
Periodic Kernel - The periodic kernel (derived by David Mackay) allows one to model functions that repeat themselves exactly.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period : The distance between repititions of the function.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Periodic Kernel.
locallyPeriodic(_src, _lookback, _period, _startAtBar)
Locally Periodic Kernel - The locally periodic kernel is a periodic function that slowly varies with time. It is the product of the Periodic Kernel and the Gaussian Kernel.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period : The distance between repititions of the function.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Locally Periodic Kernel.
ahpuhelperLibrary "ahpuhelper"
Helper Library for Auto Harmonic Patterns UltimateX. It is not meaningful for others. This is supposed to be private library. But, publishing it to make sure that I don't delete accidentally. Some functions may be useful for coders.
insert_open_trades_table_column(showOpenTrades, table_id, column, colors, values, intStatus, harmonicTrailingStartState, lblSizeOpenTrades)
add data to open trades table column
Parameters:
showOpenTrades : flag to show open trades table
table_id : Table Id
column : refers to pattern data
colors : backgroud and text color array
values : cell values
intStatus : status as integer
harmonicTrailingStartState : trailing Start state as per configs
lblSizeOpenTrades : text size
Returns: nextColumn
populate_closed_stats(ClosedStatsPosition, bullishCounts, bearishCounts, bullishRetouchCounts, bearishRetouchCounts, bullishSizeMatrix, bearishSizeMatrix, bullishRR, bearishRR, allPatternLabels, flags, rowMain, rowHeaders)
populate closed stats for harmonic patterns
Parameters:
ClosedStatsPosition : Table position for closed stats
bullishCounts : Matrix containing bullish trade stats
bearishCounts : Matrix containing bearish trade stats
bullishRetouchCounts : Matrix containing bullish trade stats for those which retouched entry
bearishRetouchCounts : Matrix containing bearish trade stats for those which retouched entry
bullishSizeMatrix : Matrix containing data about size of bullish patterns
bearishSizeMatrix : Matrix containing data about size of bearish patterns
bullishRR : Matrix containing Risk Reward data of bullish patterns
bearishRR : Matrix containing Risk Reward data of bearish patterns
allPatternLabels : array containing pattern labels
flags : display flags
rowMain : Pattern header data
rowHeaders : header grouping data
Returns: void
get_rr_details(patternTradeDetails, harmonicTrailingStartState, disableTrail, breakEvenTrail)
calculate and return risk reward based on targets and stops
Parameters:
patternTradeDetails : array containing stop, entry and targets
harmonicTrailingStartState : trailing point
disableTrail : If set, ignores trailing point
breakEvenTrail : If set, trailing does not go beyond breakeven.
Returns: nextColumn
normsinvLibrary "normsinv"
Description:
Returns the inverse of the standard normal cumulative distribution.
The distribution has a mean of zero and a standard deviation of one; i.e.,
normsinv seeks that value z such that a normal distribtuion of mean of zero
and standard deviation one is equal to the input probability.
Reference:
github.com
normsinv(y0)
Returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one.
Parameters:
y0 : float, probability corresponding to the normal distribution.
Returns: float, z-score