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()
Indicateurs et stratégies
Geo. Geo.
This library provides a comprehensive set of geometric functions based on 2 simple types for point and line manipulation, point array calculations, some vector operations (Borrowed from @ricardosantos ), angle calculations, and basic polygon analysis.  It offers tools for creating, transforming, and analyzing geometric shapes and their relationships.  
View the source code for detailed documentation on each function and type.
═════════════════════════════════════════════════════════════════════════
█  OVERVIEW 
This library enhances TradingView's Pine Script with robust geometric capabilities. It introduces the  Point  and  Line  types, along with a suite of functions for various geometric operations. These functionalities empower you to perform advanced calculations, manipulations, and analyses involving points, lines, vectors, angles, and polygons directly within your Pine scripts. The example is  at the bottom of the script. ( Commented out )
█  CONCEPTS 
This library revolves around two fundamental types:
 •  Point:  Represents a point in 2D space with x and y coordinates, along with optional 'a' (angle) and 'v' (value) fields for versatile use.  Crucially, for plotting, utilize the `.to_chart_point()` method to convert Points into plottable chart.point objects.
 •  Line:  Defined by a starting  Point  and a  slope , enabling calculations like getting y for a given x, or finding intersection points.
█  FEATURES 
 •  Point Manipulation:   Perform operations like addition, subtraction, scaling, rotation, normalization, calculating distances, dot products, cross products, midpoints, and more with  Point  objects.
 •  Line Operations:  Create lines, determine their slope, calculate y from x (and vice versa), and find the intersection points of two lines.
 •  Vector Operations:  Perform vector addition, subtraction, multiplication, division, negation, perpendicular vector calculation, floor, fractional part, sine, absolute value, modulus, sign, round, scaling, rescaling, rotation, and ceiling operations.
 •  Angle Calculations:   Compute angles between points in degrees or radians, including signed, unsigned, and 360-degree angles.
 •  Polygon Analysis:  Calculate the area, perimeter, and centroid of polygons. Check if a point is inside a given polygon and determine the convex hull perimeter.
 •  Chart Plotting:  Conveniently convert  Point  objects to  chart.point  objects for plotting lines and points on the chart.  The library also includes functions for plotting lines between individual and series of points.
 •  Utility Functions:  Includes helper functions such as square root, square, cosine, sine, tangent, arc cosine, arc sine, arc tangent, atan2, absolute distance, golden ratio tolerance check, fractional part, and safe index/check for chart plotting boundaries.
█  HOW TO USE 
1 — Include the library in your script using:
 
import kaigouthro/geo/1
 
2 — Create  Point  and  Line  objects:
 
p1 = geo.Point(bar_index, close)
p2 = geo.Point(bar_index , open)
myLine = geo.Line(p1, geo.slope(p1, p2))
// maybe use that line to detect a crossing for an alert ... hmmm
 
3 — Utilize the provided functions:
 
distance = geo.distance(p1, p2)
intersection = geo.intersection(line1, line2)
 
4 — For plotting labels, lines, convert  Point  to  chart.point :
 
label.new(p1.to_chart_point(), " Hi ")
line.new(p1.to_chart_point(),p2.to_chart_point())
 
