LO1_News2024H1Library "LO1_News2024H1" Support Library for News Events f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId() f_loadExcDelayAfterNewsMins()Thư viện Pine Script®của Vantage-StackCập nhật 1
LO1_News2026H1Library "LO1_News2026H1" Support Library for News Events f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId() f_loadExcDelayAfterNewsMins()Thư viện Pine Script®của Vantage-StackCập nhật 1
LO1_News2025H2Library "LO1_News2025H2" Support Library for News Events f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId() f_loadExcDelayAfterNewsMins()Thư viện Pine Script®của Vantage-StackCập nhật 1
LO1_News2025H1Library "LO1_News2025H1" Support Library for News Events f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId() f_loadExcDelayAfterNewsMins()Thư viện Pine Script®của Vantage-StackCập nhật 1
LO1_News2024H2Library "LO1_News2024H2" Support Library for News Events f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId() f_loadExcDelayAfterNewsMins()Thư viện Pine Script®của Vantage-StackCập nhật 1
LO1_TradersPostLibrary "LO1_TradersPost" Enhanced TradersPost integration library with comprehensive order management _buildJSONField(key, value, required) Build a JSON field with proper handling of required vs optional fields Parameters: key (string) : The JSON key name value (string) : The value to include (any type, will be converted to string) required (bool) : If true, field is always included even if value is na/empty Returns: String containing JSON field or empty string if optional and na/empty _buildConditionalField(key, value) Build a conditional JSON field that's only included if value is valid Parameters: key (string) : The JSON key name value (string) : The value to include Returns: String containing JSON field or empty string if value is na/empty _buildConditionalNumericField(key, value) Build a conditional JSON field for numeric values Parameters: key (string) : The JSON key name value (float) : The numeric value Returns: String containing JSON field or empty string if value is na _buildNestedObject(objectType, price, amount, percent, stopType, limitPrice, trailAmount, trailPercent) Build nested JSON objects for takeProfit/stopLoss Parameters: objectType (string) : The type of object being built ("takeProfit" or "stopLoss") price (float) : The limit price for TP or stop price for SL amount (float) : The dollar amount (optional) percent (float) : The percentage (optional) stopType (series StopLossType) : The stop loss type - only for stopLoss limitPrice (float) : The limit price for stop_limit orders - only for stopLoss trailAmount (float) : Trailing amount for trailing stops - only for stopLoss trailPercent (float) : Trailing percent for trailing stops - only for stopLoss Returns: String containing nested JSON object or empty string if no valid data _validateAndBuildJSON(ticker, action, quantity, quantityType, orderType, sentiment, cancel, timeInForce, limitPrice, stopPrice, trailAmount, trailPercent, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, extendedHours, optionType, intrinsicValue, expiration, strikePrice, signalPrice, comment) Master JSON builder that validates parameters and constructs JSON Parameters: ticker (string) : The trading symbol action (series Action) : The order action (buy, sell, exit, etc.) quantity (float) : The order quantity quantityType (series QuantityType) : The type of quantity (fixed, dollar, percent) orderType (series OrderType) : The order type (market, limit, stop, etc.) sentiment (series Sentiment) : The position sentiment (long, short, flat) - optional cancel (bool) : Controls order cancellation (true = cancel existing orders, false = don't cancel) timeInForce (series TimeInForce) : Time in force for the order (DAY, GTC, IOC, FOK) limitPrice (float) : Price for limit orders stopPrice (float) : Price for stop orders trailAmount (float) : Trailing amount for trailing stops trailPercent (float) : Trailing percent for trailing stops takeProfitPrice (float) : Take profit limit price (absolute) takeProfitAmount (float) : Take profit dollar amount (relative) takeProfitPercent (float) : Take profit percentage (relative) stopLossPrice (float) : Stop loss price (absolute) stopLossAmount (float) : Stop loss dollar amount (relative) stopLossPercent (float) : Stop loss percentage (relative) stopLossType (series StopLossType) : Stop loss order type stopLossLimitPrice (float) : Limit price for stop_limit orders extendedHours (bool) : Enable extended hours trading (boolean) optionType (series OptionType) : Option type for options trading (both/call/put) intrinsicValue (series IntrinsicValue) : Intrinsic value filter for options (itm/otm) expiration (string) : Option expiration (date string) strikePrice (float) : Option strike price signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment for the order (shows in TradersPost UI for debugging) Returns: ErrorResponse with success status and JSON string or error details ValidateOrder(ticker, action, orderType, limitPrice, stopPrice) Validate order parameters before JSON construction Parameters: ticker (string) : Trading symbol action (series Action) : Order action orderType (series OrderType) : Order type (market, limit, stop, etc.) limitPrice (float) : Limit price for limit orders stopPrice (float) : Stop price for stop orders Returns: ErrorResponse with validation results ValidateQuantity(quantity, quantityType) Validate quantity based on type and constraints Parameters: quantity (float) : The quantity value quantityType (series QuantityType) : The type of quantity Returns: ErrorResponse with validation results ValidatePrices(entryPrice, stopPrice, takeProfitPrice, action) Validate price relationships and values Parameters: entryPrice (float) : Entry price for the order stopPrice (float) : Stop loss price takeProfitPrice (float) : Take profit price action (series Action) : Order action (buy/sell) Returns: ErrorResponse with validation results ValidateSymbol(ticker) Validate trading symbol format Parameters: ticker (string) : The symbol to validate Returns: ErrorResponse with validation results CombineValidationResults(validationResults) Create validation error collection and reporting system Parameters: validationResults (array) : Array of ErrorResponse objects from multiple validations Returns: Combined ErrorResponse with all validation results ValidateCompleteOrder(ticker, action, quantity, quantityType, orderType, limitPrice, stopPrice, takeProfitPrice) Comprehensive validation for all order parameters Parameters: ticker (string) : Trading symbol action (series Action) : Order action quantity (float) : Order quantity quantityType (series QuantityType) : Type of quantity orderType (series OrderType) : Order type limitPrice (float) : Limit price (optional) stopPrice (float) : Stop price (optional) takeProfitPrice (float) : Take profit price (optional) Returns: ErrorResponse with complete validation results CreateErrorResponse(success, errorMessages, message, severity, context, functionName) Create standardized error response Parameters: success (bool) : Whether the operation succeeded errorMessages (array) : Array of error messages message (string) : Summary message severity (series ErrorSeverity) : Error severity level context (string) : Context where error occurred functionName (string) : Name of function that generated error Returns: EnhancedErrorResponse with all error details HandleValidationError(validationResult, context, functionName) Handle validation errors with context Parameters: validationResult (ErrorResponse) : The validation result to handle context (string) : Description of what was being validated functionName (string) : Name of calling function Returns: Processed error response with enhanced context LogError(errorResponse, displayOnChart) Log error with appropriate level Parameters: errorResponse (EnhancedErrorResponse) : The error response to log displayOnChart (bool) : Whether to show error on chart CreateSuccessResponse(message, context, functionName) Create success response Parameters: message (string) : Success message context (string) : Context of successful operation functionName (string) : Name of function Returns: Success response _validateJSONConstruction(jsonString) Validate JSON construction and handle malformed data Parameters: jsonString (string) : The constructed JSON string Returns: ErrorResponse indicating if JSON is valid CreateDetailedError(success, errors, warnings, severity, context) Create detailed error response with context Parameters: success (bool) : Operation success status errors (array) : Array of error messages warnings (array) : Array of warning messages severity (series ErrorSeverity) : Error severity level context (string) : Context where error occurred Returns: DetailedErrorResponse object LogDetailedError(response) Log detailed error response with appropriate severity Parameters: response (DetailedErrorResponse) : DetailedErrorResponse to log Returns: Nothing - logs to Pine Script console CombineIntoDetailedResponse(responses, context) Combine multiple error responses into detailed response Parameters: responses (array) : Array of ErrorResponse objects to combine context (string) : Context for the combined operation Returns: DetailedErrorResponse with combined results SendAdvancedOrder(ticker, action, quantity, quantityType, orderType, sentiment, cancel, limitPrice, stopPrice, trailAmount, trailPercent, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, extendedHours, optionType, intrinsicValue, expiration, strikePrice, signalPrice, comment) Send advanced order with comprehensive parameter validation and JSON construction Parameters: ticker (string) : Symbol to trade (defaults to syminfo.ticker) action (series Action) : Order action (buy/sell/exit/cancel/add) quantity (float) : Order quantity quantityType (series QuantityType) : Type of quantity (fixed/dollar/percent) orderType (series OrderType) : Type of order (market/limit/stop/stop_limit/trailing_stop) sentiment (series Sentiment) : Position sentiment (long/short/flat, optional) cancel (bool) : Controls order cancellation (true = cancel existing, false = don't cancel, na = use defaults) limitPrice (float) : Limit price for limit orders stopPrice (float) : Stop price for stop orders trailAmount (float) : Trailing amount for trailing stops trailPercent (float) : Trailing percent for trailing stops takeProfitPrice (float) : Take profit limit price (absolute) takeProfitAmount (float) : Take profit dollar amount (relative) takeProfitPercent (float) : Take profit percentage (relative) stopLossPrice (float) : Stop loss price (absolute) stopLossAmount (float) : Stop loss dollar amount (relative) stopLossPercent (float) : Stop loss percentage (relative) stopLossType (series StopLossType) : Stop loss order type stopLossLimitPrice (float) : Limit price for stop_limit orders extendedHours (bool) : Enable extended hours trading (boolean) optionType (series OptionType) : Option type for options trading (both/call/put) intrinsicValue (series IntrinsicValue) : Intrinsic value filter for options (itm/otm) expiration (string) : Option expiration (date string) strikePrice (float) : Option strike price signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment for the order (shows in TradersPost UI for debugging) Returns: ErrorResponse with success status and JSON or error details SendSentiment(ticker, sentiment, quantity, quantityType, signalPrice, comment) Send sentiment-based position management order Parameters: ticker (string) : Symbol to manage (defaults to syminfo.ticker) sentiment (series Sentiment) : Target position sentiment (long/short/flat) quantity (float) : Position size (optional, uses account default if not specified) quantityType (series QuantityType) : Type of quantity specification signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment Returns: ErrorResponse with success status SendCancelAll(ticker, comment) Cancel all open orders for the specified symbol Parameters: ticker (string) : Symbol to cancel orders for (defaults to syminfo.ticker) comment (string) : Optional comment for the cancellation Returns: ErrorResponse with success status SendOrderNoCancelExisting(ticker, action, quantity, quantityType, orderType, sentiment, limitPrice, stopPrice, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, signalPrice, comment) Send order without canceling existing orders Parameters: ticker (string) : Symbol to trade (defaults to syminfo.ticker) action (series Action) : Order action (buy/sell/exit) quantity (float) : Order quantity quantityType (series QuantityType) : Type of quantity (fixed/dollar/percent) orderType (series OrderType) : Type of order (market/limit/stop/stop_limit) sentiment (series Sentiment) : Position sentiment (long/short/flat, optional) limitPrice (float) : Limit price for limit orders stopPrice (float) : Stop price for stop orders takeProfitPrice (float) : Take profit price takeProfitAmount (float) : Take profit amount (optional) takeProfitPercent (float) stopLossPrice (float) : Stop loss price stopLossAmount (float) : Stop loss amount (optional) stopLossPercent (float) : Stop loss percentage (optional) stopLossType (series StopLossType) : Stop loss order type stopLossLimitPrice (float) : Limit price for stop_limit orders signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment Returns: ErrorResponse with success status _buildBracketOrderParams(orderType, entryPrice, entryLimitPrice) Build bracket order parameters by routing entryPrice to correct parameter based on orderType This helper function maps the conceptual "entryPrice" to the technical parameters needed Parameters: orderType (series OrderType) : The order type for the entry order entryPrice (float) : The desired entry price (trigger for stops, limit for limits) entryLimitPrice (float) : The limit price for stop_limit orders (optional) Returns: array with correct routing SendBracketOrder(ticker, action, quantity, quantityType, orderType, entryPrice, entryLimitPrice, takeProfitPrice, stopLossPrice, takeProfitAmount, takeProfitPercent, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, signalPrice, comment) Send bracket order (entry + take profit + stop loss) Parameters: ticker (string) : Symbol to trade action (series Action) : Entry action (buy/sell) quantity (float) : Order quantity quantityType (series QuantityType) : Type of quantity specification orderType (series OrderType) : Type of entry order entryPrice (float) : Entry price (trigger price for stop orders, limit price for limit orders) entryLimitPrice (float) : Entry limit price (only for stop_limit orders, defaults to entryPrice if na) takeProfitPrice (float) : Take profit price stopLossPrice (float) : Stop loss price takeProfitAmount (float) : Take profit dollar amount (alternative to price) takeProfitPercent (float) : Take profit percentage (alternative to price) stopLossAmount (float) : Stop loss dollar amount (alternative to price) stopLossPercent (float) : Stop loss percentage (alternative to price) stopLossType (series StopLossType) : Stop loss order type stopLossLimitPrice (float) : Limit price for stop_limit orders signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment Returns: ErrorResponse with success status SendOTOOrder(primaryTicker, primaryAction, primaryQuantity, primaryOrderType, primaryPrice, secondaryTicker, secondaryAction, secondaryQuantity, secondaryOrderType, secondaryPrice, signalPrice, comment) Send One-Triggers-Other (OTO) order sequence Note: OTO linking must be configured in TradersPost strategy settings This sends two separate orders - TradersPost handles the OTO logic Parameters: primaryTicker (string) : Primary order ticker primaryAction (series Action) : Primary order action primaryQuantity (float) : Primary order quantity primaryOrderType (series OrderType) : Primary entry type primaryPrice (float) : Primary order price secondaryTicker (string) : Secondary order ticker (defaults to primary ticker) secondaryAction (series Action) : Secondary order action secondaryQuantity (float) : Secondary order quantity secondaryOrderType (series OrderType) : Secondary entry type secondaryPrice (float) : Secondary order price signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment for both orders Returns: ErrorResponse with success status SendOCOOrder(ticker, firstAction, firstQuantity, firstOrderType, firstPrice, secondAction, secondQuantity, secondOrderType, secondPrice, signalPrice, comment) Send One-Cancels-Other (OCO) order pair Note: OCO linking must be configured in TradersPost strategy settings This sends two separate orders - TradersPost handles the OCO logic Parameters: ticker (string) : Symbol for both orders firstAction (series Action) : Action for first order firstQuantity (float) : Quantity for first order firstOrderType (series OrderType) : Order type for first order firstPrice (float) : Price for first order secondAction (series Action) : Action for second order secondQuantity (float) : Quantity for second order secondOrderType (series OrderType) : Order type for second order secondPrice (float) : Price for second order signalPrice (float) : The market price at alert time (for slippage tracking) comment (string) : Optional comment Returns: ErrorResponse with success status ErrorResponse Fields: success (series bool) errors (array) message (series string) EnhancedErrorResponse Fields: success (series bool) errors (array) message (series string) severity (series ErrorSeverity) context (series string) timestamp (series int) functionName (series string) DetailedErrorResponse Fields: success (series bool) errors (array) warnings (array) severity (series ErrorSeverity) context (series string) message (series string)Thư viện Pine Script®của Vantage-StackCập nhật 111
News2024H1Library "News2024H1" - This contains news events from 2024 H1 News Events f_loadNewsRows() f_loadExcSevByTypeId() f_loadExcTagByTypeId()Thư viện Pine Script®của pking9999Cập nhật 0
SPX_0DTE_EngineLibrary "SPX_0DTE_Engine" getATM(price) Parameters: price (float) getCallStrikes(atmStrike, count) Parameters: atmStrike (int) count (int) getPutStrikes(atmStrike, count) Parameters: atmStrike (int) count (int) generateOCCSymbol(underlying, year, month, day, optionType, strike) Parameters: underlying (string) year (int) month (int) day (int) optionType (string) strike (int) getAdaptiveReference(src, lookback) Parameters: src (float) lookback (int) detectLiquidityGrabHigh(high, low, close, volume, lookback) Parameters: high (float) low (float) close (float) volume (float) lookback (int) detectLiquidityGrabLow(high, low, close, volume, lookback) Parameters: high (float) low (float) close (float) volume (float) lookback (int) getVolatilityRegime(src, bbLength, bbMult) Parameters: src (float) bbLength (int) bbMult (float) getESConfirmation(spxClose, esClose, spxHigh, esHigh, spxLow, esLow, lookback) Parameters: spxClose (float) esClose (float) spxHigh (float) esHigh (float) spxLow (float) esLow (float) lookback (int) getDeltaBias(src, adaptiveRef, esClose, spxClose) Parameters: src (float) adaptiveRef (float) esClose (float) spxClose (float) getGammaZone(src, atmStrike) Parameters: src (float) atmStrike (int) getVegaRegime(vixSymbol) Parameters: vixSymbol (simple string) isFailState(volRegime, hour, minute, vix, atr) Parameters: volRegime (int) hour (int) minute (int) vix (float) atr (float) checkCallConfluence(liquidityGrabLow, volRegime, esConfirmation, failState, deltaBias, lowGamma) Parameters: liquidityGrabLow (bool) volRegime (int) esConfirmation (int) failState (bool) deltaBias (int) lowGamma (bool) checkPutConfluence(liquidityGrabHigh, volRegime, esConfirmation, failState, deltaBias, lowGamma) Parameters: liquidityGrabHigh (bool) volRegime (int) esConfirmation (int) failState (bool) deltaBias (int) lowGamma (bool) checkProfitTarget(entryPrice, currentPrice, targetPercent, isCall) Parameters: entryPrice (float) currentPrice (float) targetPercent (float) isCall (bool) checkStopLoss(entryPrice, currentPrice, stopPercent, isCall) Parameters: entryPrice (float) currentPrice (float) stopPercent (float) isCall (bool) checkTimeExit(hour, minute) Parameters: hour (int) minute (int) checkInvalidation(esConfirmation, isCallPosition) Parameters: esConfirmation (int) isCallPosition (bool)Thư viện Pine Script®của albarqi5140
GaussianWavePacketLibrary "GaussianWavePacket" gaussianEnvelope(gamma, t, t0) Parameters: gamma (float) t (int) t0 (int) oscillatorReal(omega, t, phase) Parameters: omega (float) t (int) phase (float) oscillatorImag(omega, t, phase) Parameters: omega (float) t (int) phase (float) wavePacket(amplitude, gamma, omega, t, t0, phase) Parameters: amplitude (float) gamma (float) omega (float) t (int) t0 (int) phase (float) estimateGamma(amplitudeCurrent, amplitudePast, timeDelta) Parameters: amplitudeCurrent (float) amplitudePast (float) timeDelta (int) periodToOmega(period) Parameters: period (float) omegaToPeriod(omega) Parameters: omega (float)Thư viện Pine Script®của jaydesaigu3
News2024H2Library "News2024H2" 2024 news f_loadNewsRows()Thư viện Pine Script®của pking9999Cập nhật 1
News2026H1Library "News2026H1" - contains 2026 Jan News Day to start with f_loadNewsRows()Thư viện Pine Script®của pking9999Cập nhật 0
NewsTypesLibrary "NewsTypes" Provides the based library for the news system f_hhmmToMs(_hhmm) Parameters: _hhmm (int) f_addNews(_d, _hhmm, _tid, _dArr, _tArr, _idArr) Parameters: _d (string) _hhmm (int) _tid (int) _dArr (array) _tArr (array) _idArr (array) f_addNewsMs(_d, _ms, _tid, _dArr, _tArr, _idArr) Parameters: _d (string) _ms (int) _tid (int) _dArr (array) _tArr (array) _idArr (array) f_loadTypeSevByTypeId()Thư viện Pine Script®của pking9999Cập nhật 0
PineML_v6Library "PineML_v6" ML Library for lightweight strategies. Implements k-NN with matrix storage. method new_model(k, history, features) Създава нов модел Namespace types: series int, simple int, input int, const int Parameters: k (int) : Брой съседи (напр. 5) history (int) : Дълбочина на паметта (напр. 1000 бара) features (int) : Брой променливи, които ще следим method train(model, feature_array, label) Добавя нови данни към паметта на модела Namespace types: KNN_Model Parameters: model (KNN_Model) : Инстанцията на модела feature_array (array) : Масив с текущите стойности на индикаторите label (float) : Резултатът (класът), свързан с тези данни method predict(model, query_features) Изчислява прогноза на база текущите данни Namespace types: KNN_Model Parameters: model (KNN_Model) query_features (array) KNN_Model Fields: k_neighbors (series int) max_history (series int) features (matrix) labels (array) feature_count (series int)Thư viện Pine Script®của stoyan_valev0
LECAPS_BONCAP_LibraryLibrary "LECAPS_BONCAP_Library" getInstrumentCount() getTicker(index) Parameters: index (int) getTickerShort(index) Parameters: index (int) getMaturityPrice(index) Parameters: index (int) getMaturityTimestamp(index) Parameters: index (int) getMaturityYear(index) Parameters: index (int) getMaturityMonth(index) Parameters: index (int) getMaturityDay(index) Parameters: index (int) isBoncap(index) Parameters: index (int) isLecap(index) Parameters: index (int) getInstrumentType(index) Parameters: index (int) getDolarFuturesCount() getDolarFuturesTicker(index) Parameters: index (int) getDolarFuturesShort(index) Parameters: index (int) getDolarFuturesExpiry(index) Parameters: index (int) getDaysToMaturity(index) Parameters: index (int) getDataSummary(index) Parameters: index (int)Thư viện Pine Script®của Eco Valores5
News2025H2Library "News2025H2" f_loadTypeSevByTypeId() f_loadNewsRows()Thư viện Pine Script®của pking9999Cập nhật 1
News2025H1Library "News2025H1" f_loadTypeSevByTypeId() f_loadNewsRows()Thư viện Pine Script®của pking9999Cập nhật 0
StrategyMatrixLibLibrary "StrategyMatrixLib" render_matrix(posStr, digits, bgCol, headBg, headTxt, valCol, valTxt) Renders a strategy performance matrix (table) using strategy.* and strategy.closedtrades.* Parameters: posStr (string) : Table anchor position: "Top Left" | "Top Right" | "Bottom Left" | "Bottom Right" digits (int) : Decimal places for numeric formatting bgCol (color) : Background color for non-header cells headBg (color) : Background for header rows headTxt (color) : Text color for header rows valCol (color) : Background for value cells valTxt (color) : Text color for value cells Returns: table id The created/updated table IDThư viện Pine Script®của neghabi_mrCập nhật 0
SlopeUtilsLibrary "SlopeUtils" calcSlope(src, atr_series, length) Calculates a normalized slope based on price change relative to ATR. Parameters: src (float) : (series float) The source input (e.g., close). atr_series (float) : (series float) The ATR value for normalization. length (simple int) : (simple int) The lookback period for the slope calculation. Returns: (float) The normalized slope value.Thư viện Pine Script®của hjd17Cập nhật 0
arraysLibrary "arrays" Supplementary array methods. method delete(arr, index) remove int object from array of integers at specific index Namespace types: array Parameters: arr (array) : int array index (int) : index at which int object need to be removed Returns: void method delete(arr, index) remove float object from array of float at specific index Namespace types: array Parameters: arr (array) : float array index (int) : index at which float object need to be removed Returns: float method delete(arr, index) remove bool object from array of bool at specific index Namespace types: array Parameters: arr (array) : bool array index (int) : index at which bool object need to be removed Returns: bool method delete(arr, index) remove string object from array of string at specific index Namespace types: array Parameters: arr (array) : string array index (int) : index at which string object need to be removed Returns: string method delete(arr, index) remove color object from array of color at specific index Namespace types: array Parameters: arr (array) : color array index (int) : index at which color object need to be removed Returns: color method delete(arr, index) remove chart.point object from array of chart.point at specific index Namespace types: array Parameters: arr (array) : chart.point array index (int) : index at which chart.point object need to be removed Returns: void method delete(arr, index) remove line object from array of lines at specific index and deletes the line Namespace types: array Parameters: arr (array) : line array index (int) : index at which line object need to be removed and deleted Returns: void method delete(arr, index) remove label object from array of labels at specific index and deletes the label Namespace types: array Parameters: arr (array) : label array index (int) : index at which label object need to be removed and deleted Returns: void method delete(arr, index) remove box object from array of boxes at specific index and deletes the box Namespace types: array Parameters: arr (array) : box array index (int) : index at which box object need to be removed and deleted Returns: void method delete(arr, index) remove table object from array of tables at specific index and deletes the table Namespace types: array Parameters: arr (array) : table array index (int) : index at which table object need to be removed and deleted Returns: void method delete(arr, index) remove linefill object from array of linefills at specific index and deletes the linefill Namespace types: array Parameters: arr (array) : linefill array index (int) : index at which linefill object need to be removed and deleted Returns: void method delete(arr, index) remove polyline object from array of polylines at specific index and deletes the polyline Namespace types: array Parameters: arr (array) : polyline array index (int) : index at which polyline object need to be removed and deleted Returns: void method popr(arr) remove last int object from array Namespace types: array Parameters: arr (array) : int array Returns: int method popr(arr) remove last float object from array Namespace types: array Parameters: arr (array) : float array Returns: float method popr(arr) remove last bool object from array Namespace types: array Parameters: arr (array) : bool array Returns: bool method popr(arr) remove last string object from array Namespace types: array Parameters: arr (array) : string array Returns: string method popr(arr) remove last color object from array Namespace types: array Parameters: arr (array) : color array Returns: color method popr(arr) remove last chart.point object from array Namespace types: array Parameters: arr (array) : chart.point array Returns: void method popr(arr) remove and delete last line object from array Namespace types: array Parameters: arr (array) : line array Returns: void method popr(arr) remove and delete last label object from array Namespace types: array Parameters: arr (array) : label array Returns: void method popr(arr) remove and delete last box object from array Namespace types: array Parameters: arr (array) : box array Returns: void method popr(arr) remove and delete last table object from array Namespace types: array Parameters: arr (array) : table array Returns: void method popr(arr) remove and delete last linefill object from array Namespace types: array Parameters: arr (array) : linefill array Returns: void method popr(arr) remove and delete last polyline object from array Namespace types: array Parameters: arr (array) : polyline array Returns: void method shiftr(arr) remove first int object from array Namespace types: array Parameters: arr (array) : int array Returns: int method shiftr(arr) remove first float object from array Namespace types: array Parameters: arr (array) : float array Returns: float method shiftr(arr) remove first bool object from array Namespace types: array Parameters: arr (array) : bool array Returns: bool method shiftr(arr) remove first string object from array Namespace types: array Parameters: arr (array) : string array Returns: string method shiftr(arr) remove first color object from array Namespace types: array Parameters: arr (array) : color array Returns: color method shiftr(arr) remove first chart.point object from array Namespace types: array Parameters: arr (array) : chart.point array Returns: void method shiftr(arr) remove and delete first line object from array Namespace types: array Parameters: arr (array) : line array Returns: void method shiftr(arr) remove and delete first label object from array Namespace types: array Parameters: arr (array) : label array Returns: void method shiftr(arr) remove and delete first box object from array Namespace types: array Parameters: arr (array) : box array Returns: void method shiftr(arr) remove and delete first table object from array Namespace types: array Parameters: arr (array) : table array Returns: void method shiftr(arr) remove and delete first linefill object from array Namespace types: array Parameters: arr (array) : linefill array Returns: void method shiftr(arr) remove and delete first polyline object from array Namespace types: array Parameters: arr (array) : polyline array Returns: void method push(arr, val, maxItems) add int to the end of an array with max items cap. Objects are removed from start to maintain max items cap Namespace types: array Parameters: arr (array) : int array val (int) : int object to be pushed maxItems (int) : max number of items array can hold Returns: int method push(arr, val, maxItems) add float to the end of an array with max items cap. Objects are removed from start to maintain max items cap Namespace types: array Parameters: arr (array) : float array val (float) : float object to be pushed maxItems (int) : max number of items array can hold Returns: float method push(arr, val, maxItems) add bool to the end of an array with max items cap. Objects are removed from start to maintain max items cap Namespace types: array Parameters: arr (array) : bool array val (bool) : bool object to be pushed maxItems (int) : max number of items array can hold Returns: bool method push(arr, val, maxItems) add string to the end of an array with max items cap. Objects are removed from start to maintain max items cap Namespace types: array Parameters: arr (array) : string array val (string) : string object to be pushed maxItems (int) : max number of items array can hold Returns: string method push(arr, val, maxItems) add color to the end of an array with max items cap. Objects are removed from start to maintain max items cap Namespace types: array Parameters: arr (array) : color array val (color) : color object to be pushed maxItems (int) : max number of items array can hold Returns: color method push(arr, val, maxItems) add chart.point to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : chart.point array val (chart.point) : chart.point object to be pushed maxItems (int) : max number of items array can hold Returns: chart.point method push(arr, val, maxItems) add line to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : line array val (line) : line object to be pushed maxItems (int) : max number of items array can hold Returns: line method push(arr, val, maxItems) add label to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : label array val (label) : label object to be pushed maxItems (int) : max number of items array can hold Returns: label method push(arr, val, maxItems) add box to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : box array val (box) : box object to be pushed maxItems (int) : max number of items array can hold Returns: box method push(arr, val, maxItems) add table to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : table array val (table) : table object to be pushed maxItems (int) : max number of items array can hold Returns: table method push(arr, val, maxItems) add linefill to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : linefill array val (linefill) : linefill object to be pushed maxItems (int) : max number of items array can hold Returns: linefill method push(arr, val, maxItems) add polyline to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap Namespace types: array Parameters: arr (array) : polyline array val (polyline) : polyline object to be pushed maxItems (int) : max number of items array can hold Returns: polyline method unshift(arr, val, maxItems) add int to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap Namespace types: array Parameters: arr (array) : int array val (int) : int object to be unshift maxItems (int) : max number of items array can hold Returns: int method unshift(arr, val, maxItems) add float to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap Namespace types: array Parameters: arr (array) : float array val (float) : float object to be unshift maxItems (int) : max number of items array can hold Returns: float method unshift(arr, val, maxItems) add bool to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap Namespace types: array Parameters: arr (array) : bool array val (bool) : bool object to be unshift maxItems (int) : max number of items array can hold Returns: bool method unshift(arr, val, maxItems) add string to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap Namespace types: array Parameters: arr (array) : string array val (string) : string object to be unshift maxItems (int) : max number of items array can hold Returns: string method unshift(arr, val, maxItems) add color to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap Namespace types: array Parameters: arr (array) : color array val (color) : color object to be unshift maxItems (int) : max number of items array can hold Returns: color method unshift(arr, val, maxItems) add chart.point to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : chart.point array val (chart.point) : chart.point object to be unshift maxItems (int) : max number of items array can hold Returns: chart.point method unshift(arr, val, maxItems) add line to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : line array val (line) : line object to be unshift maxItems (int) : max number of items array can hold Returns: line method unshift(arr, val, maxItems) add label to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : label array val (label) : label object to be unshift maxItems (int) : max number of items array can hold Returns: label method unshift(arr, val, maxItems) add box to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : box array val (box) : box object to be unshift maxItems (int) : max number of items array can hold Returns: box method unshift(arr, val, maxItems) add table to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : table array val (table) : table object to be unshift maxItems (int) : max number of items array can hold Returns: table method unshift(arr, val, maxItems) add linefill to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : linefill array val (linefill) : linefill object to be unshift maxItems (int) : max number of items array can hold Returns: linefill method unshift(arr, val, maxItems) add polyline to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap Namespace types: array Parameters: arr (array) : polyline array val (polyline) : polyline object to be unshift maxItems (int) : max number of items array can hold Returns: polyline method isEmpty(arr) checks if an int array is either null or empty Namespace types: array Parameters: arr (array) : int array Returns: bool method isEmpty(arr) checks if a float array is either null or empty Namespace types: array Parameters: arr (array) : float array Returns: bool method isEmpty(arr) checks if a string array is either null or empty Namespace types: array Parameters: arr (array) : string array Returns: bool method isEmpty(arr) checks if a bool array is either null or empty Namespace types: array Parameters: arr (array) : bool array Returns: bool method isEmpty(arr) checks if a color array is either null or empty Namespace types: array Parameters: arr (array) : color array Returns: bool method isEmpty(arr) checks if a chart.point array is either null or empty Namespace types: array Parameters: arr (array) : chart.point array Returns: bool method isEmpty(arr) checks if a line array is either null or empty Namespace types: array Parameters: arr (array) : line array Returns: bool method isEmpty(arr) checks if a label array is either null or empty Namespace types: array Parameters: arr (array) : label array Returns: bool method isEmpty(arr) checks if a box array is either null or empty Namespace types: array Parameters: arr (array) : box array Returns: bool method isEmpty(arr) checks if a linefill array is either null or empty Namespace types: array Parameters: arr (array) : linefill array Returns: bool method isEmpty(arr) checks if a polyline array is either null or empty Namespace types: array Parameters: arr (array) : polyline array Returns: bool method isEmpty(arr) checks if a table array is either null or empty Namespace types: array Parameters: arr (array) : table array Returns: bool method isNotEmpty(arr) checks if an int array is not null and has at least one item Namespace types: array Parameters: arr (array) : int array Returns: bool method isNotEmpty(arr) checks if a float array is not null and has at least one item Namespace types: array Parameters: arr (array) : float array Returns: bool method isNotEmpty(arr) checks if a string array is not null and has at least one item Namespace types: array Parameters: arr (array) : string array Returns: bool method isNotEmpty(arr) checks if a bool array is not null and has at least one item Namespace types: array Parameters: arr (array) : bool array Returns: bool method isNotEmpty(arr) checks if a color array is not null and has at least one item Namespace types: array Parameters: arr (array) : color array Returns: bool method isNotEmpty(arr) checks if a chart.point array is not null and has at least one item Namespace types: array Parameters: arr (array) : chart.point array Returns: bool method isNotEmpty(arr) checks if a line array is not null and has at least one item Namespace types: array Parameters: arr (array) : line array Returns: bool method isNotEmpty(arr) checks if a label array is not null and has at least one item Namespace types: array Parameters: arr (array) : label array Returns: bool method isNotEmpty(arr) checks if a box array is not null and has at least one item Namespace types: array Parameters: arr (array) : box array Returns: bool method isNotEmpty(arr) checks if a linefill array is not null and has at least one item Namespace types: array Parameters: arr (array) : linefill array Returns: bool method isNotEmpty(arr) checks if a polyline array is not null and has at least one item Namespace types: array Parameters: arr (array) : polyline array Returns: bool method isNotEmpty(arr) checks if a table array is not null and has at least one item Namespace types: array Parameters: arr (array) : table array Returns: bool method flush(arr) remove all int objects in an array Namespace types: array Parameters: arr (array) : int array Returns: int method flush(arr) remove all float objects in an array Namespace types: array Parameters: arr (array) : float array Returns: float method flush(arr) remove all bool objects in an array Namespace types: array Parameters: arr (array) : bool array Returns: bool method flush(arr) remove all string objects in an array Namespace types: array Parameters: arr (array) : string array Returns: string method flush(arr) remove all color objects in an array Namespace types: array Parameters: arr (array) : color array Returns: color method flush(arr) remove all chart.point objects in an array Namespace types: array Parameters: arr (array) : chart.point array Returns: chart.point method flush(arr) remove and delete all line objects in an array Namespace types: array Parameters: arr (array) : line array Returns: line method flush(arr) remove and delete all label objects in an array Namespace types: array Parameters: arr (array) : label array Returns: label method flush(arr) remove and delete all box objects in an array Namespace types: array Parameters: arr (array) : box array Returns: box method flush(arr) remove and delete all table objects in an array Namespace types: array Parameters: arr (array) : table array Returns: table method flush(arr) remove and delete all linefill objects in an array Namespace types: array Parameters: arr (array) : linefill array Returns: linefill method flush(arr) remove and delete all polyline objects in an array Namespace types: array Parameters: arr (array) : polyline array Returns: polylineThư viện Pine Script®của FunkyMax2
bing_CountLibrary "Count" method comparisonCheck(value1, op, value2) Namespace types: series int, simple int, input int, const int Parameters: value1 (int) op (string) value2 (int)Thư viện Pine Script®của BBBing0
libSchedulerTLDR: This is a lightweight, easy-to-use way to throttle sections of Pinescript v6 scripts, the same as you'd use barstate.isconfirmed or barstate.islast. You can use this for enormous efficiency gains, provided you design your script to handle updates on differing intervals rather than computing everything on each cycle. Usage is easy: ``` import showmethegrail/libScheduler/1 as libScheduler i_tf_fetch = input.enum(libScheduler.Timeframes.C, "Fetch Interval", tooltip="Do things just once every interval, default=once per chart timeframe.") var scheduler = libScheduler.Scheduler.new().init() if scheduler.every(i_tf_fetch) // Do stuff ``` That's it. If you need to know more, the code is well-commented. Combine this with sensible caching, and you can right-size the compute-heavy sections of your script, for better stability and managed use of Pinescript compute quotas. You'll need to know the proper use of var and varip to make the most of this, but I found this effectively replaced a lot of boilerplate in throttling my own scripts. Sound software engineering, made Pinescript-level easy. That's all.Thư viện Pine Script®của showmethegrailCập nhật 110
DeeptestDeeptest: Quantitative Backtesting Library for Pine Script ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ OVERVIEW Deeptest is a Pine Script library that provides quantitative analysis tools for strategy backtesting. It calculates over 100 statistical metrics including risk-adjusted return ratios (Sharpe, Sortino, Calmar), drawdown analysis, Value at Risk (VaR), Conditional VaR, and performs Monte Carlo simulation and Walk-Forward Analysis. █ WHY THIS LIBRARY MATTERS Pine Script is a simple yet effective coding language for algorithmic and quantitative trading. Its accessibility enables traders to quickly prototype and test ideas directly within TradingView. However, the built-in strategy tester provides only basic metrics (net profit, win rate, drawdown), which is often insufficient for serious strategy evaluation. Due to this limitation, many traders migrate to alternative backtesting platforms that offer comprehensive analytics. These platforms require other language programming knowledge, environment setup, and significant time investment—often just to test a simple trading idea. Deeptest bridges this gap by bringing institutional-level quantitative analytics directly to Pine Script. Traders can now perform sophisticated analysis without leaving TradingView or learning complex external platforms. All calculations are derived from strategy.closedtrades.* , ensuring compatibility with any existing Pine Script strategy. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ ORIGINALITY AND USEFULNESS This library is original work that adds value to the TradingView community in the following ways: 1. Comprehensive Metric Suite: Implements 112+ statistical calculations in a single library, including advanced metrics not available in TradingView's built-in tester (p-value, Z-score, Skewness, Kurtosis, Risk of Ruin). 2. Monte Carlo Simulation: Implements trade-sequence randomization to stress-test strategy robustness by simulating 1000+ alternative equity curves. 3. Walk-Forward Analysis: Divides historical data into rolling in-sample and out-of-sample windows to detect overfitting by comparing training vs. testing performance. 4. Rolling Window Statistics: Calculates time-varying Sharpe, Sortino, and Expectancy to analyze metric consistency throughout the backtest period. 5. Interactive Table Display: Renders professional-grade tables with color-coded thresholds, tooltips explaining each metric, and period analysis cards for drawdowns/trades. 6. Benchmark Comparison: Automatically fetches S&P 500 data to calculate Alpha, Beta, and R-squared, enabling objective assessment of strategy skill vs. passive investing. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ KEY FEATURES Performance Metrics Net Profit, CAGR, Monthly Return, Expectancy Profit Factor, Payoff Ratio, Sample Size Compounding Effect Analysis Risk Metrics Sharpe Ratio, Sortino Ratio, Calmar Ratio (MAR) Martin Ratio, Ulcer Index Max Drawdown, Average Drawdown, Drawdown Duration Risk of Ruin, R-squared (equity curve linearity) Statistical Distribution Value at Risk (VaR 95%), Conditional VaR Skewness (return asymmetry) Kurtosis (tail fatness) Z-Score, p-value (statistical significance testing) Trade Analysis Win Rate, Breakeven Rate, Loss Rate Average Trade Duration, Time in Market Consecutive Win/Loss Streaks with Expected values Top/Worst Trades with R-multiple tracking Advanced Analytics Monte Carlo Simulation (1000+ iterations) Walk-Forward Analysis (rolling windows) Rolling Statistics (time-varying metrics) Out-of-Sample Testing Benchmark Comparison Alpha (excess return vs. benchmark) Beta (systematic risk correlation) Buy & Hold comparison R-squared vs. benchmark ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ QUICK START Basic Usage //@version=6 strategy("My Strategy", overlay=true) // Import the library import Fractalyst/Deeptest/1 as * // Your strategy logic fastMA = ta.sma(close, 10) slowMA = ta.sma(close, 30) if ta.crossover(fastMA, slowMA) strategy.entry("Long", strategy.long) if ta.crossunder(fastMA, slowMA) strategy.close("Long") // Run the analysis DT.runDeeptest() ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ METRIC EXPLANATIONS The Deeptest table displays 23 metrics across the main row, with 23 additional metrics in the complementary row. Each metric includes detailed tooltips accessible by hovering over the value. Main Row — Performance Metrics (Columns 0-6) Net Profit — (Final Equity - Initial Capital) / Initial Capital × 100 — >20%: Excellent, >0%: Profitable, <0%: Loss — Total return percentage over entire backtest period Payoff Ratio — Average Win / Average Loss — >1.5: Excellent, >1.0: Good, <1.0: Losses exceed wins — Average winning trade size relative to average losing trade. Breakeven win rate = 100% / (1 + Payoff) Sample Size — Count of closed trades — >=30: Statistically valid, <30: Insufficient data — Number of completed trades. Includes 95% confidence interval for win rate in tooltip Profit Factor — Gross Profit / Gross Loss — >=1.5: Excellent, >1.0: Profitable, <1.0: Losing — Ratio of total winnings to total losses. Uses absolute values unlike payoff ratio CAGR — (Final / Initial)^(365.25 / Days) - 1 — >=10%: Excellent, >0%: Positive growth — Compound Annual Growth Rate - annualized return accounting for compounding Expectancy — Sum of all returns / Trade count — >0.20%: Excellent, >0%: Positive edge — Average return per trade as percentage. Positive expectancy indicates profitable edge Monthly Return — Net Profit / (Months in test) — >0%: Profitable month average — Average monthly return. Geometric monthly also shown in tooltip Main Row — Trade Statistics (Columns 7-14) Avg Duration — Average time in position per trade — Mean holding period from entry to exit. Influenced by timeframe and trading style Max CW — Longest consecutive winning streak — Maximum consecutive wins. Expected value = ln(trades) / ln(1/winRate) Max CL — Longest consecutive losing streak — Maximum consecutive losses. Important for psychological risk tolerance Win Rate — Wins / Total Trades — Higher is better — Percentage of profitable trades. Breakeven win rate shown in tooltip BE Rate — Breakeven Trades / Total Trades — Lower is better — Percentage of trades that broke even (neither profit nor loss) Loss Rate — Losses / Total Trades — Lower is better — Percentage of unprofitable trades. Together with win rate and BE rate, sums to 100% Frequency — Trades per month — Trading activity level. Displays intelligently (e.g., "12/mo", "1.5/wk", "3/day") Exposure — Time in market / Total time × 100 — Lower = less risk — Percentage of time the strategy had open positions Main Row — Risk Metrics (Columns 15-22) Sharpe Ratio — (Return - Rf) / StdDev × sqrt(Periods) — >=3: Excellent, >=2: Good, >=1: Fair, <1: Poor — Measures risk-adjusted return using total volatility. Annualized using sqrt(252) for daily Sortino Ratio — (Return - Rf) / DownsideDev × sqrt(Periods) — >=2: Excellent, >=1: Good, <1: Needs improvement — Similar to Sharpe but only penalizes downside volatility. Can be higher than Sharpe Max DD — (Peak - Trough) / Peak × 100 — <5%: Excellent, 5-15%: Moderate, 15-30%: High, >30%: Severe — Largest peak-to-trough decline in equity. Critical for risk tolerance and position sizing RoR — Risk of Ruin probability — <1%: Excellent, 1-5%: Acceptable, 5-10%: Elevated, >10%: Dangerous — Probability of losing entire trading account based on win rate and payoff ratio R² — R-squared of equity curve vs. time — >=0.95: Excellent, 0.90-0.95: Good, 0.80-0.90: Moderate, <0.80: Erratic — Coefficient of determination measuring linearity of equity growth MAR — CAGR / |Max Drawdown| — Higher is better, negative = bad — Calmar Ratio. Reward relative to worst-case loss. Negative if max DD exceeds CAGR CVaR — Average of returns below VaR threshold — Lower absolute is better — Conditional Value at Risk (Expected Shortfall). Average loss in worst 5% of outcomes p-value — Binomial test probability — <0.05: Significant, 0.05-0.10: Marginal, >0.10: Likely random — Probability that observed results are due to chance. Low p-value means statistically significant edge Complementary Row — Extended Metrics Compounding — (Compounded Return / Total Return) × 100 — Percentage of total profit attributable to compounding (position sizing) Avg Win — Sum of wins / Win count — Average profitable trade return in percentage Avg Trade — Sum of all returns / Total trades — Same as Expectancy (Column 5). Displayed here for convenience Avg Loss — Sum of losses / Loss count — Average unprofitable trade return in percentage (negative value) Martin Ratio — CAGR / Ulcer Index — Similar to Calmar but uses Ulcer Index instead of Max DD Rolling Expectancy — Mean of rolling window expectancies — Average expectancy calculated across rolling windows. Shows consistency of edge Avg W Dur — Avg duration of winning trades — Average time from entry to exit for winning trades only Max Eq — Highest equity value reached — Peak equity achieved during backtest Min Eq — Lowest equity value reached — Trough equity point. Important for understanding worst-case absolute loss Buy & Hold — (Close_last / Close_first - 1) × 100 — >0%: Passive profit — Return of simply buying and holding the asset from backtest start to end Alpha — Strategy CAGR - Benchmark CAGR — >0: Has skill (beats benchmark) — Excess return above passive benchmark. Positive alpha indicates genuine value-added skill Beta — Covariance(Strategy, Benchmark) / Variance(Benchmark) — <1: Less volatile than market, >1: More volatile — Systematic risk correlation with benchmark Avg L Dur — Avg duration of losing trades — Average time from entry to exit for losing trades only Rolling Sharpe/Sortino — Dynamic based on win rate — >2: Good consistency — Rolling metric across sliding windows. Shows Sharpe if win rate >50%, Sortino if <=50% Curr DD — Current drawdown from peak — Lower is better — Present drawdown percentage. Zero means at new equity high DAR — CAGR adjusted for target DD — Higher is better — Drawdown-Adjusted Return. DAR^5 = CAGR if max DD = 5% Kurtosis — Fourth moment / StdDev^4 - 3 — ~0: Normal, >0: Fat tails, <0: Thin tails — Measures "tailedness" of return distribution (excess kurtosis) Skewness — Third moment / StdDev^3 — >0: Positive skew (big wins), <0: Negative skew (big losses) — Return distribution asymmetry VaR — 5th percentile of returns — Lower absolute is better — Value at Risk at 95% confidence. Maximum expected loss in worst 5% of outcomes Ulcer — sqrt(mean(drawdown^2)) — Lower is better — Ulcer Index - root mean square of drawdowns. Penalizes both depth AND duration ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ MONTE CARLO SIMULATION Purpose Monte Carlo simulation tests strategy robustness by randomizing the order of trades while keeping trade returns unchanged. This simulates alternative equity curves to assess outcome variability. Method Extract all historical trade returns Randomly shuffle the sequence (1000+ iterations) Calculate cumulative equity for each shuffle Build distribution of final outcomes Output The stress test table shows: Median Outcome: 50th percentile result 5th Percentile: Worst 5% of outcomes 95th Percentile: Best 95% of outcomes Success Rate: Percentage of simulations that were profitable Interpretation If 95% of simulations are profitable: Strategy is robust If median is far from actual result: High variance/unreliability If 5th percentile shows large loss: High tail risk ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ WALK-FORWARD ANALYSIS Purpose Walk-Forward Analysis (WFA) is the gold standard for detecting strategy overfitting. It simulates real-world trading by dividing historical data into rolling "training" (in-sample) and "validation" (out-of-sample) periods. A strategy that performs well on unseen data is more likely to succeed in live trading. Method The implementation uses a non-overlapping window approach following AmiBroker's gold standard methodology: Segment Calculation: Total trades divided into N windows (default: 12), IS = ~75%, OOS = ~25%, Step = OOS length Window Structure: Each window has IS (training) followed by OOS (validation). Each OOS becomes the next window's IS (rolling forward) Metrics Calculated: CAGR, Sharpe, Sortino, MaxDD, Win Rate, Expectancy, Profit Factor, Payoff Aggregation: IS metrics averaged across all IS periods, OOS metrics averaged across all OOS periods Output IS CAGR: In-sample annualized return OOS CAGR: Out-of-sample annualized return ( THE key metric ) IS/OOS Sharpe: In/out-of-sample risk-adjusted return Success Rate: % of OOS windows that were profitable Interpretation Robust: IS/OOS CAGR gap <20%, OOS Success Rate >80% Some Overfitting: CAGR gap 20-50%, Success Rate 50-80% Severe Overfitting: CAGR gap >50%, Success Rate <50% Key Principles: OOS is what matters — Only OOS predicts live performance Consistency > Magnitude — 10% IS / 9% OOS beats 30% IS / 5% OOS Window count — More windows = more reliable validation Non-overlapping OOS — Prevents data leakage ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ TABLE DISPLAY Main Table — Organized into three sections: Performance Metrics (Cols 0-6): Net Profit, Payoff, Sample Size, Profit Factor, CAGR, Expectancy, Monthly Trade Statistics (Cols 7-14): Avg Duration, Max CW, Max CL, Win, BE, Loss, Frequency, Exposure Risk Metrics (Cols 15-22): Sharpe, Sortino, Max DD, RoR, R², MAR, CVaR, p-value Color Coding 🟢 Green: Excellent performance 🟠 Orange: Acceptable performance ⚪ Gray: Neutral / Fair 🔴 Red: Poor performance ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ IMPLEMENTATION NOTES Data Source: All metrics calculated from strategy.closedtrades , ensuring compatibility with any Pine Script strategy Calculation Timing: All calculations occur on barstate.islastconfirmedhistory to optimize performance Limitations: Requires at least 1 closed trade for basic metrics, 30+ trades for reliable statistical analysis ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ QUICK NOTES ➙ This library has been developed and refined over two years of real-world strategy testing. Every calculation has been validated against industry-standard quantitative finance references. ➙ The entire codebase is thoroughly documented inline. If you are curious about how a metric is calculated or want to understand the implementation details, dive into the source code -- it is written to be read and learned from. ➙ This description focuses on usage and concepts rather than exhaustively listing every exported type and function. The library source code is thoroughly documented inline -- explore it to understand implementation details and internal logic. ➙ All calculations execute on barstate.islastconfirmedhistory to minimize runtime overhead. The library is designed for efficiency without sacrificing accuracy. ➙ Beyond analysis, this library serves as a learning resource. Study the source code to understand quantitative finance concepts, Pine Script advanced techniques, and proper statistical methodology. ➙ Metrics are their own not binary good/bad indicators. A high Sharpe ratio with low sample size is misleading. A deep drawdown during a market crash may be acceptable. Study each function and metric individually -- evaluate your strategy contextually, not by threshold alone. ➙ All strategies face alpha decay over time. Instead of over-optimizing a single strategy on one timeframe and market, build a diversified portfolio across multiple markets and timeframes. Deeptest helps you validate each component so you can combine robust strategies into a trading portfolio. ➙ Screenshots shown in the documentation are solely for visual representation to demonstrate how the tables and metrics will be displayed. Please do not compare your strategy's performance with the metrics shown in these screenshots -- they are illustrative examples only, not performance targets or benchmarks. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ HOW-TO Using Deeptest is intentionally straightforward. Just import the library and call DT.runDeeptest() at the end of your strategy code in main scope. . //@version=6 strategy("My Strategy", overlay=true) // Import the library import Fractalyst/Deeptest/1 as DT // Your strategy logic fastMA = ta.sma(close, 10) slowMA = ta.sma(close, 30) if ta.crossover(fastMA, slowMA) strategy.entry("Long", strategy.long) if ta.crossunder(fastMA, slowMA) strategy.close("Long") // Run the analysis DT.runDeeptest() And yes... it's compatible with any TradingView Strategy! 🪄 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ CREDITS Author: @Fractalyst Font Library: by @fikira - @kaigouthro - @Duyck Community: Inspired by the @PineCoders community initiative, encouraging developers to contribute open-source libraries and continuously enhance the Pine Script ecosystem for all traders. if you find Deeptest valuable in your trading journey, feel free to use it in your strategies and give a shoutout to @Fractalyst -- Your recognition directly supports ongoing development and open-source contributions to Pine Script. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ █ DISCLAIMER This library is provided for educational and research purposes. Past performance does not guarantee future results. Always test thoroughly and use proper risk management. The author is not responsible for any trading losses incurred through the use of this code.Thư viện Pine Script®của FractalystCập nhật 2121334
key_level_alerts_libLibrary "key_level_alerts_lib" shouldFireAlertAbove(level, acceptableRange, filterEnabled) Detects if price crossed above and closed above a level on this bar Parameters: level (float) : The price level to check for cross acceptableRange (float) : The maximum distance from level for close to be considered valid (used when filterEnabled=true) filterEnabled (bool) : When true, checks that close is within acceptable range above level Returns: true if price crossed and closed above the level (optionally within acceptable range) Detection logic: Condition A: Opened below level AND closed above level (direct cross up) Condition B: Opened above level, low touched/dipped to level (low <= level), closed above level shouldFireAlertBelow(level, acceptableRange, filterEnabled) Detects if price crossed below and closed below a level on this bar Parameters: level (float) : The price level to check for cross acceptableRange (float) : The maximum distance from level for close to be considered valid (used when filterEnabled=true) filterEnabled (bool) : When true, checks that close is within acceptable range below level Returns: true if price crossed and closed below the level (optionally within acceptable range) Detection logic: Condition A: Opened above level AND closed below level (direct cross down) Condition B: Opened below level, high touched/spiked to level (high >= level), closed below level processAlertAbove(level, acceptableRange, currentState, alertEnabled, filterEnabled) Process "crossed above" alert for a level - fires alert if transitioning from below/unknown to above Parameters: level (float) : The price level to check acceptableRange (float) : The acceptable range threshold for filtering currentState (int) : Current alert state (-1=below, 0=unknown, 1=above) alertEnabled (bool) : Whether the alert is enabled filterEnabled (bool) : Whether to apply acceptable range filtering Returns: tuple where newState is updated alert state and shouldFire indicates if alert should trigger State behavior: - Alert fires when: state was -1 or 0 AND cross above detected AND alert enabled - State updates to 1 (above) on any cross above - State updates to -1 (below) on any cross below (resets for next above alert) processAlertBelow(level, acceptableRange, currentState, alertEnabled, filterEnabled) Process "crossed below" alert for a level - fires alert if transitioning from above/unknown to below Parameters: level (float) : The price level to check acceptableRange (float) : The acceptable range threshold for filtering currentState (int) : Current alert state (-1=below, 0=unknown, 1=above) alertEnabled (bool) : Whether the alert is enabled filterEnabled (bool) : Whether to apply acceptable range filtering Returns: tuple where newState is updated alert state and shouldFire indicates if alert should trigger State behavior: - Alert fires when: state was 1 or 0 AND cross below detected AND alert enabled - State updates to -1 (below) on any cross below - State updates to 1 (above) on any cross above (resets for next below alert) calculateAcceptableRange(atrValue, acceptableRangePct) Calculates the acceptable range threshold for alert filtering based on ATR Parameters: atrValue (float) : The daily ATR value acceptableRangePct (float) : The acceptable range percentage (e.g., 85 for 85%) Returns: The acceptable range threshold in price units Calculation: oneFullLevel = ATR × 0.24 (24% of daily ATR = one standard key level spacing) acceptableRange = (acceptableRangePct / 100) × oneFullLevel getAlertLabelTextSize(sizeStr) Converts a size string to Pine Script size constant for labels Parameters: sizeStr (string) : The size string ("tiny", "small", "normal", "large", "huge") Returns: The corresponding Pine Script size constantThư viện Pine Script®của LiquidityTrackerCập nhật 0