Trading IQ - ICT LibraryLibrary "ICTlibrary"
Used to calculate various ICT related price levels and strategies. An ongoing project.
Hello Coders!
This library is meant for sourcing ICT related concepts. While some functions might generate more output than you require, you can specify "Lite Mode" as "true" in applicable functions to slim down necessary inputs.
isLastBar(userTF)
Identifies the last bar on the chart before a timeframe change
Parameters:
userTF (simple int) : the timeframe you wish to calculate the last bar for, must be converted to integer using 'timeframe.in_seconds()'
Returns: bool true if bar on chart is last bar of higher TF, dalse if bar on chart is not last bar of higher TF
necessaryData(atrTF)
returns necessaryData UDT for historical data access
Parameters:
atrTF (float) : user-selected timeframe ATR value.
Returns: logZ. log return Z score, used for calculating order blocks.
method gradBoxes(gradientBoxes, idColor, timeStart, bottom, top, rightCoordinate)
creates neon like effect for box drawings
Namespace types: array
Parameters:
gradientBoxes (array) : an array.new() to store the gradient boxes
idColor (color)
timeStart (int) : left point of box
bottom (float) : bottom of box price point
top (float) : top of box price point
rightCoordinate (int) : right point of box
Returns: void
checkIfTraded(tradeName)
checks if recent trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent trade id matches target name, false otherwise
checkIfClosed(tradeName)
checks if recent closed trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent closed trade id matches target name, false otherwise
IQZZ(atrMult, finalTF)
custom ZZ to quickly determine market direction.
Parameters:
atrMult (float) : an atr multiplier used to determine the required price move for a ZZ direction change
finalTF (string) : the timeframe used for the atr calcuation
Returns: dir market direction. Up => 1, down => -1
method drawBos(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showBOS, isUp)
calculates and draws Break Of Structure
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the BoS line / label
showBOS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether BoS happened during price increase or price decrease.
Returns: void
method drawMSS(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showMSS, isUp, upRejections, dnRejections, highArr, lowArr, timeArr, closeArr, openArr, atrTFarr, upRejectionsPrices, dnRejectionsPrices)
calculates and draws Market Structure Shift. This data is also used to calculate Rejection Blocks.
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the MSS line / label
showMSS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether MSS happened during price increase or price decrease.
upRejections (array)
dnRejections (array)
highArr (array) : array containing historical highs, should be taken from the UDT "necessaryData" defined above
lowArr (array) : array containing historical lows, should be taken from the UDT "necessaryData" defined above
timeArr (array) : array containing historical times, should be taken from the UDT "necessaryData" defined above
closeArr (array) : array containing historical closes, should be taken from the UDT "necessaryData" defined above
openArr (array) : array containing historical opens, should be taken from the UDT "necessaryData" defined above
atrTFarr (array) : array containing historical atr values (of user-selected TF), should be taken from the UDT "necessaryData" defined above
upRejectionsPrices (array) : array containing up rejections prices. Is sorted and used to determine selective looping for invalidations.
dnRejectionsPrices (array) : array containing down rejections prices. Is sorted and used to determine selective looping for invalidations.
Returns: void
method getTime(id, compare, timeArr)
gets time of inputted price (compare) in an array of data
this is useful when the user-selected timeframe for ICT concepts is greater than the chart's timeframe
Namespace types: array
Parameters:
id (array) : the array of data to search through, to find which index has the same value as "compare"
compare (float) : the target data point to find in the array
timeArr (array) : array of historical times
Returns: the time that the data point in the array was recorded
method OB(id, highArr, signArr, lowArr, timeArr, sign)
store bullish orderblock data
Namespace types: array
Parameters:
id (array)
highArr (array) : array of historical highs
signArr (array) : array of historical price direction "math.sign(close - open)"
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
sign (int) : orderblock direction, -1 => bullish, 1 => bearish
Returns: void
OTEstrat(OTEstart, future, closeArr, highArr, lowArr, timeArr, longOTEPT, longOTESL, longOTElevel, shortOTEPT, shortOTESL, shortOTElevel, structureDirection, oteLongs, atrTF, oteShorts)
executes the OTE strategy
Parameters:
OTEstart (chart.point)
future (int) : future time point for drawings
closeArr (array) : array of historical closes
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
longOTEPT (string) : user-selected long OTE profit target, please create an input.string() for this using the example below
longOTESL (int) : user-selected long OTE stop loss, please create an input.string() for this using the example below
longOTElevel (float) : long entry price of selected retracement ratio for OTE
shortOTEPT (string) : user-selected short OTE profit target, please create an input.string() for this using the example below
shortOTESL (int) : user-selected short OTE stop loss, please create an input.string() for this using the example below
shortOTElevel (float) : short entry price of selected retracement ratio for OTE
structureDirection (string) : current market structure direction, this should be "Up" or "Down". This is used to cancel pending orders if market structure changes
oteLongs (bool) : input.bool() for whether OTE longs can be executed
atrTF (float) : atr of the user-seleceted TF
oteShorts (bool) : input.bool() for whether OTE shorts can be executed
@exampleInputs
oteLongs = input.bool(defval = false, title = "OTE Longs", group = "Optimal Trade Entry")
longOTElevel = input.float(defval = 0.79, title = "Long Entry Retracement Level", options = , group = "Optimal Trade Entry")
longOTEPT = input.string(defval = "-0.5", title = "Long TP", options = , group = "Optimal Trade Entry")
longOTESL = input.int(defval = 0, title = "How Many Ticks Below Swing Low For Stop Loss", group = "Optimal Trade Entry")
oteShorts = input.bool(defval = false, title = "OTE Shorts", group = "Optimal Trade Entry")
shortOTElevel = input.float(defval = 0.79, title = "Short Entry Retracement Level", options = , group = "Optimal Trade Entry")
shortOTEPT = input.string(defval = "-0.5", title = "Short TP", options = , group = "Optimal Trade Entry")
shortOTESL = input.int(defval = 0, title = "How Many Ticks Above Swing Low For Stop Loss", group = "Optimal Trade Entry")
Returns: void (0)
displacement(logZ, atrTFreg, highArr, timeArr, lowArr, upDispShow, dnDispShow, masterCoords, labelLevels, dispUpcol, rightCoordinate, dispDncol, noBorders)
calculates and draws dispacements
Parameters:
logZ (float) : log return of current price, used to determine a "significant price move" for a displacement
atrTFreg (float) : atr of user-seleceted timeframe
highArr (array) : array of historical highs
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
upDispShow (int) : amount of historical upside displacements to show
dnDispShow (int) : amount of historical downside displacements to show
masterCoords (map) : a map to push the most recent displacement prices into, useful for having key levels in one data structure
labelLevels (string) : used to determine label placement for the displacement, can be inside box, outside box, or none, example below
dispUpcol (color) : upside displacement color
rightCoordinate (int) : future time for displacement drawing, best is "last_bar_time"
dispDncol (color) : downside displacement color
noBorders (bool) : input.bool() to remove box borders, example below
@exampleInputs
labelLevels = input.string(defval = "Inside" , title = "Box Label Placement", options = )
noBorders = input.bool(defval = false, title = "No Borders On Levels")
Returns: void
method getStrongLow(id, startIndex, timeArr, lowArr, strongLowPoints)
unshift strong low data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the low before an upside BoS
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
strongLowPoints (array) : array of strong low prices. Used to retrieve highest strong low price and see if need for
removal of invalidated strong lows
Returns: void
method getStrongHigh(id, startIndex, timeArr, highArr, strongHighPoints)
unshift strong high data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the high before a downside BoS
timeArr (array) : array of historical times
highArr (array) : array of historical highs
strongHighPoints (array)
Returns: void
equalLevels(highArr, lowArr, timeArr, rightCoordinate, equalHighsCol, equalLowsCol, liteMode)
used to calculate recent equal highs or equal lows
Parameters:
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
rightCoordinate (int) : a future time (right for boxes, x2 for lines)
equalHighsCol (color) : user-selected color for equal highs drawings
equalLowsCol (color) : user-selected color for equal lows drawings
liteMode (bool) : optional for a lite mode version of an ICT strategy. For more control over drawings leave as "True", "False" will apply neon effects
Returns: void
quickTime(timeString)
used to quickly determine if a user-inputted time range is currently active in NYT time
Parameters:
timeString (string) : a time range
Returns: true if session is active, false if session is inactive
macros(showMacros, noBorders)
used to calculate and draw session macros
Parameters:
showMacros (bool) : an input.bool() or simple bool to determine whether to activate the function
noBorders (bool) : an input.bool() to determine whether the box anchored to the session should have borders
Returns: void
po3(tf, left, right, show)
use to calculate HTF po3 candle
@tip only call this function on "barstate.islast"
Parameters:
tf (simple string)
left (int) : the left point of the candle, calculated as bar_index + left,
right (int) : :the right point of the candle, calculated as bar_index + right,
show (bool) : input.bool() whether to show the po3 candle or not
Returns: void
silverBullet(silverBulletStratLong, silverBulletStratShort, future, userTF, H, L, H2, L2, noBorders, silverBulletLongTP, historicalPoints, historicalData, silverBulletLongSL, silverBulletShortTP, silverBulletShortSL)
used to execute the Silver Bullet Strategy
Parameters:
silverBulletStratLong (simple bool)
silverBulletStratShort (simple bool)
future (int) : a future time, used for drawings, example "last_bar_time"
userTF (simple int)
H (float) : the high price of the user-selected TF
L (float) : the low price of the user-selected TF
H2 (float) : the high price of the user-selected TF
L2 (float) : the low price of the user-selected TF
noBorders (bool) : an input.bool() used to remove the borders from box drawings
silverBulletLongTP (series silverBulletLevels)
historicalPoints (array)
historicalData (necessaryData)
silverBulletLongSL (series silverBulletLevels)
silverBulletShortTP (series silverBulletLevels)
silverBulletShortSL (series silverBulletLevels)
Returns: void
method invalidFVGcheck(FVGarr, upFVGpricesSorted, dnFVGpricesSorted)
check if existing FVGs are still valid
Namespace types: array
Parameters:
FVGarr (array)
upFVGpricesSorted (array) : an array of bullish FVG prices, used to selective search through FVG array to remove invalidated levels
dnFVGpricesSorted (array) : an array of bearish FVG prices, used to selective search through FVG array to remove invalidated levels
Returns: void (0)
method drawFVG(counter, FVGshow, FVGname, FVGcol, data, masterCoords, labelLevels, borderTransp, liteMode, rightCoordinate)
draws FVGs on last bar
Namespace types: map
Parameters:
counter (map) : a counter, as map, keeping count of the number of FVGs drawn, makes sure that there aren't more FVGs drawn
than int FVGshow
FVGshow (int) : the number of FVGs to show. There should be a bullish FVG show and bearish FVG show. This function "drawFVG" is used separately
for bearish FVG and bullish FVG.
FVGname (string) : the name of the FVG, "FVG Up" or "FVG Down"
FVGcol (color) : desired FVG color
data (FVG)
masterCoords (map) : a map containing the names and price points of key levels. Used to define price ranges.
labelLevels (string) : an input.string with options "Inside", "Outside", "Remove". Determines whether FVG labels should be inside box, outside,
or na.
borderTransp (int)
liteMode (bool)
rightCoordinate (int) : the right coordinate of any drawings. Must be a time point.
Returns: void
invalidBlockCheck(bullishOBbox, bearishOBbox, userTF)
check if existing order blocks are still valid
Parameters:
bullishOBbox (array) : an array declared using the UDT orderBlock that contains bullish order block related data
bearishOBbox (array) : an array declared using the UDT orderBlock that contains bearish order block related data
userTF (simple int)
Returns: void (0)
method lastBarRejections(id, rejectionColor, idShow, rejectionString, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws rejectionBlocks on last bar
Namespace types: array
Parameters:
id (array) : the array, an array of rejection block data declared using the UDT rejection block
rejectionColor (color) : the desired color of the rejection box
idShow (int)
rejectionString (string) : the desired name of the rejection blocks
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
method OBdraw(id, OBshow, BBshow, OBcol, BBcol, bullishString, bearishString, isBullish, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws orderblocks and breaker blocks for data stored in UDT array()
Namespace types: array
Parameters:
id (array) : the array, an array of order block data declared using the UDT orderblock
OBshow (int) : the number of order blocks to show
BBshow (int) : the number of breaker blocks to show
OBcol (color) : color of order blocks
BBcol (color) : color of breaker blocks
bullishString (string) : the title of bullish blocks, which is a regular bullish orderblock or a bearish orderblock that's converted to breakerblock
bearishString (string) : the title of bearish blocks, which is a regular bearish orderblock or a bullish orderblock that's converted to breakerblock
isBullish (bool) : whether the array contains bullish orderblocks or bearish orderblocks. If bullish orderblocks,
the array will naturally contain bearish BB, and if bearish OB, the array will naturally contain bullish BB
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
FVG
UDT for FVG calcualtions
Fields:
H (series float) : high price of user-selected timeframe
L (series float) : low price of user-selected timeframe
direction (series string) : FVG direction => "Up" or "Down"
T (series int) : => time of bar on user-selected timeframe where FVG was created
fvgLabel (series label) : optional label for FVG
fvgLineTop (series line) : optional line for top of FVG
fvgLineBot (series line) : optional line for bottom of FVG
fvgBox (series box) : optional box for FVG
labelLine
quickly pair a line and label together as UDT
Fields:
lin (series line) : Line you wish to pair with label
lab (series label) : Label you wish to pair with line
orderBlock
UDT for order block calculations
Fields:
orderBlockData (array) : array containing order block x and y points
orderBlockBox (series box) : optional order block box
vioCount (series int) : = 0 violation count of the order block. 0 = Order Block, 1 = Breaker Block
traded (series bool)
status (series string) : = "OB" status == "OB" => Level is order block. status == "BB" => Level is breaker block.
orderBlockLab (series label) : options label for the order block / breaker block.
strongPoints
UDT for strong highs and strong lows
Fields:
price (series float) : price of the strong high or strong low
timeAtprice (series int) : time of the strong high or strong low
strongPointLabel (series label) : optional label for strong point
strongPointLine (series line) : optional line for strong point
overlayLine (series line) : optional lines for strong point to enhance visibility
overlayLine2 (series line) : optional lines for strong point to enhance visibility
displacement
UDT for dispacements
Fields:
highPrice (series float) : high price of displacement
lowPrice (series float) : low price of displacement
timeAtPrice (series int) : time of bar where displacement occurred
displacementBox (series box) : optional box to draw displacement
displacementLab (series label) : optional label for displacement
po3data
UDT for po3 calculations
Fields:
dHigh (series float) : higher timeframe high price
dLow (series float) : higher timeframe low price
dOpen (series float) : higher timeframe open price
dClose (series float) : higher timeframe close price
po3box (series box) : box to draw po3 candle body
po3line (array) : line array to draw po3 wicks
po3Labels (array) : label array to label price points of po3 candle
macros
UDT for session macros
Fields:
sessions (array) : Array of sessions, you can populate this array using the "quickTime" function located above "export macros".
prices (matrix) : Matrix of session data -> open, high, low, close, time
sessionTimes (array) : Array of session names. Pairs with array sessions.
sessionLines (matrix) : Optional array for sesion drawings.
OTEtimes
UDT for data storage and drawings associated with OTE strategy
Fields:
upTimes (array) : time of highest point before trade is taken
dnTimes (array) : time of lowest point before trade is taken
tpLineLong (series line) : line to mark tp level long
tpLabelLong (series label) : label to mark tp level long
slLineLong (series line) : line to mark sl level long
slLabelLong (series label) : label to mark sl level long
tpLineShort (series line) : line to mark tp level short
tpLabelShort (series label) : label to mark tp level short
slLineShort (series line) : line to mark sl level short
slLabelShort (series label) : label to mark sl level short
sweeps
UDT for data storage and drawings associated with liquidity sweeps
Fields:
upSweeps (matrix) : matrix containing liquidity sweep price points and time points for up sweeps
dnSweeps (matrix) : matrix containing liquidity sweep price points and time points for down sweeps
upSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
dnSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
raidExitDrawings
UDT for drawings associated with the Liquidity Raid Strategy
Fields:
tpLine (series line) : tp line for the liquidity raid entry
tpLabel (series label) : tp label for the liquidity raid entry
slLine (series line) : sl line for the liquidity raid entry
slLabel (series label) : sl label for the liquidity raid entry
m2022
UDT for data storage and drawings associated with the Model 2022 Strategy
Fields:
mTime (series int) : time of the FVG where entry limit order is placed
mIndex (series int) : array index of FVG where entry limit order is placed. This requires an array of FVG data, which is defined above.
mEntryDistance (series float) : the distance of the FVG to the 50% range. M2022 looks for the fvg closest to 50% mark of range.
mEntry (series float) : the entry price for the most eligible fvg
fvgHigh (series float) : the high point of the eligible fvg
fvgLow (series float) : the low point of the eligible fvg
longFVGentryBox (series box) : long FVG box, used to draw the eligible FVG
shortFVGentryBox (series box) : short FVG box, used to draw the eligible FVG
line50P (series line) : line used to mark 50% of the range
line100P (series line) : line used to mark 100% (top) of the range
line0P (series line) : line used to mark 0% (bottom) of the range
label50P (series label) : label used to mark 50% of the range
label100P (series label) : label used to mark 100% (top) of the range
label0P (series label) : label used to mark 0% (bottom) of the range
sweepData (array)
silverBullet
UDT for data storage and drawings associated with the Silver Bullet Strategy
Fields:
session (series bool)
sessionStr (series string) : name of the session for silver bullet
sessionBias (series string)
sessionHigh (series float) : = high high of session // use math.max(silverBullet.sessionHigh, high)
sessionLow (series float) : = low low of session // use math.min(silverBullet.sessionLow, low)
sessionFVG (series float) : if applicable, the FVG created during the session
sessionFVGdraw (series box) : if applicable, draw the FVG created during the session
traded (series bool)
tp (series float) : tp of trade entered at the session FVG
sl (series float) : sl of trade entered at the session FVG
sessionDraw (series box) : optional draw session with box
sessionDrawLabel (series label) : optional label session with label
silverBulletDrawings
UDT for trade exit drawings associated with the Silver Bullet Strategy
Fields:
tpLine (series line) : tp line drawing for strategy
tpLabel (series label) : tp label drawing for strategy
slLine (series line) : sl line drawing for strategy
slLabel (series label) : sl label drawing for strategy
unicornModel
UDT for data storage and drawings associated with the Unicorn Model Strategy
Fields:
hPoint (chart.point)
hPoint2 (chart.point)
hPoint3 (chart.point)
breakerBlock (series box) : used to draw the breaker block required for the Unicorn Model
FVG (series box) : used to draw the FVG required for the Unicorn model
topBlock (series float) : price of top of breaker block, can be used to detail trade entry
botBlock (series float) : price of bottom of breaker block, can be used to detail trade entry
startBlock (series int) : start time of the breaker block, used to set the "left = " param for the box
includes (array) : used to store the time of the breaker block, or FVG, or the chart point sequence that setup the Unicorn Model.
entry (series float) : // eligible entry price, for longs"math.max(topBlock, FVG.get_top())",
tpLine (series line) : optional line to mark PT
tpLabel (series label) : optional label to mark PT
slLine (series line) : optional line to mark SL
slLabel (series label) : optional label to mark SL
rejectionBlocks
UDT for data storage and drawings associated with rejection blocks
Fields:
rejectionPoint (chart.point)
bodyPrice (series float) : candle body price closest to the rejection point, for "Up" rejections => math.max(open, close),
rejectionBox (series box) : optional box drawing of the rejection block
rejectionLabel (series label) : optional label for the rejection block
equalLevelsDraw
UDT for data storage and drawings associated with equal highs / equal lows
Fields:
connector (series line) : single line placed at the first high or low, y = avgerage of distinguished equal highs/lows
connectorLab (series label) : optional label to be placed at the highs or lows
levels (array) : array containing the equal highs or lows prices
times (array) : array containing the equal highs or lows individual times
startTime (series int) : the time of the first high or low that forms a sequence of equal highs or lows
radiate (array) : options label to "radiate" the label in connector lab. Can be used for anything
necessaryData
UDT for data storage of historical price points.
Fields:
highArr (array) : array containing historical high points
lowArr (array) : array containing historical low points
timeArr (array) : array containing historical time points
logArr (array) : array containing historical log returns
signArr (array) : array containing historical price directions
closeArr (array) : array containing historical close points
binaryTimeArr (array) : array containing historical time points, uses "push" instead of "unshift" to allow for binary search
binaryCloseArr (array) : array containing historical close points, uses "push" instead of "unshift" to allow the correct
binaryOpenArr (array) : array containing historical optn points, uses "push" instead of "unshift" to allow the correct
atrTFarr (array) : array containing historical user-selected TF atr points
openArr (array) : array containing historical open points
Timesessions
TimeLibraryLibrary "TimeLibrary"
TODO: add library description here
Line_Type_Control(Type)
Line_Type_Control: This function changes between common line types options available are "Solid","Dashed","Dotted"
Parameters:
Type (string) : : The string to choose the line type from
Returns: Line_Type : returns the pine script equivalent of the string input
Text_Size_Switch(Text_Size)
Text_Size_Switch : This function changes between common text sizes options are "Normal", "Tiny", "Small", "Large", "Huge", "Auto"
Parameters:
Text_Size (string) : : The string to choose the text type from
Returns: Text_Type : returns the pine script equivalent of the string input
TF(TF_Period, TF_Multip)
TF generates a string representation of a time frame based on the provided time frame unit (`TF_Period`) and multiplier (`TF_Multip`).
Parameters:
TF_Period (simple string)
TF_Multip (simple int)
Returns: A string that represents the time frame in Pine Script format, depending on the `TF_Period`:
- For "Minute", it returns the multiplier as a string (e.g., "5" for 5 minutes).
- For "Hour", it returns the equivalent number of minutes (e.g., "120" for 2 hours).
- For "Day", it appends "D" to the multiplier (e.g., "2D" for 2 days).
- For "Week", it appends "W" to the multiplier (e.g., "1W" for 1 week).
- For "Month", it appends "M" to the multiplier (e.g., "3M" for 3 months).
If none of these cases match, it returns the current chart's time frame.
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip)
TF_Display generates a string representation of a time frame based on user-defined inputs or the current chart's time frame settings.
Parameters:
Chart_as_Timeframe (bool) : (bool): Determines whether to use the current chart's time frame or a custom time frame.
TF_Period` (string): The time frame unit (e.g., "Minute", "Hour", "Day", "Week", "Month").
TF_Multip` (int): The multiplier for the time frame (e.g., 15 for 15 minutes, 2 for 2 days).
TF_Period (string)
TF_Multip (int)
Returns: If `Chart_as_Timeframe` is `false`, the function returns a time frame string based on the provided `TF_Period` and `TF_Multip` values (e.g., "5Min", "2D").
If `Chart_as_Timeframe` is `true`, the function determines the current chart's time frame and returns it as a string:
For minute-based time frames, it returns the number of minutes with "Min" (e.g., "15Min") unless it's an exact hour, in which case it returns the hour (e.g., "1H").
For daily, weekly, and monthly time frames, it returns the multiplier with the appropriate unit (e.g., "1D" for daily, "1W" for weekly, "1M" for monthly).
MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)
MTF_MS_Display This function calculates and returns a modified swing length value based on the selected time frame and current chart's time frame.
Parameters:
Chart_as_Timeframe (bool)
TF_Period (string)
TF_Multip (int)
Swing_Length (int)
HTF_Structure_Control(Chart_as_Timeframe, Show_Only_On_Lower_Timeframes, TF_Period, TF_Multip)
Parameters:
Chart_as_Timeframe (bool)
Show_Only_On_Lower_Timeframes (bool)
TF_Period (string)
TF_Multip (int)
Time Zone CorrectorThe Time Zone Corrector library provides a utility function designed to adjust time based on the user's current time zone. This library supports a wide range of time zones across the Americas, Europe, Asia, and Oceania, making it highly versatile for traders around the world. It simulates a switch-case structure using ternary operators to output the appropriate time offset relative to UTC.
Whether you're dealing with market sessions in New York, Tokyo, London, or other major trading hubs, this library helps ensure your trading algorithms can accurately account for time differences. The library is particularly useful for strategies that rely on precise timing, as it dynamically adjusts the time zone offset depending on the symbol being traded.
SessionLibrary "Session"
Helper functions for trading sessions. TradingView doesn't provide correct data when
calling some of the convenience methods like session.ismarket when you are looking at futures charts. This library corrects those mistakes by providing functions with the same names as the TradingView default properties. that reference a custom defined set of session hours for futures. It also provides a way for consumers to customize the map values by calling getSessionMap() and then overwriting (or adding) custom session definitions.
getSessionMap()
Returns a map of the futures rth & eth session hours. The map is keyed with symbol:session format (eg. ES:market or ES:overnight).
Returns: A map of futures symbols and their associated session hours.
getSessionString(session, symbol, sessionMap)
Returns a session string representing the session hours (and days) for the requested symbol (or the chart's symbol if the symbol value is not provided). If the session string is not found in the collection, it will return a blank string.
Parameters:
session (string) : A string representing the session hour being requested. One of: market (regular trading hours), overnight (extended/electronic trading hours), postmarket (after-hours), premarket
symbol (string) : The symbol to check. Optional. Defaults to chart symbol.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
inSession(session, sessionMap, barsBack)
Returns true if the current symbol is currently in the session parameters defined by sessionString.
Parameters:
session (string) : A string representing the session hour being requested. One of: market (regular trading hours), overnight (extended/electronic trading hours), postmarket (after-hours), premarket
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
barsBack (int) : Private. Only used by futures to check islastbar. Optional. The default is 0.
ismarket(sessionMap)
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isfirstbar()
Returns true if the current bar is the first bar of the day's session, false otherwise. If extended session information is used, only returns true on the first bar of the pre-market bars. Works for futures (TradingView's methods do not).
Returns: bool
islastbar()
Returns true if the current bar is the last bar of the day's session, false otherwise. If extended session information is used, only returns true on the last bar of the post-market bars. Works for futures (TradingView's methods do not).
Returns: bool
ispremarket(sessionMap)
Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns false. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
ispostmarket(sessionMap)
Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns false. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isfirstbar_regular(sessionMap)
Returns true on the first regular session bar of the day, false otherwise. The result is the same whether extended session information is used or not. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
islastbar_regular(sessionMap)
Returns true on the last regular session bar of the day, false otherwise. The result is the same whether extended session information is used or not. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isovernight(sessionMap)
Returns true if the current bar is a part of the pre-market or post-market, false otherwise. On non-intraday charts always returns false.
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
getSessionHighAndLow(session, sessionMap)
Returns a tuple containing the high and low print during the specified session.
Parameters:
session (string) : The session for which to get the high & low prints. Defaults to market.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: A tuple containing
offline_detection Library
Description:
Boolean and alert functions that check if the latest user-selected symbol 'sym' has started printing. Alerts trigger by bar close.
Usage:
Mainly for 24/7 crypto exchanges. If an exchange you have alerts on goes offline, the alerts will not trigger. The offline alert is an alert to alert you of that. It's best to create the alerts while on "CRYPTOCAP:TOTAL" because it has the least downtime. The exchange you want alerts on is controlled by the 'sym' parameter. The alerts need to be enabled yourself.
Limitations:
The alerts may be triggered by no volume in a bar, so it's best to set it on timeframes higher than 1 minute. Alerts are not enabled in libraries so the functions must be imported or copied into another script. alert.freq cannot be changed by input because it becomes a series string in a function. dynamic_requests must be true to export functions using `request.*()` calls.
Example:
import NeoButane/offline_detection/1
thing = "COINBASE:BTCUSD"
offline_detection.offlineAlertNoSpam(thing)
offline_detection.onlineAlert(thing)
warningsign()
Library "offline_detection"
Creates alerts for the user-selected symbol by checking if its latest bar is current by comparing it against another chart.
isItDown(sym)
Checks if 'sym' is offline by requesting time of 'sym'.
Parameters:
sym (simple string) : (const string) The user-selected symbol in the form of "PREFIX:TICKER".
Returns: True if time of 'sym' is not available.
isItDownNoSpam(sym)
Checks if 'sym' is offline by requesting time of 'sym' once.
Parameters:
sym (simple string) : (const string) The user-selected symbol in the form of "PREFIX:TICKER".
Returns: True if time of 'sym' is not available and it was available in the previous bar close.
isItUp(sym)
Checks if 'sym' is online after being offline by using isItDown().
Parameters:
sym (simple string) : (const string) The user-selected symbol in the form of "PREFIX:TICKER".
Returns: True if time of 'sym' is available in the current bar but wasn't prior.
offlineAlert(sym)
Checks if isItDown() is true.
Parameters:
sym (simple string) : (const string) The user-selected symbol in the form of "PREFIX:TICKER".
Returns: An alert when the symbol is not online and the time in UTC. This will continue triggering every bar close until the symbol is online.
offlineAlertNoSpam(sym)
Checks if isItDown() is true.
Parameters:
sym (simple string) : (const string) The user-selected symbol in the form of "PREFIX:TICKER".
Returns: An alert when the symbol is not online and the time in UTC.
onlineAlert(sym)
Checks if isItUp() is true.
Parameters:
sym (simple string) : (const string) The user-selected symbol in the form of "PREFIX:TICKER".
Returns: An alert when the symbol is now online and the time in UTC.
warningsign()
Checks if the current chart is "CRYPTOCAP:TOTAL".
Returns: A reminder on the chart.
lib_session_gapsLibrary "lib_session_gaps"
simple lib to calculate the gaps between sessions
time_gap()
calculates the time gap between this and previous session (in case of irregular end of previous session, considering extended sessions)
Returns: the time gap between this and previous session in ms (time - time_close )
bar_gap()
calculates the bars missing between this and previous session (in case of irregular end of previous session, considering extended sessions)
Returns: the bars virtually missing between this and previous session (time gap / bar size in ms)
SessionBoxLibrary "SessionBox"
This library provides functions to manage and visualize session boxes and labels on chart. A session box is a visual representation of a trading session with properties like time, name, color and the ability to track the high and low price within that session.
SessionBox
SessionBox: stores session data and provides methods to manage that data and visualize it on the chart.
Fields:
session_time (series bool)
session_name (series string)
session_color (series color)
time_libraryLibrary "time_library"
This library provides utilities for working with time intervals in milliseconds, seconds, minutes, hours, days, and weeks. It includes functions to handle conditions based on time rather than bars.
ms(TIME)
ms - Converts a time period in string format to milliseconds.
Parameters:
TIME (string) : (series ) - The time period ("ms", "s", "m", "h", "d", "w").
Returns: (int) - The corresponding time period in milliseconds.
true_in(timestamp, period, multiplier)
true_in - Checks if the current time has reached a specific time after the given timestamp.
Parameters:
timestamp (int) : (series ) - The starting timestamp.
period (string) : (series |series ) - The period in string format ("ms", "s", "m", "h", "d", "w"), or as an integer in milliseconds.
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if current time is equal or past the end date calculated from timestamp and period.
true_in(timestamp, period, multiplier)
true_in - Checks if the current time has reached a specific time after the given timestamp.
Parameters:
timestamp (int) : (series ) - The starting timestamp.
period (int) : (series |series ) - The period in string format ("ms", "s", "m", "h", "d", "w"), or as an integer in milliseconds.
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if current time is equal or past the end date calculated from timestamp and period.
true_after(trigger, period, multiplier)
true_after - Returns true after a specified period multiplied by a multiplier has passed since a trigger was last true.
Parameters:
trigger (bool) : (series ) - The condition that triggers the timer.
period (string) : (series |series ) - The period in string format ("ms", "s", "m", "h", "d", "w"), or as an integer in milliseconds.
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if the specified time has passed since the last trigger.
true_after(trigger, ms, multiplier)
true_after - Returns true after a specified period multiplied by a multiplier has passed since a trigger was last true.
Parameters:
trigger (bool) : (series ) - The condition that triggers the timer.
ms (int)
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if the specified time has passed since the last trigger.
MS
MS - Holds common time intervals in milliseconds.
Fields:
ms (series int) : (int) - Milliseconds.
s (series int) : (int) - Seconds converted to milliseconds.
m (series int) : (int) - Minutes converted to milliseconds.
h (series int) : (int) - Hours converted to milliseconds.
d (series int) : (int) - Days converted to milliseconds.
w (series int) : (int) - Weeks converted to milliseconds.
TimeFilterLibrary "TimeFilter"
provides utilities for dates and times
inSession(session, timezone, period)
Parameters:
session (simple string)
timezone (simple string)
period (simple string)
Returns: bool inSession Whether the current time is within the defined time session
inDateRange(startDate, endDate)
Parameters:
startDate (int)
endDate (int)
Returns: bool inRange Whether the current time is within the defined date range
isWeekDay(weekDay, timezone)
Parameters:
weekDay (int)
timezone (simple string)
Returns: bool isWeekDay Whether the provided day is the current day of the week
inWeek(useMon, useTue, useWed, useThu, useFri, useSat, useSun, timezone)
Parameters:
useMon (bool)
useTue (bool)
useWed (bool)
useThu (bool)
useFri (bool)
useSat (bool)
useSun (bool)
timezone (simple string)
Returns: bool inWeek Whether the current time is one of the defined days
filter(useRange, useSession, useWeek, inRange, inSession, inWeek)
Parameters:
useRange (bool)
useSession (bool)
useWeek (bool)
inRange (bool)
inSession (bool)
inWeek (bool)
Returns: bool filter Whether the filter matches or not
FunctionTimeFrequencyLibrary "FunctionTimeFrequency"
Functions to encode time in a normalized space (-0.5, 0.5) that corresponds to the position of the
current time in the referrence frequency of time.
The purpose of normalizing the time value in this manner is to provide a consistent and easily comparable
representation of normalized time that can be used for various calculations or comparisons without needing
to consider the specific scale of time. This function can be particularly useful when working with high-precision
timing data, as it allows you to compare and manipulate time values more flexibly than using absolute second
counts alone.
Reference:
github.com
second_of_minute(t)
Second of minute encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
minute_of_hour(t)
Minute of hour encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
hour_of_day(t)
Hour of day encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
day_of_week(t)
Day of week encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
day_of_month(t)
Day of month encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
day_of_year(t)
Day of year encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
month_of_year(t)
Month of year encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
week_of_year(t)
Week of year encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
Sessions KillZones Library [TradingFinder]🔵 Introduction
"The Forex Trading Sessions" highlight the active periods across different markets where significant trading volume and influence on the forex market are evident. The primary trading sessions globally include the "Asian Session," "London Session," and "New York Session."
A "Kill Zone" refers to a segment within a session characterized by high trading volume and notably sharper price movements. Consequently, there's a higher probability of encountering price action setups within these zones. Traders capitalize on this phenomenon in pursuit of more successful trading outcomes.
If you aim to integrate sessions or kill zones into your indicators or strategies, utilizing this library can amplify the precision and efficiency of your Python script development.
🔵 How to Use
First, you can add the library to your code as shown in the example below:
import TFlab/SessionAndKillZoneLibrary_TradingFinder/1
🟣 Parameters
SessionDetector(Session_Name, Session_Time, KillZone_Time, Session_Show, KillZone_Show, AreaUpdate, MoreInfo, Session_Color, Info_Color) =>
Parameters:
•Session_Name (string)
•Session_Time (string)
•KillZone_Time (string)
•Session_Show (bool)
•KillZone_Show (bool)
•AreaUpdate (string)
•MoreInfo (bool)
•Session_Color (color)
•Info_Color (color)
Session_Name : You must enter the session name in this parameter.
Session_Time : Enter here the start and end time of the session, which should be based on the UTC time zone.
KillZone_Time : Enter the start and end times of the kill zone, which should be based on the UTC time zone, here.
Session_Show : You can control whether or not to show the session using this entry. You must set true to display and false to not display.
KillZone_Show : Using this input you can control whether the kill zone is displayed or not. You must set true to display and false to not display.
AreaUpdate : If you want the session to be determined based on the time and high and low of the session itself, you must enter "Session" and if you want the area to be determined based on the time and high and low of the kill zone, you must enter "Kill Zone".
MoreInfo : If you want more information, you should set this entry to true, otherwise set to false. This information includes the number of candles in the area, the length of time in the area and the volume of transactions in the area.
Session_Color : Enter your desired color to display the session at this section. It is recommended to use bright and sharp colors.
Info_Color : Enter your desired color to display more information in this section.
🔵 Function Outputs
The outputs of this function are direct and indirect.
🟣 Indirect outputs
These outputs include session display, kill zone display, and time and volume information of session or kill zone.
🟣 Direct outputs
There are 8 direct outputs, which are:
Session Time : If the Session is active, it outputs 1, and if the Session is inactive, it outputs 0.
Kill Zone Time : If the Kill Zone is active, it outputs 1, and if the Kill Zone is inactive, it outputs 0.
Open : Session opening price.
High : The highest price of the session.
Low : The lowest price of the session.
Close : The last price of the session.
Low Touch Alert : If "Area Update" is in "Kill Zone" mode, if the price reaches the lowest price of the kill zone in the same session after the end of the kill zone, this output will be true. You can use this output to create an alert.
High Touch Alert : If "Area Update" is in "Kill Zone" mode, if the price reaches the highest price of the kill zone in the same session after the end of the kill zone, this output will be true. You can use this output to create an alert.
Important : To use "Open", "High", "Low" and "Close", "Area Update" must be in "Session" mode.
chrono_utilsLibrary "chrono_utils"
Collection of objects and common functions that are related to datetime windows session days and time
ranges. The main purpose of this library is to handle time-related functionality and make it easy to reason about a
future bar checking if it will be part of a predefined session and/or inside a datetime window. All existing session
functionality I found in the documentation e.g. "not na(time(timeframe, session, timezone))" are not suitable for
strategy scripts, since the execution of the orders is delayed by one bar, due to the script execution happening at
the bar close. Moreover, a history operator with a negative value that looks forward is not allowed in any pinescript
expression. So, a prediction for the next bar using the bars_back argument of "time()"" and "time_close()" was
necessary. Thus, I created this library to overcome this small but very important limitation. In the meantime, I
added useful functionality to handle session-based behavior. An interesting utility that emerged from this
development is the data anomaly detection where a comparison between the prediction and the actual value is happening.
If those two values are different then a data inconsistency happened between the prediction bar and the actual bar
(probably due to a holiday, half session day, a timezone change etc..)
exTimezone(timezone)
exTimezone - Convert extended timezone to timezone string
Parameters:
timezone (simple string) : - The timezone or a special string
Returns: string representing the timezone
nameOfDay(day)
nameOfDay - Convert the day id into a short nameOfDay
Parameters:
day (int) : - The day id to convert
Returns: - The short name of the day
today()
today - Get the day id of this day
Returns: - The day id
nthDayAfter(day, n)
nthDayAfter - Get the day id of n days after the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days after the reference day
nextDayAfter(day)
nextDayAfter - Get the day id of next day after the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the next day after the reference day
nthDayBefore(day, n)
nthDayBefore - Get the day id of n days before the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days before the reference day
prevDayBefore(day)
prevDayBefore - Get the day id of previous day before the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the previous day before the reference day
tomorrow()
tomorrow - Get the day id of the next day
Returns: - The next day day id
normalize(num, min, max)
normalizeHour - Check if number is inthe range of
Parameters:
num (int)
min (int)
max (int)
Returns: - The normalized number
normalizeHour(hourInDay)
normalizeHour - Check if hour is valid and return a noralized hour range from
Parameters:
hourInDay (int)
Returns: - The normalized hour
normalizeMinute(minuteInHour)
normalizeMinute - Check if minute is valid and return a noralized minute from
Parameters:
minuteInHour (int)
Returns: - The normalized minute
monthInMilliseconds(mon)
monthInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Parameters:
mon (int) : - The month of reference to get the miliseconds
Returns: - The number of milliseconds of the month
barInMilliseconds()
barInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Returns: - The number of milliseconds in one bar
method to_string(this)
to_string - Formats the time window into a human-readable string
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The string of the time window
method to_string(this)
to_string - Formats the session days into a human-readable string with short day names
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The string of the session day short names
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_string(this)
to_string - Formats the session into a human-readable string
Namespace types: Session
Parameters:
this (Session) : - The session object with the day and the time range selection
Returns: - The string of the session
method init(this, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, refTimezone, chTimezone, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
refTimezone (simple string) : - The timezone of reference of the 'from' and 'to' dates
chTimezone (simple string) : - The target timezone to convert the 'from' and 'to' dates
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, sun, mon, tue, wed, thu, fri, sat)
init - Initialize the session days object from boolean values of each session day
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sun (bool) : - Is Sunday a trading day?
mon (bool) : - Is Monday a trading day?
tue (bool) : - Is Tuesday a trading day?
wed (bool) : - Is Wednesday a trading day?
thu (bool) : - Is Thursday a trading day?
fri (bool) : - Is Friday a trading day?
sat (bool) : - Is Saturday a trading day?
Returns: - The session days object
method init(this, unixTime)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
unixTime (int) : - The unix time
Returns: - The session time object
method init(this, hourInDay, minuteInHour)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
Returns: - The session time object
method init(this, hourInDay, minuteInHour, refTimezone)
init - Initialize the object from the hour and minute of the session time
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
refTimezone (string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method init(this, startTime, endTime)
init - Initialize the object from the start and end session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTime (SessionTime) : - The time the session begins
endTime (SessionTime) : - The time the session ends
Returns: - The session time range object
method init(this, startTimeHour, startTimeMinute, endTimeHour, endTimeMinute, refTimezone)
init - Initialize the object from the start and end session time
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTimeHour (int) : - The time hour the session begins
startTimeMinute (int) : - The time minute the session begins
endTimeHour (int) : - The time hour the session ends
endTimeMinute (int) : - The time minute the session ends
refTimezone (string)
Returns: - The session time range object
method init(this, days, timeRanges)
init - Initialize the session object from session days and time range
Namespace types: Session
Parameters:
this (Session) : - The session object that will hold the day and the time range selection
days (SessionDays) : - The session days object that defines the days the session is happening
timeRanges (array) : - The array of all the session time ranges during a session day
Returns: - The session object
method init(this, days, timeRanges, names, colors)
init - Initialize the session object from session days and time range
Namespace types: SessionView
Parameters:
this (SessionView) : - The session view object that will hold the session, the names and the color selections
days (SessionDays) : - The session days object that defines the days the session is happening
timeRanges (array) : - The array of all the session time ranges during a session day
names (array) : - The array of the names of the sessions
colors (array) : - The array of the colors of the sessions
Returns: - The session object
method get_size_in_secs(this)
get_size_in_secs - Count the seconds from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of seconds inside the time widow for the given timeframe
method get_size_in_secs(this)
get_size_in_secs - Calculate the seconds inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of seconds inside the session
method get_size_in_bars(this)
get_size_in_bars - Count the bars from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of bars inside the time widow for the given timeframe
method get_size_in_bars(this)
get_size_in_bars - Calculate the bars inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of bars inside the session for the given timeframe
method is_bar_included(this, offset_forward)
is_bar_included - Check if the given bar is between the start and end dates of the window
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
offset_forward (simple int) : - The number of bars forward. Default is 1
Returns: - Whether the current bar is inside the datetime window
method is_bar_included(this, offset_forward)
is_bar_included - Check if the given bar is inside the session as defined by the input params (what "not na(time(timeframe.period, this.to_sess_string()) )" should return if you could write it
Namespace types: Session
Parameters:
this (Session) : - The session with the day and the time range selection
offset_forward (simple int) : - The bar forward to check if it is between the from and to datetimes. Default is 1
Returns: - Whether the current time is inside the session
method to_sess_string(this)
to_sess_string - Formats the session days into a session string with day ids
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object
Returns: - The string of the session day ids
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the session into a session string
Namespace types: Session
Parameters:
this (Session) : - The session object with the day and the time range selection
Returns: - The string of the session
method from_sess_string(this, sess)
from_sess_string - Initialize the session days object from the session string
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sess (string) : - The session string part that represents the days
Returns: - The session days object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
Returns: - The session time object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time object from the session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
refTimezone (simple string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time range object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time range object from the session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method from_sess_string(this, sess)
from_sess_string - Initialize the session object from the session string in exchange timezone (syminfo.timezone)
Namespace types: Session
Parameters:
this (Session) : - The session object that will hold the day and the time range selection
sess (string) : - The session string that represents the session HHmm-HHmm,HHmm-HHmm:ddddddd
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session object from the session string
Namespace types: Session
Parameters:
this (Session) : - The session object that will hold the day and the time range selection
sess (string) : - The session string that represents the session HHmm-HHmm,HHmm-HHmm:ddddddd
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method nth_day_after(this, day, n)
nth_day_after - The nth day after the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week after the given day
method nth_day_before(this, day, n)
nth_day_before - The nth day before the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week before the given day
method next_day(this)
next_day - The next day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the next session day of the week
method previous_day(this)
previous_day - The previous day that is session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the previous session day of the week
method get_sec_in_day(this)
get_sec_in_day - Count the seconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of seconds passed from the start of the day until that session time
method get_ms_in_day(this)
get_ms_in_day - Count the milliseconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of milliseconds passed from the start of the day until that session time
method is_day_included(this, day)
is_day_included - Check if the given day is inside the session days
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day to check if it is a trading day
Returns: - Whether the current day is included in the session days
DateTimeWindow
DateTimeWindow - Object that represents a datetime window with a beginning and an end
Fields:
fromDateTime (series int) : - The beginning of the datetime window
toDateTime (series int) : - The end of the datetime window
SessionDays
SessionDays - Object that represent the trading days of the week
Fields:
days (map) : - The map that contains all days of the week and their session flag
SessionTime
SessionTime - Object that represents the time (hour and minutes)
Fields:
hourInDay (series int) : - The hour of the day that ranges from 0 to 24
minuteInHour (series int) : - The minute of the hour that ranges from 0 to 59
minuteInDay (series int) : - The minute of the day that ranges from 0 to 1440. They will be calculated based on hourInDay and minuteInHour when method is called
SessionTimeRange
SessionTimeRange - Object that represents a range that extends from the start to the end time
Fields:
startTime (SessionTime) : - The beginning of the time range
endTime (SessionTime) : - The end of the time range
isOvernight (series bool) : - Whether or not this is an overnight time range
Session
Session - Object that represents a session
Fields:
days (SessionDays) : - The map of the trading days
timeRanges (array) : - The array with all time ranges of the session during the trading days
SessionView
SessionView - Object that visualize a session
Fields:
sess (Session) : - The Session object to be visualized
names (array) : - The names of the session time ranges
colors (array) : - The colors of the session time ranges
time_and_sessionA library that provides utilities for working with trading sessions and time-based conditions. Functions include session checks, date range checks, day-of-week matching, and session high/low calculations for daily, weekly, monthly, and yearly timeframes. This library streamlines time-related calculations and enhances time-based strategies and indicators.
Library "time_and_session"
Provides functions for checking time and session-based conditions and retrieving session-specific high and low values.
is_session(session, timeframe, timezone)
Checks if the current time is within the specified trading session
Parameters:
session (string) : The trading session, defined using input.session()
timeframe (string) : The timeframe to use, defaults to the current chart's timeframe
timezone (string) : The timezone to use, defaults to the symbol's timezone
Returns: A boolean indicating whether the current time is within the specified trading session
is_date_range(start_time, end_time)
Checks if the current time is within a specified date range
Parameters:
start_time (int) : The start time, defined using input.time()
end_time (int) : The end time, defined using input.time()
Returns: A boolean indicating whether the current time is within the specified date range
is_day_of_week(sunday, monday, tuesday, wednesday, thursday, friday, saturday)
Checks if the current day of the week matches any of the specified days
Parameters:
sunday (bool) : A boolean indicating whether to check for Sunday
monday (bool) : A boolean indicating whether to check for Monday
tuesday (bool) : A boolean indicating whether to check for Tuesday
wednesday (bool) : A boolean indicating whether to check for Wednesday
thursday (bool) : A boolean indicating whether to check for Thursday
friday (bool) : A boolean indicating whether to check for Friday
saturday (bool) : A boolean indicating whether to check for Saturday
Returns: A boolean indicating whether the current day of the week matches any of the specified days
daily_high(source)
Returns the highest value of the specified source during the current daily session
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current daily session, or na if the timeframe is not suitable
daily_low(source)
Returns the lowest value of the specified source during the current daily session
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current daily session, or na if the timeframe is not suitable
regular_session_high(source, persist)
Returns the highest value of the specified source during the current regular trading session
Parameters:
source (float) : The data series to evaluate, defaults to high
persist (bool) : A boolean indicating whether to retain the last value outside of regular market hours, defaults to true
Returns: The highest value during the current regular trading session, or na if the timeframe is not suitable
regular_session_low(source, persist)
Returns the lowest value of the specified source during the current regular trading session
Parameters:
source (float) : The data series to evaluate, defaults to low
persist (bool) : A boolean indicating whether to retain the last value outside of regular market hours, defaults to true
Returns: The lowest value during the current regular trading session, or na if the timeframe is not suitable
premarket_session_high(source, persist)
Returns the highest value of the specified source during the current premarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to high
persist (bool) : A boolean indicating whether to retain the last value outside of premarket hours, defaults to true
Returns: The highest value during the current premarket trading session, or na if the timeframe is not suitable
premarket_session_low(source, persist)
Returns the lowest value of the specified source during the current premarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to low
persist (bool) : A boolean indicating whether to retain the last value outside of premarket hours, defaults to true
Returns: The lowest value during the current premarket trading session, or na if the timeframe is not suitable
postmarket_session_high(source, persist)
Returns the highest value of the specified source during the current postmarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to high
persist (bool) : A boolean indicating whether to retain the last value outside of postmarket hours, defaults to true
Returns: The highest value during the current postmarket trading session, or na if the timeframe is not suitable
postmarket_session_low(source, persist)
Returns the lowest value of the specified source during the current postmarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to low
persist (bool) : A boolean indicating whether to retain the last value outside of postmarket hours, defaults to true
Returns: The lowest value during the current postmarket trading session, or na if the timeframe is not suitable
weekly_high(source)
Returns the highest value of the specified source during the current weekly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current weekly session, or na if the timeframe is not suitable
weekly_low(source)
Returns the lowest value of the specified source during the current weekly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current weekly session, or na if the timeframe is not suitable
monthly_high(source)
Returns the highest value of the specified source during the current monthly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current monthly session, or na if the timeframe is not suitable
monthly_low(source)
Returns the lowest value of the specified source during the current monthly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current monthly session, or na if the timeframe is not suitable
yearly_high(source)
Returns the highest value of the specified source during the current yearly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current yearly session, or na if the timeframe is not suitable
yearly_low(source)
Returns the lowest value of the specified source during the current yearly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current yearly session, or na if the timeframe is not suitable
utilsLibrary "utils"
Provides a set of utility functions for use in strategies or indicators.
colorGreen(opacity)
Parameters:
opacity (int)
colorRed(opacity)
Parameters:
opacity (int)
colorTeal(opacity)
Parameters:
opacity (int)
colorBlue(opacity)
Parameters:
opacity (int)
colorOrange(opacity)
Parameters:
opacity (int)
colorPurple(opacity)
Parameters:
opacity (int)
colorPink(opacity)
Parameters:
opacity (int)
colorYellow(opacity)
Parameters:
opacity (int)
colorWhite(opacity)
Parameters:
opacity (int)
colorBlack(opacity)
Parameters:
opacity (int)
trendChangingUp(emaShort, emaLong)
Signals when the trend is starting to change in a positive direction.
Parameters:
emaShort (float)
emaLong (float)
Returns: bool
trendChangingDown(emaShort, emaLong)
Signals when the trend is starting to change in a negative direction.
Parameters:
emaShort (float)
emaLong (float)
Returns: bool
percentChange(start, end)
Returns the percent change between a start number and end number. A positive change returns a positive value and vice versa.
Parameters:
start (float)
end (float)
Returns: float
percentOf(percent, n)
Returns the number that's the percentage of the provided value.
Parameters:
percent (float) : Use 0.2 for 20 percent, 0.35 for 35 percent, etc.
n (float) : The number to calculate the percentage of.
Returns: float
targetPriceByPercent(percent, n)
Parameters:
percent (float)
n (float)
hasNegativeSlope(start, end)
Parameters:
start (float)
end (float)
timeinrange(resolution, session, timezone)
Returns true when the current time is within a given session window. Note, the time is calculated in the "America/New_York" timezone.
Parameters:
resolution (simple string) : The time interval to use to start/end the background color. Use "1" for the coloring the background up to the minute.
session (simple string) : The session string to use to identify the time window. Example: "0930-1600:23456" means normal market hours on weekdays.
timezone (simple string)
Returns: series bool
barsSinceLastEntry()
Returns the number of bars since the last entry order.
Returns: series int
barsSinceLastExit()
Returns the number of bars since the last exit order.
Returns: series int
calcSlope(ln, lookback)
Calculates the slope of the provided line based on its x,y coordinates in the previous bar to the current bar.
Parameters:
ln (float)
lookback (int)
Returns: series float
openPL()
Returns slope of the line given the start and end x,y coordinates.
Returns: series float
hasConsecutiveNegativeCandles(lookbackInput)
Returns true if the number of consecutive red candles matches the provided count.
Parameters:
lookbackInput (int) : The amount of bars to look back to check for consecutive negative bars. Default = 1.
Returns: series bool
stdevPercent(stdev, price)
Returns the standard deviation as a percentage of price.
Parameters:
stdev (float) : The standard deviation value
price (float) : The current price of the target ticker.
Returns: series float
HT: Functions LibLibrary "Functions"
is_date_equal(date1, date2, time_zone)
Parameters:
date1 (int)
date2 (int)
time_zone (string)
is_date_equal(date1, date2_str, time_zone)
Parameters:
date1 (int)
date2_str (string)
time_zone (string)
is_date_between(date_, start_year, start_month, end_year, end_month, time_zone_)
Parameters:
date_ (int)
start_year (int)
start_month (int)
end_year (int)
end_month (int)
time_zone_ (string)
is_time_equal(time1, time2_str, time_zone)
Parameters:
time1 (int)
time2_str (string)
time_zone (string)
is_time_equal(time1, time2, time_zone)
Parameters:
time1 (int)
time2 (int)
time_zone (string)
is_time_between(time_, start_hour, start_minute, end_hour, end_minute, time_zone_)
Parameters:
time_ (int)
start_hour (int)
start_minute (int)
end_hour (int)
end_minute (int)
time_zone_ (string)
is_time_between(time_, start_time, end_time, time_zone_)
Parameters:
time_ (int)
start_time (string)
end_time (string)
time_zone_ (string)
is_close(value, level, ticks)
Parameters:
value (float)
level (float)
ticks (int)
is_inrange(value, lb, hb)
Parameters:
value (float)
lb (float)
hb (float)
is_above(value, level, ticks)
Parameters:
value (float)
level (float)
ticks (int)
is_below(value, level, ticks)
Parameters:
value (float)
level (float)
ticks (int)
HolidayLibrary "Holiday"
- Full Control over Holidays and Daylight Savings Time (DLS)
The Holiday Library is an essential tool for traders and analysts who engage in backtesting and live trading . This comprehensive library enables the incorporation of crucial calendar elements - specifically Daylight Savings Time (DLS) adjustments and public holidays - into trading strategies and backtesting environments.
Key Features:
- DLS Adjustments: The library takes into account the shifts in time due to Daylight Savings. This feature is particularly vital for backtesting strategies, as DLS can impact trading hours, which in turn affects the volatility and liquidity in the market. Accurate DLS adjustments ensure that backtesting scenarios are as close to real-life conditions as possible.
- Comprehensive Holiday Metadata: The library includes a rich set of holiday metadata, allowing for the detailed scheduling of trading activities around public holidays. This feature is crucial for avoiding skewed results in backtesting, where holiday trading sessions might differ significantly in terms of volume and price movement.
- Customizable Holiday Schedules: Users can add or remove specific holidays, tailoring the library to fit various regional market schedules or specific trading requirements.
- Visualization Aids: The library supports on-chart labels, making it visually intuitive to identify holidays and DLS shifts directly on trading charts.
Use Cases:
1. Strategy Development: When developing trading strategies, it’s important to account for non-trading days and altered trading hours due to holidays and DLS. This library enables a realistic and accurate representation of these factors.
2. Risk Management: Trading around holidays can be riskier due to thinner liquidity and greater volatility. By integrating holiday data, traders can better manage their risk exposure.
3. Backtesting Accuracy: For backtesting to be effective, it must simulate the actual market conditions as closely as possible. Incorporating holidays and DLS adjustments contributes to more reliable and realistic backtesting results.
4. Global Trading: For traders active in multiple global markets, this library provides an easy way to handle different holiday schedules and DLS shifts across regions.
The Holiday Library is a versatile tool that enhances the precision and realism of trading simulations and strategy development . Its integration into the trading workflow is straightforward and beneficial for both novice and experienced traders.
EasterAlgo(_year)
Calculates the date of Easter Sunday for a given year using the Anonymous Gregorian algorithm.
`Gauss Algorithm for Easter Sunday` was developed by the mathematician Carl Friedrich Gauss
This algorithm is based on the cycles of the moon and the fact that Easter always falls on the first Sunday after the first ecclesiastical full moon that occurs on or after March 21.
While it's not considered to be 100% accurate due to rare exceptions, it does give the correct date in most cases.
It's important to note that Gauss's formula has been found to be inaccurate for some 21st-century years in the Gregorian calendar. Specifically, the next suggested failure years are 2038, 2051.
This function can be used for Good Friday (Friday before Easter), Easter Sunday, and Easter Monday (following Monday).
en.wikipedia.org
Parameters:
_year (int) : `int` - The year for which to calculate the date of Easter Sunday. This should be a four-digit year (YYYY).
Returns: tuple - The month (1-12) and day (1-31) of Easter Sunday for the given year.
easterInit()
Inits the date of Easter Sunday and Good Friday for a given year.
Returns: tuple - The month (1-12) and day (1-31) of Easter Sunday and Good Friday for the given year.
isLeapYear(_year)
Determine if a year is a leap year.
Parameters:
_year (int) : `int` - 4 digit year to check => YYYY
Returns: `bool` - true if input year is a leap year
method timezoneHelper(utc)
Helper function to convert UTC time.
Namespace types: series int, simple int, input int, const int
Parameters:
utc (int) : `int` - UTC time shift in hours.
Returns: `string`- UTC time string with shift applied.
weekofmonth()
Function to find the week of the month of a given Unix Time.
Returns: number - The week of the month of the specified UTC time.
dayLightSavingsAdjustedUTC(utc, adjustForDLS)
dayLightSavingsAdjustedUTC
Parameters:
utc (int) : `int` - The normal UTC timestamp to be used for reference.
adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS).
Returns: `int` - The adjusted UTC timestamp for the given normal UTC timestamp.
getDayOfYear(monthOfYear, dayOfMonth, weekOfMonth, dayOfWeek, lastOccurrenceInMonth, holiday)
Function gets the day of the year of a given holiday (1-366)
Parameters:
monthOfYear (int)
dayOfMonth (int)
weekOfMonth (int)
dayOfWeek (int)
lastOccurrenceInMonth (bool)
holiday (string)
Returns: `int` - The day of the year of the holiday 1-366.
method buildMap(holidayMap, holiday, monthOfYear, weekOfMonth, dayOfWeek, dayOfMonth, lastOccurrenceInMonth, closingTime)
Function to build the `holidaysMap`.
Namespace types: map
Parameters:
holidayMap (map) : `map` - The map of holidays.
holiday (string) : `string` - The name of the holiday.
monthOfYear (int) : `int` - The month of the year of the holiday.
weekOfMonth (int) : `int` - The week of the month of the holiday.
dayOfWeek (int) : `int` - The day of the week of the holiday.
dayOfMonth (int) : `int` - The day of the month of the holiday.
lastOccurrenceInMonth (bool) : `bool` - Flag indicating whether the holiday is the last occurrence of the day in the month.
closingTime (int) : `int` - The closing time of the holiday.
Returns: `map` - The updated map of holidays
holidayInit(addHolidaysArray, removeHolidaysArray, defaultHolidays)
Initializes a HolidayStorage object with predefined US holidays.
Parameters:
addHolidaysArray (array) : `array` - The array of additional holidays to be added.
removeHolidaysArray (array) : `array` - The array of holidays to be removed.
defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays.
Returns: `map` - The map of holidays.
Holidays(utc, addHolidaysArray, removeHolidaysArray, adjustForDLS, displayLabel, defaultHolidays)
Main function to build the holidays object, this is the only function from this library that should be needed. \
all functionality should be available through this function. \
With the exception of initializing a `HolidayMetaData` object to add a holiday or early close. \
\
**Default Holidays:** \
`DLS begin`, `DLS end`, `New Year's Day`, `MLK Jr. Day`, \
`Washington Day`, `Memorial Day`, `Independence Day`, `Labor Day`, \
`Columbus Day`, `Veterans Day`, `Thanksgiving Day`, `Christmas Day` \
\
**Example**
```
HolidayMetaData valentinesDay = HolidayMetaData.new(holiday="Valentine's Day", monthOfYear=2, dayOfMonth=14)
HolidayMetaData stPatricksDay = HolidayMetaData.new(holiday="St. Patrick's Day", monthOfYear=3, dayOfMonth=17)
HolidayMetaData addHolidaysArray = array.from(valentinesDay, stPatricksDay)
string removeHolidaysArray = array.from("DLS begin", "DLS end")
܂Holidays = Holidays(
܂ utc=-6,
܂ addHolidaysArray=addHolidaysArray,
܂ removeHolidaysArray=removeHolidaysArray,
܂ adjustForDLS=true,
܂ displayLabel=true,
܂ defaultHolidays=true,
܂ )
plot(Holidays.newHoliday ? open : na, title="newHoliday", color=color.red, linewidth=4, style=plot.style_circles)
```
Parameters:
utc (int) : `int` - The UTC time shift in hours
addHolidaysArray (array) : `array` - The array of additional holidays to be added
removeHolidaysArray (array) : `array` - The array of holidays to be removed
adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS)
displayLabel (bool) : `bool` - Flag indicating whether to display a label on the chart
defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays
Returns: `HolidayObject` - The holidays object | Holidays = (holidaysMap: map, newHoliday: bool, holiday: string, dayString: string)
HolidayMetaData
HolidayMetaData
Fields:
holiday (series string) : `string` - The name of the holiday.
dayOfYear (series int) : `int` - The day of the year of the holiday.
monthOfYear (series int) : `int` - The month of the year of the holiday.
dayOfMonth (series int) : `int` - The day of the month of the holiday.
weekOfMonth (series int) : `int` - The week of the month of the holiday.
dayOfWeek (series int) : `int` - The day of the week of the holiday.
lastOccurrenceInMonth (series bool)
closingTime (series int) : `int` - The closing time of the holiday.
utc (series int) : `int` - The UTC time shift in hours.
HolidayObject
HolidayObject
Fields:
holidaysMap (map) : `map` - The map of holidays.
newHoliday (series bool) : `bool` - Flag indicating whether today is a new holiday.
activeHoliday (series bool) : `bool` - Flag indicating whether today is an active holiday.
holiday (series string) : `string` - The name of the holiday.
dayString (series string) : `string` - The day of the week of the holiday.
ForecastingThis Forecasting library has a couple of Novel and traditional approaches to forecasting stock prices.
Traditionally, it provides a basic ARIMA forecaster using simple autoregression, as well as a linear regression and quadratic regression channel forecaster.
Novel approaches to forecasting include:
1) A Moving Average based Forecaster (modelled after ARIMA), it is capable of forecasting based on a user selected SMA.
2) Z-Score Forecast: Forecasting based on Z-Score (example displayed in chart).
Library "Forecasting"
ARIMA_Modeller(src)
: Creates a generic autoregressive ARIMA model
Parameters:
src (float)
Returns: : arima_result, arima_ucl, arima_lcl, arima_cor, arima_r2, arima_err, y1, y2, y3, y0
machine_learning_regression(output, x1, x2, x3, x4, x5, show_statistics)
: Creates an automatic regression based forecast model (can be used for other regression operations) from a list of possible independent variables.
Parameters:
output (float)
x1 (float)
x2 (float)
x3 (float)
x4 (float)
x5 (float)
show_statistics (bool)
Returns: : result, upper bound levels, lower bound levels, optional statitics table that displays the model parameters and statistics
time_series_linear_forecast(src, forecast_length, standard_deviation_extension_1, standard_deviation_extension_2)
: Creates a simple linear regression time series channel
Parameters:
src (float)
forecast_length (int)
standard_deviation_extension_1 (float)
standard_deviation_extension_2 (float)
Returns: : Linreg Channel
quadratic_time_series_forecast(src, forecast_length)
: Creates a simple quadratic regression time series channel
Parameters:
src (float)
forecast_length (int)
Returns: : Quadratic Regression Channel
moving_average_forecaster(source, train_time, ma_length, forecast_length, forecast_result, upper_bound_result, lower_bound_result)
: Creates an ARIMA style moving average forecaster
Parameters:
source (float)
train_time (int)
ma_length (int)
forecast_length (int)
forecast_result (float )
upper_bound_result (float )
lower_bound_result (float )
Returns: : forecast_result, upper_bound_result, lower_bound_result, moving_average, ucl, lcl
zscore_forecast(z_length, z_source, show_alerts, forecast_length, show_forecast_table)
: Creates a Z-Score Forecast and is capable of plotting the immediate forecast via a Polyline
Parameters:
z_length (int)
z_source (float)
show_alerts (bool)
forecast_length (int)
show_forecast_table (bool)
Returns: : The export is void, it will export the Polyline forecast and the Z-forecast table if you enable it.
chrono_utilsLibrary "chrono_utils"
Collection of objects and common functions that are related to datetime windows session days and time
ranges. The main purpose of this library is to handle time-related functionality and make it easy to reason about a
future bar and see if it is part of a predefined user session and/or inside a datetime window. All existing session
functions I found in the documentation e.g. "not na(time(timeframe, session, timezone))" are not suitable for
strategies, since the execution of the orders is delayed by one bar due to the execution happening at the bar close.
So a prediction for the next bar is necessary. Moreover, a history operator with a negative value is not allowed e.g.
`not na(time(timeframe, session, timezone) )` expression is not valid. Thus, I created this library to overcome
this small but very important limitation. In the meantime, I added useful functionality to handle session-based
behavior. An interesting utility that emerged from this development is data anomaly detection where a comparison
between the prediction and the actual value is happening. If those two values are different then a data inconsistency
happens between the prediction bar and the actual bar (probably due to a holiday or half session day etc..)
exTimezone(timezone)
exTimezone - Convert extended timezone to timezone string
Parameters:
timezone (simple string) : - The timezone or a special string
Returns: string representing the timezone
nameOfDay(day)
nameOfDay - Convert the day id into a short nameOfDay
Parameters:
day (int) : - The day id to convert
Returns: - The short name of the day
today()
today - Get the day id of this day
Returns: - The day id
nthDayAfter(day, n)
nthDayAfter - Get the day id of n days after the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days after the reference day
nextDayAfter(day)
nextDayAfter - Get the day id of next day after the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the next day after the reference day
nthDayBefore(day, n)
nthDayBefore - Get the day id of n days before the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days before the reference day
prevDayBefore(day)
prevDayBefore - Get the day id of previous day before the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the previous day before the reference day
tomorrow()
tomorrow - Get the day id of the next day
Returns: - The next day day id
normalize(num, min, max)
normalizeHour - Check if number is inthe range of
Parameters:
num (int)
min (int)
max (int)
Returns: - The normalized number
normalizeHour(hourInDay)
normalizeHour - Check if hour is valid and return a noralized hour range from
Parameters:
hourInDay (int)
Returns: - The normalized hour
normalizeMinute(minuteInHour)
normalizeMinute - Check if minute is valid and return a noralized minute from
Parameters:
minuteInHour (int)
Returns: - The normalized minute
monthInMilliseconds(mon)
monthInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Parameters:
mon (int) : - The month of reference to get the miliseconds
Returns: - The number of milliseconds of the month
barInMilliseconds()
barInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Returns: - The number of milliseconds in one bar
method init(this, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, refTimezone, chTimezone, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
refTimezone (simple string) : - The timezone of reference of the 'from' and 'to' dates
chTimezone (simple string) : - The target timezone to convert the 'from' and 'to' dates
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, sun, mon, tue, wed, thu, fri, sat)
init - Initialize the session days object from boolean values of each session day
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sun (bool) : - Is Sunday a trading day?
mon (bool) : - Is Monday a trading day?
tue (bool) : - Is Tuesday a trading day?
wed (bool) : - Is Wednesday a trading day?
thu (bool) : - Is Thursday a trading day?
fri (bool) : - Is Friday a trading day?
sat (bool) : - Is Saturday a trading day?
Returns: - The session days objectfrom_chart
method init(this, unixTime)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
unixTime (int) : - The unix time
Returns: - The session time object
method init(this, hourInDay, minuteInHour)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
Returns: - The session time object
method init(this, hourInDay, minuteInHour, refTimezone)
init - Initialize the object from the hour and minute of the session time
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
refTimezone (string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method init(this, startTime, endTime)
init - Initialize the object from the start and end session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTime (SessionTime) : - The time the session begins
endTime (SessionTime) : - The time the session ends
Returns: - The session time range object
method init(this, startTimeHour, startTimeMinute, endTimeHour, endTimeMinute, refTimezone)
init - Initialize the object from the start and end session time
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTimeHour (int) : - The time hour the session begins
startTimeMinute (int) : - The time minute the session begins
endTimeHour (int) : - The time hour the session ends
endTimeMinute (int) : - The time minute the session ends
refTimezone (string)
Returns: - The session time range object
method init(this, days, timeRanges)
init - Initialize the user session object from session days and time range
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object that will hold the day and the time range selection
days (SessionDays) : - The session days object that defines the days the session is happening
timeRanges (SessionTimeRange ) : - The array of all the session time ranges during a session day
Returns: - The user session object
method to_string(this)
to_string - Formats the time window into a human-readable string
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The string of the time window
method to_string(this)
to_string - Formats the session days into a human-readable string with short day names
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The string of the session day short names
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_string(this)
to_string - Formats the user session into a human-readable string
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object with the day and the time range selection
Returns: - The string of the user session
method to_string(this)
to_string - Formats the bar into a human-readable string
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The string of the bar times
method to_string(this)
to_string - Formats the chart session into a human-readable string
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that contains the days and the time range shown in the chart
Returns: - The string of the chart session
method get_size_in_secs(this)
get_size_in_secs - Count the seconds from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of seconds inside the time widow for the given timeframe
method get_size_in_secs(this)
get_size_in_secs - Calculate the seconds inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of seconds inside the session
method get_size_in_bars(this)
get_size_in_bars - Count the bars from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of bars inside the time widow for the given timeframe
method get_size_in_bars(this)
get_size_in_bars - Calculate the bars inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of bars inside the session for the given timeframe
method from_chart(this)
from_chart - Initialize the session days object from the chart
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
Returns: - The user session object
method from_chart(this)
from_chart - Initialize the session time range object from the chart
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
Returns: - The session time range object
method from_chart(this)
from_chart - Initialize the session object from the chart
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that will hold the days and the time range shown in the chart
Returns: - The chart session object
method to_sess_string(this)
to_sess_string - Formats the session days into a session string with day ids
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object
Returns: - The string of the session day ids
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the user session into a session string
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object with the day and the time range selection
Returns: - The string of the user session
method to_sess_string(this)
to_sess_string - Formats the chart session into a session string
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that contains the days and the time range shown in the chart
Returns: - The string of the chart session
method from_sess_string(this, sess)
from_sess_string - Initialize the session days object from the session string
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sess (string) : - The session string part that represents the days
Returns: - The session days object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
Returns: - The session time object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time object from the session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
refTimezone (simple string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time range object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time range object from the session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method from_sess_string(this, sess)
from_sess_string - Initialize the user session object from the session string in exchange timezone (syminfo.timezone)
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object that will hold the day and the time range selection
sess (string) : - The session string that represents the user session HHmm-HHmm,HHmm-HHmm:ddddddd
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the user session object from the session string
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object that will hold the day and the time range selection
sess (string) : - The session string that represents the user session HHmm-HHmm,HHmm-HHmm:ddddddd
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method nth_day_after(this, day, n)
nth_day_after - The nth day after the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week after the given day
method nth_day_before(this, day, n)
nth_day_before - The nth day before the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week before the given day
method next_day(this)
next_day - The next day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the next session day of the week
method previous_day(this)
previous_day - The previous day that is session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the previous session day of the week
method get_sec_in_day(this)
get_sec_in_day - Count the seconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of seconds passed from the start of the day until that session time
method get_ms_in_day(this)
get_ms_in_day - Count the milliseconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of milliseconds passed from the start of the day until that session time
method eq(this, other)
eq - Compare two bars
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
other (Bar) : - The bar object to compare with
Returns: - Whether this bar is equal to the other one
method get_open_time(this)
get_open_time - The open time object
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The open time object
method get_close_time(this)
get_close_time - The close time object
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The close time object
method get_time_range(this)
get_time_range - Get the time range of the bar
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The time range that the bar is in
getBarNow()
getBarNow - Get the current bar object with time and time_close timestamps
Returns: - The current bar
getFixedBarNow()
getFixedBarNow - Get the current bar with fixed width defined by the timeframe. Note: There are case like SPX 15min timeframe where the last session bar is only 10min. This will return a bar of 15 minutes
Returns: - The current bar
method is_in_window(this, win)
is_in_window - Check if the given bar is between the start and end dates of the window
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if it is between the from and to datetimes of the window
win (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - Whether the current bar is inside the datetime window
method is_in_timerange(this, rng)
is_in_timerange - Check if the given bar is inside the session time range
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if it is between the from and to datetimes
rng (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - Whether the bar is inside the session time range and if this part of the next trading day
method is_in_days(this, days)
is_in_days - Check if the given bar is inside the session days
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if its day is a trading day
days (SessionDays) : - The session days object with the day selection
Returns: - Whether the current bar day is inside the session
method is_in_session(this, sess)
is_in_session - Check if the given bar is inside the session as defined by the input params (what "not na(time(timeframe.period, this.to_sess_string()) )" should return if you could write it
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if it is between the from and to datetimes
sess (UserSession) : - The user-defined session object with the day and the time range selection
Returns: - Whether the current time is inside the session
method next_bar(this, offsetBars)
next_bar - Predicts the next bars open and close time based on the charts session
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that contains the days and the time range shown in the chart
offsetBars (simple int) : - The number of bars forward
Returns: - Whether the current time is inside the session
DateTimeWindow
DateTimeWindow - Object that represents a datetime window with a beginning and an end
Fields:
fromDateTime (series int) : - The beginning of the datetime window
toDateTime (series int) : - The end of the datetime window
SessionDays
SessionDays - Object that represent the trading days of the week
Fields:
days (map) : - The map that contains all days of the week and their session flag
SessionTime
SessionTime - Object that represents the time (hour and minutes)
Fields:
hourInDay (series int) : - The hour of the day that ranges from 0 to 24
minuteInHour (series int) : - The minute of the hour that ranges from 0 to 59
minuteInDay (series int) : - The minute of the day that ranges from 0 to 1440. They will be calculated based on hourInDay and minuteInHour when method is called
SessionTimeRange
SessionTimeRange - Object that represents a range that extends from the start to the end time
Fields:
startTime (SessionTime) : - The beginning of the time range
endTime (SessionTime) : - The end of the time range
isOvernight (series bool) : - Whether or not this is an overnight time range
UserSession
UserSession - Object that represents a user-defined session
Fields:
days (SessionDays) : - The map of the user-defined trading days
timeRanges (SessionTimeRange ) : - The array with all time ranges of the user-defined session during the trading days
Bar
Bar - Object that represents the bars' open and close times
Fields:
openUnixTime (series int) : - The open time of the bar
closeUnixTime (series int) : - The close time of the bar
chartDayOfWeek (series int)
ChartSession
ChartSession - Object that represents the default session that is shown in the chart
Fields:
days (SessionDays) : - A map with the trading days shown in the chart
timeRange (SessionTimeRange) : - The time range of the session during a trading day
isFinalized (series bool)
High Risk Trading TimeLibrary "HighRiskTradingTime"
Utilities for time range labeling
openTime()
timeMinInDay(t, timezone)
Convert given time to minutes of day
Parameters:
t (int) : Time
timezone (string) : Timezone of the input h:m
@return Minutes of day
All exported functions args should be typified
timeMinInDayManual(h, m)
Convert given hour and minute to minutes of day
Parameters:
h (int) : Hour in a day
m (int) : Minute in a day
isForexHighRiskTime()
Return if current time is High Risk for Forex
TimeFormattingLibraryLibrary "TimeFormattingLibrary"
Time formatting functions: formating functions to make timestrings more human readable friendly (for both fixed time and time-elapsed).
Also functions for last and first instance in month of day of week input.
Also a function for identifying bank holiday Mondays.
timeFormatFxn(showDayOfWeek, showDayOfMonth, showMonth, showYear, showHrMin, _time, _timezone)
converts time into readable format
Parameters:
showDayOfWeek (bool) : if you want to show day of week (i.e. Mon, Tues etc)
showDayOfMonth (bool) : if you want to show day number of month with superscript ordinals (i.e. 1ˢᵗ, 2ⁿᵈ, etc)
showMonth (bool) : if you want to show the month (i.e. Jan, Feb, etc)
showYear (bool) : if you want to show the year (i.e. 2023)
showHrMin (bool) : if you want to show time in 24hr clock format
_time (int) : is the unix time (i.e. time or time_close)
_timezone (string) : the user timezone input as string (e.g. "America/New_York", "UTC-5", "GMT+0530")
Returns: time date string
timeElapsedFxn(timespan)
converts timespan into readable format
Parameters:
timespan (int) : is the length of time in milliseconds to be converted into a human readable string
Returns: timespan string (whether it be a for showing 'time-elapsed' or for showing a 'countdown timer')
isFirstXdayofmonth(_dayofweek)
gives bool result for when first occurence in month of the day-of-week input
Parameters:
_dayofweek (int) : (can be integer 1-7 or can be dayofweek variable; i.e. dayofweek.wednesday)
isLastXdayofmonth(_dayofweek)
gives bool result for when last occurence in month of the day-of-week input
Parameters:
_dayofweek (int) : (can be integer 1-7 or can be dayofweek variable; i.e. dayofweek.wednesday)
wasBankHolidayMonday()
gives bool result for if yesterday was a bank holiday monday. Only for use with with request.security() function, see example code below
MarketHolidaysLibrary "MarketHolidays"
The MarketHolidays library compiles market holidays (including historical special market closures) into arrays, which can then be utilized in TradingView indicators and strategies to account for non-trading days. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
getHolidays(_country)
The getHolidays function aggregates holiday data from different time periods to create a single array with market holidays for a specified country.
Parameters:
_country (string) : The country code for which to retrieve market holidays. Accepts syminfo.country or pre-set country code in ISO 3166-1 alpha-2 format.
Returns: An array of timestamps of market holidays \ non-trading days for the given country.
holidays_2020to2025Library "holidays_2020to2025"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)
holidays_2015to2020Library "holidays_2015to2020"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)