utilitiesLibrary for commonly used utilities, for visualizing rolling returns, correlations and sharpe
Formatting
jsonbuilderLibrary   "jsonbuilder" 
JsonBuilder for easiest way to generate json string
 JSONBuilder(pairs) 
  Create JSONBuilder instance
  Parameters:
     pairs (array) : Pairs list, not required for users
 method addField(this, key, value, kind) 
  Add Json Object
  Namespace types: _JSONBuilder
  Parameters:
     this (_JSONBuilder) 
     key (string) : Field key
     value (string) : Field value
     kind (series Kind) : Kind value
 method execute(this) 
  Create json string
  Namespace types: _JSONBuilder
  Parameters:
     this (_JSONBuilder) 
 method addArray(this, key, value) 
  Add Json Array
  Namespace types: _JSONBuilder
  Parameters:
     this (_JSONBuilder) 
     key (string) : Field key
     value (array<_JSONBuilder>) : Object value array
 method addObject(this, key, value) 
  Add Json Object
  Namespace types: _JSONBuilder
  Parameters:
     this (_JSONBuilder) 
     key (string) : Field key
     value (_JSONBuilder) : Object value
 _JSONBuilder 
  JSONBuilder type
  Fields:
     pairs (array) : Pairs data
Helper Lib by tristanlee85Library   "helpers" 
This library offers various functions and types based on the algorithmic
concepts as authored by ICT.
 kv(key, value) 
  Returns a string of the key/value set, suitable for debug logging
  Parameters:
     key (string) 
     value (string) 
  Returns: A string formatted as "{key}: {value}"
 kv(key, value) 
  Parameters:
     key (string) 
     value (int) 
 kv(key, value) 
  Parameters:
     key (string) 
     value (float) 
 kv(key, value) 
  Parameters:
     key (string) 
     value (bool) 
 method enable(this, enable) 
  Enable/Disable debug logging
  Namespace types: Debugger
  Parameters:
     this (Debugger) 
     enable (bool) : Set to `true` by default.
 method group(this, label) 
  Creates a group label for nested debug() invocations
  Namespace types: Debugger
  Parameters:
     this (Debugger) 
     label (string) 
 method groupEnd(this, label) 
  Ends the specified debug group
  Namespace types: Debugger
  Parameters:
     this (Debugger) 
     label (string) 
 method log(this, s, arg1, arg2, arg3, arg4, arg5) 
  Logs the param values if debug mode is enabled
  Namespace types: Debugger
  Parameters:
     this (Debugger) 
     s (string) : Title of the log message
     arg1 (string) 
     arg2 (string) 
     arg3 (string) 
     arg4 (string) 
     arg5 (string) 
 method logIf(this, expr, s, arg1, arg2, arg3, arg4, arg5) 
  Same behavior as debug() except will only log if the passed expression is true
  Namespace types: Debugger
  Parameters:
     this (Debugger) 
     expr (bool) : Boolean expression to determine if debug logs should be logged
     s (string) : Title of the log message
     arg1 (string) 
     arg2 (string) 
     arg3 (string) 
     arg4 (string) 
     arg5 (string) 
 style_getLineStyleFromType(opt) 
  Returns the corresponding line style constant for the given LineStyleType
  Parameters:
     opt (series LineStyleType) : The selected line style type
  Returns: The Pine Script line style constant
 style_getTextSizeFromType(opt) 
  Returns the corresponding text size constant for the given TextSizeType
  Parameters:
     opt (series TextSizeType) : The selected text size type
  Returns: The Pine Script text size constant
 style_getTextHAlignFromType(t) 
  Returns the corresponding horizontal text align constant for the given HAlignType
  Parameters:
     t (series HAlignType) : The selected text align type
  Returns: The Pine Script text align constant
 style_getTextVAlignFromType(t) 
  Returns the corresponding vertical text align constant for the given VAlignType
  Parameters:
     t (series VAlignType) : The selected text align type
  Returns: The Pine Script text align constant
 format_sentimentType(sentiment, pd) 
  Used to produce a string with the sentiment and PD array type (e.g., "+FVG")
  Parameters:
     sentiment (series SentimentType) : The sentiment value (e.g., SentimentType.BULLISH)
     pd (series PDArrayType) : The price data array (e.g., PDArrayType.FVG)
  Returns: A formatted string with the sentiment and PD array (e.g., "+FVG")
 format_timeToString(timestamp) 
  Formats a UNIX timestamp into a date and time string based on predefined formats
  Parameters:
     timestamp (int) : The UNIX timestamp to format
  Returns: A formatted string as "MM-dd (E) - HH:mm"
 method init(this) 
  Initializes the session and validates the configuration. This MUST be called immediately after creating a new instance.
  Namespace types: Session
  Parameters:
     this (Session) : The Session object reference
  Returns: The Session object (chainable) or throws a runtime error if invalid
 method isActive(this, _time) 
  Determines if the session is active based on the current bar time
  Namespace types: Session
  Parameters:
     this (Session) : The Session object reference
     _time (int) 
  Returns: `true` if the session is currently active; `false` otherwise
 method draw(this) 
  Draws the line and optional label
  Namespace types: LineLabel
  Parameters:
     this (LineLabel) : The LineLabel object reference
  Returns: The LineLabel object (chainable)
 method extend(this, x) 
  Extends the line and label right to the specified bar index
  Namespace types: LineLabel
  Parameters:
     this (LineLabel) : The LineLabel object reference
     x (int) : The bar index to extend to
  Returns: The LineLabel object (chainable)
 method destroy(this) 
  Removes the line and label from the chart
  Namespace types: LineLabel
  Parameters:
     this (LineLabel) : The LineLabel object reference
 isFVG(includeVI, barIdx) 
  Checks if the previous bars form a Fair Value Gap (FVG)
  Parameters:
     includeVI (bool) : If true, includes Volume Imbalance in the FVG calculation
     barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
  Returns: A Gap object if a FVG is detected; otherwise, `na`
 isVolumeImbalance(barIdx) 
  Checks if the previous bars form a Volume Imbalance (VI)
  Parameters:
     barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
  Returns: A Gap object if a VI is detected; otherwise, `na`
 isLiquidityVoid(barIdx) 
  Checks if the previous bars form a Liquidity Void (LV)
  Parameters:
     barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
  Returns: A Gap object if an LV is detected; otherwise, `na`
 isSwingPoint(barIdx) 
  Checks if the previous bars form a swing point
  Parameters:
     barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
  Returns: A SwingPoint object if a swing point is detected; otherwise, `na`
 Debugger 
  A debug logging utility with group support
  Fields:
     enabled (series bool) 
     _debugGroupStack (array) 
 Session 
  Defines a trading session with a name and time range. When creating a new instance of this type, you MUST call init() immediately.
  Fields:
     name (series string) : A display-friendly name (e.g., "NY AM")
     session (series string) : A string defining the session time range (e.g., "1300-1400")
     enabled (series bool) : Optional flag for custom logic; defaults to false
     start (series int) : UNIX time representing the session start (set via isActive())
     end (series int) : UNIX time representing the session end (set via isActive())
     _t (series int) 
     _start_HH (series float) 
     _start_mm (series float) 
     _end_HH (series float) 
     _end_mm (series float) 
 Gap 
  Represents a price inefficiency (gap) with details on sentiment and price levels
  Fields:
     type (series SentimentType) : The sentiment of the gap (e.g., SentimentType.BULLISH)
     name (series string) : A display-friendly name (e.g., "+FVG")
     startTime (series int) : UNIX time value for the gap's start
     endTime (series int) : UNIX time value for the gap's end
     startIndex (series int) : Bar index where the gap starts
     endIndex (series int) : Bar index where the gap ends
     gapLow (series float) : The lowest price level of the gap
     gapHigh (series float) : The highest price level of the gap
     ce (series float) : The consequent encroachment level of the gap
 SwingPoint 
  Represents a swing point with details on type and price level
  Fields:
     type (series SwingPointType) : The type of swing point (e.g., SwingPointType.HIGH)
     time (series int) : UNIX time value for the swing point
     barIdx (series int) : Bar index where the swing point occurs
     price (series float) : The price level of the swing point which is either the high or low of the middle bar
 LineLabel 
  Combines a line and box type to produce a line with a label that is properly aligned
  Fields:
     x (series int) : The X-axis starting point as a bar index
     y (series float) : The Y-axis starting point as the price level
     color (series color) : Both the line and text color
     width (series int) : Thickness of the line
     label (series string) : Text to display
     showLabel (series bool) : Boolean to conditionally show/hide the label (default is false)
     lineStyle (series LineStyleType) : The style of the line
     textSize (series TextSizeType) 
     _b (series box) 
     _l (series line)
TextLibrary   "Text" 
library to format text in different  fonts  or  cases  plus a  sort  function.
🔸  Credits and Usage 
This library is inspired by the work of three authors (in chronological order of publication date):
 
 Unicode font function - JD  -  Duyck 
 UnicodeReplacementFunction  -  wlhm 
 font  -  kaigouthro 
 
🔹  Fonts 
Besides extra added font options, the  toFont(fromText, font)  method uses a different technique. On the first runtime bar (whether it is  barstate.isfirst ,  barstate.islast , or between) regular letters and numbers and mapped with the chosen font. After this, each character is replaced using the build-in  key - value pair   map function .
Also an  enum Efont  is included. 
Note: Some fonts are not complete, for example there isn't a replacement for every character in Superscript/Subscript.
Example of usage (besides the included table example):
 import fikira/Text/1 as t
