PINE LIBRARY

nineLivesUtilLib

109
Library "nineLivesUtilLib"

isDateInRange(currentTime, useTimeFilter, startDate, endDate)
  Checks if the current time is within the specified date range.
  Parameters:
    currentTime (int): The current bar's time (time).
    useTimeFilter (bool): Bool 📅: Enable the date range filter.
    startDate (int): Timestamp 📅: The start date for the filter.
    endDate (int): Timestamp 📅: The end date for the filter.
  Returns: True if the current time is within the range or filtering is disabled, false otherwise.
Example
inDateRange = nineLivesUtilLib.isDateInRange(time, useTimeFilter, startDate, endDate)
if inDateRange
// Execute trading logic

checkVolumeCondition(currentVolume, useVolumeFilter, volumeThresholdMultiplier, volumeLength)
  Checks if the current volume meets the threshold condition.
  Parameters:
    currentVolume (float): The current bar's volume (volume).
    useVolumeFilter (bool): Bool 📊: Enable the volume filter.
    volumeThresholdMultiplier (float): Float 📊: Volume threshold relative to average (e.g., 1.5 for 1.5x average).
    volumeLength (int): Int 📊: Lookback length for the volume average.
  Returns: True if the volume condition is met or filtering is disabled, false otherwise.
Example
volumeOk = nineLivesUtilLib.checkVolumeCondition(volume, useVolumeFilter, volumeThreshold, volumeLength)
if volumeOk
// Proceed with trading logic

checkMultiTimeframeCondition(currentClose, currentOpen, htfClose, htfOpen, useMultiTimeframe, alignment)
  Checks alignment with higher timeframe direction.
  Parameters:
    currentClose (float): Float: The current bar's closing price (close).
    currentOpen (float): Float: The current bar's opening price (open).
    htfClose (float): Float: The closing price from the higher timeframe (must be fetched by the calling script using request.security).
    htfOpen (float): Float: The opening price from the higher timeframe (must be fetched by the calling script using request.security).
    useMultiTimeframe (bool): Bool ⏱️: Enable multi-timeframe analysis.
    alignment (string): String ⏱️: Desired alignment ("same", "opposite", "any").
  Returns: True if the timeframe alignment condition is met or analysis is disabled, false otherwise.
Example
// In the calling script:
[htfClose, htfOpen] = request.security(syminfo.tickerid, higherTimeframe, [close, open])
tfOk = nineLivesUtilLib.checkMultiTimeframeCondition(close, open, htfClose, htfOpen, useMultiTimeframe, tfAlignment)
if tfOk
// Proceed with trading logic

checkMarketRegime(useMarketRegime, regimeIndicator, regimeThreshold, regimeLength, regimeMode)
  Detects the market regime (trending or ranging) and checks if trading is allowed.
  Parameters:
    useMarketRegime (bool): Bool 🔍: Enable market regime detection.
    regimeIndicator (string): String 🔍: Indicator to use ("ADX" or "Volatility").
    regimeThreshold (int): Int 🔍: Threshold for trend strength/volatility.
    regimeLength (simple int): Int 🔍: Lookback length for the indicator.
    regimeMode (string): String 🔍: Trading mode based on regime ("trend_only", "range_only", "adaptive").
  Returns: A tuple containing:
[0]: conditionMet (bool) - True if trading is allowed based on the regime mode and detection, false otherwise.
[1]: inTrendingRegime (bool) - True if the current regime is trending based on the indicator and threshold.
Example
[regimeOk, isTrending] = nineLivesUtilLib.checkMarketRegime(useMarketRegime, regimeIndicator, regimeThreshold, regimeLength, regimeMode)
if regimeOk
// Proceed with trading logic

applyCooldown(buySignal, sellSignal, cooldownBars)
  Applies a cooldown period after a signal.
  Parameters:
    buySignal (bool): Bool: Buy signal (potentially after primary entry logic).
    sellSignal (bool): Bool: Sell signal (potentially after primary entry logic).
    cooldownBars (int): Int ⏳: The number of bars to wait after a signal before allowing another.
  Returns: A tuple containing:
[0]: cooldownFilteredBuy (bool) - Buy signal after cooldown filter.
[1]: cooldownFilteredSell (bool) - Sell signal after cooldown filter.
Example
[cooldownBuy, cooldownSell] = nineLivesUtilLib.applyCooldown(rawBuySignal, rawSellSignal, iCool)

