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?
Indicadores e estratégias
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.
LocalLimitLibrary "LocalLimit"
Calculates the local upper or local lower limit for a given series. Applying multiple passes produces what appears like support or resistance levels.
See Local Limits for more detail.
upper(src) Produces the recent local upper limit for a given series.
Parameters:
src : The source series to derive from.
lower(src) Produces the recent local lower limit for a given series.
Parameters:
src : The source series to derive from.
UnicodeReplacementFunctionLibrary "UnicodeReplacementFunction"
Unicode Characters Replacement function for strings.
replaceFont(_str, _fontType) Unicode Character Replace Function
Parameters:
_str : String input
_fontType : Font Type Selector
Returns: Replaced Char String with any custom font type choosed
SgjoeLibraryLibrary "SgjoeLibrary"
Custom functions
highest_when(float, float) Permits a condition to be used with highest(high,condition)
Parameters:
float : _high_series The High for the condition
float : _when The condition such as close > high
Returns: The high(s) at the point(s) the condition was true
lowest_when(float, float) Permits a condition to be used with lowest(low,condition)
Parameters:
float : _low_series The Low for the condition
float : _when The condition such as close < low
Returns: The low(s) at the point(s) the condition was true
MomentumSignalsLibrary "MomentumSignals"
Contains utilities varying algorithms for detecting key changes in momentum. Note: Momentum is not velocity and should be used in conjunction with other indicators. A change in momentum does not mean a reversal of velocity or trend.
simple(primary, secondary, len) Compares two series for changes in momentum to derive signal values.
Parameters:
primary : The primary series (typically a moving average) to look for changes in momentum.
secondary : The secondary series (typically derived moving average of the primary) to use as a comparison value.
len : The number of bars to measure the change in momentum.
filtered(primary, secondary, len, stdlen, stdMultiple) Compares two series for changes in momentum to derive signal values. Uses statistics to filter out changes in momentum.
Parameters:
primary : The primary series (typically a moving average) to look for changes in momentum.
secondary : The secondary series (typically derived moving average of the primary) to use as a comparison value.
len : The number of bars to measure the change in momentum.
stdlen : The number of bars to measure the change in momentum for filtering.
stdMultiple : The multiple of the change in momentum to use before reversiing.
special(primary, secondary, stdlen, stdMultiple) Compares two series for changes in momentum to derive signal values. Uses statistics to filter out changes in momentum. Does not signal when likely overbought or oversold.
Parameters:
primary : The primary series (typically a moving average) to look for changes in momentum.
secondary : The secondary series (typically derived moving average of the primary) to use as a comparison value.
stdlen : The number of bars to measure the change in momentum for filtering.
stdMultiple : The multiple of the change in momentum to use before reversiing.
GenericTradingLibrary "GenericTrading"
This library aims to collect rare but useful operations for
get_most_recent_long_or_short_position_closed_index() : returns most recent long/short closed bar index.
get_most_recent_long_or_short_position_open_index() : returns most recent long/short closed bar index.
These two functions designed to help to speed up the coding for strategies that contains "re-enter" logic.
These two functions also could applies in the situations where time-count is needed in your condition.
MomentumLibrary "Momentum"
Contains utilities varying algorithms for measuring momentum.
simple(fast, slow, src, fastType, slowType) Derives momentum from two moving averages of different lengths.
Parameters:
fast : The length of the fast moving average.
slow : The length of the slow moving average.
src : The series to measure from. Default is 'close'.
fastType : The type of moving average the fast should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
slowType : The type of moving average the slow should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
stochRSI(fast, fast, rsiLen, stochLen, src, kmode) Returns the K and D values of a Stochastic RSI. Allows for different moving averages to produce the K value.
Parameters:
fast : The length to average the stochastic.
fast : The length to smooth out K and produce D.
rsiLen : The length of the RSI.
stochLen : The length of stochastic.
src : The series to measure from. Default is 'close'.
kmode : The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
Returns:
macd(fast, slow, signal, src, fastType, slowType, slowType) Same as well-known MACD formula but allows for different moving averages types to be used.
Parameters:
fast : The length of the fast moving average.
slow : The length of the slow moving average.
signal : The length of average to applied to smooth out the signal.
src : The series to measure from. Default is 'close'.
fastType : The type of moving average the fast should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
slowType : The type of moving average the slow should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
slowType : The type of moving average the signal should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
Returns:
arsenalLibrary "arsenal"
This library is a collection of weapons that will help us win the war against the market.
isNewbar(res, timezone) Checks if the res is in new bar at the current timeframe
Parameters:
res : - resolution of the bar to check if new
timezone : - timezone of the resolution
Returns: ch: - 1=true, 0=false
VolatilityLibrary "Volatility"
Functions for determining if volatility (true range) is within or exceeds normal.
The "True Range" (ta.tr) is used for measuring volatility.
Values are normalized by the volume adjusted weighted moving average (VAWMA) to be more like percent moves than price.
current(len) Returns the current price adjusted volatitlity ratio.
Parameters:
len : Number of bars to get a volume adjusted weighted average price.
normal(len, maxDeviation, level, gapDays, spec, res) Returns the normal upper range of volatility. Compensates for overnight gaps within a regular session.
Parameters:
len : Number of bars to measure volatility.
maxDeviation : The limit of volatility before considered an outlier.
level : The amount of standard deviation after cleaning outliers to be considered within normal.
gapDays : The number of days in the past to measure overnight gap volaility.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
isNormal(len, maxDeviation, level, gapDays, spec, res) Returns true if the volatility (true range) is within normal levels. Compensates for overnight gaps within a regular session.
Parameters:
len : Number of bars to measure volatility.
maxDeviation : The limit of volatility before considered an outlier.
level : The amount of standard deviation after cleaning outliers to be considered within normal.
gapDays : The number of days in the past to measure overnight gap volaility.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
severity(len, maxDeviation, level, gapDays, spec, res) Returns ratio of the current value to the normal value. Compensates for overnight gaps within a regular session.
Parameters:
len : Number of bars to measure volatility.
maxDeviation : The limit of volatility before considered an outlier.
level : The amount of standard deviation after cleaning outliers to be considered within normal.
gapDays : The number of days in the past to measure overnight gap volaility.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
DataCleanerLibrary "DataCleaner"
Functions for acquiring outlier levels and acquiring a cleaned version of a series.
outlierLevel(src, len, level) Gets the (standard deviation) outlier level for a given series.
Parameters:
src : The series to average and add a multiple of the standard deviation to.
len : The The number of bars to measure.
level : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
Returns: The average of the series plus the multiple of the standard deviation.
cleanUsing(src, result, len, maxDeviation) Returns an array representing the result series with (outliers provided by the source) removed.
Parameters:
src : The source series to read from.
result : The result series.
len : The maximum size of the resultant array.
maxDeviation : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
Returns: An array containing the cleaned series.
clean(src, len, maxDeviation) Returns an array representing the source series with outliers removed.
Parameters:
src : The source series to read from.
len : The maximum size of the resultant array.
maxDeviation : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
Returns: An array containing the cleaned series.
outlierLevelAdjusted(src, level, len, maxDeviation) Gets the (standard deviation) outlier level for a given series after a single pass of removing any outliers.
Parameters:
src : The series to average and add a multiple of the standard deviation to.
level : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
len : The The number of bars to measure.
maxDeviation : The optional standard deviation level to use when cleaning the series. The default is the value of the provided level.
Returns: The average of the series plus the multiple of the standard deviation.