ATR_InfoWhat Is the Average True Range (ATR)?
The average true range (ATR) is a technical analysis indicator, introduced by market technician J. Welles Wilder Jr. in his book New Concepts in Technical Trading Systems, that measures market volatility by decomposing the entire range of an asset price for that period.
Each instrument per unit of time passes its average value of the true range, but there are moments when the volatility explodes or abruptly decays, these phenomena introduce large distortions into the average value of the true range.
The ATR_WPB function calculates the average value of the true range for the specified number of bars, while excluding paranormally large and paranormally small bars from the calculation of the average.
For example, if the instrument has passed a small ATR value, then it has many chances to continue moving, but if the instrument has passed its ATR value, then the chances of continuing to move are extremely low.
Library "ATR_Info"
ATR_Info: Calculates ATR without paranormal bars
ATR_WPB(source, period, psmall, pbig)
ATR_WPB: Calculates ATR without paranormal bars
Parameters:
source (float) : ATR_WPB: (series float) The sequence of data on the basis of which the ATP calculation will be made
period (int) : ATR_WPB: (int) Sequence size for ATR calculation
psmall (float) : ATR_WPB: (float) Coefficient for paranormally small bar
pbig (float) : ATR_WPB: (float) Coefficient for paranormally big bar
Returns: ATR_WPB: (float) ATR without paranormal bars
Statistics
lib_priceactionLibrary "lib_priceaction"
a library for everything related to price action, starting off with displacements
displacement(len, min_strength, o, c)
calculate if there is a displacement and how strong it is
Parameters:
len (int) : The amount of candles to consider for the deviation
min_strength (float) : The minimum displacement strength to trigger a signal
o (float) : The source series on which calculations are based
c (float) : The source series on which calculations are based
Returns: a tuple of (bool signal, float displacement_strength)
Overgeared Library Economic Calendar-----------------------------------------------------------
Base on script -> jdehorty/EconomicCalendar
Very Big Thanks to jdehorty/EconomicCalendar
-----------------------------------------------------------
CNTLibraryLibrary "CNTLibrary"
Custom Functions To Help Code In Pinescript V5
Coded By Christian Nataliano
First Coded In 10/06/2023
Last Edited In 22/06/2023
Huge Shout Out To © ZenAndTheArtOfTrading and his ZenLibrary V5, Some Of The Custom Functions Were Heavily Inspired By Matt's Work & His Pine Script Mastery Course
Another Shout Out To The TradingView's Team Library ta V5
//====================================================================================================================================================
// Custom Indicator Functions
//====================================================================================================================================================
GetKAMA(KAMA_lenght, Fast_KAMA, Slow_KAMA)
Calculates An Adaptive Moving Average Based On Perry J Kaufman's Calculations
Parameters:
KAMA_lenght (int) : Is The KAMA Lenght
Fast_KAMA (int) : Is The KAMA's Fastes Moving Average
Slow_KAMA (int) : Is The KAMA's Slowest Moving Average
Returns: Float Of The KAMA's Current Calculations
GetMovingAverage(Source, Lenght, Type)
Get Custom Moving Averages Values
Parameters:
Source (float) : Of The Moving Average, Defval = close
Lenght (simple int) : Of The Moving Average, Defval = 50
Type (string) : Of The Moving Average, Defval = Exponential Moving Average
Returns: The Moving Average Calculation Based On Its Given Source, Lenght & Calculation Type (Please Call Function On Global Scope)
GetDecimals()
Calculates how many decimals are on the quote price of the current market © ZenAndTheArtOfTrading
Returns: The current decimal places on the market quote price
Truncate(number, decimalPlaces)
Truncates (cuts) excess decimal places © ZenAndTheArtOfTrading
Parameters:
number (float)
decimalPlaces (simple float)
Returns: The given number truncated to the given decimalPlaces
ToWhole(number)
Converts pips into whole numbers © ZenAndTheArtOfTrading
Parameters:
number (float)
Returns: The converted number
ToPips(number)
Converts whole numbers back into pips © ZenAndTheArtOfTrading
Parameters:
number (float)
Returns: The converted number
GetPctChange(value1, value2, lookback)
Gets the percentage change between 2 float values over a given lookback period © ZenAndTheArtOfTrading
Parameters:
value1 (float)
value2 (float)
lookback (int)
BarsAboveMA(lookback, ma)
Counts how many candles are above the MA © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are above the MA
BarsBelowMA(lookback, ma)
Counts how many candles are below the MA © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are below the EMA
BarsCrossedMA(lookback, ma)
Counts how many times the EMA was crossed recently © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many times price recently crossed the EMA
GetPullbackBarCount(lookback, direction)
Counts how many green & red bars have printed recently (ie. pullback count) © ZenAndTheArtOfTrading
Parameters:
lookback (int)
direction (int)
Returns: The bar count of how many candles have retraced over the given lookback & direction
GetSwingHigh(Lookback, SwingType)
Check If Price Has Made A Recent Swing High
Parameters:
Lookback (int) : Is For The Swing High Lookback Period, Defval = 7
SwingType (int) : Is For The Swing High Type Of Identification, Defval = 1
Returns: A Bool - True If Price Has Made A Recent Swing High
GetSwingLow(Lookback, SwingType)
Check If Price Has Made A Recent Swing Low
Parameters:
Lookback (int) : Is For The Swing Low Lookback Period, Defval = 7
SwingType (int) : Is For The Swing Low Type Of Identification, Defval = 1
Returns: A Bool - True If Price Has Made A Recent Swing Low
//====================================================================================================================================================
// Custom Risk Management Functions
//====================================================================================================================================================
CalculateStopLossLevel(OrderType, Entry, StopLoss)
Calculate StopLoss Level
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, Defval = na
StopLoss (float) : Is The Custom StopLoss Distance, Defval = 2x ATR Below Close
Returns: Float - The StopLoss Level In Actual Price As A
CalculateStopLossDistance(OrderType, Entry, StopLoss)
Calculate StopLoss Distance In Pips
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
StopLoss (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
Returns: Float - The StopLoss Value In Pips
CalculateTakeProfitLevel(OrderType, Entry, StopLossDistance, RiskReward)
Calculate TakeProfit Level
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, Defval = na
StopLossDistance (float)
RiskReward (float)
Returns: Float - The TakeProfit Level In Actual Price
CalculateTakeProfitDistance(OrderType, Entry, TakeProfit)
Get TakeProfit Distance In Pips
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
TakeProfit (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
Returns: Float - The TakeProfit Value In Pips
CalculateConversionCurrency(AccountCurrency, SymbolCurrency, BaseCurrency)
Get The Conversion Currecny Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
Parameters:
AccountCurrency (simple string) : Is For The Account Currency Used
SymbolCurrency (simple string) : Is For The Current Symbol Currency (Front Symbol)
BaseCurrency (simple string) : Is For The Current Symbol Base Currency (Back Symbol)
Returns: Tuple Of A Bollean (Convert The Currency ?) And A String (Converted Currency)
CalculateConversionRate(ConvertCurrency, ConversionRate)
Get The Conversion Rate Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
Parameters:
ConvertCurrency (bool) : Is To Check If The Current Symbol Needs To Be Converted Or Not
ConversionRate (float) : Is The Quoted Price Of The Conversion Currency (Input The request.security Function Here)
Returns: Float Price Of Conversion Rate (If In The Same Currency Than Return Value Will Be 1.0)
LotSize(LotSizeSimple, Balance, Risk, SLDistance, ConversionRate)
Get Current Lot Size
Parameters:
LotSizeSimple (bool) : Is To Toggle Lot Sizing Calculation (Simple Is Good Enough For Stocks & Crypto, Whilst Complex Is For Forex)
Balance (float) : Is For The Current Account Balance To Calculate The Lot Sizing Based Off
Risk (float) : Is For The Current Risk Per Trade To Calculate The Lot Sizing Based Off
SLDistance (float) : Is The Current Position StopLoss Distance From Its Entry Price
ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
Returns: Float - Position Size In Units
ToLots(Units)
Converts Units To Lots
Parameters:
Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
Returns: Float - Position Size In Lots
ToUnits(Lots)
Converts Lots To Units
Parameters:
Lots (float) : Is For How Many Lots Need To Be Converted Into Units (Minimun 0.01 Units)
Returns: Int - Position Size In Units
ToLotsInUnits(Units)
Converts Units To Lots Than Back To Units
Parameters:
Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
Returns: Float - Position Size In Lots That Were Rounded To Units
ATRTrail(OrderType, SourceType, ATRPeriod, ATRMultiplyer, SwingLookback)
Calculate ATR Trailing Stop
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
SourceType (int) : Is To Determine Where To Calculate The ATR Trailing From, Defval = close
ATRPeriod (simple int) : Is To Change Its ATR Period, Defval = 20
ATRMultiplyer (float) : Is To Change Its ATR Trailing Distance, Defval = 1
SwingLookback (int) : Is To Change Its Swing HiLo Lookback (Only From Source Type 5), Defval = 7
Returns: Float - Number Of The Current ATR Trailing
DangerZone(WinRate, AvgRRR, Filter)
Calculate Danger Zone Of A Given Strategy
Parameters:
WinRate (float) : Is The Strategy WinRate
AvgRRR (float) : Is The Strategy Avg RRR
Filter (float) : Is The Minimum Profit It Needs To Be Out Of BE Zone, Defval = 3
Returns: Int - Value, 1 If Out Of Danger Zone, 0 If BE, -1 If In Danger Zone
IsQuestionableTrades(TradeTP, TradeSL)
Checks For Questionable Trades (Which Are Trades That Its TP & SL Level Got Hit At The Same Candle)
Parameters:
TradeTP (float) : Is The Trade In Question Take Profit Level
TradeSL (float) : Is The Trade In Question Stop Loss Level
Returns: Bool - True If The Last Trade Was A "Questionable Trade"
//====================================================================================================================================================
// Custom Strategy Functions
//====================================================================================================================================================
OpenLong(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue)
Open A Long Order Based On The Given Params
Parameters:
EntryID (string) : Is The Trade Entry ID, Defval = "Long"
LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
Comment (string) : Is The Order Comment, Defval = Long Entry Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
OpenShort(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue)
Open A Short Order Based On The Given Params
Parameters:
EntryID (string) : Is The Trade Entry ID, Defval = "Short"
LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
Comment (string) : Is The Order Comment, Defval = Short Entry Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
TP_SLExit(FromID, TPLevel, SLLevel, PercentageClose, Comment, CommentValue)
Exits Based On Predetermined TP & SL Levels
Parameters:
FromID (string) : Is The Trade ID That The TP & SL Levels Be Palced
TPLevel (float) : Is The Take Profit Level
SLLevel (float) : Is The StopLoss Level
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
CloseLong(ExitID, PercentageClose, Comment, CommentValue, Instant)
Exits A Long Order Based On A Specified Condition
Parameters:
ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Long"
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Instant (bool) : Is For Exit Execution Type, Defval = false
Returns: Void
CloseShort(ExitID, PercentageClose, Comment, CommentValue, Instant)
Exits A Short Order Based On A Specified Condition
Parameters:
ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Short"
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Instant (bool) : Is For Exit Execution Type, Defval = false
Returns: Void
BrokerCheck(Broker)
Checks Traded Broker With Current Loaded Chart Broker
Parameters:
Broker (string) : Is The Current Broker That Is Traded
Returns: Bool - True If Current Traded Broker Is Same As Loaded Chart Broker
OpenPC(LicenseID, OrderType, UseLimit, LimitPrice, SymbolPrefix, Symbol, SymbolSuffix, Risk, SL, TP, OrderComment, Spread)
Compiles Given Parameters Into An Alert String Format To Open Trades Using Pine Connector
Parameters:
LicenseID (string) : Is The Users PineConnector LicenseID
OrderType (int) : Is The Desired OrderType To Open
UseLimit (bool) : Is If We Want To Enter The Position At Exactly The Previous Closing Price
LimitPrice (float) : Is The Limit Price Of The Trade (Only For Pending Orders)
SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
Symbol (string) : Is The Traded Symbol
SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
Risk (float) : Is The Trade Risk Per Trade / Fixed Lot Sizing
SL (float) : Is The Trade SL In Price / In Pips
TP (float) : Is The Trade TP In Price / In Pips
OrderComment (string) : Is The Executed Trade Comment
Spread (float) : is The Maximum Spread For Execution
Returns: String - Pine Connector Order Syntax Alert Message
ClosePC(LicenseID, OrderType, SymbolPrefix, Symbol, SymbolSuffix)
Compiles Given Parameters Into An Alert String Format To Close Trades Using Pine Connector
Parameters:
LicenseID (string) : Is The Users PineConnector LicenseID
OrderType (int) : Is The Desired OrderType To Close
SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
Symbol (string) : Is The Traded Symbol
SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
Returns: String - Pine Connector Order Syntax Alert Message
//====================================================================================================================================================
// Custom Backtesting Calculation Functions
//====================================================================================================================================================
CalculatePNL(EntryPrice, ExitPrice, LotSize, ConversionRate)
Calculates Trade PNL Based On Entry, Eixt & Lot Size
Parameters:
EntryPrice (float) : Is The Trade Entry
ExitPrice (float) : Is The Trade Exit
LotSize (float) : Is The Trade Sizing
ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
Returns: Float - The Current Trade PNL
UpdateBalance(PrevBalance, PNL)
Updates The Previous Ginve Balance To The Next PNL
Parameters:
PrevBalance (float) : Is The Previous Balance To Be Updated
PNL (float) : Is The Current Trade PNL To Be Added
Returns: Float - The Current Updated PNL
CalculateSlpComm(PNL, MaxRate)
Calculates Random Slippage & Commisions Fees Based On The Parameters
Parameters:
PNL (float) : Is The Current Trade PNL
MaxRate (float) : Is The Upper Limit (In Percentage) Of The Randomized Fee
Returns: Float - A Percentage Fee Of The Current Trade PNL
UpdateDD(MaxBalance, Balance)
Calculates & Updates The DD Based On Its Given Parameters
Parameters:
MaxBalance (float) : Is The Maximum Balance Ever Recorded
Balance (float) : Is The Current Account Balance
Returns: Float - The Current Strategy DD
CalculateWR(TotalTrades, LongID, ShortID)
Calculate The Total, Long & Short Trades Win Rate
Parameters:
TotalTrades (int) : Are The Current Total Trades That The Strategy Has Taken
LongID (string) : Is The Order ID Of The Long Trades Of The Strategy
ShortID (string) : Is The Order ID Of The Short Trades Of The Strategy
Returns: Tuple Of Long WR%, Short WR%, Total WR%, Total Winning Trades, Total Losing Trades, Total Long Trades & Total Short Trades
CalculateAvgRRR(WinTrades, LossTrades)
Calculates The Overall Strategy Avg Risk Reward Ratio
Parameters:
WinTrades (int) : Are The Strategy Winning Trades
LossTrades (int) : Are The Strategy Losing Trades
Returns: Float - The Average RRR Values
CAGR(StartTime, StartPrice, EndTime, EndPrice)
Calculates The CAGR Over The Given Time Period © TradingView
Parameters:
StartTime (int) : Is The Starting Time Of The Calculation
StartPrice (float) : Is The Starting Price Of The Calculation
EndTime (int) : Is The Ending Time Of The Calculation
EndPrice (float) : Is The Ending Price Of The Calculation
Returns: Float - The CAGR Values
//====================================================================================================================================================
// Custom Plot Functions
//====================================================================================================================================================
EditLabels(LabelID, X1, Y1, Text, Color, TextColor, EditCondition, DeleteCondition)
Edit / Delete Labels
Parameters:
LabelID (label) : Is The ID Of The Selected Label
X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
Text (string) : Is The Text Than Wants To Be Written In The Label
Color (color) : Is The Color Value Change Of The Label Text
TextColor (color)
EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
Returns: Void
EditLine(LineID, X1, Y1, X2, Y2, Color, EditCondition, DeleteCondition)
Edit / Delete Lines
Parameters:
LineID (line) : Is The ID Of The Selected Line
X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
X2 (int) : Is The X2 Coordinate IN BARINDEX Xloc
Y2 (float) : Is The Y2 Coordinate IN PRICE Yloc
Color (color) : Is The Color Value Change Of The Line
EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
Returns: Void
//====================================================================================================================================================
// Custom Display Functions (Using Tables)
//====================================================================================================================================================
FillTable(TableID, Column, Row, Title, Value, BgColor, TextColor, ToolTip)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
Column (int) : Is The Current Column Of The Table That Wants To Be Edited
Row (int) : Is The Current Row Of The Table That Wants To Be Edited
Title (string) : Is The String Title Of The Current Cell Table
Value (string) : Is The String Value Of The Current Cell Table
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
ToolTip (string) : Is The ToolTip Of The Current Cell In The Table
Returns: Void
DisplayBTResults(TableID, BgColor, TextColor, StartingBalance, Balance, DollarReturn, TotalPips, MaxDD)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
StartingBalance (float) : Is The Account Starting Balance
Balance (float)
DollarReturn (float) : Is The Account Dollar Reture
TotalPips (float) : Is The Total Pips Gained / loss
MaxDD (float) : Is The Maximum Drawdown Over The Backtesting Period
Returns: Void
DisplayBTResultsV2(TableID, BgColor, TextColor, TotalWR, QTCount, LongWR, ShortWR, InitialCapital, CumProfit, CumFee, AvgRRR, MaxDD, CAGR, MeanDD)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
TotalWR (float) : Is The Strategy Total WR In %
QTCount (int) : Is The Strategy Questionable Trades Count
LongWR (float) : Is The Strategy Total WR In %
ShortWR (float) : Is The Strategy Total WR In %
InitialCapital (float) : Is The Strategy Initial Starting Capital
CumProfit (float) : Is The Strategy Ending Cumulative Profit
CumFee (float) : Is The Strategy Ending Cumulative Fee (Based On Randomized Fee Assumptions)
AvgRRR (float) : Is The Strategy Average Risk Reward Ratio
MaxDD (float) : Is The Strategy Maximum DrawDown In Its Backtesting Period
CAGR (float) : Is The Strategy Compounded Average GRowth In %
MeanDD (float) : Is The Strategy Mean / Average Drawdown In The Backtesting Period
Returns: Void
//====================================================================================================================================================
// Custom Pattern Detection Functions
//====================================================================================================================================================
BullFib(priceLow, priceHigh, fibRatio)
Calculates A Bullish Fibonacci Value (From Swing Low To High) © ZenAndTheArtOfTrading
Parameters:
priceLow (float)
priceHigh (float)
fibRatio (float)
Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
BearFib(priceLow, priceHigh, fibRatio)
Calculates A Bearish Fibonacci Value (From Swing High To Low) © ZenAndTheArtOfTrading
Parameters:
priceLow (float)
priceHigh (float)
fibRatio (float)
Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
GetBodySize()
Gets The Current Candle Body Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Body Size IN POINTS
GetTopWickSize()
Gets The Current Candle Top Wick Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Top Wick Size IN POINTS
GetBottomWickSize()
Gets The Current Candle Bottom Wick Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Bottom Wick Size IN POINTS
GetBodyPercent()
Gets The Current Candle Body Size As A Percentage Of Its Entire Size Including Its Wicks © ZenAndTheArtOfTrading
Returns: The Current Candle Body Size IN PERCENTAGE
GetTopWickPercent()
Gets The Current Top Wick Size As A Percentage Of Its Entire Body Size
Returns: Float - The Current Candle Top Wick Size IN PERCENTAGE
GetBottomWickPercent()
Gets The Current Bottom Wick Size As A Percentage Of Its Entire Bodu Size
Returns: Float - The Current Candle Bottom Size IN PERCENTAGE
BullishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Engulfing Candle
Parameters:
Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Engulfing Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Engulfing Candle
BearishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bearish Engulfing Candle
Parameters:
Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Engulfing Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Engulfing Candle
Hammer(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod)
Checks If The Current Bar Is A Hammer Candle
Parameters:
Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
Star(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod)
Checks If The Current Bar Is A Hammer Candle
Parameters:
Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
Doji(MaxWickSize, MaxBodySize, DojiType, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Doji Candle
Parameters:
MaxWickSize (float) : To Specify The Maximum Lenght Of Its Upper & Lower Wick, Defval = 2
MaxBodySize (float) : To Specify The Maximum Lenght Of Its Candle Body IN PERCENT, Defval = 0.05
DojiType (int)
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Doji Candle
BullishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Harami Candle
Parameters:
Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Harami Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Harami Candle
BearishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Harami Candle
Parameters:
Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Harami Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Harami Candle
//====================================================================================================================================================
// Custom Time Functions
//====================================================================================================================================================
BarInSession(sess, useFilter)
Determines if the current price bar falls inside the specified session © ZenAndTheArtOfTrading
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls within the given time session
BarOutSession(sess, useFilter)
Determines if the current price bar falls outside the specified session © ZenAndTheArtOfTrading
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls outside the given time session
DateFilter(startTime, endTime)
Determines if this bar's time falls within date filter range © ZenAndTheArtOfTrading
Parameters:
startTime (int)
endTime (int)
Returns: A boolean - true if the current bar falls within the given dates
DayFilter(monday, tuesday, wednesday, thursday, friday, saturday, sunday)
Checks if the current bar's day is in the list of given days to analyze © ZenAndTheArtOfTrading
Parameters:
monday (bool)
tuesday (bool)
wednesday (bool)
thursday (bool)
friday (bool)
saturday (bool)
sunday (bool)
Returns: A boolean - true if the current bar's day is one of the given days
AUSSess()
Checks If The Current Australian Forex Session In Running
Returns: Bool - True If Currently The Australian Session Is Running
ASIASess()
Checks If The Current Asian Forex Session In Running
Returns: Bool - True If Currently The Asian Session Is Running
EURSess()
Checks If The Current European Forex Session In Running
Returns: Bool - True If Currently The European Session Is Running
USSess()
Checks If The Current US Forex Session In Running
Returns: Bool - True If Currently The US Session Is Running
UNIXToDate(Time, ConversionType, TimeZone)
Converts UNIX Time To Datetime
Parameters:
Time (int) : Is The UNIX Time Input
ConversionType (int) : Is The Datetime Output Format, Defval = DD-MM-YYYY
TimeZone (string) : Is To Convert The Outputed Datetime Into The Specified Time Zone, Defval = Exchange Time Zone
Returns: String - String Of Datetime
Risk ManagementLibrary "RiskManagement"
This library keeps your money in check, and is used for testing and later on webhook-applications too. It has four volatility functions and two of them can be used to calculate a Stop-Loss, like Average True Range. It also can calculate Position Size, and the Risk Reward Ratio. But those calculations don't take leverage into account.
position_size(portfolio, risk, entry, stop_loss, use_leverage, qty_as_integer)
This function calculates the definite amount of contracts/shares/units you should use to buy or sell. This value can used by `strategy.entry(qty)` for example.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. Possible values are between 0.1 and 100%. Same usecase with strategy(default_qty_type=strategy.percent_of_equity,default_qty_value=100), except its calculation the risk only.
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
use_leverage (bool) : This value is optional. When not used or when set to false then this function will let you invest your portfolio at max.
qty_as_integer (bool) : This value is optional. When set to true this function will return a value used with integers. The largest integer less than or equal to the given number. Because some Broker/Exchanges let you trade hole contracts/shares/units only.
Returns: float
position_size_currency(portfolio, risk, entry, stop_loss)
This function calculates the definite amount of currency you should use when going long or short.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. For example: 1 is 100% and 0,01 is 1%. Default amount is 0.02 (2%).
entry (float) : This is the limit-/market-price for the current investment. In other words: The price per contract/share/units you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
Returns: float
rrr(entry, stop_loss, take_profit)
This function calculates the Risk Reward Ratio. Common values are between 1.5 and 2.0 and you should not go lower except for very few special cases.
Parameters:
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
take_profit (float) : This is the limit-/market-price when to take profits.
Returns: float
change_in_price(length)
This function calculates the difference between price now and close price of the candle 'n' bars before that. If prices are very volatile but closed where they began, then this method would show zero volatility. Over many calculations, this method returns a reasonable measure of volatility, but will always be lower than those using the highs and lows.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
maximum_price_fluctuation(length)
This function measures volatility over most recent candles, which could be used as an estimate of risk. It may also be effective as the basis for a stop-loss or take-profit, like the ATR but it ignores the frequency of directional changes within the time interval. In other words: The difference between the highest high and lowest low over 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
absolute_price_changes(length)
This function measures volatility over most recent close prices. This is excellent for comparing volatility. It includes both frequency and magnitude. In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
annualized_volatility(length)
This function measures volatility over most recent close prices. Its the standard deviation of close over the past 'n' periods, times the square root of the number of periods in a year.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
AlgebraLibLibrary "AlgebraLib"
f_signaldraw(_side, _date)
: Draw a simple label with Buy or Sell signal
Parameters:
_side (string)
_date (int)
Returns: : VOID, it draws a new label
KernelFunctionsFiltersLibrary "KernelFunctionsFilters"
This library provides filters for non-repainting kernel functions for Nadaraya-Watson estimator implementations made by @jdehorty. Filters include a smoothing formula and zero lag formula. You can find examples in the code. For more information check out the original library KernelFunctions.
rationalQuadratic(_src, _lookback, _relativeWeight, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
_relativeWeight (simple float)
startAtBar (simple int)
_filter (simple string)
gaussian(_src, _lookback, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
startAtBar (simple int)
_filter (simple string)
periodic(_src, _lookback, _period, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
_period (simple int)
startAtBar (simple int)
_filter (simple string)
locallyPeriodic(_src, _lookback, _period, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
_period (simple int)
startAtBar (simple int)
_filter (simple string)
j(line1, line2)
Parameters:
line1 (float)
line2 (float)
Position_controlLibrary "Position_control"
This is a library for defining positions and working with them.
f_calculateLeverage(_Leverage, _maintenance, _value, _direction)
Calculate the leverage used in a trade.
@description This function calculates the leverage used in a trade, based on the value of the trade, the maintenance margin, and the direction of the trade.
Parameters:
_Leverage (float) : The leverage used in the trade, as a floating point number.
_maintenance (float) : The maintenance margin percentage, as a floating point number.
_value (float) : The value of the trade, as a floating point number.
_direction (string) : The direction of the trade, either "long" or "short".
Returns: The leverage used in the trade, as a floating point number.
f_calculate_PL(_Position, _max_TP, _Position_index, _show_profit, _i_decimals_contracts, _i_decimals_prercent)
Calculate the profit or loss for a given trade.
@description This function calculates the profit or loss for a given trade, based on the position type, maximum take profit, position index, and whether to show the profit as a percentage or a value.
Parameters:
_Position (t_Position_type ) : An array of position types for the trade.
_max_TP (int) : The maximum take profit for the trade, as an integer value.
_Position_index (int) : The index of the position in the array, as an integer value.
_show_profit (bool) : A boolean value indicating whether to show the profit as a percentage or a value.
_i_decimals_contracts (int)
_i_decimals_prercent (int)
Returns: The profit or loss for the trade, as a floating point number.
f_drawposition(_Position, _Parameters, _Position_index)
draws a position on the chart
@description via sending in a typo of Position this function is able to drawout Stoploss, Entrybox, Takeprofits and the required labels with information
Parameters:
_Position (t_Position_type ) : array of type t_Position_type containing the position information.
_Parameters (t_drawing_parameters)
_Position_index (int) : the index of the current position.
Returns: None but boxes / lines / labels on the chart itself
t_TP_Variant
Fields:
TP_Type (series__string)
TP_Parameter_1 (series__integer)
TP_Parameter_2 (series__integer)
TP_Parameter_3 (series__float)
TP_Parameter_4 (series__float)
t_TPs
Fields:
TP_Price (series__float)
TP_Lot (series__float)
TP_Variant (|t_TP_Variant|#OBJ)
TP_Active (series__bool)
t_SLs
Fields:
SL_Price (series__float)
SL_Lot (series__float)
SL_Active (series__bool)
t_Position_type
Fields:
Lot (series__float)
Leverage (series__float)
Maintenance (series__float)
Starttime (series__integer)
Entry_Start (series__float)
Stoptime (series__integer)
Entry_Stop (series__float)
Entryprice (series__float)
TPs (array__|t_TPs|#OBJ)
SLs (array__|t_SLs|#OBJ)
t_drawing_parameters
Fields:
ShowPos (series__bool)
ShowLIQ (series__bool)
A_Colors (array__color)
Prolong_lines (series__bool)
Str_fontsize (series__string)
Textshift (series__integer)
Decimals_contracts (series__integer)
Decimals_price (series__integer)
Decimals_percent (series__integer)
bartime (series__integer)
Metrics using Alternative Portfolio TheoryLibrary "APT_Metrics"
Portfolio metrics using alternative portfolio theory
metrics(init, cur, start, end, alpha)
Calculates APT metrics
Parameters:
init (float) : Starting Equity (strategy.initial)
cur (float)
start (int) : Start date (UNIX)
end (int) : End Date (UNIX)
alpha (float) : Confidence interval for DaR/CDaR. Defval = 0.05
Returns: Plots table with APT metrics
The metrics are shown in the bottom pane being applied to a buy-and-hold strategy.
PLEASE NOTE: This is the first draft of the library. Some calculations may be incorrect. If you spot any mistakes then please let me know and I will correct them as soon as possible. I am also open to suggestions on how to improve this.
At the moment this only works on the daily timeframe until I can find a way to universally calculate annualized volatility.
BenfordsLawLibrary "BenfordsLaw"
Methods to deal with Benford's law which states that a distribution of first and higher order digits
of numerical strings has a characteristic pattern.
"Benford's law is an observation about the leading digits of the numbers found in real-world data sets.
Intuitively, one might expect that the leading digits of these numbers would be uniformly distributed so that
each of the digits from 1 to 9 is equally likely to appear. In fact, it is often the case that 1 occurs more
frequently than 2, 2 more frequently than 3, and so on. This observation is a simplified version of Benford's law.
More precisely, the law gives a prediction of the frequency of leading digits using base-10 logarithms that
predicts specific frequencies which decrease as the digits increase from 1 to 9." ~(2)
---
reference:
- 1: en.wikipedia.org
- 2: brilliant.org
- 4: github.com
cumsum_difference(a, b)
Calculate the cumulative sum difference of two arrays of same size.
Parameters:
a (float ) : `array` List of values.
b (float ) : `array` List of values.
Returns: List with CumSum Difference between arrays.
fractional_int(number)
Transform a floating number including its fractional part to integer form ex:. `1.2345 -> 12345`.
Parameters:
number (float) : `float` The number to transform.
Returns: Transformed number.
split_to_digits(number, reverse)
Transforms a integer number into a list of its digits.
Parameters:
number (int) : `int` Number to transform.
reverse (bool) : `bool` `default=true`, Reverse the order of the digits, if true, last will be first.
Returns: Transformed number digits list.
digit_in(number, digit)
Digit at index.
Parameters:
number (int) : `int` Number to parse.
digit (int) : `int` `default=0`, Index of digit.
Returns: Digit found at the index.
digits_from(data, dindex)
Process a list of `int` values and get the list of digits.
Parameters:
data (int ) : `array` List of numbers.
dindex (int) : `int` `default=0`, Index of digit.
Returns: List of digits at the index.
digit_counters(digits)
Score digits.
Parameters:
digits (int ) : `array` List of digits.
Returns: List of counters per digit (1-9).
digit_distribution(counters)
Calculates the frequency distribution based on counters provided.
Parameters:
counters (int ) : `array` List of counters, must have size(9).
Returns: Distribution of the frequency of the digits.
digit_p(digit)
Expected probability for digit according to Benford.
Parameters:
digit (int) : `int` Digit number reference in range `1 -> 9`.
Returns: Probability of digit according to Benford's law.
benfords_distribution()
Calculated Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
benfords_distribution_aprox()
Aproximate Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
test_benfords(digits, calculate_benfords)
Tests Benford's Law on provided list of digits.
Parameters:
digits (int ) : `array` List of digits.
calculate_benfords (bool)
Returns: Tuple with:
- Counters: Score of each digit.
- Sample distribution: Frequency for each digit.
- Expected distribution: Expected frequency according to Benford's.
- Cumulative Sum of difference:
to_table(digits, _text_color, _border_color, _frame_color)
Parameters:
digits (int )
_text_color (color)
_border_color (color)
_frame_color (color)
Uptrend Downtrend Loopback Candle Identification LibThis library is for identifying uptrends and downtrends using a loopback candle analysis method. Which contains two functions:
uptrendLoopbackCandleIdentification() and downtrendLoopbackCandleIdentification() . These functions check if the current candle is part of an uptrend or downtrend, respectively, based on the specified lookback period.
The uptrendLoopbackCandleIdentification() takes two arguments: index , which is the index of the current bar, and lookbackPeriod , which is the number of previous candles to check for an uptrend. The function returns false if the index is less than the lookback period. Otherwise, it initializes a boolean variable isHigherHigh as true and loops through the previous candles. If any of the previous candles have a higher high than the current candle, isHigherHigh is set to false , and the loop breaks. Finally, the function returns the value of isHigherHigh .
The downtrendLoopbackCandleIdentification() takes the same arguments and returns false if the index is less than the lookback period. The function initializes a boolean variable isHigherLow as true and loops through the previous candles. If any of the previous candles have a higher low than the current candle, isHigherLow is set to false , and the loop breaks. The function returns the value of isHigherLow .
MathEasingFunctionsLibrary "MathEasingFunctions"
A collection of Easing functions.
Easing functions are commonly used for smoothing actions over time, They are used to smooth out the sharp edges
of a function and make it more pleasing to the eye, like for example the motion of a object through time.
Easing functions can be used in a variety of applications, including animation, video games, and scientific
simulations. They are a powerful tool for creating realistic visual effects and can help to make your work more
engaging and enjoyable to the eye.
---
Includes functions for ease in, ease out, and, ease in and out, for the following constructs:
sine, quadratic, cubic, quartic, quintic, exponential, elastic, circle, back, bounce.
---
Reference:
easings.net
learn.microsoft.com
ease_in_sine_unbound(v)
Sinusoidal function, the position over elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_sine(v)
Sinusoidal function, the position over elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_sine_unbound(v)
Sinusoidal function, the position over elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_sine(v)
Sinusoidal function, the position over elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_sine_unbound(v)
Sinusoidal function, the position over elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_sine(v)
Sinusoidal function, the position over elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quad_unbound(v)
Quadratic function, the position equals the square of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quad(v)
Quadratic function, the position equals the square of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quad_unbound(v)
Quadratic function, the position equals the square of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quad(v)
Quadratic function, the position equals the square of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quad_unbound(v)
Quadratic function, the position equals the square of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quad(v)
Quadratic function, the position equals the square of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_cubic_unbound(v)
Cubic function, the position equals the cube of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_cubic(v)
Cubic function, the position equals the cube of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_cubic_unbound(v)
Cubic function, the position equals the cube of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_cubic(v)
Cubic function, the position equals the cube of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_cubic_unbound(v)
Cubic function, the position equals the cube of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_cubic(v)
Cubic function, the position equals the cube of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quart_unbound(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quart(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quart_unbound(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quart(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quart_unbound(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quart(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quint_unbound(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quint(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quint_unbound(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quint(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quint_unbound(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quint(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_expo_unbound(v)
Exponential function, the position equals the exponential formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_expo(v)
Exponential function, the position equals the exponential formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_expo_unbound(v)
Exponential function, the position equals the exponential formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_expo(v)
Exponential function, the position equals the exponential formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_expo_unbound(v)
Exponential function, the position equals the exponential formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_expo(v)
Exponential function, the position equals the exponential formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_circ_unbound(v)
Circular function, the position equals the circular formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_circ(v)
Circular function, the position equals the circular formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_circ_unbound(v)
Circular function, the position equals the circular formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_circ(v)
Circular function, the position equals the circular formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_circ_unbound(v)
Circular function, the position equals the circular formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_circ(v)
Circular function, the position equals the circular formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_back_unbound(v)
Back function, the position retreats a bit before resuming (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_back(v)
Back function, the position retreats a bit before resuming (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_back_unbound(v)
Back function, the position retreats a bit before resuming (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_back(v)
Back function, the position retreats a bit before resuming (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_back_unbound(v)
Back function, the position retreats a bit before resuming (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_back(v)
Back function, the position retreats a bit before resuming (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_elastic_unbound(v)
Elastic function, the position oscilates back and forth like a spring (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_elastic(v)
Elastic function, the position oscilates back and forth like a spring (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_elastic_unbound(v)
Elastic function, the position oscilates back and forth like a spring (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_elastic(v)
Elastic function, the position oscilates back and forth like a spring (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_elastic_unbound(v)
Elastic function, the position oscilates back and forth like a spring (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_elastic(v)
Elastic function, the position oscilates back and forth like a spring (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_bounce_unbound(v)
Bounce function, the position bonces from the boundery (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_bounce(v)
Bounce function, the position bonces from the boundery (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_bounce_unbound(v)
Bounce function, the position bonces from the boundery (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_bounce(v)
Bounce function, the position bonces from the boundery (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_bounce_unbound(v)
Bounce function, the position bonces from the boundery (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_bounce(v)
Bounce function, the position bonces from the boundery (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
select(v, formula, effect, bounded)
Parameters:
v (float)
formula (string)
effect (string)
bounded (bool)
UtilityLibrary "Utility"
dema(src, length)
Parameters:
src (float)
length (simple int)
tema(src, length)
Parameters:
src (float)
length (simple int)
hma(src, length)
Parameters:
src (float)
length (int)
zlema(src, length)
Parameters:
src (float)
length (simple int)
stochRSI(src, lengthRSI, lengthStoch, smoothK, smoothD)
Parameters:
src (float)
lengthRSI (simple int)
lengthStoch (int)
smoothK (int)
smoothD (int)
slope(src, length)
Parameters:
src (float)
length (int)
loxxfftLibrary "loxxfft"
This code is a library for performing Fast Fourier Transform (FFT) operations. FFT is an algorithm that can quickly compute the discrete Fourier transform (DFT) of a sequence. The library includes functions for performing FFTs on both real and complex data. It also includes functions for fast correlation and convolution, which are operations that can be performed efficiently using FFTs. Additionally, the library includes functions for fast sine and cosine transforms.
Reference:
www.alglib.net
fastfouriertransform(a, nn, inversefft)
Returns Fast Fourier Transform
Parameters:
a (float ) : float , An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices.
nn (int) : int, The number of function values. It must be a power of two, but the algorithm does not validate this.
inversefft (bool) : bool, A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT.
Returns: float , Modifies the input array a in-place, which means that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution. The transformed data will have real and imaginary parts interleaved, with the real parts at even indices and the imaginary parts at odd indices.
realfastfouriertransform(a, tnn, inversefft)
Returns Real Fast Fourier Transform
Parameters:
a (float ) : float , A float array containing the real-valued function samples.
tnn (int) : int, The number of function values (must be a power of 2, but the algorithm does not validate this condition).
inversefft (bool) : bool, A boolean flag that indicates the direction of the transformation (True for inverse, False for direct).
Returns: float , Modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution.
fastsinetransform(a, tnn, inversefst)
Returns Fast Discrete Sine Conversion
Parameters:
a (float ) : float , An array of real numbers representing the function values.
tnn (int) : int, Number of function values (must be a power of two, but the code doesn't validate this).
inversefst (bool) : bool, A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST.
Returns: float , The output is the transformed array 'a', which will contain the result of the transformation.
fastcosinetransform(a, tnn, inversefct)
Returns Fast Discrete Cosine Transform
Parameters:
a (float ) : float , This is a floating-point array representing the sequence of values (time-domain) that you want to transform. The function will perform the Fast Cosine Transform (FCT) or the inverse FCT on this input array, depending on the value of the inversefct parameter. The transformed result will also be stored in this same array, which means the function modifies the input array in-place.
tnn (int) : int, This is an integer value representing the number of data points in the input array a. It is used to determine the size of the input array and control the loops in the algorithm. Note that the size of the input array should be a power of 2 for the Fast Cosine Transform algorithm to work correctly.
inversefct (bool) : bool, This is a boolean value that controls whether the function performs the regular Fast Cosine Transform or the inverse FCT. If inversefct is set to true, the function will perform the inverse FCT, and if set to false, the regular FCT will be performed. The inverse FCT can be used to transform data back into its original form (time-domain) after the regular FCT has been applied.
Returns: float , The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array.
fastconvolution(signal, signallen, response, negativelen, positivelen)
Convolution using FFT
Parameters:
signal (float ) : float , This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1.
signallen (int) : int, This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array.
response (float ) : float , This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively.
negativelen (int) : int, This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range , the response function is considered zero.
positivelen (int) : int, This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range , the response function is considered zero.
Returns: float , The resulting convolved values are stored back in the input signal array.
fastcorrelation(signal, signallen, pattern, patternlen)
Returns Correlation using FFT
Parameters:
signal (float ) : float ,This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1.
signallen (int) : int, This is an integer representing the length of the input signal array.
pattern (float ) : float , This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1.
patternlen (int) : int, This is an integer representing the length of the pattern array.
Returns: float , The signal array containing the correlation values at points from 0 to SignalLen-1.
tworealffts(a1, a2, a, b, tn)
Returns Fast Fourier Transform of Two Real Functions
Parameters:
a1 (float ) : float , An array of real numbers, representing the values of the first function.
a2 (float ) : float , An array of real numbers, representing the values of the second function.
a (float ) : float , An output array to store the Fourier transform of the first function.
b (float ) : float , An output array to store the Fourier transform of the second function.
tn (int) : float , An integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition.
Returns: float , The a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b.
█ Detailed explaination of each function
Fast Fourier Transform
The fastfouriertransform() function takes three input parameters:
1. a: An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices.
2. nn: The number of function values. It must be a power of two, but the algorithm does not validate this.
3. inversefft: A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT.
The function performs the FFT using the Cooley-Tukey algorithm, which is an efficient algorithm for computing the discrete Fourier transform (DFT) and its inverse. The Cooley-Tukey algorithm recursively breaks down the DFT of a sequence into smaller DFTs of subsequences, leading to a significant reduction in computational complexity. The algorithm's time complexity is O(n log n), where n is the number of samples.
The fastfouriertransform() function first initializes variables and determines the direction of the transformation based on the inversefft parameter. If inversefft is True, the isign variable is set to -1; otherwise, it is set to 1.
Next, the function performs the bit-reversal operation. This is a necessary step before calculating the FFT, as it rearranges the input data in a specific order required by the Cooley-Tukey algorithm. The bit-reversal is performed using a loop that iterates through the nn samples, swapping the data elements according to their bit-reversed index.
After the bit-reversal operation, the function iteratively computes the FFT using the Cooley-Tukey algorithm. It performs calculations in a loop that goes through different stages, doubling the size of the sub-FFT at each stage. Within each stage, the Cooley-Tukey algorithm calculates the butterfly operations, which are mathematical operations that combine the results of smaller DFTs into the final DFT. The butterfly operations involve complex number multiplication and addition, updating the input array a with the computed values.
The loop also calculates the twiddle factors, which are complex exponential factors used in the butterfly operations. The twiddle factors are calculated using trigonometric functions, such as sine and cosine, based on the angle theta. The variables wpr, wpi, wr, and wi are used to store intermediate values of the twiddle factors, which are updated in each iteration of the loop.
Finally, if the inversefft parameter is True, the function divides the result by the number of samples nn to obtain the correct inverse FFT result. This normalization step is performed using a loop that iterates through the array a and divides each element by nn.
In summary, the fastfouriertransform() function is an implementation of the Cooley-Tukey FFT algorithm, which is an efficient algorithm for computing the DFT and its inverse. This FFT library can be used for a variety of applications, such as signal processing, image processing, audio processing, and more.
Feal Fast Fourier Transform
The realfastfouriertransform() function performs a fast Fourier transform (FFT) specifically for real-valued functions. The FFT is an efficient algorithm used to compute the discrete Fourier transform (DFT) and its inverse, which are fundamental tools in signal processing, image processing, and other related fields.
This function takes three input parameters:
1. a - A float array containing the real-valued function samples.
2. tnn - The number of function values (must be a power of 2, but the algorithm does not validate this condition).
3. inversefft - A boolean flag that indicates the direction of the transformation (True for inverse, False for direct).
The function modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution.
The algorithm uses a combination of complex-to-complex FFT and additional transformations specific to real-valued data to optimize the computation. It takes into account the symmetry properties of the real-valued input data to reduce the computational complexity.
Here's a detailed walkthrough of the algorithm:
1. Depending on the inversefft flag, the initial values for ttheta, c1, and c2 are determined. These values are used for the initial data preprocessing and post-processing steps specific to the real-valued FFT.
2. The preprocessing step computes the initial real and imaginary parts of the data using a combination of sine and cosine terms with the input data. This step effectively converts the real-valued input data into complex-valued data suitable for the complex-to-complex FFT.
3. The complex-to-complex FFT is then performed on the preprocessed complex data. This involves bit-reversal reordering, followed by the Cooley-Tukey radix-2 decimation-in-time algorithm. This part of the code is similar to the fastfouriertransform() function you provided earlier.
4. After the complex-to-complex FFT, a post-processing step is performed to obtain the final real-valued output data. This involves updating the real and imaginary parts of the transformed data using sine and cosine terms, as well as the values c1 and c2.
5. Finally, if the inversefft flag is True, the output data is divided by the number of samples (nn) to obtain the inverse DFT.
The function does not return a value explicitly. Instead, the transformed data is stored in the input array a. After the function execution, you can access the transformed data in the a array, which will have the real part at even indices and the imaginary part at odd indices.
Fast Sine Transform
This code defines a function called fastsinetransform that performs a Fast Discrete Sine Transform (FST) on an array of real numbers. The function takes three input parameters:
1. a (float array): An array of real numbers representing the function values.
2. tnn (int): Number of function values (must be a power of two, but the code doesn't validate this).
3. inversefst (bool): A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST.
The output is the transformed array 'a', which will contain the result of the transformation.
The code starts by initializing several variables, including trigonometric constants for the sine transform. It then sets the first value of the array 'a' to 0 and calculates the initial values of 'y1' and 'y2', which are used to update the input array 'a' in the following loop.
The first loop (with index 'jx') iterates from 2 to (tm + 1), where 'tm' is half of the number of input samples 'tnn'. This loop is responsible for calculating the initial sine transform of the input data.
The second loop (with index 'ii') is a bit-reversal loop. It reorders the elements in the array 'a' based on the bit-reversed indices of the original order.
The third loop (with index 'ii') iterates while 'n' is greater than 'mmax', which starts at 2 and doubles each iteration. This loop performs the actual Fast Discrete Sine Transform. It calculates the sine transform using the Danielson-Lanczos lemma, which is a divide-and-conquer strategy for calculating Discrete Fourier Transforms (DFTs) efficiently.
The fourth loop (with index 'ix') is responsible for the final phase adjustments needed for the sine transform, updating the array 'a' accordingly.
The fifth loop (with index 'jj') updates the array 'a' one more time by dividing each element by 2 and calculating the sum of the even-indexed elements.
Finally, if the 'inversefst' flag is True, the code scales the transformed data by a factor of 2/tnn to get the inverse Fast Sine Transform.
In summary, the code performs a Fast Discrete Sine Transform on an input array of real numbers, either in the direct or inverse direction, and returns the transformed array. The algorithm is based on the Danielson-Lanczos lemma and uses a divide-and-conquer strategy for efficient computation.
Fast Cosine Transform
This code defines a function called fastcosinetransform that takes three parameters: a floating-point array a, an integer tnn, and a boolean inversefct. The function calculates the Fast Cosine Transform (FCT) or the inverse FCT of the input array, depending on the value of the inversefct parameter.
The Fast Cosine Transform is an algorithm that converts a sequence of values (time-domain) into a frequency domain representation. It is closely related to the Fast Fourier Transform (FFT) and can be used in various applications, such as signal processing and image compression.
Here's a detailed explanation of the code:
1. The function starts by initializing a number of variables, including counters, intermediate values, and constants.
2. The initial steps of the algorithm are performed. This includes calculating some trigonometric values and updating the input array a with the help of intermediate variables.
3. The code then enters a loop (from jx = 2 to tnn / 2). Within this loop, the algorithm computes and updates the elements of the input array a.
4. After the loop, the function prepares some variables for the next stage of the algorithm.
5. The next part of the algorithm is a series of nested loops that perform the bit-reversal permutation and apply the FCT to the input array a.
6. The code then calculates some additional trigonometric values, which are used in the next loop.
7. The following loop (from ix = 2 to tnn / 4 + 1) computes and updates the elements of the input array a using the previously calculated trigonometric values.
8. The input array a is further updated with the final calculations.
9. In the last loop (from j = 4 to tnn), the algorithm computes and updates the sum of elements in the input array a.
10. Finally, if the inversefct parameter is set to true, the function scales the input array a to obtain the inverse FCT.
The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array.
Fast Convolution
This code defines a function called fastconvolution that performs the convolution of a given signal with a response function using the Fast Fourier Transform (FFT) technique. Convolution is a mathematical operation used in signal processing to combine two signals, producing a third signal representing how the shape of one signal is modified by the other.
The fastconvolution function takes the following input parameters:
1. float signal: This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1.
2. int signallen: This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array.
3. float response: This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively.
4. int negativelen: This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range , the response function is considered zero.
5. int positivelen: This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range , the response function is considered zero.
The function works by:
1. Calculating the length nl of the arrays used for FFT, ensuring it's a power of 2 and large enough to hold the signal and response.
2. Creating two new arrays, a1 and a2, of length nl and initializing them with the input signal and response function, respectively.
3. Applying the forward FFT (realfastfouriertransform) to both arrays, a1 and a2.
4. Performing element-wise multiplication of the FFT results in the frequency domain.
5. Applying the inverse FFT (realfastfouriertransform) to the multiplied results in a1.
6. Updating the original signal array with the convolution result, which is stored in the a1 array.
The result of the convolution is stored in the input signal array at the function exit.
Fast Correlation
This code defines a function called fastcorrelation that computes the correlation between a signal and a pattern using the Fast Fourier Transform (FFT) method. The function takes four input arguments and modifies the input signal array to store the correlation values.
Input arguments:
1. float signal: This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1.
2. int signallen: This is an integer representing the length of the input signal array.
3. float pattern: This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1.
4. int patternlen: This is an integer representing the length of the pattern array.
The function performs the following steps:
1. Calculate the required size nl for the FFT by finding the smallest power of 2 that is greater than or equal to the sum of the lengths of the signal and the pattern.
2. Create two new arrays a1 and a2 with the length nl and initialize them to 0.
3. Copy the signal array into a1 and pad it with zeros up to the length nl.
4. Copy the pattern array into a2 and pad it with zeros up to the length nl.
5. Compute the FFT of both a1 and a2.
6. Perform element-wise multiplication of the frequency-domain representation of a1 and the complex conjugate of the frequency-domain representation of a2.
7. Compute the inverse FFT of the result obtained in step 6.
8. Store the resulting correlation values in the original signal array.
At the end of the function, the signal array contains the correlation values at points from 0 to SignalLen-1.
Fast Fourier Transform of Two Real Functions
This code defines a function called tworealffts that computes the Fast Fourier Transform (FFT) of two real-valued functions (a1 and a2) using a Cooley-Tukey-based radix-2 Decimation in Time (DIT) algorithm. The FFT is a widely used algorithm for computing the discrete Fourier transform (DFT) and its inverse.
Input parameters:
1. float a1: an array of real numbers, representing the values of the first function.
2. float a2: an array of real numbers, representing the values of the second function.
3. float a: an output array to store the Fourier transform of the first function.
4. float b: an output array to store the Fourier transform of the second function.
5. int tn: an integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition.
The function performs the following steps:
1. Combine the two input arrays, a1 and a2, into a single array a by interleaving their elements.
2. Perform a 1D FFT on the combined array a using the radix-2 DIT algorithm.
3. Separate the FFT results of the two input functions from the combined array a and store them in output arrays a and b.
Here is a detailed breakdown of the radix-2 DIT algorithm used in this code:
1. Bit-reverse the order of the elements in the combined array a.
2. Initialize the loop variables mmax, istep, and theta.
3. Enter the main loop that iterates through different stages of the FFT.
a. Compute the sine and cosine values for the current stage using the theta variable.
b. Initialize the loop variables wr and wi for the current stage.
c. Enter the inner loop that iterates through the butterfly operations within each stage.
i. Perform the butterfly operation on the elements of array a.
ii. Update the loop variables wr and wi for the next butterfly operation.
d. Update the loop variables mmax, istep, and theta for the next stage.
4. Separate the FFT results of the two input functions from the combined array a and store them in output arrays a and b.
At the end of the function, the a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b.
█ Example scripts using functions contained in loxxfft
Real-Fast Fourier Transform of Price w/ Linear Regression
Real-Fast Fourier Transform of Price Oscillator
Normalized, Variety, Fast Fourier Transform Explorer
Variety RSI of Fast Discrete Cosine Transform
STD-Stepped Fast Cosine Transform Moving Average
HarmonicPatternTrackingLibrary "HarmonicPatternTracking"
Library contains few data structures and methods for tracking harmonic pattern trades via pinescript.
method draw(this)
Creates and draws HarmonicDrawing object for given HarmonicPattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: current HarmonicPattern object
method addTrade(this)
calculates HarmonicTrade and sets trade object for HarmonicPattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: bool true if pattern trades are valid, false otherwise
method delete(this)
Deletes drawing objects of HarmonicDrawing
Namespace types: HarmonicDrawing
Parameters:
this (HarmonicDrawing) : HarmonicDrawing object
Returns: current HarmonicDrawing object
method delete(this)
Deletes drawings of harmonic pattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: current HarmonicPattern object
HarmonicDrawing
Drawing objects of Harmonic Pattern
Fields:
xa (series line) : xa line
ab (series line) : ab line
bc (series line) : bc line
cd (series line) : cd line
xb (series line) : xb line
bd (series line) : bd line
ac (series line) : ac line
xd (series line) : xd line
x (series label) : label for pivot x
a (series label) : label for pivot a
b (series label) : label for pivot b
c (series label) : label for pivot c
d (series label) : label for pivot d
xabRatio (series label) : label for XAB Ratio
abcRatio (series label) : label for ABC Ratio
bcdRatio (series label) : label for BCD Ratio
xadRatio (series label) : label for XAD Ratio
HarmonicTrade
Trade tracking parameters of Harmonic Patterns
Fields:
initialEntry (series float) : initial entry when pattern first formed.
entry (series float) : trailed entry price.
initialStop (series float) : initial stop when trade first entered.
stop (series float) : current stop updated as per trailing rules.
target1 (series float) : First target value
target2 (series float) : Second target value
target3 (series float) : Third target value
target4 (series float) : Fourth target value
status (series int) : Trade status referenced as integer
retouch (series bool) : Flag to show if the price retouched after entry
HarmonicProperties
Display and trade calculation properties for Harmonic Patterns
Fields:
fillMajorTriangles (series bool) : Display property used for using linefill for harmonic major triangles
fillMinorTriangles (series bool) : Display property used for using linefill for harmonic minor triangles
majorFillTransparency (series int) : transparency setting for major triangles
minorFillTransparency (series int) : transparency setting for minor triangles
showXABCD (series bool) : Display XABCD pivot labels
lblSizePivots (series string) : Pivot label size
showRatios (series bool) : Display Ratio labels
useLogScaleForScan (series bool) : Use log scale to determine fib ratios for pattern scanning
useLogScaleForTargets (series bool) : Use log scale to determine fib ratios for target calculation
base (series string) : base on which calculation of stop/targets are made.
entryRatio (series float) : fib ratio to calculate entry
stopRatio (series float) : fib ratio to calculate initial stop
target1Ratio (series float) : fib ratio to calculate first target
target2Ratio (series float) : fib ratio to calculate second target
target3Ratio (series float) : fib ratio to calculate third target
target4Ratio (series float) : fib ratio to calculate fourth target
HarmonicPattern
Harmonic pattern object to track entire pattern trade life cycle
Fields:
id (series int) : Pattern Id
dir (series int) : pattern direction
x (series float) : X Pivot
a (series float) : A Pivot
b (series float) : B Pivot
c (series float) : C Pivot
d (series float) : D Pivot
xBar (series int) : Bar index of X Pivot
aBar (series int) : Bar index of A Pivot
bBar (series int) : Bar index of B Pivot
cBar (series int) : Bar index of C Pivot
dBar (series int) : Bar index of D Pivot
przStart (series float) : Start of PRZ range
przEnd (series float) : End of PRZ range
patterns (bool ) : array representing the patterns
patternLabel (series string) : string representation of list of patterns
patternColor (series color) : color assigned to pattern
properties (HarmonicProperties) : HarmonicProperties object containing display and calculation properties
trade (HarmonicTrade) : HarmonicTrade object to track trades
drawing (HarmonicDrawing) : HarmonicDrawing object to manage drawings
OHLC📕 LIBRARY OHLC
🔷 Introduction
This library is a custom library designed to work with real-time bars. It allows to easily calculate OHLC values for any source.
Personally, I use this library to accurately display the highest and lowest values on visual indicators such as my progress bars.
🔷 How to Use
◼ 1. Import the OHLC library into your TradingView script:
import cryptolinx/OHLC/1
- or -
Instead of the library namespace, you can define a custom namespace as alias.
import cryptolinx/OHLC/1 as src
◼ 2. Create a new OHLC source using the `new()` function.
varip mySrc = OHLC.new() // It is required to use the `varip` keyword to init your ``
- or -
If you has set up an alias before.
varip mySrc = src.new()
===
In that case, your `` needs to be `na`, define your object like that
varip mySrc = na
◼ 3. Call the `hydrateOHLC()` method on your OHLC source to update its values:
Basic
float rsi = ta.rsi(close, 14)
mySrc.hydrateOHLC(rsi)
- or -
Inline
rsi = ta.rsi(close, 14).hydrateOHLC(mySrc)
◼ 4. The data is accessible under their corresponding names.
mySrc.open
mySrc.high
mySrc.low
mySrc.close
🔷 Note: This library only works with real-time bars and will not work with historical bars.
MarkovChainLibrary "MarkovChain"
Generic Markov Chain type functions.
---
A Markov chain or Markov process is a stochastic model describing a sequence of possible events in which the
probability of each event depends only on the state attained in the previous event.
---
reference:
Understanding Markov Chains, Examples and Applications. Second Edition. Book by Nicolas Privault.
en.wikipedia.org
www.geeksforgeeks.org
towardsdatascience.com
github.com
stats.stackexchange.com
timeseriesreasoning.com
www.ris-ai.com
github.com
gist.github.com
github.com
gist.github.com
writings.stephenwolfram.com
kevingal.com
towardsdatascience.com
spedygiorgio.github.io
github.com
www.projectrhea.org
method to_string(this)
Translate a Markov Chain object to a string format.
Namespace types: MC
Parameters:
this (MC) : `MC` . Markov Chain object.
Returns: string
method to_table(this, position, text_color, text_size)
Namespace types: MC
Parameters:
this (MC)
position (string)
text_color (color)
text_size (string)
method create_transition_matrix(this)
Namespace types: MC
Parameters:
this (MC)
method generate_transition_matrix(this)
Namespace types: MC
Parameters:
this (MC)
new_chain(states, name)
Parameters:
states (state )
name (string)
from_data(data, name)
Parameters:
data (string )
name (string)
method probability_at_step(this, target_step)
Namespace types: MC
Parameters:
this (MC)
target_step (int)
method state_at_step(this, start_state, target_state, target_step)
Namespace types: MC
Parameters:
this (MC)
start_state (int)
target_state (int)
target_step (int)
method forward(this, obs)
Namespace types: HMC
Parameters:
this (HMC)
obs (int )
method backward(this, obs)
Namespace types: HMC
Parameters:
this (HMC)
obs (int )
method viterbi(this, observations)
Namespace types: HMC
Parameters:
this (HMC)
observations (int )
method baumwelch(this, observations)
Namespace types: HMC
Parameters:
this (HMC)
observations (int )
Node
Target node.
Fields:
index (series int) : . Key index of the node.
probability (series float) : . Probability rate of activation.
state
State reference.
Fields:
name (series string) : . Name of the state.
index (series int) : . Key index of the state.
target_nodes (Node ) : . List of index references and probabilities to target states.
MC
Markov Chain reference object.
Fields:
name (series string) : . Name of the chain.
states (state ) : . List of state nodes and its name, index, targets and transition probabilities.
size (series int) : . Number of unique states
transitions (matrix) : . Transition matrix
HMC
Hidden Markov Chain reference object.
Fields:
name (series string) : . Name of thehidden chain.
states_hidden (state ) : . List of state nodes and its name, index, targets and transition probabilities.
states_obs (state ) : . List of state nodes and its name, index, targets and transition probabilities.
transitions (matrix) : . Transition matrix
emissions (matrix) : . Emission matrix
initial_distribution (float )
FunctionProbabilityViterbiLibrary "FunctionProbabilityViterbi"
The Viterbi Algorithm calculates the most likely sequence of hidden states *(called Viterbi path)*
that results in a sequence of observed events.
viterbi(observations, transitions, emissions, initial_distribution)
Calculate most probable path in a Markov model.
Parameters:
observations (int ) : array . Observation states data.
transitions (matrix) : matrix . Transition probability table, (HxH, H:Hidden states).
emissions (matrix) : matrix . Emission probability table, (OxH, O:Observed states).
initial_distribution (float ) : array . Initial probability distribution for the hidden states.
Returns: array. Most probable path.
FunctionBaumWelchLibrary "FunctionBaumWelch"
Baum-Welch Algorithm, also known as Forward-Backward Algorithm, uses the well known EM algorithm
to find the maximum likelihood estimate of the parameters of a hidden Markov model given a set of observed
feature vectors.
---
### Function List:
> `forward (array pi, matrix a, matrix b, array obs)`
> `forward (array pi, matrix a, matrix b, array obs, bool scaling)`
> `backward (matrix a, matrix b, array obs)`
> `backward (matrix a, matrix b, array obs, array c)`
> `baumwelch (array observations, int nstates)`
> `baumwelch (array observations, array pi, matrix a, matrix b)`
---
### Reference:
> en.wikipedia.org
> github.com
> en.wikipedia.org
> www.rdocumentation.org
> www.rdocumentation.org
forward(pi, a, b, obs)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
Returns: - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
forward(pi, a, b, obs, scaling)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
scaling (bool) : Normalize `alpha` scale.
Returns: - #### Tuple with:
> - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
> - `array _c`: Array with normalization scale.
backward(a, b, obs)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
backward(a, b, obs, c)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
c (float ) : Array with Normalization scaling coefficients.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
baumwelch(observations, nstates)
**(Random Initialization)** Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
nstates (int)
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`
baumwelch(observations, pi, a, b)
Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
pi (float ) : Initial probaility distribution.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`
MyLibraryLibrary "MyLibrary"
TODO: add library description here
fun(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
Commission-aware Trade LabelsCommission-aware Trade Labels
Description:
This library provides an easy way to visualize take-profit and stop-loss levels on your chart, taking into account trading commissions. The library calculates and displays the net profit or loss, along with other useful information such as risk/reward ratio, shares, and position size.
Features:
Configurable take-profit and stop-loss prices or percentages.
Set entry amount or shares.
Calculates and displays the risk/reward ratio.
Shows net profit or loss, considering trading commissions.
Customizable label appearance.
Usage:
Add the script to your chart.
Create an Order object for take-profit and stop-loss with desired configurations.
Call target_label() and stop_label() methods for each order object.
Example:
target_order = Order.new(take_profit_price=27483, stop_loss_price=28000, shares=0.2)
stop_order = Order.new(stop_loss_price=29000, shares=1)
target_order.target_label()
stop_order.stop_label()
This script is a powerful tool for visualizing your trading strategy's performance and helps you make better-informed decisions by considering trading commissions in your profit and loss calculations.
Library "tradelabels"
entry_price(this)
Parameters:
this : Order object
@return entry_price
take_profit_price(this)
Parameters:
this : Order object
@return take_profit_price
stop_loss_price(this)
Parameters:
this : Order object
@return stop_loss_price
is_long(this)
Parameters:
this : Order object
@return entry_price
is_short(this)
Parameters:
this : Order object
@return entry_price
percent_to_target(this, target)
Parameters:
this : Order object
target : Target price
@return percent
risk_reward(this)
Parameters:
this : Order object
@return risk_reward_ratio
shares(this)
Parameters:
this : Order object
@return shares
position_size(this)
Parameters:
this : Order object
@return position_size
commission_cost(this, target_price)
Parameters:
this : Order object
@return commission_cost
target_price
net_result(this, target_price)
Parameters:
this : Order object
target_price : The target price to calculate net result for (either take_profit_price or stop_loss_price)
@return net_result
create_take_profit_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_stop_loss_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_entry_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_line(this, target_price, line_color, offset_x, line_style, line_width, draw_entry_line)
Parameters:
this
target_price
line_color
offset_x
line_style
line_width
draw_entry_line
Order
Order
Fields:
entry_price : Entry price
stop_loss_price : Stop loss price
stop_loss_percent : Stop loss percent, default 2%
take_profit_price : Take profit price
take_profit_percent : Take profit percent, default 6%
entry_amount : Entry amount, default 5000$
shares : Shares
commission : Commission, default 0.04%
Bitwise, Encode, DecodeLibrary "Bitwise, Encode, Decode"
Bitwise, Encode, Decode, and more Library
docs()
Hover-Over Documentation for inside Text Editor
bAnd(a, b)
Returns the bitwise AND of two integers
Parameters:
a : `int` - The first integer
b : `int` - The second integer
Returns: `int` - The bitwise AND of the two integers
bOr(a, b)
Performs a bitwise OR operation on two integers.
Parameters:
a : `int` - The first integer.
b : `int` - The second integer.
Returns: `int` - The result of the bitwise OR operation.
bXor(a, b)
Performs a bitwise Xor operation on two integers.
Parameters:
a : `int` - The first integer.
b : `int` - The second integer.
Returns: `int` - The result of the bitwise Xor operation.
bNot(n)
Performs a bitwise NOT operation on an integer.
Parameters:
n : `int` - The integer to perform the bitwise NOT operation on.
Returns: `int` - The result of the bitwise NOT operation.
bShiftLeft(n, step)
Performs a bitwise left shift operation on an integer.
Parameters:
n : `int` - The integer to perform the bitwise left shift operation on.
step : `int` - The number of positions to shift the bits to the left.
Returns: `int` - The result of the bitwise left shift operation.
bShiftRight(n, step)
Performs a bitwise right shift operation on an integer.
Parameters:
n : `int` - The integer to perform the bitwise right shift operation on.
step : `int` - The number of bits to shift by.
Returns: `int` - The result of the bitwise right shift operation.
bRotateLeft(n, step)
Performs a bitwise right shift operation on an integer.
Parameters:
n : `int` - The int to perform the bitwise Left rotation on the bits.
step : `int` - The number of bits to shift by.
Returns: `int`- The result of the bitwise right shift operation.
bRotateRight(n, step)
Performs a bitwise right shift operation on an integer.
Parameters:
n : `int` - The int to perform the bitwise Right rotation on the bits.
step : `int` - The number of bits to shift by.
Returns: `int` - The result of the bitwise right shift operation.
bSetCheck(n, pos)
Checks if the bit at the given position is set to 1.
Parameters:
n : `int` - The integer to check.
pos : `int` - The position of the bit to check.
Returns: `bool` - True if the bit is set to 1, False otherwise.
bClear(n, pos)
Clears a particular bit of an integer (changes from 1 to 0) passes if bit at pos is 0.
Parameters:
n : `int` - The integer to clear a bit from.
pos : `int` - The zero-based index of the bit to clear.
Returns: `int` - The result of clearing the specified bit.
bFlip0s(n)
Flips all 0 bits in the number to 1.
Parameters:
n : `int` - The integer to flip the bits of.
Returns: `int` - The result of flipping all 0 bits in the number.
bFlip1s(n)
Flips all 1 bits in the number to 0.
Parameters:
n : `int` - The integer to flip the bits of.
Returns: `int` - The result of flipping all 1 bits in the number.
bFlipAll(n)
Flips all bits in the number.
Parameters:
n : `int` - The integer to flip the bits of.
Returns: `int` - The result of flipping all bits in the number.
bSet(n, pos, newBit)
Changes the value of the bit at the given position.
Parameters:
n : `int` - The integer to modify.
pos : `int` - The position of the bit to change.
newBit : `int` - na = flips bit at pos reguardless 1 or 0 | The new value of the bit (0 or 1).
Returns: `int` - The modified integer.
changeDigit(n, pos, newDigit)
Changes the value of the digit at the given position.
Parameters:
n : `int` - The integer to modify.
pos : `int` - The position of the digit to change.
newDigit : `int` - The new value of the digit (0-9).
Returns: `int` - The modified integer.
bSwap(n, i, j)
Switch the position of 2 bits of an int
Parameters:
n : `int` - int to manipulate
i : `int` - bit pos to switch with j
j : `int` - bit pos to switch with i
Returns: `int` - new int with bits switched
bPalindrome(n)
Checks to see if the binary form is a Palindrome (reads the same left to right and vice versa)
Parameters:
n : `int` - int to check
Returns: `bool` - result of check
bEven(n)
Checks if n is Even
Parameters:
n : `int` - The integer to check.
Returns: `bool` - result.
bOdd(n)
checks if n is Even if not even Odd
Parameters:
n : `int` - The integer to check.
Returns: `bool` - result.
bPowerOfTwo(n)
Checks if n is a Power of 2.
Parameters:
n : `int` - number to check.
Returns: `bool` - result.
bCount(n, to_count)
Counts the number of bits that are equal to 1 in an integer.
Parameters:
n : `int` - The integer to count the bits in.
to_count `string` - the bits to count
Returns: `int` - The number of bits that are equal to 1 in n.
GCD(a, b)
Finds the greatest common divisor (GCD) of two numbers.
Parameters:
a : `int` - The first number.
b : `int` - The second number.
Returns: `int` - The GCD of a and b.
LCM(a, b)
Finds the least common multiple (LCM) of two integers.
Parameters:
a : `int` - The first integer.
b : `int` - The second integer.
Returns: `int` - The LCM of a and b.
aLCM(nums)
Finds the LCM of an array of integers.
Parameters:
nums : `int ` - The list of integers.
Returns: `int` - The LCM of the integers in nums.
adjustedLCM(nums, LCM)
adjust an array of integers to Least Common Multiple (LCM)
Parameters:
nums : `int ` - The first integer
LCM : `int` - The second integer
Returns: `int ` - array of ints with LCM
charAt(str, pos)
gets a Char at a given position.
Parameters:
str : `string` - string to pull char from.
pos : `int` - pos to get char from string (left to right index).
Returns: `string` - char from pos of string or "" if pos is not within index range
decimalToBinary(num)
Converts a decimal number to binary
Parameters:
num : `int` - The decimal number to convert to binary
Returns: `string` - The binary representation of the decimal number
decimalToBinary(num, to_binary_int)
Converts a decimal number to binary
Parameters:
num : `int` - The decimal number to convert to binary
to_binary_int : `bool` - bool to convert to int or to string (true for int, false for string)
Returns: `string` - The binary representation of the decimal number
binaryToDecimal(binary)
Converts a binary number to decimal
Parameters:
binary : `string` - The binary number to convert to decimal
Returns: `int` - The decimal representation of the binary number
decimal_len(n)
way of finding decimal length using arithmetic
Parameters:
n `float` - floating decimal point to get length of.
Returns: `int` - number of decimal places
int_len(n)
way of finding number length using arithmetic
Parameters:
n : `int`- value to find length of number
Returns: `int` - lenth of nunber i.e. 23 == 2
float_decimal_to_whole(n)
Converts a float decimal number to an integer `0.365 to 365`.
Parameters:
n : `string` - The decimal number represented as a string.
Returns: `int` - The integer obtained by removing the decimal point and leading zeroes from s.
fractional_part(x)
Returns the fractional part of a float.
Parameters:
x : `float` - The float to get the fractional part of.
Returns: `float` - The fractional part of the float.
form_decimal(a, b, zero_fix)
helper to form 2 ints into 1 float seperated by the decimal
Parameters:
a : `int` - a int
b : `int` - b int
zero_fix : `bool` - fix for trailing zeros being truncated when converting to float
Returns: ` ` - float = float decimal of ints | string = string version of b for future use to ref length
bEncode(n1, n2)
Encodes two numbers into one using bit OR. (fastest)
Parameters:
n1 : `int` - The first number to Encodes.
n2 : `int` - The second number to Encodes.
Returns: `int` - The result of combining the two numbers using bit OR.
bDecode(n)
Decodes an integer created by the bCombine function.(fastest)
Parameters:
n : `int` - The integer to decode.
Returns: ` ` - A tuple containing the two decoded components of the integer.
Encode(a, b)
Encodes by seperating ints into left and right of decimal float
Parameters:
a : `int` - a int
b : `int` - b int
Returns: `float` - new float of encoded ints one on left of decimal point one on right
Decode(encoded)
Decodes float of 2 ints seperated by decimal point
Parameters:
encoded : `float` - the encoded float value
Returns: ` ` - tuple of the 2 ints from encoded float
encode_heavy(a, b)
Encodes by combining numbers and tracking size in the
decimal of a floating number (slowest)
Parameters:
a : `int` - a int
b : `int` - b int
Returns: `float` - new decimal of encoded ints
decode_heavy(encoded)
Decodes encoded float that tracks size of ints in float decimal
Parameters:
encoded : `float` - encoded float
Returns: ` ` - tuple of decoded ints
decimal of float (slowest)
Parameters:
encoded : `float` - the encoded float value
Returns: ` ` - tuple of the 2 ints from encoded float
Bitwise, Encode, Decode Docs
In the documentation you may notice the word decimal
not used as normal this is because when referring to
binary a decimal number is a number that
can be represented with base 10 numbers 0-9
(the wiki below explains better)
A rule of thumb for the two integers being
encoded it to keep both numbers
less than 65535 this is because anything lower uses 16 bits or less
this will maintain 100% accuracy when decoding
although it is possible to do numbers up to 2147483645 with
this library doesnt seem useful enough
to explain or demonstrate.
The functions provided work within this 32-bit range,
where the highest number is all 1s and
the lowest number is all 0s. These functions were created
to overcome the lack of built-in bitwise functions in Pinescript.
By combining two integers into a single number,
the code can access both values i.e when
indexing only one array index
for a matrices row/column, thus improving execution time.
This technique can be applied to various coding
scenarios to enhance performance.
Bitwise functions are a way to use integers in binary form
that can be used to speed up several different processes
most languages have operators to perform these function such as
`<<, >>, &, ^, |, ~`
en.wikipedia.org
DataChartLibrary "DataChart"
Library to plot scatterplot or heatmaps for your own set of data samples
draw(this)
draw contents of the chart object
Parameters:
this : Chart object
Returns: current chart object
init(this)
Initialize Chart object.
Parameters:
this : Chart object to be initialized
Returns: current chart object
addSample(this, sample, trigger)
Add sample data to chart using Sample object
Parameters:
this : Chart object
sample : Sample object containing sample x and y values to be plotted
trigger : Samples are added to chart only if trigger is set to true. Default value is true
Returns: current chart object
addSample(this, x, y, trigger)
Add sample data to chart using x and y values
Parameters:
this : Chart object
x : x value of sample data
y : y value of sample data
trigger : Samples are added to chart only if trigger is set to true. Default value is true
Returns: current chart object
addPriceSample(this, priceSampleData, config)
Add price sample data - special type of sample designed to measure price displacements of events
Parameters:
this : Chart object
priceSampleData : PriceSampleData object containing event driven displacement data of x and y
config : PriceSampleConfig object containing configurations for deriving x and y from priceSampleData
Returns: current chart object
Sample
Sample data for chart
Fields:
xValue : x value of the sample data
yValue : y value of the sample data
ChartProperties
Properties of plotting chart
Fields:
title : Title of the chart
suffix : Suffix for values. It can be used to reference 10X or 4% etc. Used only if format is not format.percent
matrixSize : size of the matrix used for plotting
chartType : Can be either scatterplot or heatmap. Default is scatterplot
outliersStart : Indicates the percentile of data to filter out from the starting point to get rid of outliers
outliersEnd : Indicates the percentile of data to filter out from the ending point to get rid of outliers.
backgroundColor
plotColor : color of plots on the chart. Default is color.yellow. Only used for scatterplot type
heatmapColor : color of heatmaps on the chart. Default is color.red. Only used for heatmap type
borderColor : border color of the chart table. Default is color.yellow.
plotSize : size of scatter plots. Default is size.large
format : data representation format in tooltips. Use mintick.percent if measuring any data in terms of percent. Else, use format.mintick
showCounters : display counters which shows totals on each quadrants. These are single cell tables at the corners displaying number of occurences on each quadrant.
showTitle : display title at the top center. Uses the title string set in the properties
counterBackground : background color of counter table cells. Default is color.teal
counterTextColor : text color of counter table cells. Default is color.white
counterTextSize : size of counter table cells. Default is size.large
titleBackground : background color of chart title. Default is color.maroon
titleTextColor : text color of the chart title. Default is color.white
titleTextSize : text size of the title cell. Default is size.large
addOutliersToBorder : If set, instead of removing the outliers, it will be added to the border cells.
useCommonScale : Use common scale for both x and y. If not selected, different scales are calculated based on range of x and y values from samples. Default is set to false.
plotchar : scatter plot character. Default is set to ascii bullet.
ChartDrawing
Chart drawing objects collection
Fields:
properties : ChartProperties object which determines the type and characteristics of chart being plotted
titleTable : table containing title of the chart.
mainTable : table containing plots or heatmaps.
quadrantTables : Array of tables containing counters of all 4 quandrants
Chart
Chart type which contains all the information of chart being plotted
Fields:
properties : ChartProperties object which determines the type and characteristics of chart being plotted
samples : Array of Sample objects collected over period of time for plotting on chart.
displacements : Array containing displacement values. Both x and y values
displacementX : Array containing only X displacement values.
displacementY : Array containing only Y displacement values.
drawing : ChartDrawing object which contains all the drawing elements
PriceSampleConfig
Configs used for adding specific type of samples called PriceSamples
Fields:
duration : impact duration for which price displacement samples are calculated.
useAtrReference : Default is true. If set to true, price is measured in terms of Atr. Else is measured in terms of percentage of price.
atrLength : atrLength to be used for measuring the price based on ATR. Used only if useAtrReference is set to true.
PriceSampleData
Special type of sample called price sample. Can be used instead of basic Sample type
Fields:
trigger : consider sample only if trigger is set to true. Default is true.
source : Price source. Default is close
highSource : High price source. Default is high
lowSource : Low price source. Default is low
tr : True range value. Default is ta.tr