Debugging
JK_Traders_Reality_LibLibrary   "JK_Traders_Reality_Lib" 
This library contains common elements used in Traders Reality scripts
 calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor) 
  calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors:  Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors:  Bull bars are blue and bear are violet.
  Parameters:
     pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
     pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
     pvsraLow (float) : the instrument low series (obtained from request.sequrity)
     pvsraClose (float) : the instrument close series (obtained from request.sequrity)
     pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
     redVectorColor (simple color) : red vector candle color
     greenVectorColor (simple color) : green vector candle color
     violetVectorColor (simple color) : violet/pink vector candle color
     blueVectorColor (simple color) : blue vector candle color
     darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
     lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return  
 adr(length, barsBack) 
  Parameters:
     length (simple int) : how many elements of the series to calculate on
     barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
 adrHigh(adr, fromDo) 
  Calculate the ADR high given an ADR
  Parameters:
     adr (float) : the adr
     fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
 adrLow(adr, fromDo) 
  Parameters:
     adr (float) : the adr
     fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
 splitSessionString(sessXTime) 
  given a session in the format 0000-0100:23456 split out the hours and minutes
  Parameters:
     sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return  
 calcSessionStartEnd(sessXTime, gmt) 
  calculate the start and end timestamps of the session
  Parameters:
     sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return  
 drawOpenRange(sessXTime, sessXcol, showOrX, gmt) 
  draw open range for a session
  Parameters:
     sessXTime (simple string) : session string in the format 0000-0100:23456
     sessXcol (simple color) : the color to be used for the opening range box shading
     showOrX (simple bool) : boolean flag to toggle displaying the opening range
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
 drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle) 
  Parameters:
     sessXTime (simple string) : session string in the format 0000-0100:23456
     showRectangleX (simple bool) 
     showLabelX (simple bool) 
     sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
     sessXLabel (simple string) : the session label text
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
 calcDst() 
  calculate market session dst on/off flags
@return   indicating if DST is on or off for a particular region
 timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis) 
  Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
  Parameters:
     previousDayOfWeek (simple string) : Monday or Satruday
     hourOfDay (simple int) : the hour of the day when psy calc is to start
     gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
 getdayOpen() 
  get the daily open - basically exchange midnight
@return the daily open value which is float price
 newBar(res) 
  new_bar: check if we're on a new bar within the session in a given resolution
  Parameters:
     res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
 toPips(val) 
  to_pips Convert value to pips
  Parameters:
     val (float) : the value to convert to pips
@return the value in pips
 rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series during the current bar
  Parameters:
     ry (float) : series float the y coordinate of the lable
     rtext (simple string) : the text of the label
     rstyle (simple string) : the style for the lable
     rcolor (simple color) : the color for the label
     valid (simple bool) : a boolean flag that allows for turning on or off a lable
     labelXOffset (int) : how much to offset the label from the current position
 rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset) 
  a function that draws a right aligned lable for a series during the current bar
  Parameters:
     ry (float) : series float the y coordinate of the lable
     rtext (string) : the text of the label
     rstyle (simple string) : the style for the lable
     rcolor (simple color) : the color for the label
     valid (simple bool) : a boolean flag that allows for turning on or off a lable
     labelOffset (int) 
 rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series only on the last bar
  Parameters:
     ry (float) : series float the y coordinate of the lable
     rtext (string) : the text of the label
     rstyle (simple string) : the style for the lable
     rcolor (simple color) : the color for the label
     valid (simple bool) : a boolean flag that allows for turning on or off a lable
     labelXOffset (int) : how much to offset the label from the current position
 drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame) 
  a function that draws a line and a label for a series
  Parameters:
     xSeries (float) : series float the y coordinate of the line/label
     res (simple string) : the desired resolution controlling when a new line will start
     tag (simple string) : the text for the lable
     xColor (simple color) : the color for the label
     xStyle (simple string) : the style for the line
     xWidth (simple int) : the width of the line
     xExtend (simple string) : extend the line
     isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
     xLabelOffset (int) 
     validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
 drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame) 
  a function that draws a line and a label for the daily open series
  Parameters:
     xSeries (float) : series float the y coordinate of the line/label
     res (simple string) : the desired resolution controlling when a new line will start
     tag (simple string) : the text for the lable
     xColor (simple color) : the color for the label
     xStyle (simple string) : the style for the line
     xWidth (simple int) : the width of the line
     xExtend (simple string) : extend the line
     isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
     xLabelOffset (int) 
     validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
 drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset) 
  draw a pivot line - the line starts one day into the past
  Parameters:
     pivotLevel (float) : series of the pivot point
     res (simple string) : the desired resolution
     tag (simple string) : the text to appear
     pivotColor (simple color) : the color of the line
     pivotLabelColor (simple color) : the color of the label
     pivotStyle (simple string) : the line style
     pivotWidth (simple int) : the line width
     pivotExtend (simple string) : extend the line
     isLabelValid (simple bool) : boolean param allows to turn label on and off
     validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
     levelStart (int) : basically when to start drawing the levels
     pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
 getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor) 
  convert the pvsra color to an internal code
  Parameters:
     pvsraColor (color) : the calculated pvsra color
     redVectorColor (simple color) : the user defined red vector color
     greenVectorColor (simple color) : the user defined green vector color
     violetVectorColor (simple color) : the user defined violet vector color
     blueVectorColor (simple color) : the user defined blue vector color
     lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
 updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor) 
  a function that draws the unrecovered vector candle zones
  Parameters:
     pvsra (int) : internal code
     direction (simple int) : above or below the current pa
     boxArr (array) : the array containing the boxes that need to be updated
     maxlevels (simple int) : the maximum number of boxes to draw
     pvsraHigh (float) : the pvsra high value series
     pvsraLow (float) : the pvsra low value series
     pvsraOpen (float) : the pvsra open value series
     pvsraClose (float) : the pvsra close value series
     transperancy (simple int) : the transparencfy of the vecor candle zones
     zoneupdatetype (simple string) : the zone update type
     zonecolor (simple color) : the zone color if overriden
     zonetype (simple string) : the zone type
     borderwidth (simple int) : the width of the border
     coloroverride (simple bool) : if the color overriden
     redVectorColor (simple color) : the user defined red vector color
     greenVectorColor (simple color) : the user defined green vector color
     violetVectorColor (simple color) : the user defined violet vector color
     blueVectorColor (simple color) : the user defined blue vector color
 cleanarr(arr) 
  clean an array from na values
  Parameters:
     arr (array) : the array to clean
@return if the array was cleaned
 calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST) 
  calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
  Parameters:
     oneWeekMillis (simple int) : a constant value
     showPsylevels (simple bool) : should psy levels be calculated
     psyType (simple string) : the type of Psylevels - crypto or forex
     sydDST (bool) : is Sydney in DST
@return  
 adrHiLo(length, barsBack, fromDO) 
  Parameters:
     length (simple int) : how many elements of the series to calculate on
     barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
     fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh  - the adr, the position of the adr High and adr Low with respect to price
 drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol) 
  Parameters:
     sessXTime (simple string) : session string in the format 0000-0100:23456
     showRectangleX (simple bool) 
     showLabelX (simple bool) 
     sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
     sessXLabel (simple string) : the session label text
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     sessionLineStyle (simple string) : the line stile for the session high low lines
     sessXcol (simple color) : - the color for the box color that will color the session
@return void
 msToHmsString(ms) 
  converts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
  Parameters:
     ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
 countdownString(openToday, closeToday, showMarketsWeekends, oneDay) 
  that calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
  Parameters:
     openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
     closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
     showMarketsWeekends (simple bool) 
     oneDay (simple int) 
 countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay) 
  that calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
  Parameters:
     sydOpenToday (int) 
     sydCloseToday (int) 
     showMarketsWeekends (simple bool) 
     oneDay (simple int)
TrailingStopLossLibrary   "TrailingStopLoss" 
简易追踪止损; 未充分测试,欢迎提交issue
 drawdown_percent(entry_bar_index, direction_long) 
  drawdown_percent: 回撤百分比
  Parameters:
     entry_bar_index (int) 
     direction_long (bool) 
  Returns: percentage: 回撤百分比 > 0
 closure_needed(entry_bar_index, initial_sl_price, percentage_ts, num_bars_tolerance, extra_drawdown_distance) 
  closure_needed: 是否满足平仓条件
  Parameters:
     entry_bar_index (int) 
     initial_sl_price (float) 
     percentage_ts (float) 
     num_bars_tolerance (int) 
     extra_drawdown_distance (float) 
  Returns: do_closure: bool 是否平仓