█  NOTES 
This description provides a concise overview. Consult the library's source code for in-depth documentation, including detailed descriptions, parameter types, and return values for each function and method. The source code is structured with comprehensive comments using the `//@` format for seamless integration with TradingView's auto-documentation features.
█  Possibilities.. 
  
  
Library   "geo" 
This library provides a comprehensive set of geometric functions and types, including point and line manipulation, vector operations, angle calculations, and polygon analysis. It offers tools for creating, transforming, and analyzing geometric shapes and their relationships.
 sqrt(value) 
  Square root function
  Parameters:
     value (float) : (float) - The number to take the square root of
  Returns: (float) - The square root of the input value
 sqr(x) 
  Square function
  Parameters:
     x (float) : (float) - The number to square
  Returns: (float) - The square of the input value
 cos(v) 
  Cosine function
  Parameters:
     v (float) : (series float) - The value to find the cosine of
  Returns: (series float) - The cosine of the input value
 sin(v) 
  Sine function
  Parameters:
     v (float) : (series float) - The value to find the sine of
  Returns: (series float) - The sine of the input value
 tan(v) 
  Tangent function
  Parameters:
     v (float) : (series float) - The value to find the tangent of
  Returns: (series float) - The tangent of the input value
 acos(v) 
  Arc cosine function
  Parameters:
     v (float) : (series float) - The value to find the arc cosine of
  Returns: (series float) - The arc cosine of the input value
 asin(v) 
  Arc sine function
  Parameters:
     v (float) : (series float) - The value to find the arc sine of
  Returns: (series float) - The arc sine of the input value
 atan(v) 
  Arc tangent function
  Parameters:
     v (float) : (series float) - The value to find the arc tangent of
  Returns: (series float) - The arc tangent of the input value
 atan2(dy, dx) 
  atan2 function
  Parameters:
     dy (float) : (float) - The y-coordinate
     dx (float) : (float) - The x-coordinate
  Returns: (float) - The angle in radians
 gap(_value1, __value2) 
  Absolute distance between any two float values
  Parameters:
     _value1 (float) : First value
     __value2 (float) 
  Returns: Absolute Positive Distance
 phi_tol(a, b, tolerance) 
  Check if the ratio is within the tolerance of the golden ratio
  Parameters:
     a (float) : (float) The first number
     b (float) : (float) The second number
     tolerance (float) : (float) The tolerance percennt as 1 = 1 percent
  Returns: (bool) True if the ratio is within the tolerance, false otherwise
 frac(x) 
  frad Fractional
  Parameters:
     x (float) : (float) - The number to convert to fractional
  Returns: (float) - The number converted to fractional
 safeindex(x, limit) 
  limiting int to hold the value within the chart range
  Parameters:
     x (float) : (float) - The number to limit
     limit (int) 
  Returns: (int) - The number limited to the chart range
 safecheck(x, limit) 
  limiting int check if within the chartplottable range
  Parameters:
     x (float) : (float) - The number to limit
     limit (int) 
  Returns: (int) - The number limited to the chart range
 interpolate(a, b, t) 
  interpolate between two values
  Parameters:
     a (float) : (float) - The first value
     b (float) : (float) - The second value
     t (float) : (float) - The interpolation factor (0 to 1)
  Returns: (float) - The interpolated value
 gcd(_numerator, _denominator) 
  Greatest common divisor of two integers
  Parameters:
     _numerator (int) 
     _denominator (int) 
  Returns: (int) The greatest common divisor
 method set_x(self, value) 
  Set the x value of the point, and pass point for chaining
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The point to modify
     value (float) : (float) The new x-coordinate
 method set_y(self, value) 
  Set the y value of the point, and pass point for chaining
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The point to modify
     value (float) : (float) The new y-coordinate
 method get_x(self) 
  Get the x value of the point
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The point to get the x-coordinate from
  Returns: (float) The x-coordinate
 method get_y(self) 
  Get the y value of the point
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The point to get the y-coordinate from
  Returns: (float) The y-coordinate
 method vmin(self) 
  Lowest element of the point
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The point
  Returns: (float) The lowest value between x and y
 method vmax(self) 
  Highest element of the point
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The point
  Returns: (float) The highest value between x and y
 method add(p1, p2) 
  Addition
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (Point) - the add of the two points
 method sub(p1, p2) 
  Subtraction
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (Point) - the sub of the two points
 method mul(p, scalar) 
  Multiplication by scalar
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point
     scalar (float) : (float) - The scalar to multiply by
  Returns: (Point) - the multiplied point of the point and the scalar
 method div(p, scalar) 
  Division by scalar
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point
     scalar (float) : (float) - The scalar to divide by
  Returns: (Point) - the divided point of the point and the scalar
 method rotate(p, angle) 
  Rotate a point around the origin by an angle (in degrees)
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point to rotate
     angle (float) : (float) - The angle to rotate by in degrees
  Returns: (Point) - the rotated point
 method length(p) 
  Length of the vector from origin to the point
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point
  Returns: (float) - the length of the point
 method length_squared(p) 
  Length squared of the vector
  Namespace types: Point
  Parameters:
     p (Point) : (Point) The point
  Returns: (float) The squared length of the point
 method normalize(p) 
  Normalize the point to a unit vector
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point to normalize
  Returns: (Point) - the normalized point
 method dot(p1, p2) 
  Dot product
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (float) - the dot of the two points
 method cross(p1, p2) 
  Cross product result (in 2D, this is a scalar)
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (float) - the cross of the two points
 method distance(p1, p2) 
  Distance between two points
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (float) - the distance of the two points
 method Point(x, y, a, v) 
  Point Create Convenience
  Namespace types: series float, simple float, input float, const float
  Parameters:
     x (float) 
     y (float) 
     a (float) 
     v (float) 
  Returns: (Point) new point
 method angle(p1, p2) 
  Angle between two points in degrees
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (float) - the angle of the first point and the second point
 method angle_between(p, pivot, other) 
  Angle between two points in degrees from a pivot point
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point to calculate the angle from
     pivot (Point) : (Point) - The pivot point
     other (Point) : (Point) - The other point
  Returns: (float) - the angle between the two points
 method translate(p, from_origin, to_origin) 
  Translate a point from one origin to another
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point to translate
     from_origin (Point) : (Point) - The origin to translate from
     to_origin (Point) : (Point) - The origin to translate to
  Returns: (Point) - the translated point
 method midpoint(p1, p2) 
  Midpoint of two points
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (Point) - The midpoint of the two points
 method rotate_around(p, angle, pivot) 
  Rotate a point around a pivot point by an angle (in degrees)
  Namespace types: Point
  Parameters:
     p (Point) : (Point) - The point to rotate
     angle (float) : (float) - The angle to rotate by in degrees
     pivot (Point) : (Point) - The pivot point to rotate around
  Returns: (Point) - the rotated point
 method multiply(_a, _b) 
  Multiply vector _a with _b
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (Point) The result of the multiplication
 method divide(_a, _b) 
  Divide vector _a by _b
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (Point) The result of the division
 method negate(_a) 
  Negative of vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to negate
  Returns: (Point) The negated point
 method perp(_a) 
  Perpendicular Vector of _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The perpendicular point
 method vfloor(_a) 
  Compute the floor of argument vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The floor of the point
 method fractional(_a) 
  Compute the fractional part of the elements from vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The fractional part of the point
 method vsin(_a) 
  Compute the sine of argument vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The sine of the point
 lcm(a, b) 
  Least common multiple of two integers
  Parameters:
     a (int) : (int) The first integer
     b (int) : (int) The second integer
  Returns: (int) The least common multiple
 method vabs(_a) 
  Compute the absolute of argument vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The absolute of the point
 method vmod(_a, _b) 
  Compute the mod of argument vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
     _b (float) : (float) The mod
  Returns: (Point) The mod of the point
 method vsign(_a) 
  Compute the sign of argument vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The sign of the point
 method vround(_a) 
  Compute the round of argument vector _a
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (Point) The round of the point
 method normalize_y(p, height) 
  normalizes the y value of a point to an input height
  Namespace types: Point
  Parameters:
     p (Point) : (Point)      - The point to normalize
     height (float) : (float) - The height to normalize to
  Returns: (Point)      - the normalized point
 centroid(points) 
  Calculate the centroid of multiple points
  Parameters:
     points (array) : (array) The array of points
  Returns: (Point) The centroid point
 random_point(_height, _width, _origin, _centered) 
  Random Point in a given height and width
  Parameters:
     _height (float) : (float) The height of the area to generate the point in
     _width (float) : (float) The width of the area to generate the point in
     _origin (Point) : (Point) The origin of the area to generate the point in (default: na, will create a Point(0, 0))
     _centered (bool) : (bool) Center the origin point in the area, otherwise, positive h/w (default: false)
  Returns: (Point) The random point in the given area
 random_point_array(_origin, _height, _width, _centered, _count) 
  Random Point Array in a given height and width
  Parameters:
     _origin (Point) : (Point) The origin of the area to generate the array (default: na, will create a Point(0, 0))
     _height (float) : (float) The height of the area to generate the array
     _width (float) : (float) The width of the area to generate the array
     _centered (bool) : (bool) Center the origin point in the area, otherwise, positive h/w (default: false)
     _count (int) : (int) The number of points to generate (default: 50)
  Returns: (array) The random point array in the given area
 method sort_points(points, by_x) 
  Sorts an array of points by x or y coordinate
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points to sort
     by_x (bool) : (bool) Whether to sort by x-coordinate (true) or y-coordinate (false)
  Returns: (array) The sorted array of points
 method equals(_a, _b) 
  Compares two points for equality
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (bool) True if the points are equal, false otherwise
 method max(origin, _a, _b) 
  Maximum of two points from origin, using dot product
  Namespace types: Point
  Parameters:
     origin (Point) 
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (Point) The maximum point
 method min(origin, _a, _b) 
  Minimum of two points from origin, using dot product
  Namespace types: Point
  Parameters:
     origin (Point) 
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (Point) The minimum point
 method avg_x(points) 
  Average x of point array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (float) The average x-coordinate
 method avg_y(points) 
  Average y of point array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (float) The average y-coordinate
 method range_x(points) 
  Range of x values in point array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (float) The range of x-coordinates
 method range_y(points) 
  Range of y values in point array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (float) The range of y-coordinates
 method max_x(points) 
  max of x values in point array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (float) The max of x-coordinates
 method min_y(points) 
  min of x values in point array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (float) The min of x-coordinates
 method scale(_a, _scalar) 
  Scale a point by a scalar
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to scale
     _scalar (float) : (float) The scalar value
  Returns: (Point) The scaled point
 method rescale(_a, _length) 
  Rescale a point to a new magnitude
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to rescale
     _length (float) : (float) The new magnitude
  Returns: (Point) The rescaled point
 method rotate_rad(_a, _radians) 
  Rotate a point by an angle in radians
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to rotate
     _radians (float) : (float) The angle in radians
  Returns: (Point) The rotated point
 method rotate_degree(_a, _degree) 
  Rotate a point by an angle in degrees
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to rotate
     _degree (float) : (float) The angle in degrees
  Returns: (Point) The rotated point
 method vceil(_a, _digits) 
  Ceil a point to a certain number of digits
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to ceil
     _digits (int) : (int) The number of digits to ceil to
  Returns: (Point) The ceiled point
 method vpow(_a, _exponent) 
  Raise both point elements to a power
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
     _exponent (float) : (float) The exponent
  Returns: (Point) The point with elements raised to the power
 method perpendicular_distance(_a, _b, _c) 
  Distance from point _a to line between _b and _c
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
     _b (Point) : (Point) The start point of the line
     _c (Point) : (Point) The end point of the line
  Returns: (float) The perpendicular distance
 method project(_a, _axis) 
  Project a point onto another
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to project
     _axis (Point) : (Point) The point to project onto
  Returns: (Point) The projected point
 method projectN(_a, _axis) 
  Project a point onto a point of unit length
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to project
     _axis (Point) : (Point) The unit length point to project onto
  Returns: (Point) The projected point
 method reflect(_a, _axis) 
  Reflect a point on another
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to reflect
     _axis (Point) : (Point) The point to reflect on
  Returns: (Point) The reflected point
 method reflectN(_a, _axis) 
  Reflect a point to an arbitrary axis
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to reflect
     _axis (Point) : (Point) The axis to reflect to
  Returns: (Point) The reflected point
 method angle_rad(_a) 
  Angle in radians of a point
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point
  Returns: (float) The angle in radians
 method angle_unsigned(_a, _b) 
  Unsigned degree angle between 0 and +180 by given two points
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (float) The unsigned angle in degrees
 method angle_signed(_a, _b) 
  Signed degree angle between -180 and +180 by given two points
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (float) The signed angle in degrees
 method angle_360(_a, _b) 
  Degree angle between 0 and 360 by given two points
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The first point
     _b (Point) : (Point) The second point
  Returns: (float) The angle in degrees (0-360)
 method clamp(_a, _vmin, _vmax) 
  Restricts a point between a min and max value
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The point to restrict
     _vmin (Point) : (Point) The minimum point
     _vmax (Point) : (Point) The maximum point
  Returns: (Point) The restricted point
 method lerp(_a, _b, _rate_of_move) 
  Linearly interpolates between points a and b by _rate_of_move
  Namespace types: Point
  Parameters:
     _a (Point) : (Point) The starting point
     _b (Point) : (Point) The ending point
     _rate_of_move (float) : (float) The rate of movement (0-1)
  Returns: (Point) The interpolated point
 method slope(p1, p2) 
  Slope of a line between two points
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
  Returns: (float) - The slope of the line
 method gety(self, x) 
  Get y-coordinate of a point on the line given its x-coordinate
  Namespace types: Line
  Parameters:
     self (Line) : (Line) - The line
     x (float) : (float) - The x-coordinate
  Returns: (float) - The y-coordinate
 method getx(self, y) 
  Get x-coordinate of a point on the line given its y-coordinate
  Namespace types: Line
  Parameters:
     self (Line) : (Line) - The line
     y (float) : (float) - The y-coordinate
  Returns: (float) - The x-coordinate
 method intersection(self, other) 
  Intersection point of two lines
  Namespace types: Line
  Parameters:
     self (Line) : (Line) - The first line
     other (Line) : (Line) - The second line
  Returns: (Point) - The intersection point
 method calculate_arc_point(self, b, p3) 
  Calculate a point on the arc defined by three points
  Namespace types: Point
  Parameters:
     self (Point) : (Point) The starting point of the arc
     b (Point) : (Point) The middle point of the arc
     p3 (Point) : (Point) The end point of the arc
  Returns: (Point) A point on the arc
 approximate_center(point1, point2, point3) 
  Approximate the center of a spiral using three points
  Parameters:
     point1 (Point) : (Point) The first point
     point2 (Point) : (Point) The second point
     point3 (Point) : (Point) The third point
  Returns: (Point) The approximate center point
 createEdge(center, radius, angle) 
  Get coordinate from center by radius and angle
  Parameters:
     center (Point) : (Point) - The center point
     radius (float) : (float) - The radius of the circle
     angle (float) : (float) - The angle in degrees
  Returns: (Point) - The coordinate on the circle
 getGrowthFactor(p1, p2, p3) 
  Get growth factor of spiral point
  Parameters:
     p1 (Point) : (Point) - The first point
     p2 (Point) : (Point) - The second point
     p3 (Point) : (Point) - The third point
  Returns: (float) - The growth factor
 method to_chart_point(point) 
  Convert Point to chart.point using chart.point.from_index(safeindex(point.x), point.y)
  Namespace types: Point
  Parameters:
     point (Point) : (Point) - The point to convert
  Returns: (chart.point) - The chart.point representation of the input point
 method plotline(p1, p2, col, width) 
  Draw a line from p1 to p2
  Namespace types: Point
  Parameters:
     p1 (Point) : (Point) First point
     p2 (Point) : (Point) Second point
     col (color) 
     width (int) 
  Returns: (line) Line object
 method drawlines(points, col, ignore_boundary) 
  Draw lines between points in an array
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
     col (color) : (color) The color of the lines
     ignore_boundary (bool) : (bool) The color of the lines
 method to_chart_points(points) 
  Draw an array of points as chart points on the chart with line.new(chartpoint1, chartpoint2, color=linecolor)
  Namespace types: array
  Parameters:
     points (array) : (array) - The points to draw
  Returns: (array) The array of chart points
 polygon_area(points) 
  Calculate the area of a polygon defined by an array of points
  Parameters:
     points (array) : (array) The array of points representing the polygon vertices
  Returns: (float) The area of the polygon
 polygon_perimeter(points) 
  Calculate the perimeter of a polygon
  Parameters:
     points (array) : (array) Array of points defining the polygon
  Returns: (float) Perimeter of the polygon
 is_point_in_polygon(point, _polygon) 
  Check if a point is inside a polygon
  Parameters:
     point (Point) : (Point) The point to check
     _polygon (array) 
  Returns: (bool) True if the point is inside the polygon, false otherwise
 method perimeter(points) 
  Calculates the convex hull perimeter of a set of points
  Namespace types: array
  Parameters:
     points (array) : (array) The array of points
  Returns: (array) The array of points forming the convex hull perimeter
 Point 
  A Point, can be used for vector, floating calcs, etc. Use the cp method for plots
  Fields:
     x (series float) : (float) The x-coordinate
     y (series float) : (float) The y-coordinate
     a (series float) : (float) An Angle storage spot
     v (series float) : (float) A Value
 Line 
  Line
  Fields:
     point (Point) : (Point) The starting point of the line
     slope (series float) : (float) The slope of the line