i_font = input.enum(t.Efont.Blocks)
if barstate.islast
    sentence  = "this sentence contains words"
    label.new(bar_index, 0, t.toFont(fromText = sentence, font = str.tostring(i_font)), style=label.style_label_lower_right)
    label.new(bar_index, 0, t.toFont(fromText = sentence, font =    "Circled"        ), style=label.style_label_lower_left )
    label.new(bar_index, 0, t.toFont(fromText = sentence, font =    "Wiggly"         ), style=label.style_label_upper_right)
    label.new(bar_index, 0, t.toFont(fromText = sentence, font =    "Upside Latin"   ), style=label.style_label_upper_left ) 
🔹  Cases 
The script includes a  toCase(fromText, case)  method to transform text into snake_case, UPPER SNAKE_CASE, kebab-case, camelCase or PascalCase, as well as an  enum Ecase .
Example of usage (besides the included table example):
 import fikira/Text/1 as t
i_case = input.enum(t.Ecase.camel)
if barstate.islast
    sentence  = "this sentence contains words"
    label.new(bar_index, 0, t.toCase(fromText = sentence, case = str.tostring(i_case)), style=label.style_label_lower_right)
    label.new(bar_index, 0, t.toCase(fromText = sentence, case =    "snake_case"     ), style=label.style_label_lower_left )
    label.new(bar_index, 0, t.toCase(fromText = sentence, case =    "PascalCase"     ), style=label.style_label_upper_right)
    label.new(bar_index, 0, t.toCase(fromText = sentence, case =    "SNAKE_CASE"     ), style=label.style_label_upper_left ) 
🔹  Sort 
The  sort(strings, order, sortByUnicodeDecimalNumbers)  method returns a sorted array of strings.
 
 strings: array of strings, for example  words = array.from("Aword", "beyond", "Space", "salt", "pepper", "swing", "someThing", "otherThing", "12345", "_firstWord")  
 order:  "asc" / "desc" (ascending / descending)
 sortByUnicodeDecimalNumbers: true/false; default = false
 
_____
• sortByUnicodeDecimalNumbers: every Unicode character is linked to a Unicode Decimal number ( wikipedia.org/wiki/List_of_Unicode_characters ), for example:
1	  49
2        50
3        51
   ...
A	  65
B        66
   ...
S	  83
   ...