TAUtilityLibLibrary   "TAUtilityLib" 
Technical Analysis Utility Library - Collection of functions for market analysis, smoothing, scaling, and structure detection
 log_snapshot(label1, val1, label2, val2, label3, val3, label4, val4, label5, val5) 
  Creates formatted log snapshot with 5 labeled values
  Parameters:
     label1 (string) 
     val1 (float) 
     label2 (string) 
     val2 (float) 
     label3 (string) 
     val3 (float) 
     label4 (string) 
     val4 (float) 
     label5 (string) 
     val5 (float) 
  Returns: void (logs to console)
 f_get_next_tf(tf, steps) 
  Gets next higher timeframe(s) from current
  Parameters:
     tf (string) : Current timeframe string
     steps (string) : "1 TF Higher" for next TF, any other value for 2 TFs higher
  Returns: Next timeframe string or na if at maximum
 f_get_prev_tf(tf) 
  Gets previous lower timeframe from current
  Parameters:
     tf (string) : Current timeframe string
  Returns: Previous timeframe string or na if at minimum
 supersmoother(_src, _length) 
  Ehler's SuperSmoother - low-lag smoothing filter
  Parameters:
     _src (float) : Source series to smooth
     _length (simple int) : Smoothing period
  Returns: Smoothed series
 butter_smooth(src, len) 
  Butterworth filter for ultra-smooth price filtering
  Parameters:
     src (float) : Source series
     len (simple int) : Filter period
  Returns: Butterworth smoothed series
 f_dynamic_ema(source, dynamic_length) 
  Dynamic EMA with variable length
  Parameters:
     source (float) : Source series
     dynamic_length (float) : Dynamic period (can vary bar to bar)
  Returns: Dynamically adjusted EMA
 dema(source, length) 
  Double Exponential Moving Average (DEMA)
  Parameters:
     source (float) : Source series
     length (simple int) : Period for DEMA calculation
  Returns: DEMA value
 f_scale_percentile(primary_line, secondary_line, x) 
  Scales secondary line to match primary line using percentile ranges
  Parameters:
     primary_line (float) : Reference series for target scale
     secondary_line (float) : Series to be scaled
     x (int) : Lookback bars for percentile calculation
  Returns: Scaled version of secondary_line
 calculate_correlation_scaling(demamom_range, demamom_min, correlation_range, correlation_min) 
  Calculates scaling factors for correlation alignment
  Parameters:
     demamom_range (float) : Range of primary series
     demamom_min (float) : Minimum of primary series
     correlation_range (float) : Range of secondary series
     correlation_min (float) : Minimum of secondary series
  Returns:   tuple for alignment
 getBB(src, length, mult, chartlevel) 
  Calculates Bollinger Bands with chart level offset
  Parameters:
     src (float) : Source series
     length (simple int) : MA period
     mult (simple float) : Standard deviation multiplier
     chartlevel (simple float) : Vertical offset for plotting
  Returns:   tuple
 get_mrc(source, length, mult, mult2, gradsize) 
  Mean Reversion Channel with multiple bands and conditions
  Parameters:
     source (float) : Price source
     length (simple int) : Channel period
     mult (simple float) : First band multiplier
     mult2 (simple float) : Second band multiplier
     gradsize (simple float) : Gradient size for zone detection
  Returns:  
 analyzeMarketStructure(highFractalBars, highFractalPrices, lowFractalBars, lowFractalPrices, trendDirection) 
  Analyzes market structure for ChoCH and BOS patterns
  Parameters:
     highFractalBars (array) : Array of high fractal bar indices
     highFractalPrices (array) : Array of high fractal prices
     lowFractalBars (array) : Array of low fractal bar indices
     lowFractalPrices (array) : Array of low fractal prices
     trendDirection (int) : Current trend (1=up, -1=down, 0=neutral)
  Returns:   - change signals and new trend direction
tvunitLibrary   "tvunit" 
 method assert(this, description, passed, bar) 
  Adds a test result to the test suite.
  Namespace types: TestSuite
  Parameters:
     this (TestSuite) : The (TestSuite) instance.
     description (string) : A description of the test.
     passed (bool) : Whether the test passed or result.
     bar (int) : The bar index at which the test was run.
  Returns: Whether the assertion passed or result.
 method assertWindow(this, runTests, description, bars, passed, stopOnFirstFailure) 
  Adds a test result to the test suite.
  Namespace types: TestSuite
  Parameters:
     this (TestSuite) : The (TestSuite) instance.
     runTests (bool) : Whether to run the tests.
     description (string) : A description of the test.
     bars (int) : The number of bars to test.
     passed (bool) : A series of boolean values indicating whether each bar passed.
     stopOnFirstFailure (bool) : Whether to stop on the first test failure.
  Returns: Whether the assertion ran or not
 method totalTests(this) 
  Returns the total number of tests in the test suite.
  Namespace types: TestSuite
  Parameters:
     this (TestSuite) : The (TestSuite) instance.
  Returns: The total number of tests.
 method totalTests(this) 
  Returns the total number of tests in the test suite.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSuite) instance.
  Returns: The total number of tests.
 method passedTests(this) 
  Returns the total number of passed tests in the test suite.
  Namespace types: TestSuite
  Parameters:
     this (TestSuite) : The (TestSuite) instance.
  Returns: The total number of passed tests.
 method passedTests(this) 
  Returns the total number of passed tests in the test suite.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSuite) instance.
  Returns: The total number of passed tests.
 method failedTests(this) 
  Returns the total number of result tests in the test suite.
  Namespace types: TestSuite
  Parameters:
     this (TestSuite) : The (TestSuite) instance.
  Returns: The total number of result tests.
 method failedTests(this) 
  Returns the total number of result tests in the test suite.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSuite) instance.
  Returns: The total number of result tests.
 newTestSession() 
  Creates a new test session instance.
  Returns: A new (TestSession) instance.
 method addNewTestSuite(this, name, description) 
  Creates a new test suite instance.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSession) instance.
     name (string) : The name of the test suite.
     description (string) : (optional) A description of the test suite.
  Returns: A new (TestSuite) instance.
 method add(this, suite) 
  Creates a new test suite instance.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSession) instance.
     suite (TestSuite) : The (TestSuite) instance to add.
  Returns: The (TestSession) instance.
 method totalSuites(this) 
  Returns the total number of sessions in the test session.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSession) instance.
  Returns: The total number of sessions.
 method report(this, show, showOnlyFailedTest) 
  Generates a report of the test session summary that is suitable for logging.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSession) instance.
     show (bool) : Optional: Whether to show the report or not. default: true
     showOnlyFailedTest (bool) : Optional: Whether to show only result tests or not. default: false
  Returns: A formatted string report of the test suite summary.
 method reportGui(this, show, pages, pageSize) 
  Generates a report of the test suite summary for the GUI.
  Namespace types: TestSession
  Parameters:
     this (TestSession) : The (TestSession) instance.
     show (bool) : Optional: Whether to show the report or not. default: true
     pages (int) : Optional: The number of pages to show (columns). default: 4
     pageSize (int) : Optional: The number of results to show per page (rows), excluding the header. default: 5
 approxEqual(a, b, tolerance) 
  Checks if two floating-point numbers are approximately equal within a specified tolerance.
  Parameters:
     a (float) : The first floating-point number.
     b (float) : The second floating-point number.
     tolerance (float) : The tolerance within which the two numbers are considered equal. Default is 1e-6.
  Returns: True if the numbers are approximately equal, false otherwise. If both are na, returns true.
 TestResult 
  Fields:
     description (series string) 
     passed (series bool) 
     bar (series int) 
 TestSuite 
  Fields:
     isEnabled (series bool) 
     name (series string) 
     description (series string) 
     tests (array) 
 TestSession 
  Fields:
     suites (array)
