DeleteArrayObject█ OVERVIEW
Delete array object according to array size such as label, line, linefill, box and table.
█ CREDITS
HeWhoMustNotBeNamed
Indicators and strategies
PriceTimeInteractive█ OVERVIEW
This library was intended to Get price of given time.input
█ CREDITS
Credits to TradingView for CAGR Custom Range.
█ FUNCTIONS
ohlc_time()
: Get OHLC price of given time.input
Parameters:
: : Time (t) must be using time.input
Returns: : OHLC
hlc_time()
: Get HLC price of given time.input
Parameters:
: : Time (t) must be using time.input
Returns: : HLC
hl_time()
: Get HL price of given time.input
Parameters:
: : Time (t) must be using time.input
Returns: : HL
AdxlLibrary "Adxl"
Functions to calculate the Average Directional Index
getDirectionUp(bar, lookback)
Bar high changed from open for bar
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getDirectionDown(bar, lookback)
Bar low changed from open for bar
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getPositiveDirectionalMovement(bar, lookback)
Positive directional movement for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getNegativeDirectionalMovement(bar, lookback)
Negative directional movement for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getTrueRangeMovingAverage(bar, lookback)
True range moving average for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getDirectionUpIndex(bar, lookback)
Direction up index for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getDirectionDownIndex(bar, lookback)
Direction down index for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getTotalDirectionIndex(bar, lookback)
Total direction index for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getAverageDirectionalIndex(bar, lookback)
Average Directional Index (ADX) for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
Heikin Ashi CandlesLibrary "heikin_ashi_candles"
This library is programmed to calculate the Heikin Ashi candles using the standard formula of Heikin Ashi Candles.
Notice the Heikin Ashi chart type isn't 100% like the results from this calculation.
You can import this library in your code to use it as a smoothing method for your strategy which operates on the standard chart type.
_close()
_open()
_high()
_low()
_ohlc4()
_hlcc4()
_hlc3()
_hl2()
CalculatePercentageSlTpLibrary "CalculatePercentageSlTp"
This Library calculate the sl and tp amount in percentage
sl_percentage(entry_price, sl_price)
this function calculates the sl value in percentage
Parameters:
entry_price : indicates the entry level
sl_price : indicates the stop loss level
Returns: stop loss in percentage
tp_percentage(entry_price, tp_price)
this function calculates the tp value in percentage
Parameters:
entry_price : indicates the entry level
tp_price : indicates the take profit level
Returns: take profit in percentage
sl_level(entry_price, sl_percentage)
this function calculates the sl level price
Parameters:
entry_price : indicates the entry level
sl_percentage : indicates the stop loss percentage
Returns: stop loss price in $
tp_level(entry_price, tp_percentage)
this function calculates the tp level price
Parameters:
entry_price : indicates the entry level
tp_percentage : indicates the take profit percentage
Returns: take profit price in $
AdxCalcHourlyLibrary "AdxCalcHourly"
getBars()
getBars: Returns the number of bars to use in the historical lookback period
Returns: simple int
directionDown()
directionDown: Calculates the direction down for bar_index
Returns: series float
directionUp()
directionUp: Calculates the direction up for bar_index
Returns: series float
trueRangeMovingAverage()
trueRangeMovingAverage: Calculates the true range moving average over the historical lookback period
Returns: series float
positiveDirectionalMovement()
positiveDirectionalMovement: Calculates the positive direction movement for bar_index
Returns: series float
negativeDirectionalMovement()
negativeDirectionalMovement: Calculates the begative direction movement for bar_index
Returns: series float
totalDirectionDown()
totalDirectionDown: Calculates the total direction down for the historical lookback period
Returns: series float
totalDirectionUp()
totalDirectionUp: Calculates the total direction up for the historical lookback period
Returns: series float
totalDirection()
totalDirection: Calculates the total direction movement for the historical lookback period
Returns: series float
averageDirectionalIndex()
averageDirectionalIndex: Calculates the average directional index (ADX) based on the trend for the historical lookback period
Returns: series float
getAdxHistoricalAverage()
getAdxHistoricalAverage: Calculates the average directional index (ADX) for the historical lookback period
Returns: series float
getAdxHistoricalHigh()
getAdxHistoricalHigh: Calculates the historical high of the directional index (ADX) for the historical lookback period
Returns: series float
getAdxHistoricalLow()
getAdxHistoricalLow: Calculates the historical low of the directional index (ADX) for the historical lookback period
Returns: series float
getAdxOpinion()
getAdxOpinion: Calculatesa recomendation for the directional index (ADX) based on the historical lookback period
Returns: series float
"Swap" - Bool/Position/Value : Array / Matrix / Var AutoswapLibrary "swap"
Side / Boundary Based All Types Swapper
- three automagical types for Arrays, Matrixes, and Variables
-- no signal : Long/ Short position autoswap
-- true / false : Boolean based side choice
-- Src / Thresh : if source is above or below the threshold
- two operating modes for variables, Holding mode only for arrays/matrixes
-- with two items, will automatically change between the two caveat is it does not delete table/box/line(fill VAR items automatically)
-- with three items, a neutral is available for NA input or neutral
- one function name for all of them. One import name that's easy to type/remember
-- make life easy for your conditional items.
side(source, thresh, _a, _b, _c)
side Change outputs based on position or a crossing level
Parameters:
source : (float) OPTIONAL value input
thresh : (float) OPTIONAL boundary line to cross
_a : (any) if Long/True/Above
_b : (any) if Short/False/Below
_c : (any) OPTIONAL NOT FOR MTX OR ARR... Neutral Item, if var/varip on a/b it will leave behind, ie, a table or box or line will not erase , if it's a varip you're sending in.
Returns: first, second, or third items based on input conditions
Please notify if bugs found.
Thanks.
RouterOrdersIronLibrary "RouterOrdersIron"
Library for routing orders to the Binance exchange.
MsgDoLongMKT(id, symbol, balance)
Returns json for Iron to buy a symbol for the amount of the balance with market order.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
MsgDoShortMKT(id, symbol, balance)
Returns json for Iron to sell a symbol for the amount of the balance with market order.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
MsgDoLongLR(id, symbol, balance)
Returns json for Iron to buy a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
MsgDoShortLR(id, symbol, balance)
Returns json for Iron to sell a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
DoLongMKT(id, symbol, balance)
Buy a symbol for the amount of the balance. It is send market order to Iron.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
DoShortMKT(id, symbol, balance)
Sell a symbol for the amount of the balance. It is send market order to Iron.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
DoLongLR(id, symbol, balance)
Buy a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
DoShortLR(id, symbol, balance)
Sell a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application.
Parameters:
id : ID of your Iron router.
symbol : Symbol for a trade, BTC example
balance : The amount for which to carry out the transaction.
Returns: true
GetQty(price, balance)
Get Qty for strategy on balance
Parameters:
price : Order price
balance : The amount for which to carry out the transaction.
Returns: Qty for strategy order TV
Moving_AveragesLibrary "Moving_Averages"
This library contains majority important moving average functions with int series support. Which means that they can be used with variable length input. For conventional use, please use tradingview built-in ta functions for moving averages as they are more precise. I'll use functions in this library for my other scripts with dynamic length inputs.
ema(src, len)
Exponential Moving Average (EMA)
Parameters:
src : Source
len : Period
Returns: Exponential Moving Average with Series Int Support (EMA)
alma(src, len, a_offset, a_sigma)
Arnaud Legoux Moving Average (ALMA)
Parameters:
src : Source
len : Period
a_offset : Arnaud Legoux offset
a_sigma : Arnaud Legoux sigma
Returns: Arnaud Legoux Moving Average (ALMA)
covwema(src, len)
Coefficient of Variation Weighted Exponential Moving Average (COVWEMA)
Parameters:
src : Source
len : Period
Returns: Coefficient of Variation Weighted Exponential Moving Average (COVWEMA)
covwma(src, len)
Coefficient of Variation Weighted Moving Average (COVWMA)
Parameters:
src : Source
len : Period
Returns: Coefficient of Variation Weighted Moving Average (COVWMA)
dema(src, len)
DEMA - Double Exponential Moving Average
Parameters:
src : Source
len : Period
Returns: DEMA - Double Exponential Moving Average
edsma(src, len, ssfLength, ssfPoles)
EDSMA - Ehlers Deviation Scaled Moving Average
Parameters:
src : Source
len : Period
ssfLength : EDSMA - Super Smoother Filter Length
ssfPoles : EDSMA - Super Smoother Filter Poles
Returns: Ehlers Deviation Scaled Moving Average (EDSMA)
eframa(src, len, FC, SC)
Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA)
Parameters:
src : Source
len : Period
FC : Lower Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average
SC : Upper Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average
Returns: Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA)
ehma(src, len)
EHMA - Exponential Hull Moving Average
Parameters:
src : Source
len : Period
Returns: Exponential Hull Moving Average (EHMA)
etma(src, len)
Exponential Triangular Moving Average (ETMA)
Parameters:
src : Source
len : Period
Returns: Exponential Triangular Moving Average (ETMA)
frama(src, len)
Fractal Adaptive Moving Average (FRAMA)
Parameters:
src : Source
len : Period
Returns: Fractal Adaptive Moving Average (FRAMA)
hma(src, len)
HMA - Hull Moving Average
Parameters:
src : Source
len : Period
Returns: Hull Moving Average (HMA)
jma(src, len, jurik_phase, jurik_power)
Jurik Moving Average - JMA
Parameters:
src : Source
len : Period
jurik_phase : Jurik (JMA) Only - Phase
jurik_power : Jurik (JMA) Only - Power
Returns: Jurik Moving Average (JMA)
kama(src, len, k_fastLength, k_slowLength)
Kaufman's Adaptive Moving Average (KAMA)
Parameters:
src : Source
len : Period
k_fastLength : Number of periods for the fastest exponential moving average
k_slowLength : Number of periods for the slowest exponential moving average
Returns: Kaufman's Adaptive Moving Average (KAMA)
kijun(_high, _low, len, kidiv)
Kijun v2
Parameters:
_high : High value of bar
_low : Low value of bar
len : Period
kidiv : Kijun MOD Divider
Returns: Kijun v2
lsma(src, len, offset)
LSMA/LRC - Least Squares Moving Average / Linear Regression Curve
Parameters:
src : Source
len : Period
offset : Offset
Returns: Least Squares Moving Average (LSMA)/ Linear Regression Curve (LRC)
mf(src, len, beta, feedback, z)
MF - Modular Filter
Parameters:
src : Source
len : Period
beta : Modular Filter, General Filter Only - Beta
feedback : Modular Filter Only - Feedback
z : Modular Filter Only - Feedback Weighting
Returns: Modular Filter (MF)
rma(src, len)
RMA - RSI Moving average
Parameters:
src : Source
len : Period
Returns: RSI Moving average (RMA)
sma(src, len)
SMA - Simple Moving Average
Parameters:
src : Source
len : Period
Returns: Simple Moving Average (SMA)
smma(src, len)
Smoothed Moving Average (SMMA)
Parameters:
src : Source
len : Period
Returns: Smoothed Moving Average (SMMA)
stma(src, len)
Simple Triangular Moving Average (STMA)
Parameters:
src : Source
len : Period
Returns: Simple Triangular Moving Average (STMA)
tema(src, len)
TEMA - Triple Exponential Moving Average
Parameters:
src : Source
len : Period
Returns: Triple Exponential Moving Average (TEMA)
thma(src, len)
THMA - Triple Hull Moving Average
Parameters:
src : Source
len : Period
Returns: Triple Hull Moving Average (THMA)
vama(src, len, volatility_lookback)
VAMA - Volatility Adjusted Moving Average
Parameters:
src : Source
len : Period
volatility_lookback : Volatility lookback length
Returns: Volatility Adjusted Moving Average (VAMA)
vidya(src, len)
Variable Index Dynamic Average (VIDYA)
Parameters:
src : Source
len : Period
Returns: Variable Index Dynamic Average (VIDYA)
vwma(src, len)
Volume-Weighted Moving Average (VWMA)
Parameters:
src : Source
len : Period
Returns: Volume-Weighted Moving Average (VWMA)
wma(src, len)
WMA - Weighted Moving Average
Parameters:
src : Source
len : Period
Returns: Weighted Moving Average (WMA)
zema(src, len)
Zero-Lag Exponential Moving Average (ZEMA)
Parameters:
src : Source
len : Period
Returns: Zero-Lag Exponential Moving Average (ZEMA)
zsma(src, len)
Zero-Lag Simple Moving Average (ZSMA)
Parameters:
src : Source
len : Period
Returns: Zero-Lag Simple Moving Average (ZSMA)
evwma(src, len)
EVWMA - Elastic Volume Weighted Moving Average
Parameters:
src : Source
len : Period
Returns: Elastic Volume Weighted Moving Average (EVWMA)
tt3(src, len, a1_t3)
Tillson T3
Parameters:
src : Source
len : Period
a1_t3 : Tillson T3 Volume Factor
Returns: Tillson T3
gma(src, len)
GMA - Geometric Moving Average
Parameters:
src : Source
len : Period
Returns: Geometric Moving Average (GMA)
wwma(src, len)
WWMA - Welles Wilder Moving Average
Parameters:
src : Source
len : Period
Returns: Welles Wilder Moving Average (WWMA)
ama(src, _high, _low, len, ama_f_length, ama_s_length)
AMA - Adjusted Moving Average
Parameters:
src : Source
_high : High value of bar
_low : Low value of bar
len : Period
ama_f_length : Fast EMA Length
ama_s_length : Slow EMA Length
Returns: Adjusted Moving Average (AMA)
cma(src, len)
Corrective Moving average (CMA)
Parameters:
src : Source
len : Period
Returns: Corrective Moving average (CMA)
gmma(src, len)
Geometric Mean Moving Average (GMMA)
Parameters:
src : Source
len : Period
Returns: Geometric Mean Moving Average (GMMA)
ealf(src, len, LAPercLen_, FPerc_)
Ehler's Adaptive Laguerre filter (EALF)
Parameters:
src : Source
len : Period
LAPercLen_ : Median Length
FPerc_ : Median Percentage
Returns: Ehler's Adaptive Laguerre filter (EALF)
elf(src, len, LAPercLen_, FPerc_)
ELF - Ehler's Laguerre filter
Parameters:
src : Source
len : Period
LAPercLen_ : Median Length
FPerc_ : Median Percentage
Returns: Ehler's Laguerre Filter (ELF)
edma(src, len)
Exponentially Deviating Moving Average (MZ EDMA)
Parameters:
src : Source
len : Period
Returns: Exponentially Deviating Moving Average (MZ EDMA)
pnr(src, len, rank_inter_Perc_)
PNR - percentile nearest rank
Parameters:
src : Source
len : Period
rank_inter_Perc_ : Rank and Interpolation Percentage
Returns: Percentile Nearest Rank (PNR)
pli(src, len, rank_inter_Perc_)
PLI - Percentile Linear Interpolation
Parameters:
src : Source
len : Period
rank_inter_Perc_ : Rank and Interpolation Percentage
Returns: Percentile Linear Interpolation (PLI)
rema(src, len)
Range EMA (REMA)
Parameters:
src : Source
len : Period
Returns: Range EMA (REMA)
sw_ma(src, len)
Sine-Weighted Moving Average (SW-MA)
Parameters:
src : Source
len : Period
Returns: Sine-Weighted Moving Average (SW-MA)
vwap(src, len)
Volume Weighted Average Price (VWAP)
Parameters:
src : Source
len : Period
Returns: Volume Weighted Average Price (VWAP)
mama(src, len)
MAMA - MESA Adaptive Moving Average
Parameters:
src : Source
len : Period
Returns: MESA Adaptive Moving Average (MAMA)
fama(src, len)
FAMA - Following Adaptive Moving Average
Parameters:
src : Source
len : Period
Returns: Following Adaptive Moving Average (FAMA)
hkama(src, len)
HKAMA - Hilbert based Kaufman's Adaptive Moving Average
Parameters:
src : Source
len : Period
Returns: Hilbert based Kaufman's Adaptive Moving Average (HKAMA)
bullratioLibrary "bullratio"
Calculate the profit/loss ratio of a permabull for configurable time range
bullratio(len)
calculates the profit/loss ratio for a permabull of age len
Parameters:
len : the number of candles to include in the running bull ratio - 0 for all time
Returns: series float of profit/loss percentage
Time FunctionsLibrary "TimeFunctions"
Utility functions to handle time in Pine Script
TimeframetoInt()
Returns an int that corresponds to a timeframe string:
"1" => 1
"5" => 5
"10" => 10
"15" => 15
"30" => 30
"60" => 60
"H1" => 60
"H4" => 240
"1D" => 1440
BarsSinceOpen()
Returns the number of bars that have passed since the opening of the New York Session.
[LIB] Array / Matrix DisplayLibrary "ArrayMatrixHUD"
Show Array or Matrix Elements In Table
For Arrays: Set the number of rows you want the data displayed in and it will generate a table, calculating the columns based on the size of the array being displayed.
For Matrix: It will automatically match the Rows and Columns to the values in the matrix.
Note: On the left, the table shows the index of the array/matrix value starting at 1. So, to call that value from inside the array, subtract 1 from the index value to the left. For matrices, keep in mind that the row and column are also starting at one when trying to call a value from the matrix. The numbering of the values on the left is for display purposes only.
viewArray(_arrayName, _pos, _txtSize, _tRows)
Array Element Display (Supports float, int, string, and bool)
Parameters:
_arrayName : ID of Array to be Displayed
_pos : Position for Table
_txtSize : Size of Table Cell Text
_tRows : Number of Rows to Display Data In (columns will be calculated accordingly)
Returns: A Display of Array Values in a Table
viewMatrix(_matrixName, _pos, _txtSize)
Matrix Element Display (Supports float, int, string, and bool)
Parameters:
_matrixName : ID of Matrix to be Displayed
_pos : Position for Table
_txtSize : Size of Table Cell Text
Returns: A Display of Matrix Values in a Table
RecursiveAlertsLibrary "RecursiveAlerts"
The library provides options to run alert() calls in loop without worrying about limitations of frequency options.
When an alert statement is called within a loop,
it will fire just once per bar irrespective of how many iterations allowed when fequency is set to alert.freq_once_per_bar or alert.freq_once_per_bar_close
it will fire continuously till it breaks when frequency is set to alert.freq_all
The function helps overcome this issue by using varip key array which resets on every bar
rAlert(message, key) Enhanced alert which can be used in loops
Parameters:
message : Alert message to be fired
key : Key to be checked to avoid repetitive alerts
Returns: array containing id of already fired alerts
Thanks to @theheirophant, @JohnBaron and @LucF for discussions and suggestion which eventually lead to this solution :)
CarlLibLibrary "CarlLib"
LastLowRedHighGreen(open, close, high, close, reqChangePerc) returns values representing the high of the most recent green and the low of the most recent red
Parameters:
open : open series
close : close series
high : high series
close : close series
reqChangePerc : the minimum require change percentage for the values to switch to new ones.
Returns:
TradingHookLibrary "TradingHook"
This library is a client script for making a webhook signal formatted string to TradingHook webhook server.
buy_message(password, amount, order_name) Make a buy Message for TradingHook.
Parameters:
password : (string) password that you set in .env file.
amount : (float) amount. If not set, your strategy qty will be sent.
order_name : (string) order_name. The default name is "Order".
Returns: (string) A string containing the formatted webhook message.
sell_message(password, percent, order_name) Make a sell message for TradingHook.
Parameters:
password : (string) password that you set in .env file.
percent : (string) what percentage of your quantity you want to sell.
order_name : (string) order_name. The default name is "Order".
Returns: (string) A string containing the formatted webhook message.
You can use TradingHook WebServer open source code in github(github.com)
PlurexSignalIntegrationLibrary "PlurexSignalIntegration"
Provides tools for integrating Strategies and Alerts into plurex.io signals.
plurexMarket() Build a Plurex market from a base and quote asset symbol.
Returns: A market string that can be used in Plurex Signal messages.
tickerToPlurexMarket() Builds simple Plurex market string from the syminfo
Returns: A market string that can be used in Plurex Signal messages.
simpleMessage(secret, action, marketOverride) Builds simple Plurex Signal Messages
Parameters:
secret : The secret for your Signal on plurex
action : The action of the message. One of .
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
executeStrategy(secret, openLong, openShort, closeLongs, closeShorts, marketOverride) Executes strategy actions with Plurex Signal messages
Parameters:
secret : The secret for your Signal on plurex
openLong : Strategy should open long if true, aggregated with other boolean values
openShort : Strategy should open short if true, aggregated with other boolean values
closeLongs : Strategy should close longs if true, aggregated with other boolean values
closeShorts : Strategy should close shorts if true, aggregated with other boolean values
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
fontilabLibrary "fontilab"
Provides function's indicators for pivot - trend - resistance.
pivots(src, lenght, isHigh) Detecting pivot points (and returning price + bar index.
Parameters:
src : The chart we analyse.
lenght : Used for the calcul.
isHigh : lookging for high if true, low otherwise.
Returns: The bar index and the price of the pivot.
calcDevThreshold(tresholdMultiplier, closePrice) Calculate deviation threshold for identifying major swings.
Parameters:
tresholdMultiplier : Usefull to equilibrate the calculate.
closePrice : Close price of the chart wanted.
Returns: The deviation threshold.
calcDev(basePrice, price) Custom function for calculating price deviation for validating large moves.
Parameters:
basePrice : The reference price.
price : The price tested.
Returns: The deviation.
pivotFoundWithLines(dev, isHigh, index, price, dev_threshold, isHighLast, pLast, iLast, lineLast) Detecting pivots that meet our deviation criteria.
Parameters:
dev : The deviation wanted.
isHigh : The type of pivot tested (high or low).
index : The Index of the pivot tested.
price : The chart price wanted.
dev_threshold : The deviation treshold.
isHighLast : The type of last pivot.
pLast : The pivot price last.
iLast : Index of the last pivot.
lineLast : The lst line.
Returns: The Line and bool is pivot High.
getDeviationPivots(thresholdMultiplier, depth, lineLast, isHighLast, iLast, pLast, deleteLines, closePrice, highPrice, lowPrice) Get pivot that meet our deviation criteria.
Parameters:
thresholdMultiplier : The treshold multiplier.
depth : The depth to calculate pivot.
lineLast : The last line.
isHighLast : The type of last pivot
iLast : Index of the last pivot.
pLast : The pivot price last.
deleteLines : If the line are draw or not.
closePrice : The chart close price.
highPrice : The chart high price.
lowPrice : The chart low price.
Returns: All pivot the informations.
getElIntArrayFromEnd() Get the last element of an int array.
getElFloatArrayFromEnd() Get the last element of an float array.
getElBoolArrayFromEnd() Get the last element of a bool array.
isTrendContinuation(isTrendUp, arrayBounds, lastPrice, precision) Check if last price is between bounds array.
Parameters:
isTrendUp : Is actual trend up.
arrayBounds : The trend array.
lastPrice : The pivot Price that just be found.
precision : The percent we add to actual bounds to validate a move.
Returns: na if price is between bounds, true if continuation, false if not.
getTrendPivots(trendBarIndexes, trendPrices, trendPricesIsHigh, interBarIndexes, interPrices, interPricesIsHigh, isTrendHesitate, isTrendUp, trendPrecision, pLast, iLast, isHighLast) Function to update array and trend related to pivot trend interpretation.
Parameters:
trendBarIndexes : The array trend bar index.
trendPrices : The array trend price.
trendPricesIsHigh : The array trend is high.
interBarIndexes : The array inter bar index.
interPrices : The array inter price.
interPricesIsHigh : The array inter ishigh.
isTrendHesitate : The actual status of is trend hesitate.
isTrendUp : The actual status of is trend up.
trendPrecision : The var precision to add in "iscontinuation" function.
pLast : The last pivot price.
iLast : The last pivot bar index.
isHighLast : The last pivot "isHigh".
Returns: trend & inter arrays, is trend hesitate, is trend up.
drawBoundLines(startIndex, startPrice, endIndex, endPrice, breakingPivotIndex, breakingPivotPrice, isTrendUp) Draw bounds and breaking line of the trend.
Parameters:
startIndex : Index of the first bound line.
startPrice : Price of first bound line.
endIndex : Index of second bound line.
endPrice : price of second bound line.
breakingPivotIndex : The breaking line index.
breakingPivotPrice : The breaking line price.
isTrendUp : The actual status of the trend.
Returns: The lines bounds and breaking line.
ColorArrayLibrary "ColorArray"
Simple color array gradient tool.
makeGradient(size, _col1, _col2, _col3, _col4, _col5) Color Gradient Array from 5 colors.
Parameters:
size : : default 10
_col1 : : default #ff0000
_col2 : : default #ffff00
_col3 : : default #00ff00
_col4 : : default #00ffff
_col5 : : default #0000ff
Returns: array of colors to specified size.
WpProbabilisticLibLibrary "WpProbabilisticLib"
Library that contains functions to calculate probabilistic based on historical candle analysis
CandleType(open, close) This function check what type of candle is, based on its close and open prices
Parameters:
open : series float (open price)
close : series float (close price)
Returns: This function return the candle type (1 for Bullish, -1 Bearish, 0 as Doji candle)
CandleTypePercentDiff(open, close, qtd_candles_before, consider_dojis) This function calculates the percentage difference between Bullish and Bearish in a candlestick range back in time and which is the type with the least occurrences
Parameters:
open : series float (open price series)
close : series float (close price series)
qtd_candles_before : simple int (Number of candles before to calculate)
consider_dojis : simple string (How to consider dojis (no consider "NO", as bearish "AS_RED", as bullish "AS_GREEN"))
Returns: tuple(float, int) (Returns the percentage difference between Bullish and Bearish candles and which type of candle has the least occurrences)
external_input_utilsLibrary "external_input_utils"
Collection of external input utilities for conversion and other hacky functions
str_to_src(value) str_to_src - Convert the string value to the coresponding source series. It can be used to limit the "input.source" choices provided to the end user.
The most interesting part is that it can be used to overcome the "one input.source call limitation" for external inputs to your script
Parameters:
value : - The string equivalent to the source to be converted
Returns: series of the coresponding source
eval_cond(input, operator, value, defval) eval_cond - Evaluate the condition given an operator
Parameters:
input : - The input to be compared with. It can be an external input or a regular one
operator : - The string operator that describe the coparison operation
value : - The value to compare with the input. This can be a serries or a constant
defval : - The boolean value to return when 'noop' is selected
Returns: series of bool the result of the operation evaluation
Price Displacement - Candlestick (OHLC) CalculationsA Magical little helper friend for Candle Math.
When composing scripts, it is often necessary to manipulate the math around the OHLC. At times, you want a scalar (absolute) value others you want a vector (+/-). Sometimes you want the open - close and sometimes you want just the positive number of the body size. You might want it in ticks or you might want it in points or you might want in percentages. And every time you try to put it together you waste precious time and brain power trying to think about how to properly structure what you're looking for. Not to mention it's normally not that aesthetically pleasing to look at in the code.
So, this fixes all of that.
Using this library. A function like 'pd.pt(_exp)' can call any kind of candlestick math you need. The function returns the candlestick math you define using particular expressions.
Candle Math Functions Include:
Points:
pt(_exp) Absolute Point Displacement. Point quantity of given size parameters according to _exp.
vpt(_exp) Vector Point Displacement. Point quantity of given size parameters according to _exp.
Ticks:
tick(_exp) Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
vtick(_exp) Vector Tick Displacement. Tick quantity of given size parameters according to _exp.
Percentages:
pct(_exp, _prec) Absolute Percent Displacement. (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
vpct(_exp, _prec) Vector Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
Expressions You Can Use with Formulas:
The expressions are simple (simple strings that is) and I did my best to make them sensible, generally using just the ohlc abreviations. I also included uw, lw, bd, and rg for when you're just trying to pull a candle component out. That way you don't have to think about which of the ohlc you're trying to get just use pd.tick("uw") and now the variable is assigned the length of the upper wick, absolute value, in ticks. If you wanted the vector in pts its pd.vpt("uw"). It also makes changing things easy too as I write it out.
Expression List:
Combinations
"oh" = open - high
"ol" = open - low
"oc" = open - close
"ho" = high - open
"hl" = high - low
"hc" = high - close
"lo" = low - open
"lh" = low - high
"lc" = low - close
"co" = close - open
"ch" = close - high
"cl" = close - low
Candle Components
"uw" = Upper Wick
"bd" = Body
"lw" = Lower Wick
"rg" = Range
Pct() Only
"scp" = Scalar Close Position
"sop" = Scalar Open Position
"vcp" = Vector Close Position
"vop" = Vector Open Position
The attributes are going to be available in the pop up dialogue when you mouse over the function, so you don't really have to remember them. I tried to make that look as efficient as possible. You'll notice it follows the OHLC pattern. Thus, "oh" precedes "ho" (heyo) because "O" would be first in the OHLC. Its a way to help find the expression you're looking for quickly. Like looking through an alphabetized list for traders.
There is a copy/paste console friendly helper list in the script itself.
Additional Notes on the Pct() Only functions:
This is the original reason I started writing this. These concepts place a rating/value on the bar based on candle attributes in one number. These formulas put a open or close value in a percentile of the bar relative to another aspect of the bar.
Scalar - Non-directional. Absolute Value.
Scalar Position: The position of the price attribute relative to the scale of the bar range (high - low)
Example: high = 100. low = 0. close = 25.
(A) Measure price distance C-L. How high above the low did the candle close (e.g. close - low = 25)
(B) Divide by bar range (high - low). 25 / (100 - 0) = .25
Explaination: The candle closed at the 25th percentile of the bar range given the bar range low = 0 and bar range high = 100.
Formula: scp = (close - low) / (high - low)
Vector = Directional.
Vector Position: The position of the price attribute relative to the scale of the bar midpoint (Vector Position at hl2 = 0)
Example: high = 100. low = 0. close = 25.
(A) Measure Price distance C-L: How high above the low did the candle close (e.g. close - low = 25)
(B) Measure Price distance H-C: How far below the high did the candle close (e.g. high - close = 75)
(C) Take Difference: A - B = C = -50
(D) Divide by bar range (high - low). -50 / (100 - 0) = -0.50
Explaination: Candle close at the midpoint between hl2 and the low.
Formula: vcp = { / (high - low) }
Thank you for checking this out. I hope no one else has already done this (because it took half the day) and I hope you find value in it. Be well. Trade well.
Library "PD"
Price Displacement
pt(_exp) Absolute Point Displacement. Point quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Point size of given expression as an absolute value.
vpt(_exp) Vector Point Displacement. Point quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Point size of given expression as a vector.
tick(_exp) Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Tick size of given expression as an absolute value.
vtick(_exp) Vector Tick Displacement. Tick quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Tick size of given expression as a vector.
pct(_exp, _prec) Absolute Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
Parameters:
_exp : (string) Expression
_prec : (int) Overload - Place value precision definition
Returns: Percent size of given expression as decimal.
vpct(_exp, _prec) Vector Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
Parameters:
_exp : (string) Expression
_prec : (int) Overload - Place value precision definition
Returns: Percent size of given expression as decimal.
SizeAndPlaceLibrary "SizeAndPlace"
size and location shortcuts
posYtoInt(string) posYtoInt as titled..
Parameters:
string : _inp
posXtoInt(string) posXtoInt as titled..
Parameters:
string : _inp
sizeToInt(string) sizeToInt as titled..
Parameters:
string : size
sizeToString(int) sizeToString as titled..
Parameters:
int : size
sizeStringToSize(string) sizeStringToSize as titled..
Parameters:
string : size
locationIntToStr(int) locationIntToStr as titled..
Parameters:
int : inp
locStringToLoc(string) locStringToLoc as titled..
Parameters:
string : location
posIntToString(int, int) posIntToString as titled..
Parameters:
int : _x
int : _y
PivotThis library was designed to create three different datasets using Bill Williams fractals. The goal is to spot trends in reversal data and ultimately use these datasets to help predict future price reversals.
First, the pivot() function is used to initialize and populate three separate arrays (high pivot , low pivot , all pivots ). Since each high/low price depends on the bar_index, the bar_index, pivot direction(high/low), and high/low values are compressed into a string to maintain the data's integrity ("__"). Once each string array is populated and organized by bar_index, all three are returned inside a tuple. The return value must be deconstructed H,L,A =pivot() for each array's values to be accessed using getPivot() . This boilerplate allows for data to be accessed more efficiently in a recursive environment. getPivot() was designed to be used inside of a for or while block to populate matrices for further analyses. Again, getPivot() return values must be exposed through deconstruction. x,d,y =getPivot(). See code for more details.
pivot(int XLR) initializes and populates arrays
Parameters
XLR - number of bars to the left and right that must be lower for a high to be considered a pivotHigh, or vice versa. This number will drastically change the size and scope of the returned datasets. smaller values will produce much larger datasets, which might model short term price activity well. In contrast, larger values will produce smaller datasets which might model longer term price activity well.
Returns - tuple [string ]
getPivot(string arrayID, int index) accesses array data
Parameters
arrayID - the variable name for one of the three arrays returned by pivot().
index - the index of the provided array, with 0 being the most recent pivot point. can be set to " i " in a loop to access values recursively
Returns - tuple