IndexBasketsLibrary "IndexBaskets" Centralized Top 10 Ticker Baskets. Update weights here to sync all indicators. getBasket(name) Parameters: name (string) Basket Fields: tickers (array) weights (array)Pine Script®库由codename_trading提供0
funyLibrary "funy" 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 returnsPine Script®库由mrlingamtrades提供0
MovingAveragesLibrary "MovingAverages" A collection of O(1) numerically stable moving averages that support anchors and fractional lengths up to 100k bars. Pine Script has a robust set of moving averages suitable for a majority of cases, making these alternatives useful only if you need anchoring, fractional lengths, or more than 5k bars. Included are the classic SMA , EMA , RMA , WMA , VWMA , VWAP , HMA , SWMA , Linear Regression , and ATR . The common parameters are: source (float) : Series of values to process. length (simple float) : Number of bars. Optional. anchor (bool) : The condition that triggers a calculation reset. Optional. parity (simple bool) : Sets if built-in function should be used. Optional. Other DSP filter adaptations include One Euro , Laguerre , Super Smoother , and Holt , as well as rate limiting functions such as Smooth Damp and Slew Rate Limiter . ANCHORING This is the libraries first and primary benefit. Akin to the built-in VWAP, anchoring is managed by passing a series bool into the function. For sessional anchoring, the included new_session() returns true on the first bar of intraday sessions, and stabilize_anchor() helps reduce near-anchor volatility. When no length is provided, the series continues indefinitely until a new anchor is set. Values during the warmup period are returned. source = close length = 9.5 anchor = ma.new_session() // Assumes library is imported as "ma" swma = ma.swma(source, length, anchor).stabilize_anchor(source, length, anchor) STREAMING UPDATES Rather than naively using loops to recalculate the whole series on each bar, linear interpolation (aka. "lerping") is used to incrementally update and translate between values. The canonical formula being: a + (b - a) * t. This formula is effectively an EMA, but it's applicable to nearly all averaging equations. Coupling this technique with a circular buffer captures 3 of the 5 benefits this library offers: O(1) computation, fractional lengths, and 100k bars. NUMERIC STABILITY The last benefit is how the library minimizes floating point errors. When possible, Pine Script functions are used for mathematical parity. Otherwise Kahan summation error compensation is used when calculating an average. Not only does this keep custom implementations stable throughout the series, it also helps keep them within 1.0e-10 of the built-in functions. Automatically defaulting to the built-in functions can be disabled by setting parity to false .Pine Script®库由liquid-trader提供已更新 3
basechartpatternsLibrary "basechartpatterns" Library having complete chart pattern implementation getPatternNameById(id) Returns pattern name by id Parameters: id (int) : pattern id Returns: Pattern name method find(points, properties, dProperties, ohlcArray) Find patterns based on array of points Namespace types: array Parameters: points (array) : array of chart.point objects properties (ScanProperties type from SwSpace/abstractchartpatterns/1) : ScanProperties object dProperties (DrawingProperties type from SwSpace/abstractchartpatterns/1) : DrawingProperties object ohlcArray (array type from SwSpace/ohlc/1) Returns: Flag indicating if the pattern is valid, Current Pattern object method find(this, properties, dProperties, patterns, ohlcArray) Find patterns based on the currect zigzag object but will not store them in the pattern array. Namespace types: zg.Zigzag Parameters: this (Zigzag type from SwSpace/ZigzagLite/1) : Zigzag object containing pivots properties (ScanProperties type from SwSpace/abstractchartpatterns/1) : ScanProperties object dProperties (DrawingProperties type from SwSpace/abstractchartpatterns/1) : DrawingProperties object patterns (array type from SwSpace/abstractchartpatterns/1) : Array of Pattern objects ohlcArray (array type from SwSpace/ohlc/1) Returns: Flag indicating if the pattern is valid, Current Pattern objectPine Script®库由SwSpace提供1
abstractchartpatternsLibrary "abstractchartpatterns" Library having abstract types and methods for chart pattern implementations method checkSize(filters, points) checks if the series of pivots are within the size filter Namespace types: SizeFilters Parameters: filters (SizeFilters) : SizeFilters object containing size criteria to be matched points (array) : list of pivot points Returns: true if matches the size filter, false otherwise checkBarRatio(p1, p2, p3, properties) checks if three zigzag pivot points are having uniform bar ratios Parameters: p1 (chart.point) : First pivot point p2 (chart.point) : Second pivot point p3 (chart.point) : Third pivot point properties (ScanProperties) Returns: true if points are having uniform bar ratio getRatioDiff(p1, p2, p3) gets ratio difference between 3 pivot combinations Parameters: p1 (chart.point) p2 (chart.point) p3 (chart.point) Returns: returns the ratio difference between pivot2/pivot1 ratio and pivot3/pivot2 ratio method inspect(points, stratingBar, endingBar, direction, ohlcArray) Creates a trend line between 2 or 3 points and validates and selects best combination Namespace types: array Parameters: points (array) : Array of chart.point objects used for drawing trend line stratingBar (int) : starting bar of the trend line endingBar (int) : ending bar of the trend line direction (float) : direction of the last pivot. Tells whether the line is joining upper pivots or the lower pivots ohlcArray (array type from SwSpace/ohlc/1) : Array of OHLC values Returns: boolean flag indicating if the trend line is valid and the trend line object as tuple method draw(this) draws pattern on the chart Namespace types: Pattern Parameters: this (Pattern) : Pattern object that needs to be drawn Returns: Current Pattern object method erase(this) erase the given pattern on the chart Namespace types: Pattern Parameters: this (Pattern) : Pattern object that needs to be erased Returns: Current Pattern object method pushWithLimit(this, p, maxItems) push Pattern object to the array by keeping maxItems limit Namespace types: array Parameters: this (array) : array of Pattern objects p (Pattern) : Pattern object to be added to array @oaram maxItems Max number of items the array can hold maxItems (int) Returns: Current Pattern array method deepcopy(this) Perform deep copy of a chart point array Namespace types: array Parameters: this (array) : array of chart.point objects Returns: deep copy array DrawingProperties Object containing properties for pattern drawing Fields: patternLineWidth (series int) : Line width of the pattern trend lines showZigzag (series bool) : show zigzag associated with pattern zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true showPatternLabel (series bool) : display pattern label containing the name patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6 pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values. deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns. Pattern Object containing Individual Pattern data Fields: dir (series int) : direction of the last pivot points (array) : array of Zigzag Pivot points trendLine1 (Line type from SwSpace/LineWrapper/1) : First trend line joining pivots 1, 3, 5 trendLine2 (Line type from SwSpace/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6) properties (DrawingProperties) : DrawingProperties Object carrying common properties patternColor (series color) : Individual pattern color. Lines and labels will be using this color. ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios zigzagLine (series polyline) : Internal zigzag line drawing Object pivotLabels (array) : array containning Pivot labels patternLabel (series label) : pattern label Object patternType (series int) : integer representing the pattern type patternName (series string) : Type of pattern in string SizeFilters Object containing properties for pattern size filters Fields: filterByBar (series bool) : If set filter the patterns by the bar range minPatternBars (series int) : Used only when filterByBar is set to true. Minimum bars range for pattern size maxPatternBars (series int) : Used only when filterByBar is set to true. Maximum bars range for pattern size filterByPercent (series bool) : Filters patterns by percent of price if set minPatternPercent (series int) : Used only when filterByPercent is set. Minimum pattern size in terms of percent of price maxPatternPercent (series int) : Used only when filterByPercent is set. Maximum pattern size in terms of percent of price ScanProperties Object containing properties for pattern scanning Fields: offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan. numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6 errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true avoidOverlap (series bool) : avoid overlapping patterns. ignoreIfEntryCrossed (series bool) : Ignore the trade if close price does not fall within the price entry price range allowedPatterns (array) : array of bool encoding the allowed pattern types. allowedLastPivotDirections (array) : array of int representing allowed last pivot direction for each pattern types themeColors (array) : color array of themes to be used. filters (SizeFilters)Pine Script®库由SwSpace提供已更新 0
ZigzagLiteLibrary "ZigzagLite" Lighter version of the Zigzag Library. Without indicators and sub-component divisions method getPrices(pivots) Gets the array of prices from array of Pivots Namespace types: array Parameters: pivots (array) : array array of Pivot objects Returns: array array of pivot prices method getBars(pivots) Gets the array of bars from array of Pivots Namespace types: array Parameters: pivots (array) : array array of Pivot objects Returns: array array of pivot bar indices method getPoints(pivots) Gets the array of chart.point from array of Pivots Namespace types: array Parameters: pivots (array) : array array of Pivot objects Returns: array array of pivot points method getPoints(this) Gets the array of chart.point from Zigzag Object Namespace types: Zigzag Parameters: this (Zigzag) : Zigzag object Returns: array array of pivot points method calculate(this, ohlc, ltfHighTime, ltfLowTime) Calculate zigzag based on input values and indicator values Namespace types: Zigzag Parameters: this (Zigzag) : Zigzag object ohlc (array) : Array containing OHLC values. Can also have custom values for which zigzag to be calculated ltfHighTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time. ltfLowTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time. Returns: current Zigzag object method calculate(this) Calculate zigzag based on properties embedded within Zigzag object Namespace types: Zigzag Parameters: this (Zigzag) : Zigzag object Returns: current Zigzag object method nextlevel(this) Calculate Next Level Zigzag based on the current calculated zigzag object Namespace types: Zigzag Parameters: this (Zigzag) : Zigzag object Returns: Next Level Zigzag object method clear(this) Clears zigzag drawings array Namespace types: array Parameters: this (array) : array Returns: void method clear(this) Clears zigzag drawings array Namespace types: array Parameters: this (array) : array Returns: void method drawplain(this) draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate Namespace types: ZigzagDrawing Parameters: this (ZigzagDrawing) : ZigzagDrawing object Returns: ZigzagDrawing object method drawplain(this) draws fresh zigzag based on properties embedded in ZigzagDrawingPL object without trying to calculate Namespace types: ZigzagDrawingPL Parameters: this (ZigzagDrawingPL) : ZigzagDrawingPL object Returns: ZigzagDrawingPL object method drawfresh(this, ohlc) draws fresh zigzag based on properties embedded in ZigzagDrawing object Namespace types: ZigzagDrawing Parameters: this (ZigzagDrawing) : ZigzagDrawing object ohlc (array) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC Returns: ZigzagDrawing object method drawcontinuous(this, ohlc) draws zigzag based on the zigzagmatrix input Namespace types: ZigzagDrawing Parameters: this (ZigzagDrawing) : ZigzagDrawing object ohlc (array) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC Returns: PivotCandle PivotCandle represents data of the candle which forms either pivot High or pivot low or both Fields: _high (series float) : High price of candle forming the pivot _low (series float) : Low price of candle forming the pivot length (series int) : Pivot length pHighBar (series int) : represents number of bar back the pivot High occurred. pLowBar (series int) : represents number of bar back the pivot Low occurred. pHigh (series float) : Pivot High Price pLow (series float) : Pivot Low Price Pivot Pivot refers to zigzag pivot. Each pivot can contain various data Fields: point (chart.point) : pivot point coordinates dir (series int) : direction of the pivot. Valid values are 1, -1, 2, -2 level (series int) : is used for multi level zigzags. For single level, it will always be 0 ratio (series float) : Price Ratio based on previous two pivots sizeRatio (series float) : ratio of current zigzag wave size in comparison to last zigzag wave in the same direction barRatio (series float) : Bar Ratio based on previous two pivots ZigzagFlags Flags required for drawing zigzag. Only used internally in zigzag calculation. Should not set the values explicitly Fields: newPivot (series bool) : true if the calculation resulted in new pivot doublePivot (series bool) : true if the calculation resulted in two pivots on same bar updateLastPivot (series bool) : true if new pivot calculated replaces the old one. Zigzag Zigzag object which contains whole zigzag calculation parameters and pivots Fields: length (series int) : Zigzag length. Default value is 5 numberOfPivots (series int) : max number of pivots to hold in the calculation. Default value is 20 offset (series int) : Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar. level (series int) : Zigzag calculation level - used in multi level recursive zigzags zigzagPivots (array) : array which holds the last n pivots calculated. flags (ZigzagFlags) : ZigzagFlags object which is required for continuous drawing of zigzag lines. ZigzagObject Zigzag Drawing Object Fields: zigzagLine (series line) : Line joining two pivots zigzagLabel (series label) : Label which can be used for drawing the values, ratios, directions etc. ZigzagProperties Object which holds properties of zigzag drawing. To be used along with ZigzagDrawing Fields: lineColor (series color) : Zigzag line color. Default is color.blue lineWidth (series int) : Zigzag line width. Default is 1 lineStyle (series string) : Zigzag line style. Default is line.style_solid. showLabel (series bool) : If set, the drawing will show labels on each pivot. Default is false textColor (series color) : Text color of the labels. Only applicable if showLabel is set to true. maxObjects (series int) : Max number of zigzag lines to display. Default is 300 xloc (series string) : Time/Bar reference to be used for zigzag drawing. Default is Time - xloc.bar_time. curved (series bool) : Boolean field to print curved zigzag - used only with polyline implementation force_overlay (series bool) : force drawing in price overlay ZigzagDrawing Object which holds complete zigzag drawing objects and properties. Fields: zigzag (Zigzag) : Zigzag object which holds the calculations. properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag drawings (array) : array which contains lines and labels of zigzag drawing. ZigzagDrawingPL Object which holds complete zigzag drawing objects and properties - polyline version Fields: zigzag (Zigzag) : Zigzag object which holds the calculations. properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag zigzagLabels (array) zigzagLine (series polyline) : polyline object of zigzag linesPine Script®库由SwSpace提供0
LineWrapperLibrary "LineWrapper" Wrapper Type for Line. Useful when you want to store the line details without drawing them. Can also be used in scnearios where you collect lines to be drawn and draw together towards the end. method draw(this) draws line as per the wrapper object contents Namespace types: Line Parameters: this (Line) : (series Line) Line object. Returns: current Line object method draw(this) draws lines as per the wrapper object array Namespace types: array Parameters: this (array) : (series array) Array of Line object. Returns: current Array of Line objects method update(this) updates or redraws line as per the wrapper object contents Namespace types: Line Parameters: this (Line) : (series Line) Line object. Returns: current Line object method update(this) updates or redraws lines as per the wrapper object array Namespace types: array Parameters: this (array) : (series array) Array of Line object. Returns: current Array of Line objects method delete(this) Deletes the underlying line drawing object Namespace types: Line Parameters: this (Line) : (series Line) Line object. Returns: Current Line object method get_price(this, bar) get line price based on bar Namespace types: Line Parameters: this (Line) : (series Line) Line object. bar (int) : (series/int) bar at which line price need to be calculated Returns: line price at given bar. Line Line Wrapper object Fields: p1 (chart.point) p2 (chart.point) xloc (series string) : (series string) See description of x1 argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index. extend (series string) : (series string) If extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points. Default value is extend.none. color (series color) : (series color) Line color. style (series string) : (series string) Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. width (series int) : (series int) Line width in pixels. obj (series line) : line objectPine Script®库由SwSpace提供0
utilsLibrary "utils" Few essentials captured together (subset of arrayutils) timer(timeStart, timeEnd) finds difference between two timestamps Parameters: timeStart (int) : start timestamp timeEnd (int) Returns: check_overflow(pivots, barArray, dir) finds difference between two timestamps Parameters: pivots (array) : pivots array barArray (array) : pivot bar array dir (int) : direction for which overflow need to be checked Returns: bool overflow get_trend_series(pivots, length, highLow, trend) finds series of pivots in particular trend Parameters: pivots (array) : pivots array length (int) : length for which trend series need to be checked highLow (int) : filter pivot high or low trend (int) : Uptrend or Downtrend Returns: int trendIndexes get_trend_series(pivots, firstIndex, lastIndex) finds series of pivots in particular trend Parameters: pivots (array) : pivots array firstIndex (int) : First index of the series lastIndex (int) : Last index of the series Returns: int trendIndexes getConsolidatedLabel(include, labels, separator) Consolidates labels into single string by concatenating it with given separator Parameters: include (array) : array of conditions to include label or not labels (array) : string array of labels separator (simple string) : Separator for concatenating labels Returns: string labelText getColors(theme) gets array of colors based on theme Parameters: theme (simple string) : dark or light theme Returns: color themeColorsPine Script®库由SwSpace提供0
ohlcLibrary "ohlc" Library having OHLC and Indicator type and method implementations. getOhlcArray(o, h, l, c, highBeforeLow, highAfterLow, lowBeforeHigh, lowAfterHigh, barindex, bartime, indicators) get array of OHLC values when called on every bar Parameters: o (float) : Open price h (float) : High Price l (float) : Low Price c (float) : Close Price highBeforeLow (float) : to be calculated based on lower timeframe. high price attained within the candle before reaching the lowest point. highAfterLow (float) : to be calculated based on lower timeframe. high price attained within the candle after reaching the lowest point. lowBeforeHigh (float) : to be calculated based on lower timeframe. low price attained within the candle before reaching the highest point. lowAfterHigh (float) : to be calculated based on lower timeframe. low price attained within the candle after reaching the highest point. barindex (int) : bar_index of OHLC data bartime (int) : time of OHLC cata indicators (array) : array containing indicator Returns: Array of OHLC objects pushWithLimit(this, item, maxItems) Push items to OHLC array with maxItems limit Parameters: this (array) item (OHLC) : OHLC Item to be pushed to the array maxItems (int) : max Items the array can hold at a time Returns: current object pushWithLimit(this, item, maxItems) Push items to Indicator array with maxItems limit Parameters: this (array) item (Indicator) : Indicator Item to be pushed to the array maxItems (int) : max Items the array can hold at a time Returns: current object unshiftWithLimit(this, item, maxItems) Unshift items to OHLC array with maxItems limit Parameters: this (array) item (OHLC) : OHLC Item to be unshifted to the array maxItems (int) : max Items the array can hold at a time Returns: current object unshiftWithLimit(this, item, maxItems) Unshift items to Indicator array with maxItems limit Parameters: this (array) item (Indicator) : Indicator Item to be unshifted to the array maxItems (int) : max Items the array can hold at a time Returns: current object method getPoints(indicators) get array of points based on array of indicator values Namespace types: array Parameters: indicators (array) : Array containing indicator objects Returns: array of indicator points method plot(indicator, xloc, line_color, line_style, line_width) plots an array of Indicator using polyline Namespace types: array Parameters: indicator (array) : Array containing indicator objects xloc (string) : can have values xloc.bar_index or xloc.bar_time. Used for drawing the line based on either bars or time. line_color (color) : color in which the plots need to be printed on chart. line_style (string) : line style line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both line_width (int) : width of the plot line Returns: array of plot polyline Indicator Object containing Indicator name and value Fields: name (series string) : Indicator Name value (chart.point) : Indicator Value as a chart point OHLC Object containing OHLC and indicator values Fields: o (series float) : Open price h (series float) : High Price l (series float) : Low Price c (series float) : Close Price highBeforeLow (series float) : to be calculated based on lower timeframe. high price attained within the candle before reaching the lowest point. highAfterLow (series float) : to be calculated based on lower timeframe. high price attained within the candle after reaching the lowest point. lowBeforeHigh (series float) : to be calculated based on lower timeframe. low price attained within the candle before reaching the highest point. lowAfterHigh (series float) : to be calculated based on lower timeframe. low price attained within the candle after reaching the highest point. barindex (series int) : bar_index of OHLC data bartime (series int) : time of OHLC cata indicators (array) : array containing indicatorPine Script®库由SwSpace提供0
pubLibCandlestickPatternsLibrary "pubLibCandlestickPatterns" candlestick pattern conditions for indicator and strategy development doji() bull_marubozu() bear_marubozu() spinning_top() bull_belt_hold_line() bear_belt_hold_line() bull_breakaway() bear_breakaway() concealing_baby_swallow() bull_counterattack() bear_counterattack() dark_cloud_cover() long_legged_doji() southern_doji() northern_doji() dumpling_top() bull_engulfing() bear_engulfing() frypan_bottom() hammer() hanging_man() bull_harami() bear_harami() bull_harami_cross() bear_harami_cross() high_wave() bull_hikkake() bear_hikkake() homing_pigeon() in_neck() bull_kicking() bear_kicking() matching_low() on_neck() piercing() bull_separating_lines() bear_separating_lines() upgap_side_by_side_white_lines() downgap_side_by_side_white_lines() stalled() bull_star() bear_star() bull_doji_star() bear_doji_star() morning_star() evening_star() morning_doji_star() evening_doji_star() abandoned_baby_bottom() abandoned_baby_top() inverted_hammer() shooting_star() dragonfly_doji() gravestone_doji() stick_sandwich() upward_gapping_tasuki() downward_gapping_tasuki() three_black_crows() advance_block() three_advancing_white_soldiers() bull_three_line_strike() bear_three_line_strike() rising_three_methods() falling_three_methods() three_stars_in_the_south() thrusting() tower_bottom() tower_top() tri_star_bottom() tri_star_top() tweezer_bottom() tweezer_top() upside_gap_two_crows()Pine Script®库由theEccentricTrader提供0
RSMPatternLibLibrary "RSMPatternLib" RSM Pattern Library - All chart patterns from PATTERNS.md Implements: Candlestick patterns, Support/Resistance, Gaps, Triangles, Volume Divergence, and more ALL PATTERNS ARE OWN IMPLEMENTATION - No external dependencies EDGE CASES HANDLED: - Zero/tiny candle bodies - Missing volume data - Low bar count scenarios - Integer division issues - Price normalization for different instruments bullishEngulfing(minBodyRatio, minPrevBodyRatio) Detects Bullish Engulfing pattern Parameters: minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3) minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1) Returns: bool True when bullish engulfing detected EDGE CASES: Handles doji previous candle, zero range, tiny bodies bearishEngulfing(minBodyRatio, minPrevBodyRatio) Detects Bearish Engulfing pattern Parameters: minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3) minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1) Returns: bool True when bearish engulfing detected EDGE CASES: Handles doji previous candle, zero range, tiny bodies doji(maxBodyRatio, minRangeAtr) Detects Doji candle (indecision) Parameters: maxBodyRatio (float) : Maximum body size as ratio of total range (default 0.1) minRangeAtr (float) : Minimum range as multiple of ATR to filter flat candles (default 0.3) Returns: bool True when doji detected EDGE CASES: Filters out no-movement bars, handles zero range shootingStar(wickMultiplier, maxLowerWickRatio, minBodyAtrRatio) Detects Shooting Star (bearish reversal) Parameters: wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0) maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5) minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1) Returns: bool True when shooting star detected EDGE CASES: Handles zero body (uses range-based check), tiny bodies hammer(wickMultiplier, maxUpperWickRatio, minBodyAtrRatio) Detects Hammer (bullish reversal) Parameters: wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0) maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5) minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1) Returns: bool True when hammer detected EDGE CASES: Handles zero body (uses range-based check), tiny bodies invertedHammer(wickMultiplier, maxLowerWickRatio) Detects Inverted Hammer (bullish reversal after downtrend) Parameters: wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0) maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5) Returns: bool True when inverted hammer detected EDGE CASES: Same as shootingStar but requires bullish close hangingMan(wickMultiplier, maxUpperWickRatio) Detects Hanging Man (bearish reversal after uptrend) Parameters: wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0) maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5) Returns: bool True when hanging man detected NOTE: Identical to hammer - context (uptrend) determines meaning morningStar(requireGap, minAvgBars) Detects Morning Star (3-candle bullish reversal) Parameters: requireGap (bool) : Whether to require gap between candles (default false for crypto/forex) minAvgBars (int) : Minimum bars for average body calculation (default 14) Returns: bool True when morning star pattern detected EDGE CASES: Gap is optional, handles low bar count, uses shifted average eveningStar(requireGap, minAvgBars) Detects Evening Star (3-candle bearish reversal) Parameters: requireGap (bool) : Whether to require gap between candles (default false for crypto/forex) minAvgBars (int) : Minimum bars for average body calculation (default 14) Returns: bool True when evening star pattern detected EDGE CASES: Gap is optional, handles low bar count gapUp() Detects Gap Up Returns: bool True when current bar opens above previous bar's high gapDown() Detects Gap Down Returns: bool True when current bar opens below previous bar's low gapSize() Returns gap size in price Returns: float Gap size (positive for gap up, negative for gap down, 0 for no gap) gapPercent() Returns gap size as percentage Returns: float Gap size as percentage of previous close gapType(volAvgLen, breakawayMinPct, highVolMult) Classifies gap type based on volume Parameters: volAvgLen (int) : Length for volume average (default 20) breakawayMinPct (float) : Minimum gap % for breakaway (default 1.0) highVolMult (float) : Volume multiplier for high volume (default 1.5) Returns: string Gap type: "Breakaway", "Common", "Continuation", or "None" EDGE CASES: Handles missing volume data, low bar count swingHigh(leftBars, rightBars) Detects swing high using pivot Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) Returns: float Swing high price or na swingLow(leftBars, rightBars) Detects swing low using pivot Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) Returns: float Swing low price or na higherHigh(leftBars, rightBars, lookback) Checks if current swing high is higher than previous swing high Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) lookback (int) : How many bars back to search for previous pivot (default 50) Returns: bool True when higher high pattern detected EDGE CASES: Searches backwards for pivots instead of using var (library-safe) higherLow(leftBars, rightBars, lookback) Checks if current swing low is higher than previous swing low Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) lookback (int) : How many bars back to search for previous pivot (default 50) Returns: bool True when higher low pattern detected lowerHigh(leftBars, rightBars, lookback) Checks if current swing high is lower than previous swing high Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) lookback (int) : How many bars back to search for previous pivot (default 50) Returns: bool True when lower high pattern detected lowerLow(leftBars, rightBars, lookback) Checks if current swing low is lower than previous swing low Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) lookback (int) : How many bars back to search for previous pivot (default 50) Returns: bool True when lower low pattern detected bullishTrend(leftBars, rightBars, lookback) Detects Bullish Trend (HH + HL within lookback) Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) lookback (int) : Lookback period (default 50) Returns: bool True when making higher highs AND higher lows bearishTrend(leftBars, rightBars, lookback) Detects Bearish Trend (LH + LL within lookback) Parameters: leftBars (int) : Bars to left for pivot (default 5) rightBars (int) : Bars to right for pivot (default 5) lookback (int) : Lookback period (default 50) Returns: bool True when making lower highs AND lower lows nearestResistance(lookback, leftBars, rightBars) Finds nearest resistance level above current price Parameters: lookback (int) : Number of bars to look back (default 50) leftBars (int) : Pivot left bars (default 5) rightBars (int) : Pivot right bars (default 5) Returns: float Nearest resistance level or na EDGE CASES: Pre-computes pivots, handles bounds properly nearestSupport(lookback, leftBars, rightBars) Finds nearest support level below current price Parameters: lookback (int) : Number of bars to look back (default 50) leftBars (int) : Pivot left bars (default 5) rightBars (int) : Pivot right bars (default 5) Returns: float Nearest support level or na resistanceBreakout(lookback, leftBars, rightBars) Detects resistance breakout Parameters: lookback (int) : Number of bars to look back (default 50) leftBars (int) : Pivot left bars (default 5) rightBars (int) : Pivot right bars (default 5) Returns: bool True when price breaks above resistance EDGE CASES: Uses previous bar's resistance to avoid lookahead supportBreakdown(lookback, leftBars, rightBars) Detects support breakdown Parameters: lookback (int) : Number of bars to look back (default 50) leftBars (int) : Pivot left bars (default 5) rightBars (int) : Pivot right bars (default 5) Returns: bool True when price breaks below support bullishVolumeDivergence(leftBars, rightBars, lookback) Detects Bullish Volume Divergence (price makes lower low, volume decreases) Parameters: leftBars (int) : Pivot left bars (default 5) rightBars (int) : Pivot right bars (default 5) lookback (int) : Bars to search for previous pivot (default 50) Returns: bool True when bullish volume divergence detected EDGE CASES: Library-safe (no var), searches for previous pivot bearishVolumeDivergence(leftBars, rightBars, lookback) Detects Bearish Volume Divergence (price makes higher high, volume decreases) Parameters: leftBars (int) : Pivot left bars (default 5) rightBars (int) : Pivot right bars (default 5) lookback (int) : Bars to search for previous pivot (default 50) Returns: bool True when bearish volume divergence detected rangeContracting(lookback) Detects if price is in a contracting range (triangle formation) Parameters: lookback (int) : Bars to analyze (default 20) Returns: bool True when range is contracting EDGE CASES: Uses safe integer division, checks minimum lookback ascendingTriangle(lookback, flatTolerance) Detects Ascending Triangle (flat top, rising bottom) Parameters: lookback (int) : Bars to analyze (default 20) flatTolerance (float) : Max normalized slope for "flat" line (default 0.002) Returns: bool True when ascending triangle detected EDGE CASES: Safe division, normalized slope, minimum lookback descendingTriangle(lookback, flatTolerance) Detects Descending Triangle (falling top, flat bottom) Parameters: lookback (int) : Bars to analyze (default 20) flatTolerance (float) : Max normalized slope for "flat" line (default 0.002) Returns: bool True when descending triangle detected symmetricalTriangle(lookback, minSlope) Detects Symmetrical Triangle (converging trend lines) Parameters: lookback (int) : Bars to analyze (default 20) minSlope (float) : Minimum normalized slope magnitude (default 0.0005) Returns: bool True when symmetrical triangle detected doubleBottom(tolerance, minSpanBars, lookback) Detects Double Bottom (W pattern) - OWN IMPLEMENTATION Two swing lows at similar price levels with a swing high between them Parameters: tolerance (float) : Max price difference between lows as % (default 3) minSpanBars (int) : Minimum bars between the two lows (default 5) lookback (int) : Max bars to search for pattern (default 100) Returns: bool True when double bottom detected doubleTop(tolerance, minSpanBars, lookback) Detects Double Top (M pattern) - OWN IMPLEMENTATION Two swing highs at similar price levels with a swing low between them Parameters: tolerance (float) : Max price difference between highs as % (default 3) minSpanBars (int) : Minimum bars between the two highs (default 5) lookback (int) : Max bars to search for pattern (default 100) Returns: bool True when double top detected tripleBottom(tolerance, minSpanBars, lookback) Detects Triple Bottom - OWN IMPLEMENTATION Three swing lows at similar price levels Parameters: tolerance (float) : Max price difference between lows as % (default 3) minSpanBars (int) : Minimum total bars for pattern (default 10) lookback (int) : Max bars to search for pattern (default 150) Returns: bool True when triple bottom detected tripleTop(tolerance, minSpanBars, lookback) Detects Triple Top - OWN IMPLEMENTATION Three swing highs at similar price levels Parameters: tolerance (float) : Max price difference between highs as % (default 3) minSpanBars (int) : Minimum total bars for pattern (default 10) lookback (int) : Max bars to search for pattern (default 150) Returns: bool True when triple top detected bearHeadShoulders() Detects Bearish Head and Shoulders (OWN IMPLEMENTATION) Head is higher than both shoulders, shoulders roughly equal, with valid neckline STRICT VERSION - requires proper structure, neckline, and minimum span Returns: bool True when bearish H&S detected bullHeadShoulders() Detects Bullish (Inverse) Head and Shoulders (OWN IMPLEMENTATION) Head is lower than both shoulders, shoulders roughly equal, with valid neckline STRICT VERSION - requires proper structure, neckline, and minimum span Returns: bool True when bullish H&S detected bearAscHeadShoulders() Detects Bearish Ascending Head and Shoulders (variant) Returns: bool True when pattern detected bullAscHeadShoulders() Detects Bullish Ascending Head and Shoulders (variant) Returns: bool True when pattern detected bearDescHeadShoulders() Detects Bearish Descending Head and Shoulders (variant) Returns: bool True when pattern detected bullDescHeadShoulders() Detects Bullish Descending Head and Shoulders (variant) Returns: bool True when pattern detected isSwingLow() Re-export: Detects swing low Returns: bool True when swing low detected isSwingHigh() Re-export: Detects swing high Returns: bool True when swing high detected swingHighPrice(idx) Re-export: Gets swing high price at index Parameters: idx (int) : Index (0 = most recent) Returns: float Swing high price swingLowPrice(idx) Re-export: Gets swing low price at index Parameters: idx (int) : Index (0 = most recent) Returns: float Swing low price swingHighBarIndex(idx) Re-export: Gets swing high bar index Parameters: idx (int) : Index (0 = most recent) Returns: int Bar index of swing high swingLowBarIndex(idx) Re-export: Gets swing low bar index Parameters: idx (int) : Index (0 = most recent) Returns: int Bar index of swing low cupBottom(smoothLen, minDepthAtr, maxDepthAtr) Detects Cup and Handle pattern formation Uses price acceleration and depth analysis Parameters: smoothLen (int) : Smoothing length for price (default 10) minDepthAtr (float) : Minimum cup depth as ATR multiple (default 1.0) maxDepthAtr (float) : Maximum cup depth as ATR multiple (default 5.0) Returns: bool True when potential cup bottom detected EDGE CASES: Added depth filter, ATR validation cupHandle(lookback, maxHandleRetraceRatio) Detects potential handle formation after cup Parameters: lookback (int) : Bars to look back for cup (default 30) maxHandleRetraceRatio (float) : Maximum handle retracement of cup depth (default 0.5) Returns: bool True when handle pattern detected bullishPatternCount() Returns count of bullish patterns detected Returns: int Number of bullish patterns currently active bearishPatternCount() Returns count of bearish patterns detected Returns: int Number of bearish patterns currently active detectedPatterns() Returns string description of detected patterns Returns: string Comma-separated list of detected patternsPine Script®库由azgron提供已更新 0
OverfittingMetricsLibrary "OverfittingMetrics" calculateMetrics(tradeResults, tradeTypes, minTrades, startCapital) Parameters: tradeResults (array) tradeTypes (array) minTrades (int) startCapital (float) randomizeParameter(baseValue, variationPercent, seed) Parameters: baseValue (float) variationPercent (float) seed (int) classifyMarket(priceSeries, lookbackLength) Parameters: priceSeries (float) lookbackLength (simple int) checkOverfittingWarnings(winRate, profitFactor, totalTrades) Parameters: winRate (float) profitFactor (float) totalTrades (int) calculateConsistency(tradeResults) Parameters: tradeResults (array) isOverfitDetected(winRate, profitFactor, totalTrades, minTrades) Parameters: winRate (float) profitFactor (float) totalTrades (int) minTrades (int) getOverfitScore(winRate, profitFactor, totalTrades) Parameters: winRate (float) profitFactor (float) totalTrades (int)Pine Script®库由TadLopes提供0
SimpleTableA library for when you just want to get a table up with the least hassle. The function `f_drawTableFromColumns()`, is intended to be the simplest possible way to draw a table with the least code in the calling script. Just pass in between one and ten arrays that contain the strings you want to show. Each string array represents one column. That's it. You get a table back. If you want to style the table you can optionally pass colours, size, and whether the table has a header row that should be displayed differently. An example usage section demonstrates creating a three-column table. The function automatically sizes the table based on the number of non-na arrays and the maximum column length. Optional styling parameters cover table position, text size, text alignment, text colour, cell background, header background, header text, and border width. If you don't supply any of these arguments, the table uses some sensible default values. The table is created and updated on the last bar only, with caching to avoid unnecessary redraws. Column shrink detection clears the table only when required, preventing stale cell content. This is not a full-fledged table management library; there are already lots of those published. It is (I believe and hope) the easiest library to use. For example, you don't need to supply a matrix, or a user-defined type full of settings. The library wraps the input arrays into a map, and uses a user-defined type, but internally, so you don't need to worry about it. Just supply one or more arrays with some text. f_drawTableFromColumnArrays(_a_col1, _a_col2, _a_col3, _a_col4, _a_col5, _a_col6, _a_col7, _a_col8, _a_col9, _a_col10, _position, _textSize, _textAlign, _textColor, _cellBgColor, _headerBgColor, _headerTextColor, _hasHeaderRow, _borderWidth) Renders a table using up to ten string arrays. The table size is derived from the number of non-na arrays and the maximum length across the supplied arrays. Parameters: _a_col1 (array) : (array) Column 1 values. Supply na to omit. _a_col2 (array) : (array) Column 2 values. Supply na to omit. _a_col3 (array) : (array) Column 3 values. Supply na to omit. _a_col4 (array) : (array) Column 4 values. Supply na to omit. _a_col5 (array) : (array) Column 5 values. Supply na to omit. _a_col6 (array) : (array) Column 6 values. Supply na to omit. _a_col7 (array) : (array) Column 7 values. Supply na to omit. _a_col8 (array) : (array) Column 8 values. Supply na to omit. _a_col9 (array) : (array) Column 9 values. Supply na to omit. _a_col10 (array) : (array) Column 10 values. Supply na to omit. _position (string) : (TablePosition) Table position on the chart. Default is top right. _textSize (string) : (TableTextSize) Text size for all cells. Default is normal. _textAlign (string) : (TableTextAlign) Horizontal alignment for all cells. Default is left. _textColor (color) : (color) Text colour for all cells. Default is chart foreground color. _cellBgColor (color) : (color) Background colour for all cells. Uses a default if na. Default is gray 90%. _headerBgColor (color) : (color) Background colour for the header row. Uses a default if na. Default is gray 75%. _headerTextColor (color) : (color) Text colour for the header row. Uses a default if na. _hasHeaderRow (bool) : (bool) If true, row 0 is treated as a header. Default is true. _borderWidth (int) : (int) Table border width. Must be non-negative. Default is 1. Returns: The table object, so the caller can store the table ID if required.Pine Script®库由SimpleCryptoLife提供9
historicalEngine by N&M🇬🇧 English Introduction historicalEngine is a Pine Script library designed for advanced state-based backtesting. It does not test a single strategy, but evaluates full market configurations (trend, structure, momentum, multi-TF context). Each trade is linked to a unique state hash, revealing which conditions truly perform over time. The engine computes professional metrics: PnL, win rate, expectancy, Sharpe, drawdown, reliability. It includes dynamic TP/SL, liquidation logic, early exits, realistic fees and slippage. Built to be modular, extensible, and efficient, it plugs into any indicator. Goal: turn historical data into a statistical trading edge. V1 – a solid foundation for adaptive and data-driven trading systems. Pine Script®库由N_M_提供已更新 1
tradeEngineLibrary "tradeEngine" calculateLiquidationPrice(entryPrice, isLong, leverage, buffer) Parameters: entryPrice (float) isLong (bool) leverage (int) buffer (float) calculateTPLevels(entryPrice, atr, isLong, risk) Parameters: entryPrice (float) atr (float) isLong (bool) risk (RiskConfig) calculateSL(entryLow, entryHigh, isLong, risk) Parameters: entryLow (float) entryHigh (float) isLong (bool) risk (RiskConfig) simulateTrade(highs, lows, closes, entryIdx, entryPrice, entryLow, entryHigh, entryATR, isLong, risk, maxBars) Parameters: highs (array) lows (array) closes (array) entryIdx (int) entryPrice (float) entryLow (float) entryHigh (float) entryATR (float) isLong (bool) risk (RiskConfig) maxBars (int) createRiskConfig(leverage, liqBuffer, useTP1, tp1ATR, useTP2, tp2ATR, useSL, slBuffer, maker, taker, slip) Parameters: leverage (int) liqBuffer (float) useTP1 (bool) tp1ATR (float) useTP2 (bool) tp2ATR (float) useSL (bool) slBuffer (float) maker (float) taker (float) slip (float) TradeResult Fields: exitType (series string) exitBarIdx (series int) exitPrice (series float) finalPnL (series float) maxPnL (series float) tp1Hit (series bool) tp2Hit (series bool) slHit (series bool) liquidated (series bool) barsInTrade (series int) tp1Level (series float) tp2Level (series float) slLevel (series float) liqLevel (series float) RiskConfig Fields: leverage (series int) liquidationBuffer (series float) useTP1 (series bool) tp1ATR (series float) useTP2 (series bool) tp2ATR (series float) useFixedSL (series bool) slBuffer (series float) makerFee (series float) takerFee (series float) slippage (series float)Pine Script®库由N_M_提供1
matrixCoreLibrary "matrixCore" analyzeCandleStructure(o, h, l, c, atr, smallBodyThreshold, longWickRatio) Parameters: o (float) h (float) l (float) c (float) atr (float) smallBodyThreshold (float) longWickRatio (float) isRedRejectionCandle(o, l, c, redRejectionWickMin) Parameters: o (float) l (float) c (float) redRejectionWickMin (float) isEqual(a, b, tol) Parameters: a (float) b (float) tol (float) detectPattern(kf, km, ks, tol) Parameters: kf (float) km (float) ks (float) tol (float) calculateStateHash(kp, ep, pp, comp, cType, slope, tfH, tfL, redRej) Parameters: kp (int) ep (int) pp (int) comp (int) cType (int) slope (int) tfH (bool) tfL (bool) redRej (bool) createStateConfig(kp, ep, pp, comp, cType, slope, tfH, tfL, redRej, hash) Parameters: kp (int) ep (int) pp (int) comp (int) cType (int) slope (int) tfH (bool) tfL (bool) redRej (bool) hash (int) createBarSnapshot(barIdx, o, h, l, c, atr, ema, stateHash, kp, ep, pp, comp, cType, slope, tfH, tfL, redRej) Parameters: barIdx (int) o (float) h (float) l (float) c (float) atr (float) ema (float) stateHash (int) kp (int) ep (int) pp (int) comp (int) cType (int) slope (int) tfH (bool) tfL (bool) redRej (bool) stateToString(cfg) Parameters: cfg (StateConfig) getTablePosition(pos) Parameters: pos (string) getGradientColor(value, minVal, maxVal) Parameters: value (float) minVal (float) maxVal (float) StateConfig Fields: kijunPattern (series int) emaPattern (series int) pricePos (series int) compression (series int) candleType (series int) emaSlope (series int) tfHigherBullish (series bool) tfLowerBullish (series bool) redRejection (series bool) hash (series int) BarSnapshot Fields: barIndex (series int) openPrice (series float) highPrice (series float) lowPrice (series float) closePrice (series float) atr (series float) emaFast (series float) stateHash (series int) kijunPattern (series int) emaPattern (series int) pricePos (series int) compression (series int) candleType (series int) emaSlope (series int) tfHigherBullish (series bool) tfLowerBullish (series bool) redRejection (series bool)Pine Script®库由N_M_提供0
TimeframeAlignTHE PROBLEM THIS LIBRARY SOLVES When you use `request.security()` to get data from a Higher Timeframe (HTF) and try to draw objects like boxes, lines, or labels, they appear at the wrong horizontal position . This is the "floating in space" problem. Why does this happen? The `bar_index` in Pine Script refers to where data was RECEIVED , not where the event OCCURRED . Consider this scenario: • You're on a 5-minute chart • You request 1-hour data for drawing an FVG (Fair Value Gap) • A 1H candle spans 12 chart bars (60min / 5min = 12) • But your code draws at `bar_index - 1` or `bar_index - 3` • The result: your FVG box is only 2-3 bars wide instead of spanning the correct 12-36 bars This library solves that by tracking where HTF bars actually start and end on your chart timeframe. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ HOW TO USE THIS LIBRARY Step 1: Import the Library ``` import ArunaReborn/TimeframeAlign/1 as tfa ``` Step 2: Create a Tracker for Each HTF ``` var tfa.HTFTracker tracker1H = tfa.createTracker("60") ``` Step 3: Update the Tracker Every Bar ``` tfa.updateTracker(tracker1H, "60") ``` Step 4: Use Synced Drawing Functions ``` if tfa.htfBarChanged(tracker1H) tfa.syncedBox(tracker1H, 3, 1, topPrice, bottomPrice, color.new(color.green, 80)) ``` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ EXPORTED TYPES TimeframePair Stores metadata about the relationship between source and chart timeframes. • sourceTimeframe - The HTF/LTF being compared • chartTimeframe - Current chart timeframe • isHTF - True if source is higher than chart • isLTF - True if source is lower than chart • barRatio - Chart bars per source bar • secondsRatio - Time ratio between timeframes MTFEventData Stores synchronized event data with correct bar positions. • price - Price level of the event • eventTime - Unix timestamp of the event • chartBarStart - Chart bar_index where event's TF bar started • chartBarEnd - Chart bar_index where event's TF bar ended • htfOffset - The HTF offset used • isValid - True if synchronization succeeded HTFTracker Tracks HTF bar boundaries. Create one per timeframe you need to track. • htfTimeframe - The timeframe being tracked • currentStartBar - Where current HTF bar started • currentEndBar - Where current HTF bar ends (provisional) • startHistory - Array of historical start positions • endHistory - Array of historical end positions • lastUpdateBar - Last bar_index when updated • barJustChanged - True if HTF bar changed on this chart bar (set by updateTracker) SyncedBox Managed box with synchronization metadata. • bx - The Pine Script box object • htfTimeframe - Source timeframe • leftHtfOffset / rightHtfOffset - HTF offsets for edges • topPrice / bottomPrice - Price boundaries • extendRight - Auto-extend flag SyncedLine Managed line with synchronization metadata. • ln - The Pine Script line object • htfTimeframe - Source timeframe • htfOffset - Anchor offset • price - Price level (horizontal lines) • isHorizontal - Line orientation • extendRight - Auto-extend flag SyncedLabel Managed label with synchronization metadata. • lbl - The Pine Script label object • htfTimeframe - Source timeframe • htfOffset - Anchor offset • price - Price level • anchorPoint - "start", "end", or "middle" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ EXPORTED FUNCTIONS ━━ CORE FUNCTIONS ━━ getTimeframeInfo(sourceTimeframe) Analyzes relationship between a source TF and chart TF. Returns: TimeframePair with comparison metadata createTracker(htfTimeframe) Creates a new HTF tracker. Call once per timeframe, store with `var`. Returns: HTFTracker instance updateTracker(tracker, htfTimeframe, historyDepth) Updates tracker with current bar data. Call on every bar. • htfTimeframe: The timeframe string (must match createTracker) • historyDepth: Max HTF bars to track (default 500) Returns: Updated tracker getStartBar(tracker, htfOffset) Gets chart bar_index where a specific HTF bar started. • htfOffset: 0=current, 1=previous, 2=two bars ago, etc. Returns: bar_index or na getEndBar(tracker, htfOffset) Gets chart bar_index where a specific HTF bar ended. Returns: bar_index or na htfBarChanged(tracker) Detects when HTF bar just changed. Returns: True on first chart bar of new HTF bar findBarAtTime(timestamp, maxLookback) Searches backward to find chart bar containing a timestamp. • maxLookback: How far back to search (default 500) Returns: bar_index or na syncEventToChart(tracker, eventPrice, eventTime, anchorPoint) Generic sync function mapping any event to correct chart position. • anchorPoint: "start", "end", or "middle" Returns: MTFEventData ━━ DRAWING CREATION FUNCTIONS ━━ syncedBox(tracker, leftHtfOffset, rightHtfOffset, topPrice, bottomPrice, bgcolor, ...) Creates a box at correct HTF-aligned position. • leftHtfOffset: HTF bars back for left edge • rightHtfOffset: HTF bars back for right edge • extendRight: Auto-extend to current bar Returns: SyncedBox or na syncedHLine(tracker, htfOffset, price, lineColor, lineStyle, lineWidth, extendRight) Creates horizontal line anchored to HTF bar start. • extendRight: If true, extends to current bar (default true) Returns: SyncedLine or na syncedVLine(tracker, htfOffset, atStart, lineColor, lineStyle, lineWidth) Creates vertical line at HTF bar boundary. • atStart: True=start of HTF bar, False=end Returns: SyncedLine or na syncedLabel(tracker, htfOffset, price, labelText, anchorPoint, ...) Creates label at correct HTF-aligned position. • anchorPoint: "start", "end", or "middle" Returns: SyncedLabel or na syncedPlotValue(tracker, value, htfOffset) Returns value for plotting only at synced positions. Returns: value if current bar is within HTF range, otherwise na ━━ UPDATE FUNCTIONS ━━ updateSyncedBox(syncedBox, extendToCurrentBar) Extends existing box's right edge to current bar. Returns: Updated SyncedBox updateSyncedLine(syncedLine, extendToCurrentBar) Extends existing horizontal line to current bar. Returns: Updated SyncedLine updateSyncedLabel(syncedLabel, tracker, newText, newPrice) Updates label text/price while maintaining sync. Returns: Updated SyncedLabel ━━ CONVENIENCE FUNCTIONS ━━ htfBarStartIndex(htfTimeframe, htfOffset, historyDepth) Simple function to get HTF bar start without explicit tracker. ⚠️ Only tracks ONE timeframe. For multiple TFs, use createTracker pattern. Returns: bar_index or na htfBarEndIndex(htfTimeframe, htfOffset, historyDepth) Simple function to get HTF bar end without explicit tracker. ⚠️ Only tracks ONE timeframe. For multiple TFs, use createTracker pattern. Returns: bar_index or na ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ COMPLETE USAGE EXAMPLES Example 1: FVG Box with Auto-Extend ``` //@version=6 indicator("FVG with Synced Drawing", overlay=true) import ArunaReborn/TimeframeAlign/1 as tfa htfInput = input.timeframe("60", "HTF for FVG") // Create tracker for chosen timeframe var tfa.HTFTracker fvgTracker = tfa.createTracker(htfInput) tfa.updateTracker(fvgTracker, htfInput) // Get FVG data from HTF (confirmed bars with offset) = request.security(syminfo.tickerid, htfInput, [low , high , low > high ], lookahead=barmerge.lookahead_off) // Store managed box var tfa.SyncedBox fvgBox = na // Create synced box when FVG detected if fvgDetected and tfa.htfBarChanged(fvgTracker) fvgBox := tfa.syncedBox(fvgTracker, 3, 1, fvgTop, fvgBot, color.new(color.green, 85), color.green, 1, "FVG", color.white, true) // Extend box to current bar each tick if not na(fvgBox) tfa.updateSyncedBox(fvgBox, true) ``` Example 2: HTF Support/Resistance Lines ``` //@version=6 indicator("HTF S/R Lines", overlay=true) import ArunaReborn/TimeframeAlign/1 as tfa htfInput = input.timeframe("240", "HTF for S/R") // Create and update tracker var tfa.HTFTracker srTracker = tfa.createTracker(htfInput) tfa.updateTracker(srTracker, htfInput) // Get HTF high/low (confirmed with offset) = request.security(syminfo.tickerid, htfInput, [high , low ], lookahead=barmerge.lookahead_off) // Track lines var tfa.SyncedLine resistanceLine = na var tfa.SyncedLine supportLine = na // Create new lines when HTF bar changes if tfa.htfBarChanged(srTracker) resistanceLine := tfa.syncedHLine(srTracker, 1, htfHigh, color.red, line.style_solid, 2, true) supportLine := tfa.syncedHLine(srTracker, 1, htfLow, color.green, line.style_solid, 2, true) // Auto-extend lines each bar if not na(resistanceLine) tfa.updateSyncedLine(resistanceLine, true) if not na(supportLine) tfa.updateSyncedLine(supportLine, true) ``` Example 3: Multiple Timeframes ``` //@version=6 indicator("Multi-TF Boxes", overlay=true) import ArunaReborn/TimeframeAlign/1 as tfa // Create separate tracker for each timeframe var tfa.HTFTracker tracker1H = tfa.createTracker("60") var tfa.HTFTracker tracker4H = tfa.createTracker("240") var tfa.HTFTracker trackerD = tfa.createTracker("1D") // Update ALL trackers every bar (pass the same TF string) tfa.updateTracker(tracker1H, "60") tfa.updateTracker(tracker4H, "240") tfa.updateTracker(trackerD, "1D") // Now use each tracker independently for drawing // Each tracker maintains its own separate boundary history ``` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ NON-REPAINTING COMPLIANCE To ensure non-repainting behavior, always use this pattern with request.security: ``` = request.security(syminfo.tickerid, htfTimeframe, [value1 , value2 ], // Use offset for confirmed data lookahead=barmerge.lookahead_off) // Never use lookahead_on ``` The ` ` offset ensures you're using the previous completed HTF bar, not the current forming bar. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ HISTORY DEPTH PARAMETER The `historyDepth` parameter controls how many HTF bars are tracked: • Default: 500 HTF bars • Maximum: Limited by Pine Script's array constraints • Higher values = more historical accuracy but more memory usage • Lower values = less memory but may return `na` for older offsets Adjust based on your needs: ``` tfa.updateTracker(tracker, 100) // Track 100 HTF bars (light) tfa.updateTracker(tracker, 1000) // Track 1000 HTF bars (heavier) ``` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ IMPORTANT NOTES 1. One Tracker Per Timeframe : If you need multiple HTFs, create separate trackers for each. The convenience functions (htfBarStartIndex, htfBarEndIndex) only track one TF. 2. Update Every Bar : Always call updateTracker() unconditionally on every bar, not inside conditionals. 3. HTF Only : This library is designed for Higher Timeframe data. For LTF aggregation, use findBarAtTime() for time-based lookups. 4. Drawing Limits : Pine Script has limits on drawing objects. Use box.delete(), line.delete(), label.delete() to clean up old objects. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ TROUBLESHOOTING Q: My boxes/lines still appear at wrong positions A: Make sure you're calling updateTracker() on every bar (not inside an if statement) and using the correct htfOffset values. Q: Functions return na A: The htfOffset might be larger than available history. Increase historyDepth or use a smaller offset. Q: Multiple timeframes don't work correctly A: Don't use the convenience functions for multiple TFs. Create separate HTFTracker instances with createTracker() for each timeframe. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ CHANGELOG v1 - Initial release • HTFTracker pattern for reliable multi-TF tracking • Synced drawing functions for boxes, lines, labels • Update functions for extending drawings • Convenience functions for simple single-TF use cases Pine Script®库由ArunaReborn提供已更新 0
Plan Limit TimerA Pine Script library that helps developers monitor script execution time against TradingView's plan-specific timeout limits. Displays a visual debug table with runtime metrics, percentage of limit consumed, and color-coded status warnings. WHAT THIS LIBRARY DOES TradingView enforces different script timeout limits based on subscription tier: • Basic : 20 seconds • Essential / Plus / Premium : 40 seconds • Ultimate : 100 seconds This library measures your script's total execution time and displays it relative to these limits, helping you optimize indicators for users on different plans. THE DEBUG TABLE When enabled, a table appears on your chart showing: • Plan : The selected TradingView subscription tier • Limit : Maximum allowed execution time for that plan • Runtime : Measured script execution time • Per Bar : Average time spent per bar • Bars : Number of bars processed • % Used : Percentage of timeout limit consumed (color-coded) • Status : OK (green), WARNING (yellow), DANGER (orange), or EXCEEDED (red) HOW IT WORKS The library captures a timestamp at the start of your script using timenow, then calculates the elapsed time at the end. It compares this against the selected plan's timeout limit to determine percentage used and status. Technical Note : Pine Script's timenow variable has approximately 1-second precision. Scripts that execute in under 1 second may display 0ms. This is a platform limitation, not a library issue. For detailed per-function profiling, use TradingView's built-in Pine Profiler (More → Profiler mode in the Editor). EXPORTED FUNCTIONS startTimer() Call at the very beginning of your script. Returns a timestamp. getStats(startTime, plan) Calculates timing statistics. Returns a TimingStats object with all metrics. showTimingTable(stats, plan, tablePosition, showOnlyOnLast) Renders the debug table on the chart. debugTiming(startTime, plan, tablePosition) Convenience function combining getStats() and showTimingTable() in one call. isApproachingLimit(stats, threshold) Returns true if execution time has reached the specified percentage of the limit. getRemainingMs(stats) Returns milliseconds remaining before timeout. formatSummary(stats) Returns a compact single-line string for labels or tooltips. addTimingLabel(stats, barIdx, price, labelStyle, textSize) Creates a color-coded chart label displaying timing statistics. Useful for visual debugging without the full table. Returns the label object for further customization. EXPORTED CONSTANTS • LIMIT_BASIC = 20 • LIMIT_ESSENTIAL = 40 • LIMIT_PLUS = 40 • LIMIT_PREMIUM = 40 • LIMIT_ULTIMATE = 100 EXPORTED TYPE: TimingStats Object containing: • totalTimeMs (float): Total execution time in milliseconds • timePerBarMs (float): Average time per bar • barsTimed (int): Number of bars measured • barsSkipped (int): Bars excluded from measurement • planLimitMs (int): Plan timeout in milliseconds • percentUsed (float): Percentage of limit consumed • status (string): "OK", "WARNING", "DANGER", or "EXCEEDED" HOW TO USE IN YOUR INDICATOR //@version=6 indicator("My Indicator", overlay = true) import YourUsername/PlanLimitTimer/1 as timer // User selects their TradingView plan planInput = input.string("basic", "Your Plan", options = ) // START TIMING - must be first startTime = timer.startTimer() // Your indicator calculations here sma20 = ta.sma(close, 20) rsi14 = ta.rsi(close, 14) plot(sma20) // END TIMING - must be last timer.debugTiming(startTime, planInput) ADVANCED USAGE EXAMPLE //@version=6 indicator("Advanced Example", overlay = true) import YourUsername/PlanLimitTimer/1 as timer planInput = input.string("basic", "Plan", options = ) startTime = timer.startTimer() // Your calculations... sma = ta.sma(close, 200) plot(sma) // Get stats for programmatic use stats = timer.getStats(startTime, planInput) // Option 1: Use addTimingLabel for a quick visual indicator if barstate.islast timer.addTimingLabel(stats, bar_index, high) // Option 2: Show custom warning label if approaching limit if timer.isApproachingLimit(stats, 70.0) and barstate.islast label.new(bar_index, low, "Warning: " + timer.formatSummary(stats), color = color.orange, textcolor = color.white, style = label.style_label_up) // Display the debug table timer.showTimingTable(stats, planInput, position.bottom_right) IMPORTANT LIMITATIONS 1. Precision : Timing precision is approximately 1 second due to timenow behavior. Fast scripts show 0ms. 2. Variability : Results vary based on TradingView server load. The same script may show different times across runs. 3. Total Time Only : This library measures total script execution time, not individual function timing. For per-function analysis, use the Pine Profiler in the Editor. 4. Historical Bars : On historical bars, timenow reflects when the script loaded, not individual bar processing times. USE CASES • Optimization Debugging : See how close your script is to timeout limits • Multi-Plan Support : Help users select appropriate settings for their subscription tier • Performance Regression : Detect when changes increase execution time • Documentation : Show users the performance characteristics of your indicator Pine Script®库由ArunaReborn提供已更新 0
News2026H2Library "News2026H2" - 2026 News Events Support Lib f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId() f_loadExcDelayAfterNewsMins()Pine Script®库由pking9999提供0
T5_TradeEngineLibrary "T5_TradeEngine" tick(close_, high_, low_, ema21, ema50, ema200, atrPct, emaGapPct, btcEma50, btcEma200, btcFilterEffective, isBarClose, crossUp21_50, crossDown21_50, allowEntries, exitOnOppositeCross, feeBps, useSR_TPSL, srLeft, srRight, srLookbackPivots, srBufferPct, srMinDistPct, srMinNetAfterFeesPct, srFallbackToATR, tp1CapPct, slCapPct, useTP2Trail, trailExitOnCloseOnly, tp2CapPct, trailCapPct, holdBars) Parameters: close_ (float) high_ (float) low_ (float) ema21 (float) ema50 (float) ema200 (float) atrPct (float) emaGapPct (float) btcEma50 (float) btcEma200 (float) btcFilterEffective (bool) isBarClose (bool) crossUp21_50 (bool) crossDown21_50 (bool) allowEntries (bool) exitOnOppositeCross (bool) feeBps (float) useSR_TPSL (bool) srLeft (int) srRight (int) srLookbackPivots (int) srBufferPct (float) srMinDistPct (float) srMinNetAfterFeesPct (float) srFallbackToATR (bool) tp1CapPct (float) slCapPct (float) useTP2Trail (bool) trailExitOnCloseOnly (bool) tp2CapPct (float) trailCapPct (float) holdBars (int)Pine Script®库由quentinosamudiamentmh7v提供0
ZigZag ATRZigZag ATR Library A volatility-adaptive ZigZag indicator that uses Average True Range (ATR) instead of fixed percentage deviation to detect pivot points. This makes the ZigZag dynamically adjust to market conditions — tighter during low volatility, wider during high volatility. Why ATR instead of Percentage? The standard ZigZag uses a fixed percentage threshold (e.g., 5%) to determine when price has reversed enough to form a new pivot. This approach has limitations: A 5% move means very different things for a $10 stock vs a $500 stock During high volatility, fixed percentages create too many pivots (noise) During low volatility, fixed percentages may miss significant structure ATR-based deviation solves these issues by measuring reversals in terms of actual volatility , not arbitrary percentages. Key Features Volatility-adaptive pivot detection using ATR × multiplier threshold Automatic adjustment to changing market conditions Full customization of ATR length and multiplier Optional line extension to current price Pivot labels showing price, volume, and price change Clean library structure for easy integration Settings ATR Length — Period for ATR calculation (default: 14) ATR Multiplier — How many ATRs price must move to confirm a new pivot (default: 2.0) Depth — Bars required for pivot detection (default: 10) Extend to Last Bar — Draw provisional line to current price Display options — Toggle price, volume, and change labels How to Use import YourUsername/ZigZagATR/1 as zz // Create settings var zz.Settings settings = zz.Settings.new( 14, // ATR length 2.0, // ATR multiplier 10 // Depth ) // Create ZigZag instance var zz.ZigZag zigZag = zz.newInstance(settings) // Calculate ATR and update on each bar float atrValue = ta.atr(14) zigZag.update(atrValue) Exported Types Settings — Configuration for calculation and display Pivot — Stores pivot point data, lines, and labels ZigZag — Main object maintaining state and pivot history Exported Functions newInstance(settings) — Creates a new ZigZag object update(atrValue) — Updates the ZigZag with current ATR (call once per bar) lastPivot() — Returns the most recent pivot point Recommended Multiplier Values 1.0 - 1.5 → More sensitive, more pivots, better for scalping 2.0 - 2.5 → Balanced, good for swing trading (default) 3.0+ → Less sensitive, major pivots only, better for position trading Based on TradingView's official ZigZag library, modified to use ATR-based deviation threshold.Pine Script®库由DeepEntropy提供已更新 222
demark_poolLibrary "demark_pool" f_labelArrayClear(pool, run) Parameters: pool (array) run (bool) f_labelPushCap(pool, l, cap) Parameters: pool (array) l (label) cap (int) f_labelTrimCap(pool, run, cap) Parameters: pool (array) run (bool) cap (int)Pine Script®库由Anchoritezzz提供0
demark_uiLibrary "demark_ui" f_dashUpdate6x2(dash, c00, c10, c01, c11, c02, c12, c12TextColor, c03, c13, c04, c14, c05, c15, bg, tc, ts) Parameters: dash (table) c00 (string) c10 (string) c01 (string) c11 (string) c02 (string) c12 (string) c12TextColor (color) c03 (string) c13 (string) c04 (string) c14 (string) c05 (string) c15 (string) bg (color) tc (color) ts (string)Pine Script®库由Anchoritezzz提供已更新 1