BecakFloatingPanelsLibrary   "BecakFloatingPanels" 
Library for creating floating indicator panels with MACD, RSI, and Stochastic indicators
 calculateMacd(source, fastLength, slowLength, signalLength) 
  Calculate MACD components
  Parameters:
     source (float) : Price source for calculation
     fastLength (simple int) : Fast EMA period
     slowLength (simple int) : Slow EMA period
     signalLength (simple int) : Signal line period
  Returns: MacdData MACD calculation results
 calculateRsi(source, length) 
  Calculate RSI
  Parameters:
     source (float) : Price source for calculation
     length (simple int) : RSI period
  Returns: float RSI value
 calculateStochastic(source, high, low, kLength, kSmoothing, dSmoothing) 
  Calculate Stochastic components
  Parameters:
     source (float) : Price source for calculation
     high (float) : High prices
     low (float) : Low prices
     kLength (int) : %K period
     kSmoothing (int) : %K smoothing period
     dSmoothing (int) : %D smoothing period
  Returns: StochData Stochastic calculation results
 calculateStochSignals(stochK, stochD, overboughtLevel, oversoldLevel) 
  Calculate Stochastic signals
  Parameters:
     stochK (float) : Stochastic %K series
     stochD (float) : Stochastic %D series
     overboughtLevel (float) : Overbought threshold
     oversoldLevel (float) : Oversold threshold
  Returns: StochSignals Signal flags
 calculateChartMetrics(high, low, lookbackLength) 
  Calculate chart range and positioning metrics
  Parameters:
     high (float) : High prices
     low (float) : Low prices
     lookbackLength (int) : Lookback period
  Returns: ChartMetrics Chart positioning data
 calculateMacdRange(macdLine, signalLine, histogram, safeLookback) 
  Calculate MACD range for normalization
  Parameters:
     macdLine (float) : MACD line series
     signalLine (float) : Signal line series
     histogram (float) : Histogram series
     safeLookback (int) : Lookback period
  Returns: MacdRange MACD range metrics
 initVisualArrays() 
  Initialize visual arrays
  Returns: VisualArrays Container with initialized arrays
 clearVisuals(visuals) 
  Clear all visual elements
  Parameters:
     visuals (VisualArrays) : VisualArrays container
  Returns: void
 calculatePanelPositions(chartMetrics, oscPlacement, panelHeight, panelSpacing, centerOffset) 
  Calculate panel positions based on placement option
  Parameters:
     chartMetrics (ChartMetrics) : Chart metrics object
     oscPlacement (string) : Panel placement option
     panelHeight (float) : Panel height percentage
     panelSpacing (float) : Panel spacing percentage
     centerOffset (float) : Center offset percentage
  Returns: PanelPositions Panel boundary coordinates
 createPanelBackgrounds(visuals, positions, panelLeft, panelRight, showBackground, transparency) 
  Create panel backgrounds
  Parameters:
     visuals (VisualArrays) : VisualArrays container
     positions (PanelPositions) : PanelPositions object
     panelLeft (int) : Left boundary
     panelRight (int) : Right boundary
     showBackground (bool) : Show background flag
     transparency (int) : Background transparency
  Returns: void
 drawReferenceLines(visuals, positions, chartMetrics, macdRange, dataLeft, dataRight, panelHeight, rsiOverbought, rsiOversold, stochOverbought, stochOversold) 
  Draw reference lines for all panels
  Parameters:
     visuals (VisualArrays) : VisualArrays container
     positions (PanelPositions) : PanelPositions object
     chartMetrics (ChartMetrics) : ChartMetrics object
     macdRange (MacdRange) : MacdRange object
     dataLeft (int) : Left data boundary
     dataRight (int) : Right data boundary
     panelHeight (float) : Panel height percentage
     rsiOverbought (int) : RSI overbought level
     rsiOversold (int) : RSI oversold level
     stochOverbought (int) : Stochastic overbought level
     stochOversold (int) : Stochastic oversold level
  Returns: void
 drawMacdIndicator(visuals, macdLine, signalLine, histogram, macdRange, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight) 
  Draw MACD indicator
  Parameters:
     visuals (VisualArrays) : VisualArrays container
     macdLine (float) : MACD line series
     signalLine (float) : Signal line series
     histogram (float) : Histogram series
     macdRange (MacdRange) : MacdRange object
     positions (PanelPositions) : PanelPositions object
     chartMetrics (ChartMetrics) : ChartMetrics object
     barIndex (int) : Current bar index
     nextBarIndex (int) : Next bar index
     barIndexOffset (int) : Horizontal offset
     panelHeight (float) : Panel height percentage
  Returns: void
 drawRsiIndicator(visuals, rsiValue, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight) 
  Draw RSI indicator
  Parameters:
     visuals (VisualArrays) : VisualArrays container
     rsiValue (float) : RSI value
     positions (PanelPositions) : PanelPositions object
     chartMetrics (ChartMetrics) : ChartMetrics object
     barIndex (int) : Current bar index
     nextBarIndex (int) : Next bar index
     barIndexOffset (int) : Horizontal offset
     panelHeight (float) : Panel height percentage
  Returns: void
 drawStochasticIndicator(visuals, stochK, stochD, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight, stochOverbought, stochOversold) 
  Draw Stochastic indicator
  Parameters:
     visuals (VisualArrays) : VisualArrays container
     stochK (float) : Stochastic %K series
     stochD (float) : Stochastic %D series
     positions (PanelPositions) : PanelPositions object
     chartMetrics (ChartMetrics) : ChartMetrics object
     barIndex (int) : Current bar index
     nextBarIndex (int) : Next bar index
     barIndexOffset (int) : Horizontal offset
     panelHeight (float) : Panel height percentage
     stochOverbought (int) : Overbought level
     stochOversold (int) : Oversold level
  Returns: void
 addStochasticSignals(visuals, buySignal, sellSignal, positions, chartMetrics, currentBarIndex, barIndexOffset, panelHeight, signalIndex) 
  Add Stochastic buy/sell signals
  Parameters:
     visuals (VisualArrays) : VisualArrays container
     buySignal (bool) : Buy signal series
     sellSignal (bool) : Sell signal series
     positions (PanelPositions) : PanelPositions object
     chartMetrics (ChartMetrics) : ChartMetrics object
     currentBarIndex (int) : Current bar index
     barIndexOffset (int) : Horizontal offset
     panelHeight (float) : Panel height percentage
     signalIndex (int) : Signal index for lookback
  Returns: void
 setPanelLabels(macdLabel, rsiLabel, stochLabel, positions, chartMetrics, labelOffset, panelHeight, barIndexOffset) 
  Set panel title labels
  Parameters:
     macdLabel (label) : MACD label reference
     rsiLabel (label) : RSI label reference
     stochLabel (label) : Stochastic label reference
     positions (PanelPositions) : PanelPositions object
     chartMetrics (ChartMetrics) : ChartMetrics object
     labelOffset (int) : Label horizontal offset
     panelHeight (float) : Panel height percentage
     barIndexOffset (int) : Horizontal offset
  Returns: void
 showDebugInfo(chartMetrics, debugMode) 
  Display debug information
  Parameters:
     chartMetrics (ChartMetrics) : ChartMetrics object
     debugMode (bool) : Debug mode flag
  Returns: void
 ChartMetrics 
  Chart metrics container
  Fields:
     visibleHigh (series float) : Highest visible price
     visibleLow (series float) : Lowest visible price
     chartRange (series float) : Price range of chart
     chartCenter (series float) : Center point of chart
 MacdData 
  MACD calculation results
  Fields:
     macdLine (series float) : Main MACD line
     signalLine (series float) : Signal line
     histogram (series float) : MACD histogram
 MacdRange 
  MACD range metrics for normalization
  Fields:
     highest (series float) : Highest MACD value
     lowest (series float) : Lowest MACD value
     BRange (series float) : Total range
 StochData 
  Stochastic calculation results
  Fields:
     k_smooth (series float) : Smoothed %K line
     d (series float) : %D line
 StochSignals 
  Stochastic signals
  Fields:
     buySignal (series bool) : Buy signal flag
     sellSignal (series bool) : Sell signal flag
 PanelPositions 
  Panel positioning data
  Fields:
     macdTop (series float) : MACD panel top
     macdBottom (series float) : MACD panel bottom
     rsiTop (series float) : RSI panel top
     rsiBottom (series float) : RSI panel bottom
     stochTop (series float) : Stochastic panel top
     stochBottom (series float) : Stochastic panel bottom
 VisualArrays 
  Visual elements arrays container
  Fields:
     macdLines (array) : Array of MACD lines
     macdHist (array) : Array of MACD histogram boxes
     rsiLines (array) : Array of RSI lines
     stochLines (array) : Array of Stochastic lines
     stochAreas (array) : Array of Stochastic areas
     stochSignals (array) : Array of Stochastic signals
     panelBackgrounds (array) : Array of panel backgrounds
TFPS_EngineLibrary   "TFPS_Engine" 
 f_calculate_lead_lag(series1, series2, length, max_lag) 
  Parameters:
     series1 (float) 
     series2 (float) 
     length (int) 
     max_lag (int) 
 f_calculate_pressure_score(spx_ticker, vix_ticker, dxy_ticker, us10y_ticker, benchmark_source, trend_lookback, score_smoothing, use_dynamic_weights, corr_lookback, w_spx, w_vix, w_dxy, w_us10y, zscore_lookback, max_lag) 
  Parameters:
     spx_ticker (string) 
     vix_ticker (string) 
     dxy_ticker (string) 
     us10y_ticker (string) 
     benchmark_source (float) 
     trend_lookback (int) 
     score_smoothing (simple int) 
     use_dynamic_weights (bool) 
     corr_lookback (int) 
     w_spx (float) 
     w_vix (float) 
     w_dxy (float) 
     w_us10y (float) 
     zscore_lookback (int) 
     max_lag (int) 
 LeadLagOutput 
  Fields:
     best_lag (series int) 
     max_corr (series float) 
 TFPS_Output 
  Fields:
     historical_score (series float) 
     smoothed_score (series float) 
     z_score (series float) 
     regime_signal (series int) 
     lead_lag_bars (series int) 
     lead_lag_corr (series float) 
     weight_spx (series float) 
     weight_vix (series float) 
     weight_dxy (series float) 
     weight_us10y (series float)