applyAllFilters(rawBuy, rawSell, inDateRange, tradeDirection, volumeOk, tfOk, regimeOk, drawdownOk, cooldownOkBuy, cooldownOkSell)
  Applies all filtering conditions to the buy and sell signals.
  Parameters:
    rawBuy (bool): Bool: The initial buy signal candidate (from primary entry logic, e.g., after cooldown).
    rawSell (bool): Bool: The initial sell signal candidate (from primary entry logic, e.g., after cooldown).
    inDateRange (bool): Bool 📅: Result from isDateInRange.
    tradeDirection (string): String 🔄: Overall trade direction preference ("longs_only", "shorts_only", "both").
    volumeOk (bool): Bool 📊: Result from checkVolumeCondition.
    tfOk (bool): Bool ⏱️: Result from checkMultiTimeframeCondition.
    regimeOk (bool): Bool 🔍: Result from checkMarketRegime.
    drawdownOk (bool): Bool 📉: Result from checkDrawdownExceeded (or equivalent).
    cooldownOkBuy (bool): Bool ⏳: Result from applyCooldown for buy.
    cooldownOkSell (bool): Bool ⏳: Result from applyCooldown for sell.
  Returns: A tuple containing:
[0]: finalBuySignal (bool) - The final buy signal after all filters.
[1]: finalSellSignal (bool) - The final sell signal after all filters.
Example
[finalBuy, finalSell] = nineLivesUtilLib.applyAllFilters(cooldownBuy, cooldownSell, inDateRange, tradeDirection, volumeOk, tfOk, regimeOk, !drawdownExceeded, cooldownBuy, cooldownSell)
NOTE: This function filters signals generated by your primary entry logic (e.g., EMA crossover).

checkDrawdownExceeded(currentEquity, useMaxDrawdown, maxDrawdownPercent)
  Tracks maximum equity and checks if current drawdown exceeds a threshold.
  Parameters:
    currentEquity (float): Float: The strategy's current equity (strategy.equity).
    useMaxDrawdown (bool): Bool 📉: Enable max drawdown protection.
    maxDrawdownPercent (float): Float 📉: The maximum allowed drawdown as a percentage.
  Returns: True if drawdown protection is enabled and the current drawdown exceeds the threshold, false otherwise.
Example
drawdownExceeded = nineLivesUtilLib.checkDrawdownExceeded(strategy.equity, useMaxDrawdown, maxDrawdownPercent)
if drawdownExceeded
// Consider stopping entries or exiting positions in the strategy script

calculateExitPrice(positionAvgPrice, percentage, isStop, isLong)
  Calculates a stop loss or take profit price based on a percentage from the average entry price.
  Parameters:
    positionAvgPrice (float): Float: The average price of the current position (strategy.position_avg_price).
    percentage (float): Float: The stop loss or take profit percentage (e.g., 2.0 for 2%).
    isStop (bool): Bool: True if calculating a stop loss price, false if calculating a take profit price.
    isLong (bool): Bool: True if the position is long, false if short.
  Returns: The calculated stop price or take profit price, or na if no position or percentage is invalid.
Example
longSL = nineLivesUtilLib.calculateExitPrice(strategy.position_avg_price, stopLossPercent, true, true)
shortTP = nineLivesUtilLib.calculateExitPrice(strategy.position_avg_price, takeProfitPercent, false, false)

calculateTrailingStopLevel(positionAvgPrice, trailOffsetPercent, trailPercent, currentHigh, currentLow, isLong)
  Calculates the current trailing stop level for a position.
  Parameters:
    positionAvgPrice (float): Float: The average price of the current position (strategy.position_avg_price).
    trailOffsetPercent (float): Float 🔄: The percentage price movement to activate the trailing stop.
    trailPercent (float): Float 🔄: The percentage distance the stop trails behind the price.
    currentHigh (float): Float: The current bar's high (high).
    currentLow (float): Float: The current bar's low (low).
    isLong (bool): Bool: True if the position is long, false if short.
  Returns: The calculated trailing stop price if active, otherwise na.
Example
longTrailStop = nineLivesUtilLib.calculateTrailingStopLevel(strategy.position_avg_price, trailOffset, trailPercent, high, low, true)
shortTrailStop = nineLivesUtilLib.calculateTrailingStopLevel(strategy.position_avg_price, trailOffset, trailPercent, high, low, false)
if not na(longTrailStop)
strategy.exit("Long Trail", from_entry="Long", stop=longTrailStop)

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.