GOMTRY.
lib_statemachine_modifiedLibrary   "lib_statemachine_modified" 
Modified to fix bugs and create getState and priorState methods.
 method step(this, before, after, condition) 
  Namespace types: StateMachine
  Parameters:
     this (StateMachine) 
     before (int) : (int): Current state before transition
     after (int) : (int): State to transition to
     condition (bool) : (bool): Condition to trigger the transition
  Returns: (bool): True if the state changed, else False
 method step(this, after, condition) 
  Namespace types: StateMachine
  Parameters:
     this (StateMachine) 
     after (int) : (int): State to transition to
     condition (bool) : (bool): Condition to trigger the transition
  Returns: (bool): True if the state changed, else False
 method currentState(this) 
  Namespace types: StateMachine
  Parameters:
     this (StateMachine) 
 method previousState(this) 
  Namespace types: StateMachine
  Parameters:
     this (StateMachine) 
 method changed(this, within_bars) 
  Namespace types: StateMachine
  Parameters:
     this (StateMachine) 
     within_bars (int) : (int): Number of bars to look back for a state change
  Returns: (bool): True if a state change occurred within the timeframe, else False
 method reset(this, condition, min_occurrences) 
  Namespace types: StateMachine
  Parameters:
     this (StateMachine) 
     condition (bool) : (bool): Condition to trigger the reset
     min_occurrences (int) : (int): Minimum number of times the condition must be true to reset
  Returns: (bool): True if the state was reset, else False
 StateMachine 
  Fields:
     state (series int) 
     neutral (series int) 
     enabled (series bool) 
     reset_counter (series int) 
     prior_state (series int) 
     last_change_bar (series int)
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.
metaconnectorLibrary   "metaconnector" 
metaconnector
 buy_market_order(License_ID, symbol, lot) 
  Places a buy market order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
  Returns: String syntax for the buy market order
 sell_market_order(License_ID, symbol, lot) 
  Places a sell market order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
  Returns: String syntax for the sell market order
 buy_limit_order(License_ID, symbol, lot, price) 
  Places a buy limit order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     price (float) : Limit price for the order
  Returns: String syntax for the buy limit order
 sell_limit_order(License_ID, symbol, lot, price) 
  Places a sell limit order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     price (float) : Limit price for the order
  Returns: String syntax for the sell limit order
 stoploss_for_buy_order(License_ID, symbol, lot, stoploss_price) 
  Places a stop-loss order for a buy position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     stoploss_price (float) 
  Returns: String syntax for the buy stop-loss order
 stoploss_for_sell_order(License_ID, symbol, lot, stoploss_price) 
  Places a stop-loss order for a sell position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     stoploss_price (float) 
  Returns: String syntax for the sell stop-loss order
 takeprofit_for_buy_order(License_ID, symbol, lot, target_price) 
  Places a take-profit order for a buy position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     target_price (float) 
  Returns: String syntax for the buy take-profit order
 takeprofit_for_sell_order(License_ID, symbol, lot, target_price) 
  Places a take-profit order for a sell position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     target_price (float) 
  Returns: String syntax for the sell take-profit order
 buy_stop_order(License_ID, symbol, lot, price) 
  Places a buy stop order above the current market price
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     price (float) : Stop order price
  Returns: String syntax for the buy stop order
 sell_stop_order(License_ID, symbol, lot, price) 
  Places a sell stop order below the current market price
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     price (float) : Stop order price
  Returns: String syntax for the sell stop order
 close_all_positions(License_ID, symbol) 
  Closes all positions for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
  Returns: String syntax for closing all positions
 close_buy_positions(License_ID, symbol) 
  Closes all buy positions for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
  Returns: String syntax for closing all buy positions
 close_sell_positions(License_ID, symbol) 
  Closes all sell positions for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
  Returns: String syntax for closing all sell positions
 close_partial_buy_position(License_ID, symbol, lot) 
  Closes a partial buy position for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to close
  Returns: String syntax for closing a partial buy position
 close_partial_sell_position(License_ID, symbol, lot) 
  Closes a partial sell position for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to close
  Returns: String syntax for closing a partial sell position
Request█   OVERVIEW 
This library is a tool for Pine Script™ programmers that consolidates access to a wide range of lesser-known data feeds available on TradingView, including metrics from the FRED database, FINRA short sale volume, open interest, and COT data. The functions in this library simplify requests for these data feeds, making them easier to retrieve and use in custom scripts. 
█   CONCEPTS 
 Federal Reserve Economic Data (FRED) 
 FRED  (Federal Reserve Economic Data) is a comprehensive online database curated by the Federal Reserve Bank of St. Louis. It provides free access to extensive economic and financial data from U.S. and international sources. FRED includes numerous economic indicators such as GDP, inflation, employment, and interest rates. Additionally, it provides financial market data, regional statistics, and international metrics such as exchange rates and trade balances. 
Sourced from reputable organizations, including U.S. government agencies, international institutions, and other public and private entities, FRED enables users to analyze over 825,000 time series, download their data in various formats, and integrate their information into analytical tools and programming workflows. 
On TradingView, FRED data is available from ticker identifiers with the "FRED:" prefix. Users can search for FRED symbols in the "Symbol Search" window, and Pine scripts can retrieve data for these symbols via `request.*()` function calls.
 FINRA Short Sale Volume 
FINRA (the Financial Industry Regulatory Authority) is a non-governmental organization that supervises and regulates U.S. broker-dealers and securities professionals. Its primary aim is to protect investors and ensure integrity and transparency in financial markets. 
FINRA's  Short Sale Volume data  provides detailed information about daily short-selling activity across U.S. equity markets. This data tracks the volume of short sales reported to FINRA's trade reporting facilities (TRFs), including shares sold on FINRA-regulated Alternative Trading Systems (ATSs) and over-the-counter (OTC) markets, offering transparent access to short-selling information not typically available from exchanges. This data helps market participants, researchers, and regulators monitor trends in short-selling and gain insights into bearish sentiment, hedging strategies, and potential market manipulation. Investors often use this data alongside other metrics to assess stock performance, liquidity, and overall trading activity. 
It is important to note that FINRA's Short Sale Volume data does not consolidate short sale information from public exchanges and excludes trading activity that is not publicly disseminated.
TradingView provides ticker identifiers for requesting Short Sale Volume data with the format "FINRA:_SHORT_VOLUME", where "" is a supported U.S. equities symbol (e.g., "AAPL"). 
 Open Interest (OI) 
 Open interest  is a cornerstone indicator of market activity and sentiment in derivatives markets such as options or futures. In contrast to volume, which measures the number of contracts opened or closed within a period, OI measures the number of  outstanding contracts  that are not yet settled. This distinction makes OI a more robust indicator of how money flows through derivatives, offering meaningful insights into liquidity, market interest, and trends. Many traders and investors analyze OI alongside volume and price action to gain an enhanced perspective on market dynamics and reinforce trading decisions. 
TradingView offers many ticker identifiers for requesting OI data with the format "_OI", where "" represents a derivative instrument's  ticker ID  (e.g., "COMEX:GC1!").
 Commitment of Traders (COT) 
 Commitment of Traders  data provides an informative weekly breakdown of the aggregate positions held by various market participants, including commercial hedgers, non-commercial speculators, and small traders, in the U.S. derivative markets. Tallied and managed by the  Commodity Futures Trading Commission (CFTC) , these reports provide traders and analysts with detailed insight into an asset's open interest and help them assess the actions of various market players. COT data is valuable for gaining a deeper understanding of market dynamics, sentiment, trends, and liquidity, which helps traders develop informed trading strategies.
TradingView has numerous ticker identifiers that provide access to time series containing data for various COT metrics. To learn about COT ticker IDs and how they work, see our  LibraryCOT  publication. 
█   USING THE LIBRARY 
 Common function characteristics 
 • This library's functions construct ticker IDs with valid formats based on their specified parameters, then use them as the `symbol` argument in  request.security()  to retrieve data from the specified context. 
 • Most of these functions automatically select the timeframe of a data request because the data feeds are not available for all timeframes. 
 • All the functions have  two  overloads. The first overload of each function uses values with the  "simple"  qualifier to define the requested context, meaning the context does not change after the first script execution. The second accepts  "series"  values, meaning it can request data from different contexts across executions. 
 • The `gaps` parameter in most of these functions specifies whether the returned data is `na` when a new value is unavailable for request. By default, its value is `false`, meaning the call returns the last retrieved data when no new data is available. 
 • The `repaint` parameter in applicable functions determines whether the request can fetch the latest unconfirmed values from a higher timeframe on realtime bars, which might repaint after the script restarts. If `false`, the function only returns confirmed higher-timeframe values to avoid repainting. The default value is `true`.
 `fred()` 