TrailingStopLibraryLibrary   "TrailingStopLibrary" 
专业移动止盈库 - 为Pine Script策略提供完整的追踪止盈功能。支持做多做空双向交易,基于风险回报比智能激活,提供收盘价和高低价两种判断模式。包含完整的状态管理、调试信息和易用的API接口。适用于股票、外汇、加密货币等各种市场的风险管理。
@version 1.0
@author runto2006
 new_config(enabled, activation_ratio, pullback_percent, price_type) 
  创建移动止盈配置对象
  Parameters:
     enabled (bool) : (bool) 是否启用移动止盈,默认true
     activation_ratio (float) : (float) 激活盈亏比,默认4.0,表示盈利4倍止损距离时激活
     pullback_percent (float) : (float) 回撤百分比,默认1.0,表示回撤1%时触发止盈
     price_type (string) : (string) 价格类型,默认"close"。"close"=收盘价模式,"hl"=高低价模式
  Returns: Config 配置对象
 new_state() 
  创建移动止盈状态对象
  Returns: State 初始化的状态对象
 reset(state) 
  重置移动止盈状态
  Parameters:
     state (State) : (State) 要重置的状态对象
  Returns: void
 calc_activation_target(entry_price, stop_price, activation_ratio, is_long) 
  计算激活目标价格
  Parameters:
     entry_price (float) : (float) 入场价格
     stop_price (float) : (float) 止损价格
     activation_ratio (float) : (float) 激活盈亏比
     is_long (bool) : (bool) 是否为多头持仓
  Returns: float 激活目标价格,如果输入无效则返回na
 get_check_price(price_type, is_long, for_activation) 
  获取用于判断的价格
  Parameters:
     price_type (string) : (string) 价格类型:"close"或"hl"
     is_long (bool) : (bool) 是否为多头持仓
     for_activation (bool) : (bool) 是否用于激活判断,影响高低价的选择方向
  Returns: float 当前判断价格
 check_activation(config, state, entry_price, stop_price, is_long, has_position) 
  检查是否应该激活移动止盈
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     entry_price (float) : (float) 入场价格
     stop_price (float) : (float) 止损价格
     is_long (bool) : (bool) 是否为多头持仓
     has_position (bool) : (bool) 是否有持仓
  Returns: bool 是否成功激活
 update_tracking(config, state, is_long) 
  更新移动止盈的追踪价格
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     is_long (bool) : (bool) 是否为多头持仓
  Returns: void
 check_trigger(config, state, entry_price, is_long) 
  检查是否触发移动止盈
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     entry_price (float) : (float) 入场价格
     is_long (bool) : (bool) 是否为多头持仓
  Returns: bool 是否触发止盈
 process(config, state, entry_price, stop_price, is_long, has_position) 
  一体化处理移动止盈逻辑
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     entry_price (float) : (float) 入场价格
     stop_price (float) : (float) 止损价格
     is_long (bool) : (bool) 是否为多头持仓
     has_position (bool) : (bool) 是否有持仓
  Returns: bool 是否触发止盈
 get_trigger_price(config, state, is_long) 
  获取当前触发价格
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     is_long (bool) : (bool) 是否为多头持仓
  Returns: float 触发价格,未激活时返回na
 get_pullback_percent(config, state, entry_price, is_long) 
  计算当前回撤百分比
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     entry_price (float) : (float) 入场价格
     is_long (bool) : (bool) 是否为多头持仓
  Returns: float 当前回撤百分比,未激活时返回na
 get_status_info(config, state, entry_price, is_long) 
  获取状态信息字符串(用于调试)
  Parameters:
     config (Config) : (Config) 移动止盈配置
     state (State) : (State) 移动止盈状态
     entry_price (float) : (float) 入场价格
     is_long (bool) : (bool) 是否为多头持仓
  Returns: string 详细的状态信息
 Config 
  移动止盈配置对象
  Fields:
     enabled (series bool) : (bool) 是否启用移动止盈功能
     activation_ratio (series float) : (float) 激活盈亏比 - 盈利达到止损距离的多少倍时激活追踪
     pullback_percent (series float) : (float) 回撤百分比 - 从最优价格回撤多少百分比时触发止盈
     price_type (series string) : (string) 价格判断类型 - "close"使用收盘价,"hl"使用高低价
 State 
  移动止盈状态对象
  Fields:
     activated (series bool) : (bool) 是否已激活追踪止盈
     highest_price (series float) : (float) 激活后记录的最高价格
     lowest_price (series float) : (float) 激活后记录的最低价格
     activation_target (series float) : (float) 激活目标价格
RifleShooterLibLibrary   "RifleShooterLib" 
Provides a collection of helper functions in support of the Rifle Shooter Indicators.
Functions support the key components of the Rifle Trade algorithm including
* measuring momentum
* identifying paraboloic price action (to disable the algorthim during such time)
* determine the lookback criteria of X point movement in last N minutes
* processing and navigating between the 23/43/73 levels
* maintaining a status table of algorithm progress
 toStrRnd(val, digits) 
  Parameters:
     val (float) 
     digits (int) 
 _isValidTimeRange(startTimeInput, endTimeInput) 
  Parameters:
     startTimeInput (string) 
     endTimeInput (string) 
 _normalize(_src, _min, _max) 
  _normalize Normalizes series with unknown min/max using historical min/max.
  Parameters:
     _src (float) : Source series to normalize
     _min (float) : minimum value of the rescaled series
     _max (float) : maximum value of the rescaled series
  Returns: The series scaled with values between min and max
 arrayToSeries(arrayInput) 
  arrayToSeries Return an array from the provided series.
  Parameters:
     arrayInput (array) : Source array to convert to a series
  Returns: The array as a series datatype
 f_parabolicFiltering(_activeCount, long, shooterRsi, shooterRsiLongThreshold, shooterRsiShortThreshold, fiveMinuteRsi, fiveMinRsiLongThreshold, fiveMinRsiShortThreshold, shooterRsiRoc, shooterRsiRocLongThreshold, shooterRsiRocShortThreshold, quickChangeLookbackBars, quckChangeThreshold, curBarChangeThreshold, changeFromPrevBarThreshold, maxBarsToholdParabolicMoveActive, generateLabels) 
  f_parabolicFiltering Return true when price action indicates a parabolic active movement based on the provided inputs and thresholds.
  Parameters:
     _activeCount (int) 
     long (bool) 
     shooterRsi (float) 
     shooterRsiLongThreshold (float) 
     shooterRsiShortThreshold (float) 
     fiveMinuteRsi (float) 
     fiveMinRsiLongThreshold (float) 
     fiveMinRsiShortThreshold (float) 
     shooterRsiRoc (float) 
     shooterRsiRocLongThreshold (float) 
     shooterRsiRocShortThreshold (float) 
     quickChangeLookbackBars (int) 
     quckChangeThreshold (int) 
     curBarChangeThreshold (int) 
     changeFromPrevBarThreshold (int) 
     maxBarsToholdParabolicMoveActive (int) 
     generateLabels (bool) 
 rsiValid(rsi, buyThreshold, sellThreshold) 
  rsiValid Returns true if the provided RSI value is withing the associated threshold. For the unused threshold set it to na
  Parameters:
     rsi (float) 
     buyThreshold (float) 
     sellThreshold (float) 
 squezeBands(source, length) 
  squezeBands Returns the squeeze bands momentum color of current source series input
  Parameters:
     source (float) 
     length (int) 
 f_momentumOscilator(source, length, transperency) 
  f_momentumOscilator Returns the squeeze pro momentum value and bar color states of the series input
  Parameters:
     source (float) 
     length (int) 
     transperency (int) 
 f_getLookbackExtreme(lowSeries, highSeries, lbBars, long) 
  f_getLookbackExtreme Return the highest high or lowest low over the look back window
  Parameters:
     lowSeries (float) 
     highSeries (float) 
     lbBars (int) 
     long (bool) 
 f_getInitialMoveTarget(lbExtreme, priveMoveOffset, long) 
  f_getInitialMoveTarget Return the point delta required to achieve an initial rifle move (X points over Y lookback)
  Parameters:
     lbExtreme (float) 
     priveMoveOffset (int) 
     long (bool) 
 isSymbolSupported(sym) 
  isSymbolSupported Return true if provided symbol is one of the supported DOW Rifle Indicator symbols
  Parameters:
     sym (string) 
 getBasePrice(price) 
  getBasePrice Returns integer portion of provided float
  Parameters:
     price (float) 
 getLastTwoDigitsOfPrice(price) 
  getBasePrice Returns last two integer numerals of provided float value
  Parameters:
     price (float) 
 getNextLevelDown(price, lowestLevel, middleLevel, highestLevel) 
  getNextLevelDown Returns the next level above the provided price value
  Parameters:
     price (float) 
     lowestLevel (float) 
     middleLevel (float) 
     highestLevel (float) 
 getNextLevelUp(price, lowestLevel, middleLevel, highestLevel) 
  getNextLevelUp Returns the next level below the provided price value
  Parameters:
     price (float) 
     lowestLevel (float) 
     middleLevel (float) 
     highestLevel (float) 
 isALevel(price, lowestLevel, middleLevel, highestLevel) 
  isALevel Returns true if the provided price is onve of the specified levels
  Parameters:
     price (float) 
     lowestLevel (float) 
     middleLevel (float) 
     highestLevel (float) 
 getClosestLevel(price, lowestLevel, middleLevel, highestLevel) 
  getClosestLevel Returns the level closest to the price value provided
  Parameters:
     price (float) 
     lowestLevel (float) 
     middleLevel (float) 
     highestLevel (float) 
 f_fillSetupTableCell(_table, _col, _row, _text, _bgcolor, _txtcolor, _text_size) 
  f_fillSetupTableCell Helper function to fill a setup table celll
  Parameters:
     _table (table) 
     _col (int) 
     _row (int) 
     _text (string) 
     _bgcolor (color) 
     _txtcolor (color) 
     _text_size (string) 
 f_fillSetupTableRow(_table, _row, _col0Str, _col1Str, _col2Str, _bgcolor, _textColor, _textSize) 
  f_fillSetupTableRow Helper function to fill a setup table row
  Parameters:
     _table (table) 
     _row (int) 
     _col0Str (string) 
     _col1Str (string) 
     _col2Str (string) 
     _bgcolor (color) 
     _textColor (color) 
     _textSize (string) 
 f_addBlankRow(_table, _row) 
  f_addBlankRow Helper function to fill a setup table row with empty values
  Parameters:
     _table (table) 
     _row (int) 
 f_updateVersionTable(versionTable, versionStr, versionDateStr) 
  f_updateVersionTable Helper function to fill the version table with provided values
  Parameters:
     versionTable (table) 
     versionStr (string) 
     versionDateStr (string) 
 f_updateSetupTable(_table, parabolicMoveActive, initialMoveTargetOffset, initialMoveAchieved, shooterRsi, shooterRsiValid, rsiRocEnterThreshold, shooterRsiRoc, fiveMinuteRsi, fiveMinuteRsiValid, requireValid5MinuteRsiForEntry, stallLevelOffset, stallLevelExceeded, stallTargetOffset, recoverStallLevelValid, curBarChangeValid, volumeRoc, volumeRocThreshold, enableVolumeRocForTrigger, tradeActive, entryPrice, curCloseOffset, curSymCashDelta, djiCashDelta, showDjiDelta, longIndicator, fontSize) 
  f_updateSetupTable Manages writing current data to the setup table
  Parameters:
     _table (table) 
     parabolicMoveActive (bool) 
     initialMoveTargetOffset (float) 
     initialMoveAchieved (bool) 
     shooterRsi (float) 
     shooterRsiValid (bool) 
     rsiRocEnterThreshold (float) 
     shooterRsiRoc (float) 
     fiveMinuteRsi (float) 
     fiveMinuteRsiValid (bool) 
     requireValid5MinuteRsiForEntry (bool) 
     stallLevelOffset (float) 
     stallLevelExceeded (bool) 
     stallTargetOffset (float) 
     recoverStallLevelValid (bool) 
     curBarChangeValid (bool) 
     volumeRoc (float) 
     volumeRocThreshold (float) 
     enableVolumeRocForTrigger (bool) 
     tradeActive (bool) 
     entryPrice (float) 
     curCloseOffset (float) 
     curSymCashDelta (float) 
     djiCashDelta (float) 
     showDjiDelta (bool) 
     longIndicator (bool) 
     fontSize (string)