_  	  95
`	  96
a         97
b	  98
   ...
o	111
p	112
q      113
r       114
s	115
   ... 
This means, if we sort without adjusting ( sortByUnicodeDecimalNumbers = true ), in ascending order, the letter b (98 - small) would be after S (83 - Capital).
By disabling  sortByUnicodeDecimalNumbers , Capital letters are intermediate transformed to  str.lower()  after which the Unicode Decimal number is retrieved from the small number instead of the capital number. For example S (83) -> s (115), after which the number 115 is used to sort instead of 83.
Example of usage (besides the included table example):
 import fikira/Text/1 as t
if barstate.islast
    aWords  = array.from("Aword", "beyond", "Space", "salt", "pepper", "swing", "someThing", "otherThing", "12345", "_firstWord") 
    label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'asc' , sortByUnicodeDecimalNumbers = false)), style=label.style_label_lower_right)
    label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'desc', sortByUnicodeDecimalNumbers = false)), style=label.style_label_lower_left )
    label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'asc' , sortByUnicodeDecimalNumbers = true )), style=label.style_label_upper_right)
    label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'desc', sortByUnicodeDecimalNumbers = true )), style=label.style_label_upper_left ) 
🔸  Methods/functions 
 method toFont(fromText, font) 
  toFont   : Transforms text into the selected font
  Namespace types: series string, simple string, input string, const string
  Parameters:
     fromText (string) 
     font (string) 
  Returns: `fromText` transformed to desired `font`
 method toCase(fromText, case) 
  toCase   : formats text to snake_case, UPPER SNAKE_CASE, kebab-case, camelCase or PascalCase
  Namespace types: series string, simple string, input string, const string
  Parameters:
     fromText (string) 
     case (string) 
  Returns: `fromText` formatted to desired `case`
 method sort(strings, order, sortByUnicodeDecimalNumbers) 
  sort     : sorts an array of strings, ascending/descending and by Unicode Decimal numbers or not.
  Namespace types: array
  Parameters:
     strings (array) 
     order (string) 
     sortByUnicodeDecimalNumbers (bool) 
  Returns: Sorted array of strings
TimezoneFormatIANAUTCLibrary   "TimezoneFormatIANAUTC" 
Provides either the full IANA timezone identifier or the corresponding UTC offset for TradingView’s built-in variables and functions.
 tz(_tzname, _format) 
  Parameters:
     _tzname (string) : "London", "New York", "Istanbul", "+1:00", "-03:00" etc.
     _format (string) : "IANA" or "UTC"
  Returns:  "Europe/London", "America/New York", "UTC+1:00"
 Example Code 
 import ARrowofTime/TimezoneFormatIANAUTC/1 as libtz
sesTZInput  = input.string(defval = "Singapore", title = "Timezone")
example1    = libtz.tz("London", "IANA")        // Return Europe/London
example2    = libtz.tz("London", "UTC")         // Return UTC+1:00
example3    = libtz.tz("UTC+5", "IANA")         // Return UTC+5:00
example4    = libtz.tz("UTC+4:30", "UTC")       // Return UTC+4:30
example5    = libtz.tz(sesTZInput, "IANA")      // Return Asia/Singapore
example6    = libtz.tz(sesTZInput, "UTC")       // Return UTC+8:00
sesTime1    = time("","1300-1700", example1)    // returns the UNIX time of the current bar in session time or na
sesTime2    = time("","1300-1700", example2)    // returns the UNIX time of the current bar in session time or na
sesTime3    = time("","1300-1700", example3)    // returns the UNIX time of the current bar in session time or na
sesTime4    = time("","1300-1700", example4)    // returns the UNIX time of the current bar in session time or na
sesTime5    = time("","1300-1700", example5)    // returns the UNIX time of the current bar in session time or na
sesTime6    = time("","1300-1700", example6)    // returns the UNIX time of the current bar in session time or na 
 Parameter Format Guide 
This section explains how to properly format the parameters for the  tz(_tzname, _format)  function.
 _tzname  (string) must be either;
 
 A valid timezone name exactly as it appears in the chart’s lower-right corner (e.g. New York, London).
 A valid UTC offset in ±H:MM or ±HH:MM format. Hours: 0–14 (zero-padded or not, e.g. +1:30, +01:30, -0:00). Minutes: Must be 00, 15, 30, or 45
 
 examples; 
 
 "New York" → ✅ Valid chart label
 "London" → ✅ Valid chart label
 "Berlin" → ✅ Valid chart label
 "America/New York" → ❌ Invalid chart label. (Use "New York" instead)
 "+1:30" → ✅ Valid offset with single-digit hour
 "+01:30" → ✅ Valid offset with zero-padded hour
 "-05:00" → ✅ Valid negative offset
 "-0:00" → ✅ Valid zero offset
 "+1:1" → ❌ Invalid (minute must be 00, 15, 30, or 45)
 "+2:50" → ❌ Invalid (minute must be 00, 15, 30, or 45)
 "+15:00" → ❌ Invalid (hour must be 14 or below)
 
 _tztype  (string) must be either;
 
 "IANA" → returns full IANA timezone identifier (e.g. "Europe/London").  When a time function call uses an IANA time zone identifier for its timezone argument, its calculations adjust automatically for historical and future changes to the specified region’s observed time, such as daylight saving time (DST) and updates to time zone boundaries, instead of using a fixed offset from UTC.
 "UTC" → returns UTC offset string (e.g. "UTC+01:00")
TimeframeInputToStringMaps a worded string for timeframes useful when working with the input.timeframe settings input. Use like timeframeToString("120") and the output will be "2 hour"
light_logLight Log - A Defensive Programming Library for Pine Script 
 Overview 
The Light Log library transforms Pine Script development by introducing structured logging and defensive programming patterns typically found in enterprise languages like C#. This library addresses a fundamental challenge in Pine Script: the lack of sophisticated error handling and debugging tools that developers expect when building complex trading systems.
At its core, Light Log provides three transformative capabilities that work together to create more reliable and maintainable code. First, it wraps all native Pine Script types in error-aware containers, allowing values to carry validation state alongside their data. Second, it offers a comprehensive logging system with severity levels and conditional rendering. Third, it includes defensive programming utilities that catch errors early and make code self-documenting.
 The Philosophy of Errors as Values 
Traditional Pine Script error handling relies on runtime errors that halt execution, making it difficult to build resilient systems that can gracefully handle edge cases. Light Log introduces a paradigm shift by treating errors as first-class values that flow through your program alongside regular data.
When you wrap a value using Light Log's type system, you're not just storing data – you're creating a container that can carry both the value and its validation state. For example, when you call  myNumber.INT() , you receive an INT object that contains both the integer value and a Log object that can describe any issues with that value. This approach, inspired by functional programming languages, allows errors to propagate through calculations without causing immediate failures.
Consider how this changes error handling in practice. Instead of a calculation failing catastrophically when it encounters invalid input, it can produce a result object that contains both the computed value (which might be na) and a detailed log explaining what went wrong. Subsequent operations can check  has_error()  to decide whether to proceed or handle the error condition gracefully.
 The Typed Wrapper System 
Light Log provides typed wrappers for every native Pine Script type: INT, FLOAT, BOOL, STRING, COLOR, LINE, LABEL, BOX, TABLE, CHART_POINT, POLYLINE, and LINEFILL. These wrappers serve multiple purposes beyond simple value storage.
Each wrapper type contains two fields: the value field  v  holds the actual data, while the error field  e  contains a Log object that tracks the value's validation state. This dual nature enables powerful programming patterns. You can perform operations on wrapped values and accumulate error information along the way, creating an audit trail of how values were processed.
The wrapper system includes convenient methods for converting between wrapped and unwrapped values. The extension methods like  INT() ,  FLOAT() , etc., make it easy to wrap existing values, while the  from_INT() ,  from_FLOAT()  methods extract the underlying values when needed. The  has_error()  method provides a consistent interface for checking whether any wrapped value has encountered issues during processing.
 The Log Object: Your Debugging Companion 
The Log object represents the heart of Light Log's debugging capabilities. Unlike simple string concatenation for error messages, the Log object provides a structured approach to building, modifying, and rendering diagnostic information.
Each Log object carries three essential pieces of information: an error type (info, warning, error, or runtime_error), a message string that can be built incrementally, and an active flag that controls conditional rendering. This structure enables sophisticated logging patterns where you can build up detailed diagnostic information throughout your script's execution and decide later whether and how to display it.
The Log object's methods support fluent chaining, allowing you to build complex messages in a readable way. The  write()  and  write_line()  methods append text to the log, while  new_line()  adds formatting. The  clear()  method resets the log for reuse, and the rendering methods ( render_now() ,  render_condition() , and the general  render() ) control when and how messages appear.
 Defensive Programming Made Easy 
Light Log's argument validation functions transform how you write defensive code. Instead of cluttering your functions with verbose validation logic, you can use concise, self-documenting calls that make your intentions clear.
The  argument_error()  function provides strict validation that halts execution when conditions aren't met – perfect for catching programming errors early. For less critical issues,  argument_log_warning()  and  argument_log_error()  record problems without stopping execution, while  argument_log_info()  provides debug visibility into your function's behavior.
These functions follow a consistent pattern: they take a condition to check, the function name, the argument name, and a descriptive message. This consistency makes error messages predictable and helpful, automatically formatting them to show exactly where problems occurred.
 Building Modular, Reusable Code 
Light Log encourages a modular approach to Pine Script development by providing tools that make functions more self-contained and reliable. When functions validate their inputs and return wrapped values with error information, they become true black boxes that can be safely composed into larger systems.
The  void_return()  function addresses Pine Script's requirement that all code paths return a value, even in error handling branches. This utility function provides a clean way to satisfy the compiler while making it clear that a particular code path should never execute.
The static log pattern, initialized with  init_static_log() , enables module-wide error tracking. You can create a persistent Log object that accumulates information across multiple function calls, building a comprehensive diagnostic report that helps you understand complex behaviors in your indicators and strategies.
 Real-World Applications 
In practice, Light Log shines when building sophisticated trading systems. Imagine developing a complex indicator that processes multiple data streams, performs statistical calculations, and generates trading signals. With Light Log, each processing stage can validate its inputs, perform calculations, and pass along both results and diagnostic information.
For example, a moving average calculation might check that the period is positive, that sufficient data exists, and that the input series contains valid values. Instead of failing silently or throwing runtime errors, it can return a FLOAT object that contains either the calculated average or a detailed explanation of why the calculation couldn't be performed.
Strategy developers benefit even more from Light Log's capabilities. Complex entry and exit logic often involves multiple conditions that must all be satisfied. With Light Log, each condition check can contribute to a comprehensive log that explains exactly why a trade was or wasn't taken, making strategy debugging and optimization much more straightforward.
 Performance Considerations 
While Light Log adds a layer of abstraction over raw Pine Script values, its design minimizes performance impact. The wrapper objects are lightweight, containing only two fields. The logging operations only consume resources when actually rendered, and the conditional rendering system ensures that production code can run with logging disabled for maximum performance.
The library follows Pine Script best practices for performance, using appropriate data structures and avoiding unnecessary operations. The var keyword in  init_static_log()  ensures that persistent logs don't create new objects on every bar, maintaining efficiency even in real-time calculations.
 Getting Started 
Adopting Light Log in your Pine Script projects is straightforward. Import the library, wrap your critical values, add validation to your functions, and use Log objects to track important events. Start small by adding logging to a single function, then expand as you see the benefits of better error visibility and code organization.
Remember that Light Log is designed to grow with your needs. You can use as much or as little of its functionality as makes sense for your project. Even simple uses, like adding argument validation to key functions, can significantly improve code reliability and debugging ease.
 Transform your Pine Script development experience with Light Log – because professional trading systems deserve professional development tools. 
 Light Log Technical Deep Dive: Advanced Patterns and Architecture 
 Understanding Errors as Values 
The concept of "errors as values" represents a fundamental shift in how we think about error handling in Pine Script. In traditional Pine Script development, errors are events – they happen at a specific moment in time and immediately interrupt program flow. Light Log transforms errors into data – they become information that flows through your program just like any other value.
This transformation has profound implications. When errors are values, they can be stored, passed between functions, accumulated, transformed, and inspected. They become part of your program's data flow rather than exceptions to it. This approach, popularized by languages like Rust with its Result type and Haskell with its Either monad, brings functional programming's elegance to Pine Script.
Consider a practical example. Traditional Pine Script might calculate a momentum indicator like this:
 momentum = close - close 
If  period  is invalid or if there isn't enough historical data, this calculation might produce  na  or cause subtle bugs. With Light Log's approach:
 calculate_momentum(src, period)=>
    result = src.FLOAT()
    
    if period <= 0
        result.e.write("Invalid period: must be positive", true, ErrorType.error)
        result.v := na
    else if bar_index < period
        result.e.write("Insufficient data: need " + str.tostring(period) + " bars", true, ErrorType.warning)
        result.v := na
    else
        result.v := src - src 
        result.e.write("Momentum calculated successfully", false, ErrorType.info)
    
    result 
Now the function returns not just a value but a complete computational result that includes diagnostic information. Calling code can make intelligent decisions based on both the value and its associated metadata.
 The Monad Pattern in Pine Script 
While Pine Script lacks the type system features to implement true monads, Light Log brings monadic thinking to Pine Script development. The wrapped types (INT, FLOAT, etc.) act as computational contexts that carry both values and metadata through a series of transformations.
The key insight of monadic programming is that you can chain operations while automatically propagating context. In Light Log, this context is the error state. When you have a FLOAT that contains an error, operations on that FLOAT can check the error state and decide whether to proceed or propagate the error.
This pattern enables what functional programmers call "railway-oriented programming" – your code follows a success track when all is well but can switch to an error track when problems occur. Both tracks lead to the same destination (a result with error information), but they take different paths based on the validity of intermediate values.
 Composable Error Handling 
Light Log's design encourages composition – building complex functionality from simpler, well-tested components. Each component can validate its inputs, perform its calculation, and return a result with appropriate error information. Higher-level functions can then combine these results intelligently.
Consider building a complex trading signal from multiple indicators:
 generate_signal(src, fast_period, slow_period, signal_period) =>
    log = init_static_log(ErrorType.info)
    
    // Calculate components with error tracking
    fast_ma = calculate_ma(src, fast_period)
    slow_ma = calculate_ma(src, slow_period)
    
    // Check for errors in components
    if fast_ma.has_error()
        log.write_line("Fast MA error: " + fast_ma.e.message, true)
    if slow_ma.has_error()
        log.write_line("Slow MA error: " + slow_ma.e.message, true)
    
    // Proceed with calculation if no errors
    signal = 0.0.FLOAT()
    if not (fast_ma.has_error() or slow_ma.has_error())
        macd_line = fast_ma.v - slow_ma.v
        signal_line = calculate_ma(macd_line, signal_period)
        
        if signal_line.has_error()
            log.write_line("Signal line error: " + signal_line.e.message, true)
            signal.e := log
        else
            signal.v := macd_line - signal_line.v
            log.write("Signal generated successfully")
    else
        signal.e := log
        signal.v := na
    
    signal 
This composable approach makes complex calculations more reliable and easier to debug. Each component is responsible for its own validation and error reporting, and the composite function orchestrates these components while maintaining comprehensive error tracking.
 The Static Log Pattern 
The  init_static_log()  function introduces a powerful pattern for maintaining state across function calls. In Pine Script, the  var  keyword creates variables that persist across bars but are initialized only once. Light Log leverages this to create logging objects that can accumulate information throughout a script's execution.
This pattern is particularly valuable for debugging complex strategies where you need to understand behavior across multiple bars. You can create module-level logs that track important events:
 // Module-level diagnostic log
diagnostics = init_static_log(ErrorType.info)
// Track strategy decisions across bars
check_entry_conditions() =>
    diagnostics.clear()  // Start fresh each bar
    
    diagnostics.write_line("Bar " + str.tostring(bar_index) + " analysis:")
    
    if close > sma(close, 20)
        diagnostics.write_line("Price above SMA20", false)
    else
        diagnostics.write_line("Price below SMA20 - no entry", true, ErrorType.warning)
    
    if volume > sma(volume, 20) * 1.5
        diagnostics.write_line("Volume surge detected", false)
    else
        diagnostics.write_line("Normal volume", false)
    
    // Render diagnostics based on verbosity setting
    if debug_mode
        diagnostics.render_now() 
 Advanced Validation Patterns 
Light Log's argument validation functions enable sophisticated precondition checking that goes beyond simple null checks. You can implement complex validation logic while keeping your code readable:
 validate_price_data(open_val, high_val, low_val, close_val) =>
    argument_error(na(open_val) or na(high_val) or na(low_val) or na(close_val), 
                   "validate_price_data", "OHLC values", "contain na values")
    
    argument_error(high_val < low_val, 
                   "validate_price_data", "high/low", "high is less than low")
    
    argument_error(close_val > high_val or close_val < low_val,
                   "validate_price_data", "close", "is outside high/low range")
    
    argument_log_warning(high_val == low_val,
                        "validate_price_data", "high/low", "are equal (no range)") 
This validation function documents its requirements clearly and fails fast with helpful error messages when assumptions are violated. The mix of errors (which halt execution) and warnings (which allow continuation) provides fine-grained control over how strict your validation should be.
 Performance Optimization Strategies 
While Light Log adds abstraction, careful design minimizes overhead. Understanding Pine Script's execution model helps you use Light Log efficiently.
Pine Script executes once per bar, so operations that seem expensive in traditional programming might have negligible impact. However, when building real-time systems, every optimization matters. Light Log provides several patterns for efficient use:
 Lazy Evaluation:  Log messages are only built when they'll be rendered. Use conditional logging to avoid string concatenation in production:
 if debug_mode
    log.write_line("Calculated value: " + str.tostring(complex_calculation)) 
 Selective Wrapping:  Not every value needs error tracking. Wrap values at API boundaries and critical calculation points, but use raw values for simple operations:
 // Wrap at boundaries
input_price = close.FLOAT()
validated_period = validate_period(input_period).INT()
// Use raw values internally
sum = 0.0
for i = 0 to validated_period.v - 1
    sum += close 
 Error Propagation:  When errors occur early, avoid expensive calculations:
 process_data(input) =>
    validated = validate_input(input)
    if validated.has_error()
        validated  // Return early with error
    else
        // Expensive processing only if valid
        perform_complex_calculation(validated) 
 Integration Patterns 
Light Log integrates smoothly with existing Pine Script code. You can adopt it incrementally, starting with critical functions and expanding coverage as needed.
 Boundary Validation:  Add Light Log at the boundaries of your system – where user input enters and where final outputs are produced. This catches most errors while minimizing changes to existing code.
 Progressive Enhancement:  Start by adding argument validation to existing functions. Then wrap return values. Finally, add comprehensive logging. Each step improves reliability without requiring a complete rewrite.
 Testing and Debugging:  Use Light Log's conditional rendering to create debug modes for your scripts. Production users see clean output while developers get detailed diagnostics:
 // User input for debug mode
debug = input.bool(false, "Enable debug logging")
// Conditional diagnostic output
if debug
    diagnostics.render_now()
else
    diagnostics.render_condition()  // Only shows errors/warnings 
 Future-Proofing Your Code 
Light Log's patterns prepare your code for Pine Script's evolution. As Pine Script adds more sophisticated features, code that uses structured error handling and defensive programming will adapt more easily than code that relies on implicit assumptions.
The type wrapper system, in particular, positions your code to take advantage of potential future features or more sophisticated type inference. By thinking in terms of wrapped values and error propagation today, you're building code that will remain maintainable and extensible tomorrow.
 Light Log doesn't just make your Pine Script better today – it prepares it for the trading systems you'll need to build tomorrow. 
Library   "light_log" 
A lightweight logging and defensive programming library for Pine Script.
Designed for modular and extensible scripts, this utility provides structured runtime validation,
conditional logging, and reusable `Log` objects for centralized error propagation.
It also introduces a typed wrapping system for all native Pine values (e.g., `INT`, `FLOAT`, `LABEL`),
allowing values to carry errors alongside data. This enables functional-style flows with built-in
validation tracking, error detection (`has_error()`), and fluent chaining.
Inspired by structured logging patterns found in systems like C#, it reduces boilerplate,
enforces argument safety, and encourages clean, maintainable code architecture.
 method INT(self, error_type) 
  Wraps an `int` value into an `INT` struct with an optional log severity.
  Namespace types: series int, simple int, input int, const int
  Parameters:
     self (int) : The raw `int` value to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: An `INT` object containing the value and a default Log instance.
 method FLOAT(self, error_type) 
  Wraps a `float` value into a `FLOAT` struct with an optional log severity.
  Namespace types: series float, simple float, input float, const float
  Parameters:
     self (float) : The raw `float` value to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `FLOAT` object containing the value and a default Log instance.
 method BOOL(self, error_type) 
  Wraps a `bool` value into a `BOOL` struct with an optional log severity.
  Namespace types: series bool, simple bool, input bool, const bool
  Parameters:
     self (bool) : The raw `bool` value to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `BOOL` object containing the value and a default Log instance.
 method STRING(self, error_type) 
  Wraps a `string` value into a `STRING` struct with an optional log severity.
  Namespace types: series string, simple string, input string, const string
  Parameters:
     self (string) : The raw `string` value to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `STRING` object containing the value and a default Log instance.
 method COLOR(self, error_type) 
  Wraps a `color` value into a `COLOR` struct with an optional log severity.
  Namespace types: series color, simple color, input color, const color
  Parameters:
     self (color) : The raw `color` value to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `COLOR` object containing the value and a default Log instance.
 method LINE(self, error_type) 
  Wraps a `line` object into a `LINE` struct with an optional log severity.
  Namespace types: series line
  Parameters:
     self (line) : The raw `line` object to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `LINE` object containing the value and a default Log instance.
 method LABEL(self, error_type) 
  Wraps a `label` object into a `LABEL` struct with an optional log severity.
  Namespace types: series label
  Parameters:
     self (label) : The raw `label` object to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `LABEL` object containing the value and a default Log instance.
 method BOX(self, error_type) 
  Wraps a `box` object into a `BOX` struct with an optional log severity.
  Namespace types: series box
  Parameters:
     self (box) : The raw `box` object to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `BOX` object containing the value and a default Log instance.
 method TABLE(self, error_type) 
  Wraps a `table` object into a `TABLE` struct with an optional log severity.
  Namespace types: series table
  Parameters:
     self (table) : The raw `table` object to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `TABLE` object containing the value and a default Log instance.
 method CHART_POINT(self, error_type) 
  Wraps a `chart.point` value into a `CHART_POINT` struct with an optional log severity.
  Namespace types: chart.point
  Parameters:
     self (chart.point) : The raw `chart.point` value to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `CHART_POINT` object containing the value and a default Log instance.
 method POLYLINE(self, error_type) 
  Wraps a `polyline` object into a `POLYLINE` struct with an optional log severity.
  Namespace types: series polyline, series polyline, series polyline, series polyline
  Parameters:
     self (polyline) : The raw `polyline` object to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `POLYLINE` object containing the value and a default Log instance.
 method LINEFILL(self, error_type) 
  Wraps a `linefill` object into a `LINEFILL` struct with an optional log severity.
  Namespace types: series linefill
  Parameters:
     self (linefill) : The raw `linefill` object to wrap.
     error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
  Returns: A `LINEFILL` object containing the value and a default Log instance.
 method from_INT(self) 
  Extracts the integer value from an INT wrapper.
  Namespace types: INT
  Parameters:
     self (INT) : The wrapped INT instance.
  Returns: The underlying `int` value.
 method from_FLOAT(self) 
  Extracts the float value from a FLOAT wrapper.
  Namespace types: FLOAT
  Parameters:
     self (FLOAT) : The wrapped FLOAT instance.
  Returns: The underlying `float` value.
 method from_BOOL(self) 
  Extracts the boolean value from a BOOL wrapper.
  Namespace types: BOOL
  Parameters:
     self (BOOL) : The wrapped BOOL instance.
  Returns: The underlying `bool` value.
 method from_STRING(self) 
  Extracts the string value from a STRING wrapper.
  Namespace types: STRING
  Parameters:
     self (STRING) : The wrapped STRING instance.
  Returns: The underlying `string` value.
 method from_COLOR(self) 
  Extracts the color value from a COLOR wrapper.
  Namespace types: COLOR
  Parameters:
     self (COLOR) : The wrapped COLOR instance.
  Returns: The underlying `color` value.
 method from_LINE(self) 
  Extracts the line object from a LINE wrapper.
  Namespace types: LINE
  Parameters:
     self (LINE) : The wrapped LINE instance.
  Returns: The underlying `line` object.
 method from_LABEL(self) 
  Extracts the label object from a LABEL wrapper.
  Namespace types: LABEL
  Parameters:
     self (LABEL) : The wrapped LABEL instance.
  Returns: The underlying `label` object.
 method from_BOX(self) 
  Extracts the box object from a BOX wrapper.
  Namespace types: BOX
  Parameters:
     self (BOX) : The wrapped BOX instance.
  Returns: The underlying `box` object.
 method from_TABLE(self) 
  Extracts the table object from a TABLE wrapper.
  Namespace types: TABLE
  Parameters:
     self (TABLE) : The wrapped TABLE instance.
  Returns: The underlying `table` object.
 method from_CHART_POINT(self) 
  Extracts the chart.point from a CHART_POINT wrapper.
  Namespace types: CHART_POINT
  Parameters:
     self (CHART_POINT) : The wrapped CHART_POINT instance.
  Returns: The underlying `chart.point` value.
 method from_POLYLINE(self) 
  Extracts the polyline object from a POLYLINE wrapper.
  Namespace types: POLYLINE
  Parameters:
     self (POLYLINE) : The wrapped POLYLINE instance.
  Returns: The underlying `polyline` object.
 method from_LINEFILL(self) 
  Extracts the linefill object from a LINEFILL wrapper.
  Namespace types: LINEFILL
  Parameters:
     self (LINEFILL) : The wrapped LINEFILL instance.
  Returns: The underlying `linefill` object.
 method has_error(self) 
  Returns true if the INT wrapper has an active log entry.
  Namespace types: INT
  Parameters:
     self (INT) : The INT instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the FLOAT wrapper has an active log entry.
  Namespace types: FLOAT
  Parameters:
     self (FLOAT) : The FLOAT instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the BOOL wrapper has an active log entry.
  Namespace types: BOOL
  Parameters:
     self (BOOL) : The BOOL instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the STRING wrapper has an active log entry.
  Namespace types: STRING
  Parameters:
     self (STRING) : The STRING instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the COLOR wrapper has an active log entry.
  Namespace types: COLOR
  Parameters:
     self (COLOR) : The COLOR instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the LINE wrapper has an active log entry.
  Namespace types: LINE
  Parameters:
     self (LINE) : The LINE instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the LABEL wrapper has an active log entry.
  Namespace types: LABEL
  Parameters:
     self (LABEL) : The LABEL instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the BOX wrapper has an active log entry.
  Namespace types: BOX
  Parameters:
     self (BOX) : The BOX instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the TABLE wrapper has an active log entry.
  Namespace types: TABLE
  Parameters:
     self (TABLE) : The TABLE instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the CHART_POINT wrapper has an active log entry.
  Namespace types: CHART_POINT
  Parameters:
     self (CHART_POINT) : The CHART_POINT instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the POLYLINE wrapper has an active log entry.
  Namespace types: POLYLINE
  Parameters:
     self (POLYLINE) : The POLYLINE instance to check.
  Returns: True if an error or message is active in the log.
 method has_error(self) 
  Returns true if the LINEFILL wrapper has an active log entry.
  Namespace types: LINEFILL
  Parameters:
     self (LINEFILL) : The LINEFILL instance to check.
  Returns: True if an error or message is active in the log.
 void_return() 
  Utility function used when a return is syntactically required but functionally unnecessary.
  Returns: Nothing. Function never executes its body.
 argument_error(condition, function, argument, message) 
  Throws a runtime error when a condition is met. Used for strict argument validation.
  Parameters:
     condition (bool) : Boolean expression that triggers the runtime error.
     function (string) : Name of the calling function (for formatting).
     argument (string) : Name of the problematic argument.
     message (string) : Description of the error cause.
  Returns: Never returns. Halts execution if the condition is true.
 argument_log_info(condition, function, argument, message) 
  Logs an informational message when a condition is met. Used for optional debug visibility.
  Parameters:
     condition (bool) : Boolean expression that triggers the log.
     function (string) : Name of the calling function.
     argument (string) : Argument name being referenced.
     message (string) : Informational message to log.
  Returns: Nothing. Logs if the condition is true.
 argument_log_warning(condition, function, argument, message) 
  Logs a warning when a condition is met. Non-fatal but highlights potential issues.
  Parameters:
     condition (bool) : Boolean expression that triggers the warning.
     function (string) : Name of the calling function.
     argument (string) : Argument name being referenced.
     message (string) : Warning message to log.
  Returns: Nothing. Logs if the condition is true.
 argument_log_error(condition, function, argument, message) 
  Logs an error message when a condition is met. Does not halt execution.
  Parameters:
     condition (bool) : Boolean expression that triggers the error log.
     function (string) : Name of the calling function.
     argument (string) : Argument name being referenced.
     message (string) : Error message to log.
  Returns: Nothing. Logs if the condition is true.
 init_static_log(error_type, message, active) 
  Initializes a persistent (var) Log object. Ideal for global logging in scripts or modules.
  Parameters:
     error_type (series ErrorType) : Initial severity level (required).
     message (string) : Optional starting message string. Default value of ("").
     active (bool) : Whether the log should be flagged active on initialization. Default value of (false).
  Returns: A static Log object with the given parameters.
 method new_line(self) 
  Appends a newline character to the Log message. Useful for separating entries during chained writes.
  Namespace types: Log
  Parameters:
     self (Log) : The Log instance to modify.
  Returns: The updated Log object with a newline appended.
 method write(self, message, flag_active, error_type) 
  Appends a message to a Log object without a newline. Updates severity and active state if specified.
  Namespace types: Log
  Parameters:
     self (Log) : The Log instance being modified.
     message (string) : The text to append to the log.
     flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
     error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
  Returns: The updated Log object.
 method write_line(self, message, flag_active, error_type) 
  Appends a message to a Log object, prefixed with a newline for clarity.
  Namespace types: Log
  Parameters:
     self (Log) : The Log instance being modified.
     message (string) : The text to append to the log.
     flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
     error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
  Returns: The updated Log object.
 method clear(self, flag_active, error_type) 
  Clears a Log object’s message and optionally reactivates it. Can also update the error type.
  Namespace types: Log
  Parameters:
     self (Log) : The Log instance being cleared.
     flag_active (bool) : Whether to activate the log after clearing. Default value of (false).
     error_type (series ErrorType) : Optional new error type to assign. If not provided, the previous type is retained. Default value of (na).
  Returns: The cleared Log object.
 method render_condition(self, flag_active, error_type) 
  Conditionally renders the log if it is active. Allows overriding error type and controlling active state afterward.
  Namespace types: Log
  Parameters:
     self (Log) : The Log instance to evaluate and render.
     flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
     error_type (series ErrorType) : Optional error type override. Useful for contextual formatting just before rendering. Default value of (na).
  Returns: The updated Log object.
 method render_now(self, flag_active, error_type) 
  Immediately renders the log regardless of `active` state. Allows overriding error type and active flag.
  Namespace types: Log
  Parameters:
     self (Log) : The Log instance to render.
     flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
     error_type (series ErrorType) : Optional error type override. Allows dynamic severity adjustment at render time. Default value of (na).
  Returns: The updated Log object.
 render(self, condition, flag_active, error_type) 
  Renders the log conditionally or unconditionally. Allows full control over render behavior.
  Parameters:
     self (Log) : The Log instance to render.
     condition (bool) : If true, renders only if the log is active. If false, always renders. Default value of (false).
     flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
     error_type (series ErrorType) : Optional error type override passed to the render methods. Default value of (na).
  Returns: The updated Log object.
 Log 
  A structured object used to store and render logging messages.
  Fields:
     error_type (series ErrorType) : The severity level of the message (from the ErrorType enum).
     message (series string) : The text of the log message.
     active (series bool) : Whether the log should trigger rendering when conditionally evaluated.
 INT 
  A wrapped integer type with attached logging for validation or tracing.
  Fields:
     v (series int) : The underlying `int` value.
     e (Log) : Optional log object describing validation status or error context.
 FLOAT 
  A wrapped float type with attached logging for validation or tracing.
  Fields:
     v (series float) : The underlying `float` value.
     e (Log) : Optional log object describing validation status or error context.
 BOOL 
  A wrapped boolean type with attached logging for validation or tracing.
  Fields:
     v (series bool) : The underlying `bool` value.
     e (Log) : Optional log object describing validation status or error context.
 STRING 
  A wrapped string type with attached logging for validation or tracing.
  Fields:
     v (series string) : The underlying `string` value.
     e (Log) : Optional log object describing validation status or error context.
 COLOR 
  A wrapped color type with attached logging for validation or tracing.
  Fields:
     v (series color) : The underlying `color` value.
     e (Log) : Optional log object describing validation status or error context.
 LINE 
  A wrapped line object with attached logging for validation or tracing.
  Fields:
     v (series line) : The underlying `line` value.
     e (Log) : Optional log object describing validation status or error context.
 LABEL 
  A wrapped label object with attached logging for validation or tracing.
  Fields:
     v (series label) : The underlying `label` value.
     e (Log) : Optional log object describing validation status or error context.
 BOX 
  A wrapped box object with attached logging for validation or tracing.
  Fields:
     v (series box) : The underlying `box` value.
     e (Log) : Optional log object describing validation status or error context.
 TABLE 
  A wrapped table object with attached logging for validation or tracing.
  Fields:
     v (series table) : The underlying `table` value.
     e (Log) : Optional log object describing validation status or error context.
 CHART_POINT 
  A wrapped chart point with attached logging for validation or tracing.
  Fields:
     v (chart.point) : The underlying `chart.point` value.
     e (Log) : Optional log object describing validation status or error context.
 POLYLINE 
  A wrapped polyline object with attached logging for validation or tracing.
  Fields:
     v (series polyline) : The underlying `polyline` value.
     e (Log) : Optional log object describing validation status or error context.
 LINEFILL 
  A wrapped linefill object with attached logging for validation or tracing.
  Fields:
     v (series linefill) : The underlying `linefill` value.
     e (Log) : Optional log object describing validation status or error context.
CommonUtils█ OVERVIEW 
This library is a utility tool for Pine Script™ developers. It provides a collection of helper functions designed to simplify common tasks such as mapping user-friendly string inputs to Pine Script™ constants and formatting timeframe strings for display. The primary goal is to make main scripts cleaner, more readable, and reduce repetitive boilerplate code. It is envisioned as an evolving resource, with potential for new utilities to be added over time based on community needs and feedback.
 █  CONCEPTS 
The library primarily focuses on two main concepts:
 Input Mapping 
Pine Script™ often requires specific constants for function parameters (e.g., `line.style_dashed` for line styles, `position.top_center` for table positions). However, presenting these technical constants directly to users in script inputs can be confusing. Input mapping involves:
 
  Allowing users to select options from more descriptive, human-readable strings (e.g., "Dashed", "Top Center") in the script's settings.
  Providing functions within this library (e.g., `mapLineStyle`, `mapTablePosition`) that take these user-friendly strings as input.
  Internally, these functions use switch statements or similar logic to convert (map) the input string to the corresponding Pine Script™ constant required by built-in functions.
 
This approach enhances user experience and simplifies the main script's logic by centralizing the mapping process.
 Timeframe Formatting 
Raw timeframe strings obtained from variables like `timeframe.period` (e.g., "1", "60", "D", "W") or user inputs are not always ideal for direct display in labels or panels. The `formatTimeframe` function addresses this by:
 
  Taking a raw timeframe string as input.
  Parsing this string to identify its numerical part and unit (e.g., minutes, hours, days, weeks, months, seconds, milliseconds).
  Converting it into a more standardized and readable format (e.g., "1min", "60min", "Daily", "Weekly", "1s", "10M").
  Offering an optional `customSuffix` parameter (e.g., " FVG", " Period") to append to the formatted string, making labels more descriptive, especially in multi-timeframe contexts.
 
The function is designed to correctly interpret various common timeframe notations used in TradingView.
 █  NOTES 
 
   Ease of Use:  The library functions are designed with simple and understandable signatures. They typically take a string input and return the corresponding Pine Script™ constant or a formatted string.
   Default Behaviors:  Mapping functions (`mapLineStyle`, `mapTablePosition`, `mapTextSize`) generally return a sensible default value (e.g., `line.style_solid` for `mapLineStyle`) in case of a non-matching input. This helps prevent errors in the main script.
   Extensibility of Formatting:  The `formatTimeframe` function, with its `customSuffix` parameter, allows for flexible customization of timeframe labels to suit the specific descriptive needs of different indicators or contexts.
   Performance Considerations:  These utility functions primarily use basic string operations and switch statements. For typical use cases, their impact on overall script performance is negligible. However, if a function like `formatTimeframe` were to be called excessively in a loop with dynamic inputs (which is generally not its intended use), performance should be monitored.
   No Dependencies:  This library is self-contained and does not depend on any other external Pine Script™ libraries.
 
 █  EXPORTED FUNCTIONS 
 mapLineStyle(styleString) 
  Maps a user-provided line style string to its corresponding Pine Script™ line style constant.
  Parameters:
     styleString (simple string) : The input string representing the desired line style (e.g., "Solid", "Dashed", "Dotted" - typically from constants like LS1, LS2, LS3).
  Returns: The Pine Script™ constant for the line style (e.g., line.style_solid). Defaults to line.style_solid if no match.
 mapTablePosition(positionString) 
  Maps a user-provided table position string to its corresponding Pine Script™ position constant.
  Parameters:
     positionString (simple string) : The input string representing the desired table position (e.g., "Top Right", "Top Center" - typically from constants like PP1, PP2).
  Returns: The Pine Script™ constant for the table position (e.g., position.top_right). Defaults to position.top_right if no match.
 mapTextSize(sizeString) 
  Maps a user-provided text size string to its corresponding Pine Script™ size constant.
  Parameters:
     sizeString (simple string) : The input string representing the desired text size (e.g., "Tiny", "Small" - typically from constants like PTS1, PTS2).
  Returns: The Pine Script™ constant for the text size (e.g., size.tiny). Defaults to size.small if no match.
 formatTimeframe(tfInput, customSuffix) 
  Formats a raw timeframe string into a more display-friendly string, optionally appending a custom suffix.
  Parameters:
     tfInput (simple string) : The raw timeframe string from user input or timeframe.period (e.g., "1", "60", "D", "W", "1S", "10M", "2H").
     customSuffix (simple string) : An optional suffix to append to the formatted timeframe string (e.g., " FVG", " Period"). Defaults to an empty string.
  Returns: The formatted timeframe string (e.g., "1min", "60min", "Daily", "Weekly", "1s", "10min", "2h") with the custom suffix appended.
FvgPanel█ OVERVIEW 
This library provides functionalities for creating and managing a display panel within a Pine Script™ indicator. Its primary purpose is to offer a structured way to present Fair Value Gap (FVG) information, specifically the nearest bullish and bearish FVG levels across different timeframes (Current, MTF, HTF), directly on the chart. The library handles the table's structure, header initialization, and dynamic cell content updates.
 █ CONCEPTS 
The core of this library revolves around presenting summarized FVG data in a clear, tabular format. Key concepts include:
 FVG Data Aggregation and Display 
The panel is designed to show at-a-glance information about the closest active FVG mitigation levels. It doesn't calculate these FVGs itself but relies on the main script to provide this data. The panel is structured with columns for timeframes (TF), Bullish FVGs, and Bearish FVGs, and rows for "Current" (LTF), "MTF" (Medium Timeframe), and "HTF" (High Timeframe).
 The `panelData` User-Defined Type (UDT) 
To facilitate the transfer of information to be displayed, the library defines a UDT named `panelData`. This structure is central to the library's operation and is designed to hold all necessary values for populating the panel's data cells for each relevant FVG. Its fields include:
 
  Price levels for the nearest bullish and bearish FVGs for LTF, MTF, and HTF (e.g., `nearestBullMitLvl`, `nearestMtfBearMitLvl`).
  Boolean flags to indicate if these FVGs are classified as "Large Volume" (LV) (e.g., `isNearestBullLV`, `isNearestMtfBearLV`).
  Color information for the background and text of each data cell, allowing for conditional styling based on the FVG's status or proximity (e.g., `ltfBullBgColor`, `mtfBearTextColor`).
 
The design of `panelData` allows the main script to prepare all display-related data and styling cues in one object, which is then passed to the `updatePanel` function for rendering. This separation of data preparation and display logic keeps the library focused on its presentation task.
 Visual Cues and Formatting 
 
   Price Formatting:  Price levels are formatted to match the instrument's minimum tick size using an internal `formatPrice` helper function, ensuring consistent and accurate display.
   Large FVG Icon:  If an FVG is marked as a "Large Volume" FVG in the `panelData` object, a user-specified icon (e.g., an emoji) is prepended to its price level in the panel, providing an immediate visual distinction.
   Conditional Styling:  The background and text colors for each FVG level displayed in the panel can be individually controlled via the `panelData` object, enabling the main script to implement custom styling rules (e.g., highlighting the overall nearest FVG across all timeframes).
   Handling Missing Data:  If no FVG data is available for a particular cell (i.e., the corresponding level in `panelData` is `na`), the panel displays "---" and uses a specified background color for "Not Available" cells.
 
 █ CALCULATIONS AND USE 
Using the `FvgPanel` typically involves a two-stage process: initialization and dynamic updates.
 Step 1: Panel Creation 
First, an instance of the panel table is created once, usually during the script's initial setup. This is done using the `createPanel` function.
 
  Call `createPanel()` with parameters defining its position on the chart, border color, border width, header background color, header text color, and header text size.
  This function initializes the table with three columns ("TF", "Bull FVG", "Bear FVG") and three data rows labeled "Current", "MTF", and "HTF", plus a header row.
  Store the returned `table` object in a `var` variable to persist it across bars.
 
 
// Example:
var table infoPanel = na
if barstate.isfirst
    infoPanel := panel.createPanel(
         position.top_right,
         color.gray,
         1,
         color.new(color.gray, 50),
         color.white,
         size.small
       )
 
 Step 2: Panel Updates 
On each bar, or whenever the FVG data changes (typically on `barstate.islast` or `barstate.isrealtime` for efficiency), the panel's content needs to be refreshed. This is done using the `updatePanel` function.
 
  Populate an instance of the `panelData` UDT with the latest FVG information. This includes setting the nearest bullish/bearish mitigation levels for LTF, MTF, and HTF, their LV status, and their desired background and text colors.
  Call `updatePanel()`, passing the persistent `table` object (from Step 1), the populated `panelData` object, the icon string for LV FVGs, the default text color for FVG levels, the background color for "N/A" cells, and the general text size for the data cells.
  The `updatePanel` function will then clear previous data and fill the table cells with the new values and styles provided in the `panelData` object.
 
 
// Example (inside a conditional block like 'if barstate.islast'):
var panelData fvgDisplayData = panelData.new()
// ... (logic to populate fvgDisplayData fields) ...
// fvgDisplayData.nearestBullMitLvl = ...
// fvgDisplayData.ltfBullBgColor = ...
// ... etc.
if not na(infoPanel)
    panel.updatePanel(
         infoPanel,
         fvgDisplayData,
         "🔥", // LV FVG Icon
         color.white,
         color.new(color.gray, 70), // NA Cell Color
         size.small
       )
 
This workflow ensures that the panel is drawn only once and its cells are efficiently updated as new data becomes available.
 █ NOTES 
 
   Data Source:  This library is solely responsible for the visual presentation of FVG data in a table. It does  not  perform any FVG detection or calculation. The calling script must compute or retrieve the FVG levels, LV status, and desired styling to populate the `panelData` object.
   Styling Responsibility:  While `updatePanel` applies colors passed via the `panelData` object, the logic for *determining* those colors (e.g., highlighting the closest FVG to the current price) resides in the calling script.
   Performance:  The library uses `table.cell()` to update individual cells, which is generally more efficient than deleting and recreating the table on each update. However, the frequency of `updatePanel` calls should be managed by the main script (e.g., using `barstate.islast` or `barstate.isrealtime`) to avoid excessive processing on historical bars.
   `series float` Handling:  The price level fields within the `panelData` UDT (e.g., `nearestBullMitLvl`) can accept `series float` values, as these are typically derived from price data. The internal `formatPrice` function correctly handles `series float` for display.
   Dependencies:  The `FvgPanel` itself is self-contained and does not import other user libraries. It uses standard Pine Script™ table and string functionalities.
 
 █ EXPORTED TYPES 
 panelData 
  Represents the data structure for populating the FVG information panel. 
  Fields:
     nearestBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point (bottom for bull) on the LTF. 
     isNearestBullLV (series bool) : True if the nearest bullish FVG on the LTF is a Large Volume FVG. 
     ltfBullBgColor (series color) : Background color for the LTF bullish FVG cell in the panel. 
     ltfBullTextColor (series color) : Text color for the LTF bullish FVG cell in the panel. 
     nearestBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point (top for bear) on the LTF. 
     isNearestBearLV (series bool) : True if the nearest bearish FVG on the LTF is a Large Volume FVG. 
     ltfBearBgColor (series color) : Background color for the LTF bearish FVG cell in the panel. 
     ltfBearTextColor (series color) : Text color for the LTF bearish FVG cell in the panel. 
     nearestMtfBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point on the MTF. 
     isNearestMtfBullLV (series bool) : True if the nearest bullish FVG on the MTF is a Large Volume FVG. 
     mtfBullBgColor (series color) : Background color for the MTF bullish FVG cell. 
     mtfBullTextColor (series color) : Text color for the MTF bullish FVG cell. 
     nearestMtfBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point on the MTF. 
     isNearestMtfBearLV (series bool) : True if the nearest bearish FVG on the MTF is a Large Volume FVG. 
     mtfBearBgColor (series color) : Background color for the MTF bearish FVG cell. 
     mtfBearTextColor (series color) : Text color for the MTF bearish FVG cell. 
     nearestHtfBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point on the HTF. 
     isNearestHtfBullLV (series bool) : True if the nearest bullish FVG on the HTF is a Large Volume FVG. 
     htfBullBgColor (series color) : Background color for the HTF bullish FVG cell. 
     htfBullTextColor (series color) : Text color for the HTF bullish FVG cell. 
     nearestHtfBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point on the HTF. 
     isNearestHtfBearLV (series bool) : True if the nearest bearish FVG on the HTF is a Large Volume FVG. 
     htfBearBgColor (series color) : Background color for the HTF bearish FVG cell. 
     htfBearTextColor (series color) : Text color for the HTF bearish FVG cell. 
 █ EXPORTED FUNCTIONS 
 createPanel(position, borderColor, borderWidth, headerBgColor, headerTextColor, headerTextSize) 
  Creates and initializes the FVG information panel (table).  Sets up the header rows and timeframe labels. 
  Parameters:
     position (simple string) : The position of the panel on the chart (e.g., position.top_right).  Uses position.* constants. 
     borderColor (simple color) : The color of the panel's border. 
     borderWidth (simple int) : The width of the panel's border. 
     headerBgColor (simple color) : The background color for the header cells. 
     headerTextColor (simple color) : The text color for the header cells. 
     headerTextSize (simple string) : The text size for the header cells (e.g., size.small).  Uses size.* constants. 
  Returns: The newly created table object representing the panel. 
 updatePanel(panelTable, data, lvIcon, defaultTextColor, naCellColor, textSize) 
  Updates the content of the FVG information panel with the latest FVG data. 
  Parameters:
     panelTable (table) : The table object representing the panel to be updated. 
     data (panelData) : An object containing the FVG data to display. 
     lvIcon (simple string) : The icon (e.g., emoji) to display next to Large Volume FVGs. 
     defaultTextColor (simple color) : The default text color for FVG levels if not highlighted. 
     naCellColor (simple color) : The background color for cells where no FVG data is available ("---"). 
     textSize (simple string) : The text size for the FVG level data (e.g., size.small).
  Returns: _void
KTUtilsLibrary   "KTUtils" 
Utility functions for technical analysis indicators, trend detection, and volatility confirmation.
 MGz(close, length) 
  MGz
@description Moving average smoother used for signal processing
  Parameters:
     close (float) : float Price input (typically close)
     length (int) : int Length of smoothing period
  Returns: float Smoothed value
 atrConf(length) 
  atrConf
@description Calculates Average True Range (ATR) for volatility confirmation
  Parameters:
     length (simple int) : int Length for ATR calculation
  Returns: float ATR value
 f(input) 
  f
@description Simple Moving Average with fixed length
  Parameters:
     input (float) : float Input value
  Returns: float Smoothed average
 bcwSMA(s, l, m) 
  bcwSMA
@description Custom smoothing function with weight multiplier
  Parameters:
     s (float) : float Signal value
     l (int) : int Length of smoothing
     m (int) : int Weighting multiplier
  Returns: float Smoothed output
 MGxx(close, length) 
  MGxx
@description Custom Weighted Moving Average (WMA) variant
  Parameters:
     close (float) : float Price input
     length (int) : int Period length
  Returns: float MGxx smoothed output
 _PerChange(lengthTime) 
  _PerChange
@description Measures percentage price change over a period and range deviation
  Parameters:
     lengthTime (int) : int Period for change measurement
  Returns: tuple Measured change, high deviation, low deviation
 dirmov(len) 
  dirmov
@description Calculates directional movement components
  Parameters:
     len (simple int) : int Lookback period
  Returns: tuple Plus and Minus DI values
 adx(dilen, adxlen) 
  adx
@description Calculates Average Directional Index (ADX)
  Parameters:
     dilen (simple int) : int Length for DI calculation
     adxlen (simple int) : int Length for ADX smoothing
  Returns: float ADX value
 trChopAnalysis() 
  trChopAnalysis
@description Identifies chop and trend phases based on True Range Bollinger Bands
  Returns: tuple TR SMA, chop state, trending state
 wtiAnalysis(haclose, close, filterValue) 
  wtiAnalysis
@description Wave Trend Indicator (WTI) with signal crossover logic
  Parameters:
     haclose (float) : float Heikin-Ashi close
     close (float) : float Standard close
     filterValue (simple int) : int Smoothing length
  Returns: tuple WTI lines and direction states
 basicTrend(hahigh, halow, close, open, filterValue) 
  basicTrend
@description Determines trend direction based on HA high/low and close
  Parameters:
     hahigh (float) : float Heikin-Ashi high
     halow (float) : float Heikin-Ashi low
     close (float) : float Standard close
     open (float) : float Standard open
     filterValue (simple int) : int Smoothing period
  Returns: tuple Uptrend, downtrend flags
 metrics(close, filterValue) 
  metrics
@description Common market metrics
  Parameters:
     close (float) : float Price input
     filterValue (int) : int RSI smoothing length
  Returns: tuple VWMA, SMA10, RSI, smoothed RSI
 piff(close, trend_change) 
  piff
@description Price-Informed Forward Forecasting (PIFF) model for trend strength
  Parameters:
     close (float) : float Price input
     trend_change (float) : float Change in trend
  Returns: tuple Percent change, flags for trend direction
 getMACD() 
  getMACD
@description Returns MACD, signal line, and histogram
  Returns: tuple MACD line, Signal line, Histogram
 getStoch() 
  getStoch
@description Returns K and D lines of Stochastic Oscillator
  Returns: tuple K and D lines
 getKDJ() 
  getKDJ
@description KDJ momentum oscillator
  Returns: tuple K, D, J, Average
 getBBRatio() 
  getBBRatio
@description Bollinger Band Ratio (BBR) and signal flags
  Returns: tuple Basis, Upper, Lower, BBR, BBR Up, BBR Down
 getSupertrend() 
  getSupertrend
@description Supertrend values and direction flags
  Returns: tuple Supertrend, Direction, Up, Down
visualizationLibrary   "visualization" 
 method tagLine(message, priceLevel, showCondition, labelPosition, labelSize, offsetX, textColor, bgColor, lineWidth, lineStyle) 
  Creates a textLabel with line at specified price level
  Namespace types: series string, simple string, input string, const string
  Parameters:
     message (string) : Text to display in the textLabel. If starts with '$', price included. Empty = no textLabel
     priceLevel (float) : Price level for textLabel and line positioning
     showCondition (bool) : Condition to display the textLabel and line
     labelPosition (string) : Label position ("above", "below")
     labelSize (string) : Label size
     offsetX (int) : X-axis offset for textLabel and line
     textColor (color) : Text color
     bgColor (color) : Background color
     lineWidth (int) : Line width
     lineStyle (string) : Line style
  Returns: void
 textLabel(message, showCondition, position, textColor) 
  Creates dynamic labels with optional arrows
  Parameters:
     message (string) : Message to show (prefix with "!" to hide arrow)
     showCondition (bool) : Display condition
     position (string) : Label position ("above", "below")
     textColor (color) : Text color
  Returns: void
 box(showCondition, topValue, bottomValue, barsBack, borderColor, bgColor) 
  Creates a box around price range
  Parameters:
     showCondition (bool) : Condition to draw the box
     topValue (float) : Optional custom top value
     bottomValue (float) : Optional custom bottom value
     barsBack (int) : Number of bars to look back
     borderColor (color) : Box border color
     bgColor (color) : Box background color
  Returns: box Box object
jsonBuilderLibrary   "jsonBuilder" 
jsonBuilder is a lightweight Pine Script utility library for building JSON strings manually. It includes functions to convert key-value pairs into JSON format and to combine multiple pairs into a complete JSON object.
    jsonString(key, value) – Converts a string key and string value into a valid JSON key-value pair.
    jsonObject(pair1, ..., pair20) – Merges up to 20 key-value pairs into a complete JSON object string. Empty arguments are skipped automatically.
This is useful when sending structured JSON data via webhooks or external integrations from Pine Script.
TimezoneLibrary with pre-defined timezone enums that can be used to request a timezone input from the user.  The library provides a `tostring()` function to convert enum values to a valid string that can be used as a `timezone` parameter in pine script built-in functions.  The library also includes a bonus function to get a formatted UTC offset from a UNIX timestamp.
The timezone enums in this library were compiled by referencing the available timezone options from TradingView chart settings as well as multiple Wikipedia articles relating to lists of time zones.
Some enums from this library are used to retrieve an IANA time zone identifier, while other enums only use UTC/GMT offset notation.  It is important to note that the Pine Script User Manual recommends using IANA notation in most cases.
 HOW TO USE 
This library is intended to be used by Pine Coders who wish to provide their users with a simple way to input a timezone.  Using this library is as easy as 1, 2, 3:
 Step 1 
Import the library into your script.  Replace  with the latest available version number for this library.
 
//@version=6
indicator("Example")
 
import n00btraders/Timezone/ as tz
 
 Step 2 
Select one of the available enums from the library and use it as an input.  Tip: view the library source code and scroll through the enums at the top to find the best choice for your script.
 
timezoneInput = input.enum(tz.TimezoneID.EXCHANGE, "Timezone")
 
 Step 3 
Convert the user-selected input into a valid string that can be used in one of the pine script built-in functions that have a `timezone` parameter.
 
string timezone = tz.tostring(timezoneInput)
 
 EXPORTED FUNCTIONS 
There are multiple 𝚝𝚘𝚜𝚝𝚛𝚒𝚗𝚐() functions in this library: one for each timezone enum.  The function takes a single parameter: any enum field from one of the available timezone enums that are exported by this library.  Depending on the selected enum, the function will return a time zone string in either UTC/GMT notation or IANA notation.
Note: to avoid confusion with the built-in `str.tostring()` function, it is recommended to use this library's `tostring()` as a method rather than a function:
 
string timezone = timezoneInput.tostring()
 
 offset(timestamp, format, timezone, prefix, colon) 
  Formats the time offset from a UNIX timestamp represented in a specified timezone.
  Namespace types: series OffsetFormat
  Parameters:
     timestamp (int) : (series int) A UNIX time.
     format (series OffsetFormat) : (series OffsetFormat) A time offset format.
     timezone (string) : (series string) A UTC/GMT offset or IANA time zone identifier.
     prefix (string) : (series string) Optional 'UTC' or 'GMT' prefix for the result.
     colon (bool) : (series bool) Optional usage of colon separator.
  Returns: Time zone offset using the selected format.
The 𝚘𝚏𝚏𝚜𝚎𝚝() function is provided as a convenient alternative to manually using `str.format_time()` and then manipulating the result.
The OffsetFormat enum is used to decide the format of the result from the `offset()` function.  The library source code contains comments above this enum declaration that describe how each enum field will modify a time offset.
Tip: hover over the `offset()` function call in the Pine Editor to display a pop-up containing:
 
  Function description
  Detailed parameter list, including default values
  Example function calls
  Example outputs for different OffsetFormat.* enum values
 
 NOTES 
 
  At the time of this publication, Pine cannot be used to access a chart's selected time zone.  Therefore, the main benefit of this library is to provide a quick and easy way to create a pine script input for a time zone (most commonly, the same time zone selected in the user's chart settings).
  At the time of the creation of this library, there are 95 Time Zones made available in the TradingView chart settings.  If any changes are made to the time zone settings, this library will be updated to match the new changes.
  All time zone enums (and their individual fields) in this library were manually verified and tested to ensure correctness.
  An example usage of this library is included at the bottom of the source code.
  Credits to  HoanGhetti  for providing a nice  Markdown  resource which I referenced to be able to create a formatted informational pop-up for this library's `offset()` function.
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)
Milvetti_Pineconnector_LibraryLibrary   "Milvetti_Pineconnector_Library" 
This library has methods that provide practical signal transmission for Pineconnector.Developed By Milvetti
 buy(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sell(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 buyLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy limit order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 buyStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy stop order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sellLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a sell limit order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sellStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a sell stop order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
tacLibrary   "tac" 
Customised techninal analysis functions
 sar(start, inc, max) 
  returns parabolic sar with lagging value
  Parameters:
     start (float) : float: Start
     inc (float) : float: Increment
     max (float) : float: Maximum
  Returns:   Actual sar value and lagging sar value
ToolsFluentLibrary   "ToolsFluent" 
Fluent data holder object with retrieval and modification functions
 set(fluent, key, value) 
  Returns Fluent object after setting related fluent value
  Parameters:
     fluent (Fluent) : Fluent Fluent object
     key (string) : string|int Key to be set
     value (int) : int|float|bool|string|color Value to be set
  Returns: Fluent
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (float) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (bool) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (string) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (color) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (int) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (float) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (bool) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (string) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (color) 
 get(fluent, key, default) 
  Returns Fluent object key's value or default value when key not found
  Parameters:
     fluent (Fluent) : Fluent object
     key (string) 
     default (int) : int|float|bool|string|color Value to be returned when key not exists
  Returns: int|float|bool|string|color
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (float) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (bool) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (string) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (color) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (int) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (float) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (bool) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (string) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (color) 
 Fluent 
  Fluent - General purpose data holder object
  Fields:
     msi (map) : map String key, integer value info holder map. Default: na
     msf (map) : map String key, float value info holder map. Default: na
     msb (map) : map String key, boolean value info holder map. Default: na
     mss (map) : map String key, string value info holder map. Default: na
     msc (map) : map String key, color value info holder map. Default: na
     mii (map) : map Integer key, integer value info holder map. Default: na
     mif (map) : map Integer key, float value info holder map. Default: na
     mib (map) : map Integer key, boolean value info holder map. Default: na
     mis (map) : map Integer key, string value info holder map. Default: na
     mic (map) : map Integer key, color value info holder map. Default: na
ToolsPosLibrary   "ToolsPos" 
Library for general purpose position helpers
 new_pos(state, price, when, index) 
  Returns new PosInfo object
  Parameters:
     state (series PosState) :  Position state
     price (float) : float Entry price
     when (int) : int Entry bar time UNIX. Default: time
     index (int) : int Entry bar index. Default: bar_index
  Returns: PosInfo
 new_tp(pos, price, when, index, info) 
  Returns PosInfo object with new take profit info object
  Parameters:
     pos (PosInfo) : PosInfo object
     price (float) : float Entry price
     when (int) : int Entry bar time UNIX. Default: time
     index (int) : int Entry bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object. Default: na
  Returns: PosInfo
 new_re(pos, price, when, index, info) 
  Returns PosInfo object with new re-entry info object
  Parameters:
     pos (PosInfo) : PosInfo object
     price (float) : float Entry price
     when (int) : int Entry bar time UNIX. Default: time
     index (int) : int Entry bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object. Default: na
  Returns: PosInfo
 PosTPInfo 
  PosTPInfo - Position Take Profit info object
  Fields:
     price (series float) : float Take profit price
     when (series int) : int Take profit bar time UNIX. Default: time
     index (series int) : int Take profit bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object
 PosREInfo 
  PosREInfo - Position Re-Entry info object
  Fields:
     price (series float) : float Re-entry price
     when (series int) : int Re-entry bar time UNIX. Default: time
     index (series int) : int Take profit bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object
 PosInfo 
  PosInfo - Position info object
  Fields:
     state (series PosState) :  Position state
     price (series float) : float Entry price
     when (series int) : int Entry bar time UNIX. Default: time
     index (series int) : int Entry bar index. Default: bar_index
     tp (array) : PosTPInfo  Take profit info. Default: na
     re (array) : PosREInfo  Re-entry info. Default: na
     info (Info type from aybarsm/Tools/14) :  Info holder object
ToolsCollectionLibrary   "ToolsCollection" 
Helper functions for collection (map/array) type operations
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: int
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: float
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: string
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: color
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: int
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: float
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: string
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: color
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: bool
ManipulationLegHelperLibraryLibrary   "ManipulationLegHelperLibrary" 
TODO: add library description here
 devToArray(dev) 
  Parameters:
     dev (string) 
 getDev(d, bull, h, l) 
  Parameters:
     d (float) 
     bull (bool) 
     h (float) 
     l (float) 
 getBearLeg(sweeps, minLegSize, drawLegBox, boxColor) 
  Parameters:
     sweeps (int) 
     minLegSize (float) 
     drawLegBox (bool) 
     boxColor (color) 
 getBullLeg(sweeps, minSize, drawBox, boxColor) 
  Parameters:
     sweeps (int) 
     minSize (float) 
     drawBox (bool) 
     boxColor (color) 
 leg 
  Fields:
     time (series int) 
     low (series float) 
     high (series float) 
     edge (series bool) 
     edge_price (series float) 
     validated (series int) 
     sweeps (series int) 
     barC (series int) 
     bx (series box)
ToolsMapLibrary   "ToolsMap" 
Helper functions for map type operations
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: int
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: float
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: string
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: color
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: int
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: float
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: string
 map_def(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: color
ToolsLibrary   "Tools" 
Common tools
 movingAverage(maType, maSource, maLength) 
  dynamically returns MA
  Parameters:
     maType (string) : ma type
     maSource (float) : ma source
     maLength (simple int) : ma length
  Returns: ta.{sma,rma,ema,wma,vwma,hma}






