The `fred()` function retrieves the most recent value of a specified series from the Federal Reserve Economic Data (FRED) database. With this function, programmers can easily fetch macroeconomic indicators, such as GDP and unemployment rates, and use them directly in their scripts. 
 How it works 
The function's `fredCode` parameter accepts a "string" representing the unique identifier of a specific FRED series. Examples include "GDP" for the "Gross Domestic Product" series and "UNRATE" for the "Unemployment Rate" series. Over 825,000 codes are available. To access codes for available series, search the  FRED website .  
The function adds the "FRED:" prefix to the specified `fredCode` to construct a valid FRED ticker ID (e.g., "FRED:GDP"), which it uses in  request.security()  to retrieve the series data.
 Example Usage 
This line of code requests the latest value from the Gross Domestic Product series and assigns the returned value to a `gdpValue` variable:
 float gdpValue = fred("GDP") 
 `finraShortSaleVolume()` 
The `finraShortSaleVolume()` function retrieves  EOD  data from a FINRA  Short Sale Volume  series. Programmers can call this function to retrieve short-selling information for equities listed on supported exchanges, namely NASDAQ, NYSE, and NYSE ARCA. 
 How it works 
The `symbol` parameter determines which symbol's short sale volume information is retrieved by the function. If the value is  na , the function requests short sale volume data for the chart's symbol. The argument can be the name of the symbol from a supported exchange (e.g., "AAPL") or a ticker ID with an exchange prefix ("NASDAQ:AAPL"). If the `symbol` contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", or "BATS". 
The function constructs a ticker ID in the format "FINRA:ticker_SHORT_VOLUME", where "ticker" is the symbol name  without  the exchange prefix (e.g., "AAPL"). It then uses the ticker ID in  request.security()  to retrieve the available data. 
 Example Usage 
This line of code retrieves short sale volume for the chart's symbol and assigns the result to a `shortVolume` variable:
 float shortVolume = finraShortSaleVolume(syminfo.tickerid) 
This example requests short sale volume for the "NASDAQ:AAPL" symbol, irrespective of the current chart:
 float shortVolume = finraShortSaleVolume("NASDAQ:AAPL") 
 `openInterestFutures()` and `openInterestCrypto()` 
The `openInterestFutures()` function retrieves  EOD  open interest (OI) data for futures contracts. The `openInterestCrypto()` function provides more granular OI data for cryptocurrency contracts. 
 How they work 
The `openInterestFutures()` function retrieves EOD closing OI information. Its design is focused primarily on retrieving OI data for futures, as only EOD OI data is available for these instruments. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. 
The `openInterestCrypto()` function retrieves opening, high, low, and closing OI data for a cryptocurrency contract on a specified timeframe. Unlike `openInterest()`, this function can also retrieve granular data from intraday timeframes. 
Both functions contain a `symbol` parameter that determines the symbol for which the calls request OI data. The functions construct a valid OI ticker ID from the chosen symbol by appending "_OI" to the end (e.g., "CME:ES1!_OI"). 
The `openInterestFutures()` function requests and returns a two-element tuple containing the futures instrument's EOD closing OI and a "bool" condition indicating whether OI is rising.
The `openInterestCrypto()` function requests and returns a five-element tuple containing the cryptocurrency contract's opening, high, low, and closing OI, and a "bool" condition indicating whether OI is rising. 
 Example usage 
This code line calls `openInterest()` to retrieve EOD OI and the OI rising condition for a futures symbol on the chart, assigning the values to two variables in a tuple:
  = openInterestFutures(syminfo.tickerid) 
This line retrieves the EOD OI data for "CME:ES1!", irrespective of the current chart's symbol:
  = openInterestFutures("CME:ES1!") 
This example uses `openInterestCrypto()` to retrieve OHLC OI data and the OI rising condition for a cryptocurrency contract on the chart, sampled at the chart's timeframe. It assigns the returned values to five variables in a tuple:
  = openInterestCrypto(syminfo.tickerid, timeframe.period) 
This call retrieves OI OHLC and rising information for "BINANCE:BTCUSDT.P" on the "1D" timeframe:
  = openInterestCrypto("BINANCE:BTCUSDT.P", "1D") 
 `commitmentOfTraders()` 
The `commitmentOfTraders()` function retrieves data from the Commitment of Traders (COT) reports published by the Commodity Futures Trading Commission (CFTC). This function significantly simplifies the COT request process, making it easier for programmers to access and utilize the available data. 
 How It Works 
This function's parameters determine different parts of a valid ticker ID for retrieving COT data, offering a streamlined alternative to constructing complex COT ticker IDs manually. The `metricName`, `metricDirection`, and `includeOptions` parameters are required. They specify the name of the reported metric, the direction, and whether it includes information from options contracts. 
The function also includes several optional parameters. The `CFTCCode` parameter allows programmers to request data for a specific report code. If unspecified, the function requests data based on the chart symbol's root prefix, base currency, or quoted currency, depending on the `mode` argument. The call can specify the report type ("Legacy", "Disaggregated", or "Financial") and metric type ("All", "Old", or "Other") with the `typeCOT` and `metricType` parameters. 
Explore the  CFTC website  to find valid report codes for specific assets. To find detailed information about the metrics included in the reports and their meanings, see the  CFTC's Explanatory Notes . 
View the function's documentation below for detailed explanations of its parameters. For in-depth information about COT ticker IDs and more advanced functionality, refer to our previously published  COT library . 
 Available metrics 
Different COT report types provide  different metrics . The tables below list all available metrics for each type and their applicable directions:
 +------------------------------+------------------------+
|  Legacy (COT) Metric Names   |       Directions       |
+------------------------------+------------------------+
| Open Interest                | No direction           |
| Noncommercial Positions      | Long, Short, Spreading |
| Commercial Positions         | Long, Short            |
| Total Reportable Positions   | Long, Short            |
| Nonreportable Positions      | Long, Short            |
| Traders Total                | No direction           |
| Traders Noncommercial        | Long, Short, Spreading |
| Traders Commercial           | Long, Short            |
| Traders Total Reportable     | Long, Short            |
| Concentration Gross LT 4 TDR | Long, Short            |
| Concentration Gross LT 8 TDR | Long, Short            |
| Concentration Net LT 4 TDR   | Long, Short            |
| Concentration Net LT 8 TDR   | Long, Short            |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names |       Directions       |
+-----------------------------------+------------------------+
| Open Interest                     | No Direction           |
| Producer Merchant Positions       | Long, Short            |
| Swap Positions                    | Long, Short, Spreading |
| Managed Money Positions           | Long, Short, Spreading |
| Other Reportable Positions        | Long, Short, Spreading |
| Total Reportable Positions        | Long, Short            |
| Nonreportable Positions           | Long, Short            |
| Traders Total                     | No Direction           |
| Traders Producer Merchant         | Long, Short            |
| Traders Swap                      | Long, Short, Spreading |
| Traders Managed Money             | Long, Short, Spreading |
| Traders Other Reportable          | Long, Short, Spreading |
| Traders Total Reportable          | Long, Short            |
| Concentration Gross LE 4 TDR      | Long, Short            |
| Concentration Gross LE 8 TDR      | Long, Short            |
| Concentration Net LE 4 TDR        | Long, Short            |
| Concentration Net LE 8 TDR        | Long, Short            |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| Financial (COT3) Metric Names |       Directions       |
+-------------------------------+------------------------+
| Open Interest                 | No Direction           |
| Dealer Positions              | Long, Short, Spreading |
| Asset Manager Positions       | Long, Short, Spreading |
| Leveraged Funds Positions     | Long, Short, Spreading |
| Other Reportable Positions    | Long, Short, Spreading |
| Total Reportable Positions    | Long, Short            |
| Nonreportable Positions       | Long, Short            |
| Traders Total                 | No Direction           |
| Traders Dealer                | Long, Short, Spreading |
| Traders Asset Manager         | Long, Short, Spreading |
| Traders Leveraged Funds       | Long, Short, Spreading |
| Traders Other Reportable      | Long, Short, Spreading |
| Traders Total Reportable      | Long, Short            |
| Concentration Gross LE 4 TDR  | Long, Short            |
| Concentration Gross LE 8 TDR  | Long, Short            |
| Concentration Net LE 4 TDR    | Long, Short            |
| Concentration Net LE 8 TDR    | Long, Short            |
+-------------------------------+------------------------+ 
 Example usage 
This code line retrieves "Noncommercial Positions (Long)" data, without options information, from the "Legacy" report for the chart symbol's root, base currency, or quote currency:
 float nonCommercialLong = commitmentOfTraders("Noncommercial Positions", "Long", false) 
This example retrieves "Managed Money Positions (Short)" data, with options included, from the "Disaggregated" report:
 float disaggregatedData = commitmentOfTraders("Managed Money Positions", "Short", true, "", "Disaggregated") 
█   NOTES 
 • This library uses  dynamic requests , allowing dynamic ("series") arguments for the parameters defining the context (ticker ID, timeframe, etc.) of a `request.*()` function call. With this feature, a single `request.*()` call instance can flexibly retrieve data from different feeds across historical executions. Additionally, scripts can use such calls in the  local scopes  of loops, conditional structures, and even exported library functions, as demonstrated in this script. All scripts coded in Pine Script™ v6 have dynamic requests enabled by default. To learn more about the behaviors and limitations of this feature, see the  Dynamic requests  section of the Pine Script™ User Manual.
 • The library's example code offers a simple demonstration of the exported functions. The script retrieves available data using the function specified by the "Series type" input. The code requests a FRED series or COT (Legacy), FINRA Short Sale Volume, or Open Interest series for the chart's symbol with specific parameters, then plots the retrieved data as a step-line with diamond markers. 
 Look first. Then leap.  