BackTestLibLibrary   "BackTestLib" 
Allows backtesting indicator performance. Tracks typical metrics such as won/loss, profit factor, draw down, etc. Trading View strategy library provides similar (and more comprehensive)
functionality but only works with strategies. This libary was created to address performance tracking within indicators.
Two primary outputs are generated:
1. Summary Table: Displays overall performance metrics for the indicator over the chart's loaded timeframe and history
2. Details Table: Displays a table of individual trade entries and exits. This table can grow larger than the available chart space. It does have a max number of rows supported. I haven't
found a way to add scroll bars or scroll bar equivalents yet.
 f_init(data, _defaultStopLoss, _defaultTakeProfit, _useTrailingStop, _useTraingStopToBreakEven, _trailingStopActivation, _trailingStopOffset) 
  f_init Initialize the backtest data type. Called prior to using the backtester functions
  Parameters:
     data (backtesterData) : backtesterData to initialize
     _defaultStopLoss (float) : Default trade stop loss to apply
     _defaultTakeProfit (float) : Default trade take profit to apply
     _useTrailingStop (bool) : Trailing stop enabled
     _useTraingStopToBreakEven (bool) : When trailing stop active, trailing stop will increase no further than the entry price
     _trailingStopActivation (int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
     _trailingStopOffset (int) : When trailing stop active, it will trail the max price achieved by this number of points
  Returns: Initialized data set
 f_buildResultStr(_resultType, _price, _resultPoints, _numWins, _pointsWon, _numLoss, _pointsLost) 
  f_buildResultStr Helper function to construct a string of resutling data for exit tooltip labels
  Parameters:
     _resultType (string) 
     _price (float) 
     _resultPoints (float) 
     _numWins (int) 
     _pointsWon (float) 
     _numLoss (int) 
     _pointsLost (float) 
 f_buildResultLabel(data, labelVertical, labelOffset, long) 
  f_buildResultLabel Helper function to construct an Exit label for display on the chart
  Parameters:
     data (backtesterData) 
     labelVertical (bool) 
     labelOffset (int) 
     long (bool) 
 f_updateTrailingStop(_entryPrice, _curPrice, _sl, _tp, trailingStopActivationInput, trailingStopOffsetInput, useTrailingStopToBreakEven) 
  f_updateTrailingStop Helper function to advance the trailing stop as price action dictates
  Parameters:
     _entryPrice (float) 
     _curPrice (float) 
     _sl (float) 
     _tp (float) 
     trailingStopActivationInput (float) 
     trailingStopOffsetInput (float) 
     useTrailingStopToBreakEven (bool) 
  Returns: Updated stop loss for current price action
 f_enterShort(data, entryPrice, fixedStopLoss) 
  f_enterShort Helper function to enter a short and collect data necessary for tracking the trade entry
  Parameters:
     data (backtesterData) 
     entryPrice (float) 
     fixedStopLoss (float) 
  Returns: Updated backtest data
 f_enterLong(data, entryPrice, fixedStopLoss) 
  f_enterLong Helper function to enter a long and collect data necessary for tracking the trade entry
  Parameters:
     data (backtesterData) 
     entryPrice (float) 
     fixedStopLoss (float) 
  Returns: Updated backtest data
 f_exitTrade(data) 
  f_enterLong Helper function to exit a trade and update/reset tracking data
  Parameters:
     data (backtesterData) 
  Returns: Updated backtest data
 f_checkTradeConditionForExit(data, condition, curPrice, enableRealTime) 
  f_checkTradeConditionForExit Helper function to determine if provided condition indicates an exit
  Parameters:
     data (backtesterData) 
     condition (bool) : When true trade will exit
     curPrice (float) 
     enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
  Returns: Updated backtest data
 f_checkTrade(data, curPrice, curLow, curHigh, enableRealTime) 
  f_checkTrade Helper function to determine if current price action dictates stop loss or take profit exit
  Parameters:
     data (backtesterData) 
     curPrice (float) 
     curLow (float) 
     curHigh (float) 
     enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
  Returns: Updated backtest data
 f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor, _text_size) 
  f_fillCell Helper function to construct result table cells
  Parameters:
     _table (table) 
     _column (int) 
     _row (int) 
     _title (string) 
     _value (string) 
     _bgcolor (color) 
     _txtcolor (color) 
     _text_size (string) 
  Returns: Table cell
 f_prepareStatsTable(data, drawTesterSummary, drawTesterDetails, summaryTableTextSize, detailsTableTextSize, displayRowZero, summaryTableLocation, detailsTableLocation) 
  f_fillCell Helper function to populate result table
  Parameters:
     data (backtesterData) 
     drawTesterSummary (bool) 
     drawTesterDetails (bool) 
     summaryTableTextSize (string) 
     detailsTableTextSize (string) 
     displayRowZero (bool) 
     summaryTableLocation (string) 
     detailsTableLocation (string) 
  Returns: Updated backtest data
 backtesterData 
  backtesterData - container for backtest performance metrics
  Fields:
     tradesArray (array) : Array of strings with entries for each individual trade and its results
     pointsBalance (series float) : Running sum of backtest points won/loss results
     drawDown (series float) : Running sum of backtest total draw down points
     maxDrawDown (series float) : Running sum of backtest total draw down points
     maxRunup (series float) : Running sum of max points won over the backtest
     numWins (series int) : Number of wins of current backtes set
     numLoss (series int) : Number of losses of current backtes set
     pointsWon (series float) : Running sum of points won to date
     pointsLost (series float) : Running sum of points lost to date
     entrySide (series string) : Current entry long/short
     tradeActive (series bool) : Indicates if a trade is currently active
     tradeComplete (series bool) : Indicates if a trade just exited (due to stop loss or take profit)
     entryPrice (series float) : Current trade entry price
     entryTime (series int) : Current trade entry time
     sl (series float) : Current trade stop loss
     tp (series float) : Current trade take profit
     defaultStopLoss (series float) : Default trade stop loss to apply
     defaultTakeProfit (series float) : Default trade take profit to apply
     useTrailingStop (series bool) : Trailing stop enabled
     useTrailingStopToBreakEven (series bool) : When trailing stop active, trailing stop will increase no further than the entry price
     trailingStopActivation (series int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
     trailingStopOffset (series int) : When trailing stop active, it will trail the max price achieved by this number of points
     resultType (series string) : Current trade won/lost
     exitPrice (series float) : Current trade exit price
     resultPoints (series float) : Current trade points won/lost
     summaryTable (series table) : Table to deisplay summary info
     tradesTable (series table) : Table to display per trade info
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.
utilsLibrary   "utils" 
TODO: add library description here
 method getType(this) 
  Namespace types: series int, simple int, input int, const int
  Parameters:
     this (int) : int 待检测对象
  Returns: string 类型名称
 method getType(this) 
  Namespace types: series float, simple float, input float, const float
  Parameters:
     this (float) : float 待检测对象
  Returns: string 类型名称
 method getType(this) 
  Namespace types: series color, simple color, input color, const color
  Parameters:
     this (color) : color 待检测对象
  Returns: string 类型名称
 method getType(this) 
  Namespace types: series string, simple string, input string, const string
  Parameters:
     this (string) : string 待检测对象
  Returns: string 类型名称
 method getType(this) 
  Namespace types: series bool, simple bool, input bool, const bool
  Parameters:
     this (bool) : bool 待检测对象
  Returns: string 类型名称
UTSConvenienceToolsLibrary   "UTSConvenienceTools" 
Convenience tool library containing helper functions for drawing and charting.
 isDarkColor(color) 
  Determines on base of the luminance of the given color if the color can be considered a 'dark' color. Usefull for determining the readable font color for arbitrary colored backgrounds. Credits out to: 
  Parameters:
     color (color) : (color): The actual color value.
  Returns: (bool): A boolean value.
 smallLabelLowerRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points to the lower right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 smallLabelUpperRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points to the upper right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 smallLabelCenter(txt, yPos, bgColor) 
  Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points to the center.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 smallLabelDown(txt, yPos, bgColor) 
  Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 smallLabelUp(txt, yPos, bgColor) 
  Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 normalLabelLowerRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points to the lower right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 normalLabelUpperRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points to the upper right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 normalLabelCenter(txt, yPos, bgColor) 
  Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points to the center.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 normalLabelDown(txt, yPos, bgColor) 
  Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 normalLabelUp(txt, yPos, bgColor) 
  Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 largeLabelLowerRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points to the lower right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 largeLabelUpperRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points to the upper right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 largeLabelCenter(txt, yPos, bgColor) 
  Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points to the center.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 largeLabelDown(txt, yPos, bgColor) 
  Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 largeLabelUp(txt, yPos, bgColor) 
  Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 autoLabelLowerRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points to the lower right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 autoLabelUpperRight(txt, yPos, bgColor) 
  Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points to the upper right.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 autoLabelCenter(txt, yPos, bgColor) 
  Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points to the center.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 autoLabelDown(txt, yPos, bgColor) 
  Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
 autoLabelUp(txt, yPos, bgColor) 
  Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points down.
  Parameters:
     txt (string) 
     yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
     bgColor (color) : (color): The background color value.
  Returns: (bool): A boolean value.
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
iLoggerLibrary   "iLogger" 
Logger Library based on types and methods.
 method init(this) 
  init will initialize logger table and log stream array
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
  Returns: void
 method getLogger(level) 
  Namespace types: series LogLevel
  Parameters:
     level (series LogLevel) 
 method setPage(this, pageNumber) 
  setPage will set current page number of logs to display
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     pageNumber (int) : - Page number of logs to display
  Returns: void
 method nextPage(this) 
  nextPage will incremement page number to display on screen
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
  Returns: void
 method previousPage(this) 
  previousPage will decrement page number to display on screen
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
  Returns: void
 method log(this, level, message) 
  log will record message to be logged and repopulate logs displayed
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     level (series LogLevel) : logging level. Can be `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`, `CRITICAL`. Logs only if log level is higher than Loggers minimul log level set
     message (string) : log message to be recorded
  Returns: void
 method trace(this, message) 
  trace will record message to be logged with level 'TRACE'
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     message (string) : log message to be recorded
  Returns: void
 method debug(this, message) 
  debug will record message to be logged with level 'DEBUG'
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     message (string) : log message to be recorded
  Returns: void
 method info(this, message) 
  info will record message to be logged with level 'INFO'
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     message (string) : log message to be recorded
  Returns: void
 method warn(this, message) 
  warn will record message to be logged with level 'WARN'
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     message (string) : log message to be recorded
  Returns: void
 method error(this, message) 
  error will record message to be logged with level 'ERROR'
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     message (string) : log message to be recorded
  Returns: void
 method fatal(this, message) 
  fatal will record message to be logged with level 'FATAL'
  Namespace types: Logger
  Parameters:
     this (Logger) : Logger object
     message (string) : log message to be recorded
  Returns: void
 Log 
  Log Object holding log entry
  Fields:
     level (series LogLevel) : Logging level
     message (series string) : Logging message
     bartime (series int) : bar time at which log is recorded
     bar (series int) : bar index at which log is recorded
 Logger 
  Logger object which can be used for logging purposes
  Fields:
     position (series string) : position on chart where logs can be shown. Valid values are table position values. Make sure that the script does not have any other table at this position
     pageSize (series int) : size of each page of logs which can be shown on UI. Default is 10
     maxEntries (series int) : max size logs to be stored
     pageNumber (series int) : current page number of logs to display on chart
     textSize (series string) : size of text on debug table to be shown. default is size.small. Other options - size.tiny, size.normal, size.large, size.huge, size.auto
     textColor (series color) : text color of debug messages. Default is color.white
     showOnlyLast (series bool) : If set, shows the logs derived only from last bar. Default is true
     minimumLevel (series LogLevel) : Minimum level of logs to be considered for logging.
     realTime (series bool) : Print logs based on real time bar. This should be set to true for debugging indicators and false for debugging strategies.
     debugTable (series table) : table containing debug messages. It will be set in init method. Hence no need to pass this in constructor
     logs (array) : Array of Log containing logging messages. It will be set in init method. Hence no need to pass this in constructor
SCoLibraryAmsterdamLibrary   "SCoLibraryAmsterdam" 
This library contains functions to check Amsterdam strategy price events
 calcTrendMom(FilterTrendWithMa50, FilterTrendWithMa200) 
This function define the current trend and momentum force according to 4wma, 12wma, 21ema and 200sma
Parameters:
 FilterTrendWithMa50 (bool) : is set to true will filter trend result with 50sma
 FilterTrendWithMa200 (bool) : is set to true will filter trend result with 200sma
Returns: Return a positive value if trend is up (2 : strong momentum, 1 : weak momentum) and a negative value if trend is negative (-2 : strong momentum, -1 : weak momentum)
 calcPriceAmstNodeMa01(close, AtrPeriod, AtrMultiplier) 
This function checks if close, 4wma and 12wma are in contraction within a multiple of the average true range
Parameters:
 close (float) 
 AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
 AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
 calcPriceAmstNodeMa123(close, AtrPeriod, AtrMultiplier) 
This function checks if close, 12wma, 21ema and 50sma are in contraction within a multiple of the average true range
Parameters:
 close (float) 
 AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
 AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
 calcPriceInsidebar() 
This function checks inside bar candle configuration
Returns: true or false
 calcPrice12wmaExtended(close, PeriodNormalization, ExtensionPercent) 
This function checks if close is over extended from the 12wma by a multiple of the average true range
Parameters:
 close (float) 
 PeriodNormalization (int) 
 ExtensionPercent (float) 
Returns: Return true or false
 calcPrice21emaExtended(close, PeriodNormalization, ExtensionPercent) 
This function checks if close is over extended from the 21ema by a multiple of the average true range
Parameters:
 close (float) 
 PeriodNormalization (int) 
 ExtensionPercent (float) 
Returns: Return true or false
 calcPrice50smaExtended(close, PeriodNormalization, ExtensionPercent) 
This function checks if close is over extended from the 50sma by a multiple of the average true range
Parameters:
 close (float) 
 PeriodNormalization (int) 
 ExtensionPercent (float) 
Returns: Return true or false
 calcPrice200smaExtended(close, PeriodNormalization, ExtensionPercent) 
This function checks if close is over extended from the 200sma by a multiple of the average true range
Parameters:
 close (float) 
 PeriodNormalization (int) 
 ExtensionPercent (float) 
Returns: Return true or false
 calcPriceClimax(close, AtrPeriod, MovingAvgAtrMulti, VolAtrMulti) 
This function checks if price is in climax evolution by comparing the extension between 4wma and 12wma, and a multiple of the average true range
Parameters:
 close (float) 
 AtrPeriod (simple int) : is the average true range period
 MovingAvgAtrMulti (float) : is the extension ratio
 VolAtrMulti (float) : is the volume extension relative to the 21sma volume
Returns: Return true or false
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)
pslibs_revisedLibrary   "pslibs_revised" 
 f_calculate_divergence_on_close(close, mom, rsi, start_lookback, max_lookback, rsiThresholdBuy, rsiThresholdSell, minAngleDiff, run_flag) 
  Parameters:
     close (float) 
     mom (float) 
     rsi (float) 
     start_lookback (int) 
     max_lookback (int) 
     rsiThresholdBuy (float) 
     rsiThresholdSell (float) 
     minAngleDiff (float) 
     run_flag (bool) 
 f_calculate_divergence_on_low(low, mom, rsi, start_lookback, max_lookback, rsiThresholdBuy, rsiThresholdSell, minAngleDiff, run_flag) 
  Parameters:
     low (float) 
     mom (float) 
     rsi (float) 
     start_lookback (int) 
     max_lookback (int) 
     rsiThresholdBuy (float) 
     rsiThresholdSell (float) 
     minAngleDiff (float) 
     run_flag (bool) 
 f_calculate_reversal(close, low, high, macdFastPeriod, macdSlowPeriod, macdSignalPeriod, stochPeriod, prcKPeriod, stochOS, stochOB, run_flag) 
  Parameters:
     close (float) 
     low (float) 
     high (float) 
     macdFastPeriod (simple int) 
     macdSlowPeriod (simple int) 
     macdSignalPeriod (simple int) 
     stochPeriod (int) 
     prcKPeriod (int) 
     stochOS (int) 
     stochOB (int) 
     run_flag (bool) 
 is_within_first_30_minutes() 
 is_last_60_minutes() 
 is_last_30_minutes() 
 func_yestday_was_postive_trend()
