Casa_SessionsLibrary "Casa_Sessions"
Advanced trading session management library that enhances TradingView's default functionality:
Key Features:
- Accurate session detection for futures markets
- Custom session hour definitions
- Drop-in replacements for standard TradingView session functions
- Flexible session map customization
- Full control over trading windows and market hours
Perfect for traders who need precise session timing, especially when working
with futures markets or custom trading schedules.
SetSessionTimes(session_type_input, custom_session_times_input, syminfo_type, syminfo_root, syminfo_timezone)
Parameters:
session_type_input (simple string) : Input string for session selection:
- 'Custom': User-defined session times
- 'FX-Tokyo': Tokyo forex session
- 'FX-London': London forex session
- 'FX-New York': NY forex session
- 'Overnight Session (ON)': After-hours trading
- 'Day Session (RTH)': Regular trading hours
custom_session_times_input (simple string) : Session parameter for custom time windows
Only used when session_type_input is 'Custom'
syminfo_type (simple string)
syminfo_root (simple string)
syminfo_timezone (simple string)
Returns:
session_times: Trading hours for selected session
session_timezone: Market timezone (relevant for forex)
getSessionMap()
Get futures trading session hours map
Keys are formatted as 'symbol:session', examples:
- 'ES:market' - Regular trading hours (RTH)
- 'ES:overnight' - Extended trading hours (ETH)
- 'NQ:market' - NASDAQ futures RTH
- 'CL:overnight' - Crude Oil futures ETH
Returns: Map
Key: Symbol:session identifier
Value: Session hours in format "HH:MM-HH:MM"
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
getSessionHigh(session, sessionMap)
Convenience function to return the session high. Necessary if you want to call this function from within a request.security expression where you can't return a tuple.
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: The high of the session
getSessionLow(session, sessionMap)
Convenience function to return the session low. Necessary if you want to call this function from within a request.security expression where you can't return a tuple.
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: The low of the session
Casatropical
Casa_TableLibrary "Casa_Table"
A powerful library for creating customizable tables from data arrays and matrices.
Features flexible formatting options including:
- Multiple function implementations for different levels of control
- Consistent column counts required across matrix rows
- Matching dimensions needed for color arrays/matrices
- Cell spanning capabilities across rows/columns
- Rich examples demonstrating proper data structure setup
The library makes it easy to transform your data into professional-looking
tables while maintaining full control over their visual appearance.
floatArrayToCellArray(floatArray)
Helper function that converts a float array to a Cell array so it can be rendered with the fromArray function
Parameters:
floatArray (array) : (array) the float array to convert to a Cell array.
Returns: array The Cell array to return.
stringArrayToCellArray(stringArray)
Helper function that converts a string array to a Cell array so it can be rendered with the fromArray function
Parameters:
stringArray (array) : (array) the array to convert to a Cell array.
Returns: array The Cell array to return.
floatMatrixToCellMatrix(floatMatrix)
Helper function that converts a float matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
floatMatrix (matrix) : (matrix) the float matrix to convert to a string matrix.
Returns: matrix The Cell matrix to render.
stringMatrixToCellMatrix(stringMatrix)
Helper function that converts a string matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
stringMatrix (matrix) : (matrix) the string matrix to convert to a Cell matrix.
Returns: matrix The Cell matrix to return.
fromMatrix(CellMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Takes a CellMatrix and renders it as a table.
Parameters:
CellMatrix (matrix) : (matrix) The Cells to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a float matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a string matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a Cell array as a table.
Parameters:
dataArray (array) : (array) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a string array as a table.
Parameters:
dataArray (array) : (array_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a float array as a table.
Parameters:
dataArray (array) : (array_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
debug(message, position)
Renders a debug message in a table at the desired location on screen.
Parameters:
message (string) : (string) The message to render.
position (string) : (string) Optional. The position of the debug message. Defaults to position.middle_right.
Cell
Type for each cell's content and appearance
Fields:
content (series string)
bgColor (series color)
textColor (series color)
align (series string)
colspan (series int)
rowspan (series int)
Casa_UtilsLibrary "Casa_Utils"
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float) : The number to be formatted
Returns: The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: "Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int) : The hour number
minuteNumber (int) : The minute number
Returns: The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple)
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple)
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple)
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple)
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: "Solid", "Dashed", "Dotted", "None/Hidden". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string) : Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: "Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string) : Plain english position string
Returns: The string expected by tradingview functions
getRsiAvgsExpression(rsiLength)
Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
Parameters:
rsiLength (simple int) : The length of the RSI requested.
Returns: A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
getRsiPrice(rsiLevel, rsiLength, avgUp, avgDown)
use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
Parameters:
rsiLevel (float) : The RSI level to find price at.
rsiLength (int) : The length of the RSI to calculate.
avgUp (float) : The average move up of RSI.
avgDown (float) : The average move down of RSI.
Returns: The price level where the provided RSI level would be met.
getSizeFromString(sizeString)
Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: "Auto", "Huge", "Large", "Normal", "Small", "Tiny". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
sizeString (string) : Plain english size string
Returns: The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int) : The number of items to find singular/plural for.
Returns: The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string) : The string to be padded
labelStyle (string) : The style of the label being padded for.
Returns: The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int) : The number of items to find singular/plural for.
singular (string) : The string to return if num is singular. Defaults to an empty string.
plural (string) : The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: The number of secondsof that timeframe
timeframeOfChart()
Convert a timeframe string to a consistent standard.
Returns: The standard format for the string, or the unchanged value if it is unknown.
timeframeToString(timeframe)
Convert a timeframe string to a consistent standard.
Parameters:
timeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
stringToTimeframe(strTimeframe)
Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
Parameters:
strTimeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
getPriceLabel(price, labelOffset, labelStyle, labelSize, labelColor, textColor)
Defines a label for the end of a price level line.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelStyle (string) : A plain english string as defined in getLabelStyleFromString.
labelSize (string) : The size of the label.
labelColor (color) : The color of the label.
textColor (color) : The color of the label text (defaults to #ffffff)
Returns: The label that was created.
setPriceLabel(label, labelName, price, labelOffset, labelTemplate, labelStyle, labelColor, textColor)
Updates the label position & text based on price changes.
Parameters:
label (label) : The label to update.
labelName (string) : The name of the price level to be placed on the label.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelTemplate (string) : The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
labelStyle (string)
labelColor (color)
textColor (color)
getPriceLabelLine(price, labelOffset, labelColor, lineWidth)
Defines a line that will stretch from the plot line to the label.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelColor (color)
lineWidth (int) : The width of the line. Defaults to 1.
setPriceLabelLine(line, price, labelOffset, lastTime, lineColor)
Updates the price label line based on price changes.
Parameters:
line (line) : The line to update.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
lastTime (int) : The last time that the line should stretch from. Defaults to time.
lineColor (color)