█   EXPORTED FUNCTIONS 
This library exports the following functions:
 fred(fredCode, gaps) 
  Requests a value from a specified Federal Reserve Economic Data (FRED) series. FRED is a comprehensive source that hosts numerous U.S. economic datasets. To explore available FRED datasets and codes, search for specific categories or keywords at fred.stlouisfed.org Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     fredCode (series string) : The unique identifier of the FRED series. The function uses the value to create a valid ticker ID for retrieving FRED data in the format `"FRED:fredCode"`. For example, `"GDP"` refers to the "Gross Domestic Product" series ("FRED:GDP"), and `"GFDEBTN"` refers to the "Federal Debt: Total Public Debt" series ("FRED:GFDEBTN").
     gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
  Returns: (float) The value from the requested FRED series.
 finraShortSaleVolume(symbol, gaps, repaint) 
  Requests FINRA daily short sale volume data for a specified symbol from one of the following exchanges: NASDAQ, NYSE, NYSE ARCA. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request short sale volume data. If the specified value contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", "BATS".
     gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: (float) The short sale volume for the specified symbol or the chart's symbol.
 openInterestFutures(symbol, gaps, repaint) 
  Requests EOD open interest (OI) and OI rising information for a valid futures symbol. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request open interest data.
     gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: ( ) A tuple containing the following values:
    - The closing OI value for the symbol.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.
 openInterestCrypto(symbol, timeframe, gaps, repaint) 
  Requests opening, high, low, and closing open interest (OI) data and OI rising information for a valid cryptocurrency contract on a specified timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request open interest data.
     timeframe (series string) : The timeframe of the data request. If the timeframe is lower than the chart's timeframe, it causes a runtime error.
     gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the `timeframe` represents a higher timeframe, the function returns unconfirmed values from the timeframe on realtime bars, which repaint when the script restarts its executions. If `false`, it returns only confirmed higher-timeframe values to avoid repainting. The default is `true`.
  Returns: ( ) A tuple containing the following values:
    - The opening, high, low, and closing OI values for the symbol, respectively.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.
 commitmentOfTraders(metricName, metricDirection, includeOptions, CFTCCode, typeCOT, mode, metricType) 
  Requests Commitment of Traders (COT) data with specified parameters. This function provides a simplified way to access CFTC COT data available on TradingView. Calls to this function count toward a script's `request.*()` call limit. For more advanced tools and detailed information about COT data, see TradingView's  LibraryCOT  library.
  Parameters:
     metricName (series string) : One of the valid metric names listed in the library's documentation and source code.
     metricDirection (series string) : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Consult the library's documentation or code to see which direction values apply to the specified metric.
     includeOptions (series bool) : If `true`, the COT symbol includes options information. Otherwise, it does not.
     CFTCCode (series string) : Optional. The CFTC code for the asset. For example, wheat futures (root "ZW") have the code "001602". If one is not specified, the function will attempt to get a valid code for the chart symbol's root, base currency, or main currency.
     typeCOT (series string) : Optional. The type of report to request. Possible values are: "Legacy", "Disaggregated", "Financial". The default is "Legacy".
     mode (series string) : Optional. Specifies the information the function extracts from a symbol. Possible modes are:
  - "Root": The function extracts the futures symbol's root prefix information (e.g., "ES" for "ESH2020").
  - "Base currency": The function extracts the first currency from a currency pair (e.g., "EUR" for "EURUSD").
  - "Currency": The function extracts the currency of the symbol's quoted values (e.g., "JPY" for "TSE:9984" or "USDJPY").
  - "Auto": The function tries the first three modes (Root -> Base currency -> Currency) until it finds a match.
  The default is "Auto". If the specified mode is not available for the symbol, it causes a runtime error.
     metricType (series string) : Optional. The metric type. Possible values are: "All", "Old", "Other". The default is "All".
  Returns: (float) The specified Commitment of Traders data series. If no data is available, it causes a runtime error.
PremiumDiscountLibraryLibrary   "PremiumDiscountLibrary" 
 isInZone(currentTime, price, trend, tz) 
  Vérifie si le prix est en zone premium ou discount
  Parameters:
     currentTime (int) : L'heure actuelle (timestamp)
     price (float) : Le prix actuel
     trend (string) : La tendance ("bullish" ou "bearish")
     tz (string) : Le fuseau horaire pour calculer les sessions (par défaut : "GMT+1")
  Returns: true si le prix est dans la zone correcte, sinon false
KillzoneLibraryLibrary   "KillzoneLibrary" 
 isKillzone(currentTime, tz) 
  Vérifie si l'heure actuelle est dans une Killzone
  Parameters:
     currentTime (int) : L'heure actuelle (entier représentant le timestamp)
     tz (string) : Le fuseau horaire (par défaut : "GMT+1")
  Returns: true si dans une Killzone, sinon false
LibraryDivergenceV6LibraryDivergenceV6
Enhance your trading strategies with LibraryDivergenceV6, a comprehensive Pine Script library designed to simplify and optimize the detection of bullish and bearish divergences across multiple technical indicators. Whether you're developing your own indicators or seeking to incorporate robust divergence analysis into your trading systems, this library provides the essential tools and functions to accurately identify potential market reversals and continuations.
Overview
LibraryDivergenceV6 offers a suite of functions that detect divergences between price movements and key technical indicators such as the Relative Strength Index (RSI) and On-Balance Volume (OBV). By automating the complex calculations involved in divergence detection, this library enables traders and developers to implement reliable and customizable divergence strategies with ease.
Key Features
Comprehensive Divergence Detection
Bullish Divergence: Identifies instances where the indicator forms higher lows while the price forms lower lows, signaling potential upward reversals.
Bearish Divergence: Detects situations where the indicator creates lower highs while the price forms higher highs, indicating possible downward reversals.
Overbought and Oversold Conditions: Differentiates between standard and strong divergences by considering overbought and oversold levels, enhancing signal reliability.
Multi-Indicator Support
RSI (Relative Strength Index): Analyze momentum-based divergences to spot potential trend reversals.
OBV (On-Balance Volume): Incorporate volume flow into divergence analysis for a more comprehensive market perspective.
Customizable Parameters
Pivot Points Configuration: Adjust the number of bars to the left and right for pivot detection, allowing fine-tuning based on different timeframes and trading styles.
Range Settings: Define minimum and maximum bar ranges to control the sensitivity of divergence detection, reducing false signals.
Noise Cancellation: Enable or disable noise filtering to focus on significant divergences and minimize minor fluctuations.
Flexible Usage
Exported Functions: Easily integrate divergence detection into your custom indicators or trading strategies with exported functions such as DivergenceBull, DivergenceBear, DivergenceBullOversold, and DivergenceBearOverbought.
Occurrence Handling: Specify which occurrence of a divergence to consider (e.g., most recent, previous) for precise analysis.
Optimized Performance
Efficient Calculations: Designed to handle multiple occurrences and pivot points without compromising script performance.
Line Management: Automatically creates and deletes trend lines based on divergence conditions, ensuring a clean and uncluttered chart display.
MyRenkoLibraryLibrary   "MyRenkoLibrary" 
 calcRenko(real_break_size) 
  Parameters:
     real_break_size (float)
PseudoPlotLibrary   "PseudoPlot" 
PseudoPlot: behave like plot and fill using polyline
This library enables line plotting by polyline like plot() and fill().
The core of polyline() is array of chart.point array, polyline() is called in its method.
Moreover, plotarea() makes a box in main chart, plotting data within the box is enabled.
It works so slowy to manage array of chart.point, so limit the target to visible area of the chart.
Due to polyline specifications, na and expression can not be used for colors.
1. pseudoplot
pseudoplot() behaves like plot().
 
//use plot()
plot(close)
//use pseudoplot()
pseudoplot(close)
 
Pseudoplot has label. Label is enabled when title argument is set.
In the example bellow, "close value" label is shown with line.
The label is shown at right of the line when recent bar is visible.
It is shown at 15% from the left of visible area when recent bar is not visible.
Just set "" if you don't need label.
 
//use plot()
plot(close,"close value")
//use pseudoplot
pseudoplot(close, "close value")
 
Arguments are designed in an order as similar as possible to plot.
 
plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display, format, precision, force_overlay) → plot
pseudoplot(series, title, ,linecolor ,linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) → pseudo_plot
 
2. pseudofill
pseudofill() behaves like fill().
The label is shown(text only) at right of the line when recent bar is visible.
It is shown at 10% from the left of visible area when recent bar is not visible.
Just set "" if you don't need label.
 
//use plot() and fill()
p1=plot(open)
p2=plot(close)
fill(p1,p2)
//use pseudofill()
pseudofill(open,close)
 
Arguments are designed in an order as similar as possible to fill.
 
fill(hline1, hline2, color, title, editable, fillgaps, display) → void
pseudofill(series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) → pseudo_plot
 
3. plotarea and its methods
plotarea() makes a box in main chart. You can set the box position to top or bottom, and
the box height in percentage of the range of visible high and low prices.
x-coordinate of the box is from chart.left_visible_bar_time to chart.right_visible_bar_time,
y-coordinate is highest and lowest price of visible bars.
pseudoplot() and pseudofill() work as method of plotarea(box).
Usage is almost same as the function version, just set min and max value, y-coodinate is remapped automatically.
hline() is also available. The y-coordinate of hline is specified as a percentage from the bottom.
plotarea() and its associated methods are overlay=true as default.
Depending on the drawing order of the objects, plot may become invisible, so the bgcolor of plotarea should be na or tranceparent.
 