KwakPineHelperLibrary   "KwakPineHelper" 
TODO: add library description here
 fun(x) 
  TODO: add function description here
  Parameters:
     x (float) : TODO: add parameter x description here
  Returns: TODO: add what function returns
 all_opentrades_size() 
  get all opentrades size
  Returns: (float) size
 recent_opentrade_profit() 
  get recent opentrade profit
  Returns: (float) profit
 all_opentrades_profit() 
  get all opentrades profit
  Returns: (float) profit
 recent_closedtrade_profit() 
  get recent closedtrade profit
  Returns: (float) profit
 recent_opentrade_max_runup() 
  get recent opentrade max runup
  Returns: (float) runup
 recent_closedtrade_max_runup() 
  get recent closedtrade max runup
  Returns: (float) runup
 recent_opentrade_max_drawdown() 
  get recent opentrade maxdrawdown
  Returns: (float) mdd
 recent_closedtrade_max_drawdown() 
  get recent closedtrade maxdrawdown
  Returns: (float) mdd
 max_open_trades_drawdown() 
  get max open trades drawdown
  Returns: (float) mdd
 recent_opentrade_commission() 
  get recent opentrade commission
  Returns: (float) commission
 recent_closedtrade_commission() 
  get recent closedtrade commission
  Returns: (float) commission
 qty_by_percent_of_equity(percent) 
  get qty by percent of equtiy
  Parameters:
     percent (float) : (series float) percent that you want to set
  Returns: (float) quantity
 qty_by_percent_of_position_size(percent) 
  get size by percent of position size
  Parameters:
     percent (float) : (series float) percent that you want to set
  Returns: (float) size
 is_day_change() 
  get bool change of day
  Returns: (bool) day is change or not
 is_in_trade(numberOfBars) 
  get bool using number of bars
  Parameters:
     numberOfBars (int) 
  Returns: (bool) allowedToTrade
 api_msg_system(chat_id, message) 
  Parameters:
     chat_id (string) 
     message (string) 
 is_first_day() 
  Check if today is the first day
  Returns: (bool) true if today is the first day, false otherwise
 is_last_day() 
  Check if today is the last day
  Returns: (bool) true if today is the last day, false otherwise
 is_entry() 
  Check if trade is open
  Returns: (bool) true if trade is open, false otherwise
 is_close() 
  Check if trade is closed
  Returns: (bool) true if trade is closed, false otherwise
 is_win() 
  Check if trade is win
  Returns: (bool) true if trade is win, false otherwise
 is_loss() 
  Check if trade is loss
  Returns: (bool) true if trade is loss, false otherwise
