AveragesLibrary "Averages"
Contains utilities for generating averages from arrays. Useful for manipulated or cleaned data.
triangular(src, startingWeight) Calculates the triangular weighted average of a set of values where the last value has the highest weight.
Parameters:
src : The array to derive the average from.
startingWeight : The weight to begin with when calculating the average. Higher numbers will decrease the bias.
weighted(src, weights, weightDefault) Calculates the weighted average of a set of values.
Parameters:
src : The array to derive the average from.
weights : The array containing the weights for the source.
weightDefault : The default value to use when a weight is NA.
triangularWeighted(src, weights, startingWeight) Calculates the weighted average of a set of values where the last value has the highest triangular multiple.
Parameters:
src : The array to derive the average from.
weights : The array containing the weights for the source.
startingWeight : The multiple to begin with when calculating the average. Higher numbers will decrease the bias.
exponential(src) Calculates the exponential average of a set of values where the last value has the highest weight.
Parameters:
src : The array to derive the average from.
arrayFrom(src, len, omitNA) Creates an array from the provided series (oldest to newest).
Parameters:
src : The array to derive from.
len : The target length of the array.
omitNA : If true, NA values will not be added to the array and the resultant array may be shorter than the target length.
Indicators and strategies
DailyDeviationLibrary "DailyDeviation"
Helps in determining the relative deviation from the open of the day compared to the high or low values.
hlcDeltaArrays(daysPrior, maxDeviation, spec, res) Retuns a set of arrays representing the daily deviation of price for a given number of days.
Parameters:
daysPrior : Number of days back to get the close from.
maxDeviation : Maximum deviation before a value is considered an outlier. A value of 0 will not filter results.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
Returns: Where OH = Open vs High, OL = Open vs Low, and OC = Open vs Close
fromOpen(daysPrior, maxDeviation, comparison, spec, res) Retuns a value representing the deviation from the open (to the high or low) of the current day given number of days to measure from.
Parameters:
daysPrior : Number of days back to get the close from.
maxDeviation : Maximum deviation before a value is considered an outlier. A value of 0 will not filter results.
comparison : The value use in comparison to the current open for the day.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
CRC.lib Bars - Bar FunctionsLibrary "CRCBars"
min_max(open, open) Get bar min (low) and max (high) price points
Parameters:
open : Open price data
open : Close price data
Returns:
is_bullish_bearish(open, open) Get bar bullish/bearish boolean signals
Parameters:
open : Open price data
open : Close price data
Returns:
sizes(open, open, open, open) Get bar sizes based on open/high/low/close data
Parameters:
open : Open price data
open : High price data
open : Low price data
open : Close price data
Returns:
CRC.lib Characters and StringsLibrary "CRCChars"
arrow_up() : ▲
arrow_down() : ▼
warning() : ⚠
checkmark() : ✅
no_entry() : 🚫
CRCPaintLibrary "CRCPaint"
black(trans)
Parameters:
trans : Transparency value (float)
Returns: color
-------------------------------------------------------------------------- //
white()
silver()
gray()
fuchsia()
maroon()
red()
orange()
yellow()
blue()
navy()
aqua()
purple()
teal()
green()
lime()
olive()
malachite()
fern()
feldgrau()
skobeloff()
viridian()
violet()
denim()
saphhire()
cyan()
auburn()
pink()
tawny()
rust()
goldenrod()
mahogany()
boysenberry()
mauve()
cosmos()
sepia()
jazzberry()
wenge()
idx_mix()
idx_mix_size()
transparent()
rgb()
shade_mint()
shade_blush()
random()
options_expiration_and_strike_price_calculatorLibrary "options_expiration_and_strike_price_calculator"
TODO: add library description here
fun()
this is a library to help calculate options strike price and expiration that you can add to a script i use it mainly for symbol calulation to place orders to buy options on TD ameritrade so it will be set up to order options on TD ameritrade using json order placer and webhook it fills in the area in the json under symbol i suggest manually adding the year it should look like this is an example of an order to buy 10 call options using json through td ameritrade api
"complexOrderStrategyType": "NONE",
"orderType": "LIMIT",
"session": "NORMAL",
"price": "6.45",
"duration": "DAY",
"orderStrategyType": "SINGLE",
"orderLegCollection":
}
ConverterTFLibrary "ConverterTF"
I have found a bug Regarding the timeframe display, on the chart I have found that the display is numeric, for example 4Hr timeframe instead of '4H', but it turns out to be '240', which I want it to be displayed in abbreviated form. And in all other timeframes it's the same. So this library was created to solve those problems. It converts a timeframe from a numeric string type to an integer type by selecting a timeframe manually and displaying it on the chart.
CTF()
str = "240"
X.GetTF( str )
Example
str = input.timeframe(title='Time frame', defval='240')
TimeF = CTF(str)
L=label.new(bar_index, high, 'Before>> Timeframe '+str+' After>> Timeframe '+TimeF,style=label.style_label_down,size=size.large)
label.delete(L )
Custom timeframes can handle this issue as well.
An example from the use. You will find it on the bottom right hand side.
Hopefully it will be helpful to the Tradingview community. :)
TradingPortfolioLibrary "TradingPortfolio"
Simple functions for portfolio management. A portfolio is essentially
a float array with 3 positions that gets passed around
into these functions that ensure it gets properly updated as trading ensues.
An example usage:
import hugodanielcom/TradingPortfolio/XXXX as portfolio
var float my_portfolio = portfolio.init(0.0, strategy.initial_capital) // Initialize the portfolio with the strategy capital
if close < 10.0
portfolio.buy(my_portfolio, 10.0, close) // Buy when the close is below 10.0
plot(portfolio.total(my_portfolio), title = "Total portfolio value")
get_balance(portfolio) Gets the number of tokens and fiat available in the supplied portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The tokens and fiat in a tuple
set_balance(portfolio, new_crypto, new_fiat) Sets the portfolio number of tokens and fiat amounts. This function overrides the current values in the portfolio and sets the provided ones as the new portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
new_crypto : The new amount of tokens in the portfolio.
new_fiat : The new amount of fiat in the portfolio
Returns: The tokens and fiat in a tuple
init(crypto, fiat) This function returns a clean portfolio. Start by calling this function and pass its return value as an argument to the other functions in this library.
Parameters:
crypto : The initial amount of tokens in the portfolio (defaults to 0.0).
fiat : The initial amount of fiat in the portfolio (defaults to 0.0).
Returns: The portfolio (a float )
crypto(portfolio) Gets the number of tokens in the portfolio
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of tokens in the portfolio
fiat(portfolio) Gets the fiat in the portfolio
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of fiat in the portfolio
retained(portfolio) Gets the amount of reatined fiat in the portfolio. Retained fiat is not considered as part of the balance when buying/selling, but it is considered as part of the total of the portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of retained fiat in the portfolio
retain(portfolio, fiat_to_retain) Sets the amount of fiat to retain. It removes the amount from the current fiat in the portfolio and marks it as retained.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
fiat_to_retain : The amount of fiat to remove and mark as retained.
Returns: void
total(portfolio, token_value) Calculates the total fiat value of the portfolio. It multiplies the amount of tokens by the supplied value and adds to the result the current fiat and retained amount.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
token_value : The fiat value of a unit (1) of token
Returns: A float that corresponds to the total fiat value of the portfolio (retained amount included)
ratio(portfolio, token_value) Calculates the ratio of tokens / fiat. The retained amount of fiat is not considered, only the active fiat being considered for trading.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
token_value : The fiat value of a unit (1) of token
Returns: A float between 1.0 and 0.0 that corresponds to the portfolio ratio of token / fiat (i.e. 0.6 corresponds to a portfolio whose value is made by 60% tokens and 40% fiat)
can_buy(portfolio, amount, token_value) Asserts that there is enough balance to buy the requested amount of tokens.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to assert that can be bought
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true if there is capacity to buy the amount of tokens provided.
can_sell(portfolio, amount) Asserts that there is enough token balance to sell the requested amount of tokens.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to assert that can be sold
Returns: A boolean value, true if there is capacity to sold the amount of tokens provided.
buy(portfolio, amount, token_value) Adjusts the portfolio state to perform the equivalent of a buy operation (as in, buy the requested amount of tokens at the provided value and set the portfolio accordingly).
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to buy
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true the requested amount of tokens was "bought" and the portfolio updated. False if nothing was changed.
sell(portfolio, amount, token_value) Adjusts the portfolio state to perform the equivalent of a sell operation (as in, sell the requested amount of tokens at the provided value and set the portfolio accordingly).
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to sell
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true the requested amount of tokens was "sold" and the portfolio updated. False if nothing was changed.
lib_Indicators_v2_DTULibrary "lib_Indicators_v2_DTU"
This library functions returns included Moving averages, indicators with factorization, functions candles, function heikinashi and more.
Created it to feed as backend of my indicator/strategy "Indicators & Combinations Framework Advanced v2 " that will be released ASAP.
This is replacement of my previous indicator (lib_indicators_DT)
I will add an indicator example which will use this indicator named as "lib_indicators_v2_DTU example" to help the usage of this library
Additionally library will be updated with more indicators in the future
NOTES:
Indicator functions returns only one series :-(
plotcandle function returns candle series
INDICATOR LIST:
hide = 'DONT DISPLAY', //Dont display & calculate the indicator. (For my framework usage)
alma = 'alma(src,len,offset=0.85,sigma=6)', //Arnaud Legoux Moving Average
ama = 'ama(src,len,fast=14,slow=100)', //Adjusted Moving Average
acdst = 'accdist()', //Accumulation/distribution index.
cma = 'cma(src,len)', //Corrective Moving average
dema = 'dema(src,len)', //Double EMA (Same as EMA with 2 factor)
ema = 'ema(src,len)', //Exponential Moving Average
gmma = 'gmma(src,len)', //Geometric Mean Moving Average
hghst = 'highest(src,len)', //Highest value for a given number of bars back.
hl2ma = 'hl2ma(src,len)', //higest lowest moving average
hma = 'hma(src,len)', //Hull Moving Average.
lgAdt = 'lagAdapt(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter
lgAdV = 'lagAdaptV(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter variation
lguer = 'laguerre(src,len)', //Ehler's Laguerre filter
lsrcp = 'lesrcp(src,len)', //lowest exponential esrcpanding moving line
lexp = 'lexp(src,len)', //lowest exponential expanding moving line
linrg = 'linreg(src,len,loffset=1)', //Linear regression
lowst = 'lowest(src,len)', //Lovest value for a given number of bars back.
pcnl = 'percntl(src,len)', //percentile nearest rank. Calculates percentile using method of Nearest Rank.
pcnli = 'percntli(src,len)', //percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
rema = 'rema(src,len)', //Range EMA (REMA)
rma = 'rma(src,len)', //Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
sma = 'sma(src,len)', //Smoothed Moving Average
smma = 'smma(src,len)', //Smoothed Moving Average
supr2 = 'super2(src,len)', //Ehler's super smoother, 2 pole
supr3 = 'super3(src,len)', //Ehler's super smoother, 3 pole
strnd = 'supertrend(src,len,period=3)', //Supertrend indicator
swma = 'swma(src,len)', //Sine-Weighted Moving Average
tema = 'tema(src,len)', //Triple EMA (Same as EMA with 3 factor)
tma = 'tma(src,len)', //Triangular Moving Average
vida = 'vida(src,len)', //Variable Index Dynamic Average
vwma = 'vwma(src,len)', //Volume Weigted Moving Average
wma = 'wma(src,len)', //Weigted Moving Average
angle = 'angle(src,len)', //angle of the series (Use its Input as another indicator output)
atr = 'atr(src,len)', //average true range. RMA of true range.
bbr = 'bbr(src,len,mult=1)', //bollinger %%
bbw = 'bbw(src,len,mult=2)', //Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
cci = 'cci(src,len)', //commodity channel index
cctbb = 'cctbbo(src,len)', //CCT Bollinger Band Oscilator
chng = 'change(src,len)', //Difference between current value and previous, source - source .
cmo = 'cmo(src,len)', //Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
cog = 'cog(src,len)', //The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
cpcrv = 'copcurve(src,len)', //Coppock Curve. was originally developed by Edwin "Sedge" Coppock (Barron's Magazine, October 1962).
corrl = 'correl(src,len)', //Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
count = 'count(src,len)', //green avg - red avg
dev = 'dev(src,len)', //ta.dev() Measure of difference between the series and it's ta.sma
fall = 'falling(src,len)', //ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
kcr = 'kcr(src,len,mult=2)', //Keltner Channels Range
kcw = 'kcw(src,len,mult=2)', //ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
macd = 'macd(src,len)', //macd
mfi = 'mfi(src,len)', //Money Flow Index
nvi = 'nvi()', //Negative Volume Index
obv = 'obv()', //On Balance Volume
pvi = 'pvi()', //Positive Volume Index
pvt = 'pvt()', //Price Volume Trend
rise = 'rising(src,len)', //ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
roc = 'roc(src,len)', //Rate of Change
rsi = 'rsi(src,len)', //Relative strength Index
smosc = 'smi_osc(src,len,fast=5, slow=34)', //smi Oscillator
smsig = 'smi_sig(src,len,fast=5, slow=34)', //smi Signal
stdev = 'stdev(src,len)', //Standart deviation
trix = 'trix(src,len)' , //the rate of change of a triple exponentially smoothed moving average.
tsi = 'tsi(src,len)', //True Strength Index
vari = 'variance(src,len)', //ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
wilpc = 'willprc(src,len)', //Williams %R
wad = 'wad()', //Williams Accumulation/Distribution.
wvad = 'wvad()' //Williams Variable Accumulation/Distribution.
}
f_func(string, float, simple, float, float, float, simple) f_func Return selected indicator value with different parameters. New version. Use extra parameters for available indicators
Parameters:
string : FuncType_ indicator from the indicator list
float : src_ close, open, high, low,hl2, hlc3, ohlc4 or any
simple : int length_ indicator length
float : p1 extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
Returns: float Return calculated indicator value
fn_heikin(float, float, float, float) fn_heikin Return given src data (open, high,low,close) as heikin ashi candle values
Parameters:
float : o_ open value
float : h_ high value
float : l_ low value
float : c_ close value
Returns: float heikin ashi open, high,low,close vlues that will be used with plotcandle
fn_plotFunction(float, string, simple, bool) fn_plotFunction Return input src data with different plotting options
Parameters:
float : src_ indicator src_data or any other series.....
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
Returns: float
fn_funcPlotV2(string, float, simple, float, float, float, simple, string, simple, bool, bool) fn_funcPlotV2 Return selected indicator value with different parameters. New version. Use extra parameters fora available indicators
Parameters:
string : FuncType_ indicator from the indicator list
float : src_data_ close, open, high, low,hl2, hlc3, ohlc4 or any
simple : int length_ indicator length
float : p1 extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
bool : log_ Use log on function entries
Returns: float Return calculated indicator value
fn_factor(string, float, simple, float, float, float, simple, simple, string, simple, bool, bool) fn_factor Return selected indicator's factorization with given arguments
Parameters:
string : FuncType_ indicator from the indicator list
float : src_data_ close, open, high, low,hl2, hlc3, ohlc4 or any
simple : int length_ indicator length
float : p1 parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
simple : int fact_ Add double triple, Quatr factor to selected indicator (like converting EMA to 2-DEMA, 3-TEMA, 4-QEMA...)
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
bool : log_ Use log on function entries
Returns: float Return result of the function
fn_plotCandles(string, simple, float, float, float, simple, string, simple, bool, bool, bool) fn_plotCandles Return selected indicator's candle values with different parameters also heikinashi is available
Parameters:
string : FuncType_ indicator from the indicator list
simple : int length_ indicator length
float : p1 parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
bool : log_ Use log on function entries
bool : plotheikin_ Use Heikin Ashi on Plot
Returns: float
Last Available Bar InfoLibrary "Last_Available_Bar_Info"
getLastBarTimeStamp()
getAvailableBars()
This simple library is built with an aim of getting the last available bar information for the chart. This returns a constant value that doesn't change on bar change.
For backtesting with accurate results on non standard charts, it will be helpful. (Especially if you are using non standard charts like Renko Chart).
Methods
getLastBarTimeStamp()
: Returns Timestamp of the last available bar (Constant)
getAvailableBars()
:Returns Number of Available Bars on the chart (Constant)
Example
import paragjyoti2012/Last_Available_Bar_Info/v1 as LastBarInfo
last_bar_timestamp=LastBarInfo.getLastBarTimeStamp()
no_of_bars=LastBarInfo.getAvailableBars()
If you are using Renko Charts, for backtesting, it's necesary to filter out the historical bars that are not of this timeframe.
In Renko charts, once the available bars of the current timeframe (based on your Tradingview active plan) are exhausted,
previous bars are filled in with historical bars of higher timeframe. Which is detrimental for backtesting, and it leads to unrealistic results.
To get the actual number of bars available of that timeframe, you should use this security function to get the timestamp for the last (real) bar available.
tf=timeframe.period
real_available_bars = request.security(syminfo.ticker, tf , LastBarInfo.getAvailableBars() , lookahead = barmerge.lookahead_off)
last_available_bar_timestamp = request.security(syminfo.ticker, tf , LastBarInfo.getLastBarTimeStamp() , lookahead = barmerge.lookahead_off)
library TypeMovingAveragesLibrary "TypeMovingAverages"
This library function returns a moving average.
ma_fast
ma_slow
MA_selector()
Example
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © hapharmonic
//@version=5
indicator("Test MATYPE", overlay=true)
import hapharmonic/TypeMovingAverages/1 as MAType
xprd1 = input(title=' 💉Fast EMA period', defval=12)
ma_select1 = 'EMA'
xprd2 = input(title=' 💉Fast EMA period', defval=26)
ma_select2 = 'EMA'
xsmooth = input.int(title='🏄♂️Smoothing period (1 = no smoothing)', minval=1, defval=1)
ma_fast = MAType.MA_selector(close, xprd1, ma_select1,xsmooth)
ma_slow = MAType.MA_selector(close, xprd2, ma_select2,xsmooth)
plot(ma_fast, "INDICATOR",color.green)
plot(ma_slow, "INDICATOR",color.red)
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
Of course, you can run these types just by adding options. 'ma_select1 ' and 'ma_select2'
SMA', 'EMA', 'WMA', 'HMA', 'JMA', 'KAMA', 'TMA', 'VAMA', 'SMMA', 'DEMA', 'VMA', 'WWMA', 'EMA_NO_LAG', 'TSF', 'ALMA'
MTFindicatorsQuite recently TradingView added the possibility to create and use Libraries in PineScript. With this feature PineScript became higher quality of coding language overnight. Libraries enable splitting your code into multiple files, providing easier access to code reusability.
I was working on a script which included 3000 lines of code, which was recompiling 1:30 min, and recalculating over 1 minute as well. So I split it into 2 parts: main part + library containing "main logic", which I reuse in variety of scripts, but don't change too often. Result? Now recompilation of my main script takes 10 and recalculation 8 seconds!!!. I instantly fell in love with libraries.
Having said that, and being dedicated hater of security() calls, I have decided to publish a library of MTF indicators created with my own approach: "dig into formula". I have explained reasons for such approach in desription to this script:
So this library script will be a set of indicators reaching to higher timeframes. Just include one line at the beginning of the script you are creating:
import Peter_O/MTFindicators/1 as LIB
and then somewhere is the code add this line:
rsimtf=LIB.rsi_mtf(close,5,14)
All of a sudden you have access to rsimtf from 5x higher timeframe without any hassle :)
I start with RSI MTF, next ones will be ADX, Stochastic and some more. I will update this library with them here as well. Feel free to request particular indicators in comments. Maybe PSAR? Maybe Bollinger Bands?
StringtoNumberThis library is used to convert Text type numbers are numbers.
Library "StringtoNumber"
str1 = '12340' , vv = numstrToNum(str1)
numstrToNum()
Example
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © hapharmonic
//@version=5
indicator("My Script")
import hapharmonic/StringtoNumber/1 as CV
TF = '240'
GETTF = CV.numstrToNum(TF)
L = label.new(bar_index, high, '|| numstrToNum :>> || ' + str.tostring(GETTF), style=label.style_label_down,size=size.large)
label.delete(L )
PureRebalanceLibrary "PureRebalance"
A rebalance function that is pure.
Depends only on its arguments to perform the necessary calculations.
rebalance(token_price, portfolio_token_amount, portfolio_fiat_amount, rebalance_ratio) Rebalances a portfolio made of tokens and fiat to a given ratio of tokens per fiat
Parameters:
token_price : The value of a single unit (1) token
portfolio_token_amount : The number of tokens in the portfolio
portfolio_fiat_amount : Fiat available in the portfolio
rebalance_ratio : The ratio of token value / fiat that the portfolio should have after the rebalance (0.5 is used if no argument is supplied).
Returns: The number of tokens to buy or sell in order to achieve the desired portfolio ratio passed as argument (a positive value is returned if the tokens are to be bought, and negative value if the tokens are to be sold).
SessionsInBoxesLibLibrary "SessionsInBoxesLib"
Provides functions calculating the all-time high/low of values.
get_positions()
draw()
FunctionZigZagMultipleMethodsLibrary "FunctionZigZagMultipleMethods"
ZigZag Multiple Methods.
method(idx) Helper methods enumeration.
Parameters:
idx : int, index of method, range 0 to 4.
Returns: string
function(method, value_x, value_y) Multiple method ZigZag.
Parameters:
method : string, default='(MANUAL) Percent price move over X * Y', method for zigzag.
value_x : float, x value in method.
value_y : float, y value in method.
Returns: tuple with:
zigzag float
direction
reverse_line float
realtimeofpivot int
MHCustomSpotTradingLibraryLibrary "MHCustomSpotTradingLibrary"
HMA(float, float)
Parameters:
float : _src price data
float : _length Period
Returns: Hull Moving Average
EHMA(float, float)
Parameters:
float : _src price data
float : _length Period
Returns: EHMA Moving Average
THMA(float, float)
Parameters:
float : _src price data
float : _length Period
Returns: THMA Moving Average
HullMode(string, float, float)
Parameters:
string : modeSwitch Hull type
float : _src price data
float : _length Period
Returns: A Moving Average
start_Dates(int, int, int)
Parameters:
int : year
int : month
int : day
Returns: Start Date
stop_Dates(int, int, int)
Parameters:
int : year
int : month
int : day
Returns: Stop Date
f_print(string, int, int)
Parameters:
string : _text
int : col
int : row
Returns: Nothing
showStats()
greenCandle()
redCandle()
getDecimals()
truncate()
toWhole()
toPips()
getMA()
getEAP()
barsAboveMA()
barsBelowMA()
barsCrossedMA()
getPullbackBarCount()
getBodySize()
getTopWickSize()
getBottomWickSize()
getBodyPercent()
isHammer()
isStar()
isDoji()
isBullishEC()
isBearishEC()
timeFilter()
dateFilter()
dayFilter()
atrFilter()
fillCell()
AwesomeColorLibrary "AwesomeColor"
This library provides a variety of colors.
The following functions all provide different sets of colors.
The name of the function indicates the color scheme.
The usage of arguments for all functions is the same.
// @function {Color set name}
// @param _color TODO: The name of the color group.
// @returns TODO: Returns an array of colors.
arrayutilsLibrary "_arrayutils"
Library contains utility functions using arrays.
delete(arr, index)
remove an item from array at specific index. Also deletes the item
Parameters:
arr : - array from which the item needs to be deleted
index : - index of item to be deleted
Returns: void
pop(arr)
remove the last item from array. Also deletes the item
Parameters:
arr : - array from which the last item needs to be removed and deleted
Returns: void
shift(arr)
remove an item from array at index 0. Also deletes the item
Parameters:
arr : - array from which the first item needs to be removed and deleted
Returns: void
unshift(arr, val, maxItems)
add an item to the beginning of an array with max items cap
Parameters:
arr : - array to which the item needs to be added at the beginning
val : - value of item which needs to be added
maxItems : - max items array can hold. After that, items are removed from the other end
Returns: resulting array
clear(arr)
remove and delete all items in an array
Parameters:
arr : - array which needs to be cleared
Returns: void
push(arr, val, maxItems)
add an item to the end of an array with max items cap
Parameters:
arr : - array to which the item needs to be added at the beginning
val : - value of item which needs to be added
maxItems : - max items array can hold. After that, items are removed from the starting index
Returns: resulting array
check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Parameters:
pivots : pivots array
barArray : pivot bar array
dir : direction for which overflow need to be checked
Returns: bool overflow
get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Parameters:
pivots : pivots array
length : length for which trend series need to be checked
highLow : filter pivot high or low
trend : Uptrend or Downtrend
Returns: int trendIndexes
get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Parameters:
pivots : pivots array
firstIndex : First index of the series
lastIndex : Last index of the series
Returns: int trendIndexes
sma(source)
calculates sma for elements in array
Parameters:
source : source array
Returns: float sma
ema(source, length)
calculates ema for elements in array
Parameters:
source : source array
length : ema length
Returns: float ema
rma(source, length)
calculates rma for elements in array
Parameters:
source : source array
length : rma length
Returns: float rma
wma(source, length)
calculates wma for elements in array
Parameters:
source : source array
length : wma length
Returns: float wma
hma(source, length)
calculates hma for elements in array
Parameters:
source : source array
length : hma length
Returns: float hma
ma(source, matype, length)
wrapper for all moving averages based on array
Parameters:
source : source array
matype : moving average type. Valud values are: sma, ema, rma, wma and hma
length : moving average length length
Returns: float moving average
getFibSeries(numberOfFibs, start)
gets fib series in array
Parameters:
numberOfFibs : number of fibs
start : starting number
Returns: float fibArray
harmonicpatternsLibrary "harmonicpatterns"
harmonicpatterns: methods required for calculation of harmonic patterns. These are customised to be used in my scripts. But, also simple enough for others to make use of :)
isGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isGartleyPattern: Checks for harmonic pattern Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Gartley. False otherwise.
isBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isBatPattern: Checks for harmonic pattern Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Bat. False otherwise.
isButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isButterflyPattern: Checks for harmonic pattern Butterfly
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Butterfly. False otherwise.
isCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isCrabPattern: Checks for harmonic pattern Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Crab. False otherwise.
isDeepCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isDeepCrabPattern: Checks for harmonic pattern DeepCrab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is DeepCrab. False otherwise.
isCypherPattern(xabRatio, axcRatio, xadRatio, err_min, err_max) isCypherPattern: Checks for harmonic pattern Cypher
Parameters:
xabRatio : AB/XA
axcRatio : XC/AX
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Cypher. False otherwise.
isSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isSharkPattern: Checks for harmonic pattern Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Shark. False otherwise.
isNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNenStarPattern: Checks for harmonic pattern Nenstar
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Nenstar. False otherwise.
isAntiNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiNenStarPattern: Checks for harmonic pattern Anti NenStar
Parameters:
xabRatio : - AB/XA
abcRatio : - BC/AB
bcdRatio : - CD/BC
xadRatio : - AD/XA
err_min : - Minumum error threshold
err_max : - Maximum error threshold
Returns: True if the pattern is Anti NenStar. False otherwise.
isAntiSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiSharkPattern: Checks for harmonic pattern Anti Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Shark. False otherwise.
isAntiCypherPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCypherPattern: Checks for harmonic pattern Anti Cypher
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Cypher. False otherwise.
isAntiCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCrabPattern: Checks for harmonic pattern Anti Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Crab. False otherwise.
isAntiBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiBatPattern: Checks for harmonic pattern Anti Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Bat. False otherwise.
isAntiGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiGartleyPattern: Checks for harmonic pattern Anti Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Gartley. False otherwise.
isNavarro200Pattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNavarro200Pattern: Checks for harmonic pattern Navarro200
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Navarro200. False otherwise.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) isHarmonicPattern: Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
c : 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
Signal_Data_2021_09_09__2021_11_18Library "Signal_Data_2021_09_09__2021_11_18"
Functions to support my timing signals system
import_start_time(harmonic) get the start time for each harmonic signal
Parameters:
harmonic : is an integer identifying the harmonic
Returns: the starting timestamp of the harmonic data
import_signal(index, harmonic) access point for pre-processed data imported here by copy paste
Parameters:
index : is the current data index, use 0 to initialize
harmonic : is the data set to index, use 0 to initialize
Returns: the data from the indicated harmonic array starting at index, and the starting timestamp of that data
ma_functionLibrary "ma_function"
TODO: This library is a package of various MAs.
ma_function(name, source, length) This function provides the MA specified in the argument.
Parameters:
name : MA's name
source : Source value
length : Look back periods
Returns: Ma value
TableColorThemeLibrary "TableColorTheme"
TODO: This library provides the color for the table.
monokai(name) theme: Provides the colors of monokai.
Parameters:
name : TODO: The name of the color group.
Returns: TODO: Returns an array of colors.
kolormark.com
monokaipro(name) theme: Provides the colors of monokai pro.
Parameters:
name : TODO: The name of the color group.
Returns: TODO: Returns an array of colors.
theme(name) theme This function provides the color for the table.
Parameters:
name : TODO: The name of the color group.
Returns: TODO: Returns an array of colors.