//1. make a plotarea
// bgcolor should be na or transparent color.
area=plotarea("bottom",30,"plotarea",bgcolor=na)
//2. plot in a plotarea
//(min=0, max=100 is omitted as it is the default.)
area.pseudoplot(ta.rsi(close,14))
//3. draw hlines
area.hline(30,linestyle="dotted",linewidth=2)
area.hline(70,linestyle="dotted",linewidth=2)
 
4. Data structure and sub methods
Array management is most imporant part of using polyline.
I don't know the proper way to handle array, so it is managed by array and array as intermediate data.
(type xy_arrays to manage bar_time and price as independent arrays.)
method cparray() pack arrays to array, when array includes both chart.left_visible_bar_time and chart.right_visible_bar.time.
Calling polyline is implemented as methods of array of chart.point.
Method creates polyline object if array is not empty.
 
method polyline(linecolor, linewidth, linestyle, overlay) → series polyline
method polyline_fill(fillcolor, linecolor, linewidth, linestyle, overlay) → series polyline
 
Also calling label is implemented as methods of array of chart.point.
Method creates label ofject if array is not empty.
Label is located at right edge of the chart when recent bar is visible, located at left side when recent bar is invisible.
 
label(title, labelbg, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) → series label
label_for_fill(title, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) → series label
 
 visible_xyInit(series) 
  make arrays of visible x(bar_time) and y(price/value).
  Parameters:
     series (float) : (float)		series variable
  Returns: (xy_arrays)
 method remap(this, bottom, top, min, max) 
  Namespace types: xy_arrays
  Parameters:
     this (xy_arrays) 
     bottom (float) : (float)		bottom price to ajust.
     top (float) : (float)		top price to ajust.
     min (float) : (float)		min of src value.
     max (float) : (float)		max of src value.
  Returns: (xy_arrays)
 method polyline(this, linecolor, linewidth, linestyle, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     linecolor (color) : (color) 	color of polyline.
     linewidth (int) : (int) 		width of polyline.
     linestyle (string) : (string)	linestyle of polyline. default is line.style_solid("solid"), others line.style_dashed("dashed"), line.style_dotted("dotted").
     overlay (bool) : (bool)		force_overlay of polyline. default is false.
  Returns: (polyline)
 method polyline_fill(this, fillcolor, linecolor, linewidth, linestyle, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     fillcolor (color) 
     linecolor (color) : (color) 	color of polyline.
     linewidth (int) : (int) 		width of polyline.
     linestyle (string) : (string)	linestyle of polyline. default is line.style_solid("solid"), others line.style_dashed("dashed"), line.style_dotted("dotted").
     overlay (bool) : (bool)		force_overlay of polyline. default is false.
  Returns: (polyline)
 method label(this, title, labelbg, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     title (string) : (string) 	label text.
     labelbg (color) : (color) 	color of label bg.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     overlay (bool) : (bool)		force_overlay of label. default is false.
  Returns: (label)
 method label_for_fill(this, title, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     title (string) : (string) 	label text.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 10%.
     overlay (bool) : (bool)		force_overlay of label. default is false.
  Returns: (label)
 pseudoplot(series, title, linecolor, linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) 
  polyline like plot with label
  Parameters:
     series (float) : (float)		series variable to plot.
     title (string) : (string)	title if need label. default value is ""(disable label).
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labelbg (color) : (color)		color of label bg.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label text.
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudo_plot)
 method pseudoplot(this, series, title, linecolor, linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, min, max, overlay) 
  Namespace types: series box
  Parameters:
     this (box) 
     series (float) : (float)		series variable to plot.
     title (string) : (string)	title if need label. default value is ""(disable label).
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labelbg (color) : (color)		color of label bg.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label text.
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     min (float) 
     max (float) 
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudo_plot)
 pseudofill(series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) 
  fill by polyline
  Parameters:
     series1 (float) : (float)		series variable to plot.
     series2 (float) : (float)		series variable to plot.
     fillcolor (color) : (color)		color of fill.
     title (string) 
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labeltext (color) 
     labelsize (int) 
     shorttitle (string) 
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudoplot)
 method pseudofill(this, series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, min, max, overlay) 
  Namespace types: series box
  Parameters:
     this (box) 
     series1 (float) : (float)		series variable to plot.
     series2 (float) : (float)		series variable to plot.
     fillcolor (color) : (color)		color of fill.
     title (string) 
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labeltext (color) 
     labelsize (int) 
     shorttitle (string) 
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     min (float) 
     max (float) 
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudo_plot)
 plotarea(pos, height, title, bordercolor, borderwidth, bgcolor, textsize, textcolor, format, overlay) 
  subplot area in main chart
  Parameters:
     pos (string) : (string)	position of subplot area, bottom or top.
     height (int) : (float)		percentage of visible chart heght.
     title (string) : (string)	text of area box.
     bordercolor (color) : (color)	color of border.
     borderwidth (int) : (int)		width of border.
     bgcolor (color) : (string)	color of area bg.
     textsize (int) 
     textcolor (color) 
     format (string) 
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (box)
 method hline(this, ypos_from_bottom, linecolor, linestyle, linewidth, overlay) 
  Namespace types: series box
  Parameters:
     this (box) 
     ypos_from_bottom (float) : (float)		percentage of box height from the bottom of box.(bottom is 0%, top is 100%).
     linecolor (color) : (color)		color of line.
     linestyle (string) : (string)	style of line.
     linewidth (int) : (int)		width of line.
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (line)
 pseudo_plot 
  polyline and label.
  Fields:
     p (series polyline) 
     l (series label) 
 xy_arrays 
  x(bartime) and y(price or value) arrays.
  Fields:
     t (array) 
     p (array)