permutation█  OVERVIEW 
This library provides functions for generating permutations of string or float arrays, using an iterative approach where pine has no recursion. It supports allowing/limiting duplicate elements and handles large result sets by segmenting them into manageable chunks within custom  Data  types. The most combinations will vary, but the highest is around 250,000 unique combinations. depending on input array values and output length. it will return nothing if the input count is too low.
█  CONCEPTS 
This library addresses two key challenges in Pine Script:
 • Recursion Depth Limits: Pine has limitations on recursion depth. This library uses an iterative, stack-based algorithm to generate permutations, avoiding recursive function calls that could exceed these limits.
 • Array Size Limits:  Pine arrays have size restrictions. This library manages large permutation sets by dividing them into smaller segments stored within a custom  Data  or  DataFloat  type, using maps for efficient access.
█  HOW TO USE 
1 —  Include the Library:  Add this library to your script using:
 
import kaigouthro/permutation/1 as permute
 
2 —  Call the  generatePermutations  Function: 
 
stringPermutations = permute.generatePermutations(array.from("a", "b", "c"), 2, 1)
floatPermutations  = permute.generatePermutations(array.from(1.0, 2.0, 3.0), 2, 1)
 
 •  set : The input array of strings or floats.
 •  size : The desired length of each permutation.
 •  maxDuplicates  (optional): The maximum allowed repetitions of an element within a single permutation. Defaults to 1.
3 —  Access the Results:  The function returns a  Data  (for strings) or  DataFloat  (for floats) object.  These objects contain:
 •  data : An array indicating which segments are present (useful for iterating).
 •  segments : A map where keys represent segment indices and values are the actual permutation data within that segment.
 Example: Accessing Permutations 
 
for   in stringPermutations.segments
    for   in currentSegment.segments
        // Access individual permutations within the segment.
        permutation = segmennt.data
        for item in permutation
            // Use the permutation elements...
 
█  TYPES 
 •  PermutationState / PermutationStateFloat : Internal types used by the iterative algorithm to track the state of permutation generation.
 •  Data / DataFloat :  Custom types to store and manage the generated permutations in segments.
█  NOTES 
*   The library prioritizes handling potentially large permutation sets. 250,000 i about the highest achievable.
*   The segmentation logic ensures that results are accessible even when the total number of permutations exceeds Pine's array size limits.
----
Library   "permutation" 
This library provides functions for generating permutations of user input arrays containing either strings or floats. It uses an iterative, stack-based approach to handle potentially large sets and avoid recursion limitation. The library supports limiting the number of duplicate elements allowed in each permutation. Results are stored in a custom  Data  or  DataFloat  type that uses maps to segment large permutation sets into manageable chunks, addressing Pine Script's array size limitations.
 generatePermutations(set, size, maxDuplicates) 
  >  Generates permutations of a given size from a set of strings or floats. 
  Parameters:
     set (array) : (array or array) The set of strings or floats to generate permutations from.
     size (int) : (int)           The size of the permutations to generate.
     maxDuplicates (int) : (int)           The maximum number of times an element can be repeated in a permutation.
  Returns: (Data or DataFloat) A  Data  object for strings or a  DataFloat  object for floats, containing the generated permutations.
 
stringPermutations = generatePermutations(array.from("a", "b", "c"), 2, 1)
floatPermutations  = generatePermutations(array.from(1.0, 2.0, 3.0), 2, 1)
 
 generatePermutations(set, size, maxDuplicates) 
  Parameters:
     set (array) 
     size (int) 
     maxDuplicates (int) 
 PermutationState 
  PermutationState
  Fields:
     data (array) : (array) The current permutation being built.
     index (series int) : (int)           The current index being considered in the set.
     depth (series int) : (int)           The current depth of the permutation (number of elements).
     counts (map) : (map) Map to track the count of each element in the current permutation (for duplicates).
 PermutationStateFloat 
  PermutationStateFloat
  Fields:
     data (array) : (array) The current permutation being built.
     index (series int) : (int)          The current index being considered in the set.
     depth (series int) : (int)          The current depth of the permutation (number of elements).
     counts (map) : (map) Map to track the count of each element in the current permutation (for duplicates).
 Data 
  Data
  Fields:
     data (array) : (array) Array to indicate which segments are present.
     segments (map) : (map) Map to store permutation segments. Each segment contains a subset of the generated permutations.
 DataFloat 
  DataFloat
  Fields:
     data (array) : (array) Array to indicate which segments are present.
     segments (map) : (map) Map to store permutation segments. Each segment contains a subset of the generated permutations.
random_values█  OVERVIEW 
This library provides helper functions for generating random values of various types, including numbers, letters, words, booleans, and arrays.  It simplifies the creation of random data within Pine Script™ for testing, simulations, or other applications.
█  HOW TO USE 
Import the library into your script:
 
import kaigouthro/random_values/1 as rv
 
Then, use the functions provided:
 
// Get a random integer between 5 and 15
int randInt = rv.intVal(5, 15)
// Generate a random word with 8 characters
string randWord = rv.word(8)
// Create a boolean array with 5 elements
array randBoolArray = rv.boolArray(5)
// And other options! See below for details.
 
█  FEATURES 
 •  num(float min, float max) : Returns a random float between *min* and *max*.  (Internal helper function, not exported).
 •  letter() : Returns a random lowercase letter (a-z).
 •  word(int size = 0) : Returns a random word. *size* specifies the length (default: random length between 3 and 10).
 •  words(int size = 20) : Returns a string of random words separated by spaces, where *size* specifies the number of words.
 •  boolVal() : Returns a random boolean (true or false).
 •  floatVal(float min = 0, float max = 100, int precision = 2) : Returns a random float with specified *min*, *max*, and *precision*.
 •  intVal(int min = 1, int max = 100) : Returns a random integer between *min* and *max*.
 •  stringArray(int size = 0) : Returns an array of random words. *size* specifies the array length (default: random between 3 and 10).
 •  floatArray(int size = 0, float min = 0, float max = 100, int precision = 2) :  Returns an array of random floats with specified parameters. *size* determines the array length.
 •  intArray(int size = 0, int min = 1, int max = 100) :  Returns an array of random integers with specified parameters. *size* determines the array length.
 •  boolArray(int size = 0) : Returns an array of random booleans. *size* specifies the array length (default: random between 3 and 10).
█  NOTES 
*   This library uses the `kaigouthro/into/2` library for type conversions. Make sure it's available.
*   Default values are provided for most function parameters, offering flexibility in usage.
█  LICENSE 
This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at  mozilla.org 
```
**Changes and Rationale:**
*   **OVERVIEW:**  Clearly states the library's purpose.
*   **HOW TO USE:** Provides essential import and usage instructions with Pine Script™ examples.
*   **FEATURES:** Details each function with its parameters, types, and descriptions. Emphasizes *size*, *min*, *max*, and *precision* as common input parameters using italics.  Uses custom bulleted lists.
*   **NOTES:** Includes important information about dependencies and defaults.
*   **LICENSE:**  Directly links to the license URL using the proper ` ` tag.
*   **Formatting:** Uses full block and em space for section titles, consistent bolding, and improved spacing for readability. Removes unnecessary blank lines.  
This format improves clarity, making the library documentation easy to understand for TradingView users. Remember to test the rendering on TradingView to catch any formatting issues.
Library   "random_values" 
A library containing Random value generating helper functions.
 letter() 
  Random letter generator.
  Returns: (string) A random lowercase letter.
 word(size) 
  Random word generator.
  Parameters:
     size (int) : (int) The desired length of the word. If 0 or not provided, a random length between 3 and 10 is used.
  Returns: (string) A random word.
 words(size) 
  Random words generator.
  Parameters:
     size (int) : (int) The number of words to generate. If 0 or not provided, a random number between 3 and 10 is used.
  Returns: (string) A string of random words separated by spaces.
 boolVal() 
  Random boolean generator.
  Returns: (bool) A random boolean value (true or false).
 floatVal(min, max, precision) 
  Random float number generator.
  Parameters:
     min (float) : (float) The minimum float value. Defaults to 0.
     max (float) : (float) The maximum float value. Defaults to 100.
     precision (int) : (int)   The number of decimal places. Defaults to 2.
  Returns: (float) A random float number.
 intVal(min, max) 
  Random integer number generator.
  Parameters:
     min (int) : (int) The minimum integer value. Defaults to 1.
     max (int) : (int) The maximum integer value. Defaults to 100.
  Returns: (int) A random integer number.
 stringArray(size) 
  Random string array generator.
  Parameters:
     size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
  Returns: (array) An array of random words.
 floatArray(size, min, max, precision) 
  Random float array generator.
  Parameters:
     size (int) : (int)   The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
     min (float) : (float) The minimum float value. Defaults to 0.
     max (float) : (float) The maximum float value. Defaults to 100.
     precision (int) : (int)   The number of decimal places. Defaults to 2.
  Returns: (array) An array of random float numbers.
 intArray(size, min, max) 
  Random integer array generator.
  Parameters:
     size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
     min (int) : (int) The minimum integer value. Defaults to 1.
     max (int) : (int) The maximum integer value. Defaults to 100.
  Returns: (array) An array of random integer numbers.
 boolArray(size) 
  Random boolean array generator.
  Parameters:
     size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
  Returns: (array) An array of random boolean values.
Milvetti_TraderPost_LibraryLibrary   "Milvetti_TraderPost_Library" 
This library has methods that provide practical signal transmission for traderpost.Developed By Milvetti
 cancelOrders(symbol) 
  This method generates a signal in JSON format that cancels all orders for the specified pair. (If you want to cancel stop loss and takeprofit orders together, use the “exitOrder” method.
  Parameters:
     symbol (string) 
 exitOrders(symbol) 
  This method generates a signal in JSON format that close all orders for the specified pair.
  Parameters:
     symbol (string) 
 createOrder(ticker, positionType, orderType, entryPrice, signalPrice, qtyType, qty, stopLoss, stopType, stopValue, takeProfit, profitType, profitValue, timeInForce) 
  This function is designed to send buy or sell orders to traderpost. It can create customized orders by flexibly specifying parameters such as order type, position type, entry price, quantity calculation method, stop-loss, and take-profit. The purpose of the function is to consolidate all necessary details for opening a position into a single structure and present it as a structured JSON output. This format can be sent to trading platforms via webhooks.
  Parameters:
     ticker (string) : The ticker symbol of the instrument. Default value is the current chart's ticker (syminfo.ticker).
     positionType (string) : Determines the type of order (e.g., "long" or "buy" for buying and "short" or "sell" for selling).
     orderType (string) : Defines the order type for execution. Options: "market", "limit", "stop". Default is "market"
     entryPrice (float) : The price level for entry orders. Only applicable for limit or stop orders. Default is 0 (market orders ignore this).
     signalPrice (float) : Optional. Only necessary when using relative take profit or stop losses, and the broker does not support fetching quotes to perform the calculation. Default is 0
     qtyType (string) : Determines how the order quantity is calculated. Options: "fixed_quantity", "dollar_amount", "percent_of_equity", "percent_of_position".
     qty (float) : Quantity value. Can represent units of shares/contracts or a dollar amount, depending on qtyType.
     stopLoss (bool) : Enable or disable stop-loss functionality. Set to `true` to activate.
     stopType (string) : Specifies the stop-loss calculation type. Options: percent, "amount", "stopPrice", "trailPercent", "trailAmount". Default is "stopPrice"
     stopValue (float) : Stop-loss value based on stopType. Can be a percentage, dollar amount, or a specific stop price. Default is "stopPrice"
     takeProfit (bool) : Enable or disable take-profit functionality. Set to `true` to activate.
     profitType (string) : Specifies the take-profit calculation type. Options: "percent", "amount", "limitPrice". Default is "limitPrice"
     profitValue (float) : Take-profit value based on profitType. Can be a percentage, dollar amount, or a specific limit price. Default is 0
     timeInForce (string) : The time in force for your order. Options: day, gtc, opg, cls, ioc and fok
  Returns: Return result in Json format.
 addTsl(symbol, stopType, stopValue, price) 
  This method adds trailing stop loss to the current position. “Price” is the trailing stop loss starting level. You can leave price blank if you want it to start immediately
  Parameters:
     symbol (string) 
     stopType (string) : Specifies the trailing stoploss calculation type. Options: "trailPercent", "trailAmount".
     stopValue (float) : Stop-loss value based on stopType. Can be a percentage, dollar amount.
     price (float) : The trailing stop loss starting level. You can leave price blank if you want it to start immediately. Default is current price.






