Milvetti_Pineconnector_LibraryLibrary   "Milvetti_Pineconnector_Library" 
This library has methods that provide practical signal transmission for Pineconnector.Developed By Milvetti
 buy(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sell(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 buyLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy limit order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 buyStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy stop order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sellLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a sell limit order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sellStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a sell stop order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
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.
tacLibrary   "tac" 
Customised techninal analysis functions
 sar(start, inc, max) 
  returns parabolic sar with lagging value
  Parameters:
     start (float) : float: Start
     inc (float) : float: Increment
     max (float) : float: Maximum
  Returns:   Actual sar value and lagging sar value
lib_divergenceLibrary   "lib_divergence" 
offers a commonly usable function to detect divergences. This will take the default RSI or other symbols / indicators / oscillators as source data.
 divergence(osc, pivot_left_bars, pivot_right_bars, div_min_range, div_max_range, ref_low, ref_high, min_divergence_offset_fraction, min_divergence_offset_dev_len, min_divergence_offset_atr_mul) 
  Detects Divergences between Price and Oscillator action. For bullish divergences, look at trend lines between lows. For bearish divergences, look at trend lines between highs. (strong) oscillator trending, price opposing it | (medium) oscillator trending, price trend flat | (weak) price opposite trending, oscillator trend flat | (hidden) price trending, oscillator opposing it. Pivot detection is only properly done in oscillator data, reference price data is only compared at the oscillator pivot (speed optimization)
  Parameters:
     osc (float) : (series float) oscillator data (can be anything, even another instrument price)
     pivot_left_bars (simple int) : (simple int) optional number of bars left of a confirmed pivot point, confirming it is the highest/lowest in the range before and up to the pivot (default: 5)
     pivot_right_bars (simple int) : (simple int) optional number of bars right of a confirmed pivot point, confirming it is the highest/lowest in the range from and after the pivot (default: 5)
     div_min_range (simple int) : (simple int) optional minimum distance to the pivot point creating a divergence (default: 5)
     div_max_range (simple int) : (simple int) optional maximum amount of bars in a divergence (default: 50)
     ref_low (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: low)
     ref_high (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: high)
     min_divergence_offset_fraction (simple float) : (simple float) optional scaling factor for the offset zone (xDeviation) around the last oscillator H/L detecting following equal H/Ls (default: 0.01)
     min_divergence_offset_dev_len (simple int) : (simple int) optional lookback distance for the deviation detection for the offset zone around the last oscillator H/L detecting following equal H/Ls. Used as well for the ATR that does the equal H/L detection for the reference price. (default: 14)
     min_divergence_offset_atr_mul (simple float) : (simple float) optional scaling factor for the offset zone (xATR) around the last price H/L detecting following equal H/Ls (default: 1)
@return A tuple of deviation flags. 
QTALibrary   "QTA" 
This is simple library for basic Quantitative Technical Analysis for retail investors. One example of it being used can be seen here ().
 calculateKellyRatio(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns from bets.
  Returns: The calculated Kelly Ratio, which indicates the optimal bet size based on winning and losing probabilities.
 calculateAdjustedKellyFraction(kellyRatio, riskTolerance, fedStance) 
  Parameters:
     kellyRatio (float) : The calculated Kelly Ratio.
     riskTolerance (float) : A float representing the risk tolerance level.
     fedStance (string) : A string indicating the Federal Reserve's stance ("dovish", "hawkish", or neutral).
  Returns: The adjusted Kelly Fraction, constrained within the bounds of  .
 calculateStdDev(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The standard deviation of the returns, or 0 if insufficient data.
 calculateMaxDrawdown(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The maximum drawdown as a percentage.
 calculateEV(avgWinReturn, winProb, avgLossReturn) 
  Parameters:
     avgWinReturn (float) : The average return from winning bets.
     winProb (float) : The probability of winning a bet.
     avgLossReturn (float) : The average return from losing bets.
  Returns: The calculated Expected Value of the bet.
 calculateTailRatio(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The Tail Ratio, or na if the 5th percentile is zero to avoid division by zero.
 calculateSharpeRatio(avgReturn, riskFreeRate, stdDev) 
  Parameters:
     avgReturn (float) : The average return of the investment.
     riskFreeRate (float) : The risk-free rate of return.
     stdDev (float) : The standard deviation of the investment's returns.
  Returns: The calculated Sharpe Ratio, or na if standard deviation is zero.
 calculateDownsideDeviation(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The standard deviation of the downside returns, or 0 if no downside returns exist.
 calculateSortinoRatio(avgReturn, downsideDeviation) 
  Parameters:
     avgReturn (float) : The average return of the investment.
     downsideDeviation (float) : The standard deviation of the downside returns.
  Returns: The calculated Sortino Ratio, or na if downside deviation is zero.
 calculateVaR(returns, confidenceLevel) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     confidenceLevel (float) : A float representing the confidence level (e.g., 0.95 for 95% confidence).
  Returns: The Value at Risk at the specified confidence level.
 calculateCVaR(returns, varValue) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     varValue (float) : The Value at Risk threshold.
  Returns: The average Conditional Value at Risk, or na if no returns are below the threshold.
 calculateExpectedPriceRange(currentPrice, ev, stdDev, confidenceLevel) 
  Parameters:
     currentPrice (float) : The current price of the asset.
     ev (float) : The expected value (in percentage terms).
     stdDev (float) : The standard deviation (in percentage terms).
     confidenceLevel (float) : The confidence level for the price range (e.g., 1.96 for 95% confidence).
  Returns: A tuple containing the minimum and maximum expected prices.
 calculateRollingStdDev(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling standard deviation of returns.
 calculateRollingVariance(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling variance of returns.
 calculateRollingMean(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling mean of returns.
 calculateRollingCoefficientOfVariation(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling coefficient of variation of returns.
 calculateRollingSumOfPercentReturns(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling sum of percent returns.
 calculateRollingCumulativeProduct(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling cumulative product of returns.
 calculateRollingCorrelation(priceReturns, volumeReturns, window) 
  Parameters:
     priceReturns (array) : An array of floats representing the price returns.
     volumeReturns (array) : An array of floats representing the volume returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling correlation.
 calculateRollingPercentile(returns, window, percentile) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
     percentile (int) : An integer representing the desired percentile (0-100).
  Returns: An array of floats representing the rolling percentile of returns.
 calculateRollingMaxMinPercentReturns(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: A tuple containing two arrays: rolling max and rolling min percent returns.
 calculateRollingPriceToVolumeRatio(price, volData, window) 
  Parameters:
     price (array) : An array of floats representing the price data.
     volData (array) : An array of floats representing the volume data.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling price-to-volume ratio.
 determineMarketRegime(priceChanges) 
  Parameters:
     priceChanges (array) : An array of floats representing the price changes.
  Returns: A string indicating the market regime ("Bull", "Bear", or "Neutral").
 determineVolatilityRegime(price, window) 
  Parameters:
     price (array) : An array of floats representing the price data.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the calculated volatility.
 classifyVolatilityRegime(volatility) 
  Parameters:
     volatility (array) : An array of floats representing the calculated volatility.
  Returns: A string indicating the volatility regime ("Low" or "High").
 method percentPositive(thisArray) 
  Returns the percentage of positive non-na values in this array.
This method calculates the percentage of positive values in the provided array, ignoring NA values.
  Namespace types: array
  Parameters:
     thisArray (array) 
 _candleRange() 
 _PreviousCandleRange(barsback) 
  Parameters:
     barsback (int) : An integer representing how far back you want to get a range
 redCandle() 
 greenCandle() 
 _WhiteBody() 
 _BlackBody() 
 HighOpenDiff() 
 OpenLowDiff() 
 _isCloseAbovePreviousOpen(length) 
  Parameters:
     length (int) 
 _isCloseBelowPrevious() 
 _isOpenGreaterThanPrevious() 
 _isOpenLessThanPrevious() 
 BodyHigh() 
 BodyLow() 
 _candleBody() 
 _BodyAvg(length) 
  _BodyAvg function.
  Parameters:
     length (simple int) : Required (recommended is 6).
 _SmallBody(length) 
  Parameters:
     length (simple int) : Length of the slow EMA
  Returns: a series of bools, after checking if the candle body was less than body average.
 _LongBody(length) 
  Parameters:
     length (simple int) 
 bearWick() 
  bearWick() function.
  Returns: a SERIES of FLOATS, checks if it's a blackBody(open > close), if it is, than check the difference between the high and open, else checks the difference between high and close.
 bullWick() 
 barlength() 
 sumbarlength() 
 sumbull() 
 sumbear() 
 bull_vol() 
 bear_vol() 
 volumeFightMA() 
 volumeFightDelta() 
 weightedAVG_BullVolume() 
 weightedAVG_BearVolume() 
 VolumeFightDiff() 
 VolumeFightFlatFilter() 
 avg_bull_vol(userMA) 
  avg_bull_vol(int) function.
  Parameters:
     userMA (int) 
 avg_bear_vol(userMA) 
  avg_bear_vol(int) function.
  Parameters:
     userMA (int) 
 diff_vol(userMA) 
  diff_vol(int) function.
  Parameters:
     userMA (int) 
 vol_flat(userMA) 
  vol_flat(int) function.
  Parameters:
     userMA (int) 
 _isEngulfingBullish() 
 _isEngulfingBearish() 
 dojiup() 
 dojidown() 
 EveningStar() 
 MorningStar() 
 ShootingStar() 
 Hammer() 
 InvertedHammer() 
 BearishHarami() 
 BullishHarami() 
 BullishBelt() 
 BullishKicker() 
 BearishKicker() 
 HangingMan() 
 DarkCloudCover()
CandleCandle: A Comprehensive Pine Script™ Library for Candlestick Analysis 
 Overview 
The Candle library, developed in Pine Script™, provides traders and developers with a robust toolkit for analyzing candlestick data. By offering easy access to fundamental candlestick components like open, high, low, and close prices, along with advanced derived metrics such as body-to-wick ratios, percentage calculations, and volatility analysis, this library enables detailed insights into market behavior.
This library is ideal for creating custom indicators, trading strategies, and backtesting frameworks, making it a powerful resource for any Pine Script™ developer.
 Key Features 
 1. Core Candlestick Data 
 •    Open : Access the opening price of the current candle.
 •    High : Retrieve the highest price.
 •    Low : Retrieve the lowest price.
 •    Close : Access the closing price.
 2. Candle Metrics 
 •    Full Size : Calculates the total range of the candle (high - low).
 •    Body Size : Computes the size of the candle’s body (open - close).
 •    Wick Size : Provides the combined size of the upper and lower wicks.
 3. Wick and Body Ratios 
 •    Upper Wick Size  and  Lower Wick Size .
 •    Body-to-Wick Ratio  and  Wick-to-Body Ratio .
 4. Percentage Calculations 
 •    Upper Wick Percentage : The proportion of the upper wick size relative to the full candle size.
 •    Lower Wick Percentage : The proportion of the lower wick size relative to the full candle size.
 •    Body Percentage  and  Wick Percentage  relative to the candle’s range.
 5. Candle Direction Analysis 
 •   Determines if a candle is "Bullish" or "Bearish" based on its closing and opening prices.
 6. Price Metrics 
 •    Average Price : The mean of the open, high, low, and close prices.
 •    Midpoint Price : The midpoint between the high and low prices.
 7. Volatility Measurement 
 •   Calculates the standard deviation of the OHLC prices, providing a volatility metric for the current candle.
 Code Architecture 
 Example Functionality 
The library employs a modular structure, exporting various functions that can be used independently or in combination. For instance:
 
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © DevArjun
//@version=6
indicator("Candle Data", overlay = true)
import DevArjun/Candle/1 as Candle
// Body Size %
bodySize = Candle.BodySize()
// Determining the candle direction
candleDirection = Candle.CandleDirection()
// Calculating the volatility of the current candle
volatility = Candle.Volatility()
// Plotting the metrics (for demonstration)
plot(bodySize, title="Body Size", color=color.blue)
label.new(bar_index, high, candleDirection, style=label.style_circle)
 
 Scalability 
The modularity of the Candle library allows seamless integration into more extensive trading systems. Functions can be mixed and matched to suit specific analytical or strategic needs.
 Use Cases 
 Trading Strategies 
Developers can use the library to create strategies based on candle properties such as:
 •   Identifying long-bodied candles (momentum signals).
 •   Detecting wicks as potential reversal zones.
 •   Filtering trades based on candle ratios.
 Visualization 
Plotting components like body size, wick size, and directional labels helps visualize market behavior and identify patterns.
 Backtesting 
By incorporating volatility and ratio metrics, traders can design and test strategies on historical data, ensuring robust performance before live trading.
 Education 
This library is a great tool for teaching candlestick analysis and how each component contributes to market behavior.
 Portfolio Highlights 
 Project Objective 
To create a Pine Script™ library that simplifies candlestick analysis by providing comprehensive metrics and insights, empowering traders and developers with advanced tools for market analysis.
 Development Challenges and Solutions 
 •    Challenge : Achieving high precision in calculating ratios and percentages.
 •    Solution : Implemented robust mathematical operations and safeguarded against division-by-zero errors.
 •    Challenge : Ensuring modularity and scalability.
 •    Solution : Designed functions as independent modules, allowing flexible integration.
 Impact 
 •    Efficiency : The library reduces the time required to calculate complex candlestick metrics.
 •    Versatility : Supports various trading styles, from scalping to swing trading.
 •    Clarity : Clean code and detailed documentation ensure usability for developers of all levels.
 Conclusion 
The Candle library exemplifies the power of Pine Script™ in simplifying and enhancing candlestick analysis. By including this project in your portfolio, you showcase your expertise in:
 •   Financial data analysis.
 •   Pine Script™ development.
 •   Creating tools that solve real-world trading challenges.
This project demonstrates both technical proficiency and a keen understanding of market analysis, making it an excellent addition to your professional portfolio.
Library   "Candle" 
A comprehensive library to access and analyze the basic components of a candlestick, including open, high, low, close prices, and various derived metrics such as full size, body size, wick sizes, ratios, percentages, and additional analysis metrics.
 Open() 
  Open
@description Returns the opening price of the current candle.
  Returns: float - The opening price of the current candle.
 High() 
  High
@description Returns the highest price of the current candle.
  Returns: float - The highest price of the current candle.
 Low() 
  Low
@description Returns the lowest price of the current candle.
  Returns: float - The lowest price of the current candle.
 Close() 
  Close
@description Returns the closing price of the current candle.
  Returns: float - The closing price of the current candle.
 FullSize() 
  FullSize
@description Returns the full size (range) of the current candle (high - low).
  Returns: float - The full size of the current candle.
 BodySize() 
  BodySize
@description Returns the body size of the current candle (open - close).
  Returns: float - The body size of the current candle.
 WickSize() 
  WickSize
@description Returns the size of the wicks of the current candle (full size - body size).
  Returns: float - The size of the wicks of the current candle.
 UpperWickSize() 
  UpperWickSize
@description Returns the size of the upper wick of the current candle.
  Returns: float - The size of the upper wick of the current candle.
 LowerWickSize() 
  LowerWickSize
@description Returns the size of the lower wick of the current candle.
  Returns: float - The size of the lower wick of the current candle.
 BodyToWickRatio() 
  BodyToWickRatio
@description Returns the ratio of the body size to the wick size of the current candle.
  Returns: float - The body to wick ratio of the current candle.
 UpperWickPercentage() 
  UpperWickPercentage
@description Returns the percentage of the upper wick size relative to the full size of the current candle.
  Returns: float - The percentage of the upper wick size relative to the full size of the current candle.
 LowerWickPercentage() 
  LowerWickPercentage
@description Returns the percentage of the lower wick size relative to the full size of the current candle.
  Returns: float - The percentage of the lower wick size relative to the full size of the current candle.
 WickToBodyRatio() 
  WickToBodyRatio
@description Returns the ratio of the wick size to the body size of the current candle.
  Returns: float - The wick to body ratio of the current candle.
 BodyPercentage() 
  BodyPercentage
@description Returns the percentage of the body size relative to the full size of the current candle.
  Returns: float - The percentage of the body size relative to the full size of the current candle.
 WickPercentage() 
  WickPercentage
@description Returns the percentage of the wick size relative to the full size of the current candle.
  Returns: float - The percentage of the wick size relative to the full size of the current candle.
 CandleDirection() 
  CandleDirection
@description Returns the direction of the current candle.
  Returns: string - "Bullish" if the candle is bullish, "Bearish" if the candle is bearish.
 AveragePrice() 
  AveragePrice
@description Returns the average price of the current candle (mean of open, high, low, and close).
  Returns: float - The average price of the current candle.
 MidpointPrice() 
  MidpointPrice
@description Returns the midpoint price of the current candle (mean of high and low).
  Returns: float - The midpoint price of the current candle.
 Volatility() 
  Volatility
@description Returns the standard deviation of the OHLC prices of the current candle.
  Returns: float - The volatility of the current candle.
ToolsFluentLibrary   "ToolsFluent" 
Fluent data holder object with retrieval and modification functions
 set(fluent, key, value) 
  Returns Fluent object after setting related fluent value
  Parameters:
     fluent (Fluent) : Fluent Fluent object
     key (string) : string|int Key to be set
     value (int) : int|float|bool|string|color Value to be set
  Returns: Fluent
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (float) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (bool) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (string) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     value (color) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (int) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (float) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (bool) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (string) 
 set(fluent, key, value) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     value (color) 
 get(fluent, key, default) 
  Returns Fluent object key's value or default value when key not found
  Parameters:
     fluent (Fluent) : Fluent object
     key (string) 
     default (int) : int|float|bool|string|color Value to be returned when key not exists
  Returns: int|float|bool|string|color
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (float) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (bool) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (string) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (string) 
     default (color) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (int) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (float) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (bool) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (string) 
 get(fluent, key, default) 
  Parameters:
     fluent (Fluent) 
     key (int) 
     default (color) 
 Fluent 
  Fluent - General purpose data holder object
  Fields:
     msi (map) : map String key, integer value info holder map. Default: na
     msf (map) : map String key, float value info holder map. Default: na
     msb (map) : map String key, boolean value info holder map. Default: na
     mss (map) : map String key, string value info holder map. Default: na
     msc (map) : map String key, color value info holder map. Default: na
     mii (map) : map Integer key, integer value info holder map. Default: na
     mif (map) : map Integer key, float value info holder map. Default: na
     mib (map) : map Integer key, boolean value info holder map. Default: na
     mis (map) : map Integer key, string value info holder map. Default: na
     mic (map) : map Integer key, color value info holder map. Default: na
ToolsPosLibrary   "ToolsPos" 
Library for general purpose position helpers
 new_pos(state, price, when, index) 
  Returns new PosInfo object
  Parameters:
     state (series PosState) :  Position state
     price (float) : float Entry price
     when (int) : int Entry bar time UNIX. Default: time
     index (int) : int Entry bar index. Default: bar_index
  Returns: PosInfo
 new_tp(pos, price, when, index, info) 
  Returns PosInfo object with new take profit info object
  Parameters:
     pos (PosInfo) : PosInfo object
     price (float) : float Entry price
     when (int) : int Entry bar time UNIX. Default: time
     index (int) : int Entry bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object. Default: na
  Returns: PosInfo
 new_re(pos, price, when, index, info) 
  Returns PosInfo object with new re-entry info object
  Parameters:
     pos (PosInfo) : PosInfo object
     price (float) : float Entry price
     when (int) : int Entry bar time UNIX. Default: time
     index (int) : int Entry bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object. Default: na
  Returns: PosInfo
 PosTPInfo 
  PosTPInfo - Position Take Profit info object
  Fields:
     price (series float) : float Take profit price
     when (series int) : int Take profit bar time UNIX. Default: time
     index (series int) : int Take profit bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object
 PosREInfo 
  PosREInfo - Position Re-Entry info object
  Fields:
     price (series float) : float Re-entry price
     when (series int) : int Re-entry bar time UNIX. Default: time
     index (series int) : int Take profit bar index. Default: bar_index
     info (Info type from aybarsm/Tools/14) :  Info holder object
 PosInfo 
  PosInfo - Position info object
  Fields:
     state (series PosState) :  Position state
     price (series float) : float Entry price
     when (series int) : int Entry bar time UNIX. Default: time
     index (series int) : int Entry bar index. Default: bar_index
     tp (array) : PosTPInfo  Take profit info. Default: na
     re (array) : PosREInfo  Re-entry info. Default: na
     info (Info type from aybarsm/Tools/14) :  Info holder object
ToolsCollectionLibrary   "ToolsCollection" 
Helper functions for collection (map/array) type operations
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: int
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: float
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: string
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (string) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: color
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: int
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: float
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: string
 get(container, key, default) 
  Returns Map key's value with default return value option
  Parameters:
     container (map) : Map object
     key (int) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: color
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (bool) : Default return value when key not found. Default: false
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (int) : Default return value when key not found. Default: -1
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (float) : Default return value when key not found. Default: -1
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (string) : Default return value when key not found. Default: ''
  Returns: bool
 get(container, key, default) 
  Returns Array key's value with default return value option
  Parameters:
     container (array) : Array object
     key (int) : Key to be checked
     default (color) : Default return value when key not found. Default: color.white
  Returns: bool
DynamicPeriodPublicDynamic Period Calculation Library 
This library provides tools for adaptive period determination, useful for creating indicators or strategies that automatically adjust to market conditions.
 Overview 
The  Dynamic Period Library  calculates adaptive periods based on pivot points, enabling the creation of responsive indicators and strategies that adjust to market volatility.
 Key Features 
 
  Dynamic Periods: Computes periods using distances between pivot highs and lows.
  Customizable Parameters: Users can adjust detection settings and period constraints.
  Robust Handling: Includes fallback mechanisms for cases with insufficient pivot data.
 
 Use Cases 
 
  Adaptive Indicators: Build tools that respond to market volatility by adjusting their periods dynamically.
  Dynamic Strategies: Enhance trading strategies by integrating pivot-based period adjustments.
 
 Function: `dynamic_period` 
 Description 
Calculates a dynamic period based on the average distances between pivot highs and lows.
 Parameters 
 
  `left` (default: 5): Number of left-hand bars for pivot detection.
  `right` (default: 5): Number of right-hand bars for pivot detection.
  `numPivots` (default: 5): Minimum pivots required for calculation.
  `minPeriod` (default: 2): Minimum allowed period.
  `maxPeriod` (default: 50): Maximum allowed period.
  `defaultPeriod` (default: 14): Fallback period if no pivots are found.
 
 Returns 
A dynamic period calculated based on pivot distances, constrained by `minPeriod` and `maxPeriod`.
 Example 
 //@version=6
import CrimsonVault/DynamicPeriodPublic/1
left = input.int(5, "Left bars", minval = 1)
right = input.int(5, "Right bars", minval = 1)
numPivots = input.int(5, "Number of Pivots", minval = 2)
period = DynamicPeriodPublic.dynamic_period(left, right, numPivots)
plot(period, title = "Dynamic Period", color = color.blue) 
 Implementation Notes 
 
 Pivot Detection: Requires sufficient historical data to identify pivots accurately.
 Edge Cases: Ensures a default period is applied when pivots are insufficient.
 Constraints: Limits period values to a user-defined range for stability.






















