Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

//@version=5 strategy("Enhanced BTCUSDT Strategy with Supertrend and CCI", overlay=true,…

  1. User

    //@version=5 strategy("Enhanced BTCUSDT Strategy with Supertrend and CCI", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=5, initial_capital=10000, currency=currency.USD, calc_on_order_fills=true, calc_on_every_tick=true)

    // ------------------- Parameters ------------------- groupSupertrend = "Supertrend Settings" supertrendFactor = input.float(3.0, minval=1.0, title="Supertrend Factor", group=groupSupertrend) supertrendATRPeriod = input.int(10, minval=1, title="Supertrend ATR Period", group=groupSupertrend)

    groupCCI = "CCI Settings" cciLength = input.int(20, minval=1, title="CCI Length", group=groupCCI) cciUpper = input.int(100, title="CCI Overbought Level", group=groupCCI) cciLower = input.int(-100, title="CCI Oversold Level", group=groupCCI)

    groupATR = "ATR Settings" atrPeriod = input.int(14, minval=1, title="ATR Period", group=groupATR) atrMultiplierSL = input.float(1.5, minval=0.1, title="ATR Stop Loss Multiplier", step=0.1, group=groupATR) atrMultiplierTP = input.float(3.0, minval=0.1, title="ATR Take Profit Multiplier", step=0.1, group=groupATR)

    groupBB = "Bollinger Bands Settings" bbLength = input.int(20, minval=1, title="BB Length", group=groupBB) bbStdDev = input.float(2.0, minval=0.1, title="BB Standard Deviation", group=groupBB) volatilityThreshold = input.float(0.05, minval=0.001, title="Volatility Threshold", group=groupBB)

    groupRisk = "Risk Management" riskPerTrade = input.float(1.0, minval=0.1, maxval=5.0, title="Risk per Trade (%)", group=groupRisk) maxDrawdownPercent = input.float(20.0, minval=1.0, maxval=100.0, title="Max Drawdown Limit (%)", group=groupRisk)

    groupTime = "Time Filter Settings" tradeSessionStart = input.string(defval="0000", title="Trade Session Start Time (HHMM)", group=groupTime) tradeSessionEnd = input.string(defval="2359", title="Trade Session End Time (HHMM)", group=groupTime)

    // Convert input strings to timestamps tradeYear = year(timenow) tradeMonth = month(timenow) tradeDay = dayofmonth(timenow) startHour = str.tonumber(str.substring(tradeSessionStart, 0, 2)) startMinute = str.tonumber(str.substring(tradeSessionStart, 2, 4)) endHour = str.tonumber(str.substring(tradeSessionEnd, 0, 2)) endMinute = str.tonumber(str.substring(tradeSessionEnd, 2, 4))

    sessionStartTime = timestamp("GMT+0", tradeYear, tradeMonth, tradeDay, startHour, startMinute) sessionEndTime = timestamp("GMT+0", tradeYear, tradeMonth, tradeDay, endHour, endMinute)

    // ------------------- Indicators ------------------- [supertrend, supertrendDirection] = ta.supertrend(supertrendFactor, supertrendATRPeriod) cci = ta.cci(hlc3, cciLength) atr = ta.atr(atrPeriod)

    basis = ta.sma(close, bbLength) dev = bbStdDev * ta.stdev(close, bbLength) upperBB = basis + dev lowerBB = basis - dev

    bbWidth = (upperBB - lowerBB) / basis highVolatility = bbWidth > volatilityThreshold

    inTradeSession = (time >= sessionStartTime) and (time <= sessionEndTime)

    // ------------------- Strategy Logic ------------------- var float highestEquity = strategy.initial_capital highestEquity := math.max(highestEquity, strategy.equity)

    drawdown = 100 * (highestEquity - strategy.equity) / highestEquity allowTrading = drawdown < maxDrawdownPercent

    longCondition = allowTrading and inTradeSession and highVolatility and (supertrendDirection == 1) and ta.crossover(cci, cciLower) shortCondition = allowTrading and inTradeSession and highVolatility and (supertrendDirection == -1) and ta.crossunder(cci, cciUpper)

    riskAmount = strategy.equity * (riskPerTrade / 100) positionSize = riskAmount / (atr * atrMultiplierSL) positionSize := math.max(positionSize, 0)

    // ------------------- Enter and Exit Positions ------------------- if (strategy.position_size == 0) if (longCondition) strategy.entry("Long", strategy.long, qty=positionSize) if (shortCondition) strategy.entry("Short", strategy.short, qty=positionSize)

    trailPoints = atr * atrMultiplierSL

    if (strategy.position_size > 0) longStopPrice = strategy.position_avg_price - (atr * atrMultiplierSL) longTakeProfitPrice = strategy.position_avg_price + (atr * atrMultiplierTP) strategy.exit("Long Exit", "Long", stop=longStopPrice, limit=longTakeProfitPrice, trail_points=trailPoints, trail_offset=trailPoints)

    if (strategy.position_size < 0) shortStopPrice = strategy.position_avg_price + (atr * atrMultiplierSL) shortTakeProfitPrice = strategy.position_avg_price - (atr * atrMultiplierTP) strategy.exit("Short Exit", "Short", stop=shortStopPrice, limit=shortTakeProfitPrice, trail_points=trailPoints, trail_offset=trailPoints)

    // ------------------- Plotting ------------------- plot(supertrend, title="Supertrend", color=(supertrendDirection == 1 ? color.green : color.red), linewidth=2) hline(cciUpper, title="CCI Overbought Level", color=color.red, linestyle=hline.style_dotted) hline(cciLower, title="CCI Oversold Level", color=color.green, linestyle=hline.style_dotted) plot(cci, title="CCI", color=color.blue, linewidth=1)

    // Optionally, plot Bollinger Bands and highlight volatility plot(upperBB, title="Upper BB", color=color.orange, linewidth=1, style=plot.style_linebr) plot(lowerBB, title="Lower BB", color=color.orange, linewidth=1, style=plot.style_linebr) bgcolor(highVolatility ? color.new(color.yellow, 90) : na, title="High Volatility Background")

    // ------------------- Alerts ------------------- alertcondition(longCondition, title="Long Entry", message="Long Entry Signal") alertcondition(shortCondition, title="Short Entry", message="Short Entry Signal")

  2. Assistant

    Your Pine Script strategy for BTCUSDT combines multiple technical indicators—Supertrend, CCI (Commodity Channel Index), ATR (Average True Range), and Bollinger Bands—to generate trading signals with integrated risk management and time filters. Here's a comprehensive review of your script, including functionality overview, potential improvements, and recommendations.


    1. Overview of the Strategy

    Components:

    1. Supertrend Indicator:

      • Purpose: Identifies the current trend direction.
      • Parameters:
        • Factor: Multiplier for ATR.
        • ATR Period: Calculation period for ATR.
    2. CCI (Commodity Channel Index):

      • Purpose: Detects overbought and oversold conditions.
      • Parameters:
        • Length: Number of periods for CCI calculation.
        • Overbought/Oversold Levels: Thresholds to trigger signals.
    3. ATR (Average True Range):

      • Purpose: Measures market volatility for setting stop-loss and take-profit levels.
      • Parameters:
        • ATR Period: Number of periods for ATR calculation.
        • Stop Loss Multiplier: Multiplier for ATR to set stop-loss.
        • Take Profit Multiplier: Multiplier for ATR to set take-profit.
    4. Bollinger Bands:

      • Purpose: Assesses volatility; high volatility is a condition for trading.
      • Parameters:
        • Length: Number of periods for moving average.
        • Standard Deviation: Determines the width of the bands.
        • Volatility Threshold: Minimum Bollinger Band width required to enable trading.
    5. Risk Management:

      • Parameters:
        • Risk per Trade: Percentage of equity to risk on each trade.
        • Max Drawdown Limit: Maximum allowable drawdown before trading is halted.
    6. Time Filters:

      • Parameters:
        • Trade Session Start/End Time: Defines the trading window each day.

    Trading Logic:

    • Entry Conditions:

      • Long Entry:

        • Trading is allowed (drawdown < max limit).
        • Within the defined trading session.
        • High volatility (Bollinger Bands width > threshold).
        • Supertrend indicates an uptrend.
        • CCI crosses above the oversold level.
      • Short Entry:

        • Similar conditions as long but:
          • Supertrend indicates a downtrend.
          • CCI crosses below the overbought level.
    • Position Sizing:

      • Calculated based on the ATR and risk per trade to adjust for volatility.
    • Exit Conditions:

      • Stops and Take Profits: Based on ATR multipliers.
      • Trailing Stops: Also based on ATR.

    2. Code Review and Feedback

    a. Syntax and Functionality:

    • Syntax: The script syntax conforms to Pine Script v5 standards. No immediate syntax errors are apparent.

    • Variables and Calculations:

      • Correct use of ta.supertrend, ta.cci, ta.atr, and Bollinger Bands calculations.
      • Proper grouping of input parameters enhances user customization.
    • Risk Management:

      • Dynamic position sizing based on ATR and risk percentage is a strong feature.
      • Tracking and limiting drawdown helps in preserving capital.
    • Time Filtering:

      • The method to convert string inputs to timestamps is accurate.
      • Ensures trades are taken only within specified sessions.

    b. Potential Improvements:

    1. Time Zone Handling:

      • Currently, timestamp uses "GMT+0". Ensure this aligns with your trading hours. You might want to make the time zone configurable.
      • Improvement:
        timeZone = input.timezone("GMT", "Time Zone")
        sessionStartTime = timestamp(timeZone, tradeYear, tradeMonth, tradeDay, startHour, startMinute)
        sessionEndTime   = timestamp(timeZone, tradeYear, tradeMonth, tradeDay, endHour, endMinute)
        
    2. Position Sizing Calculation:

      • The current position size calculation uses positionSize = riskAmount / (atr * atrMultiplierSL). This assumes that the ATR side for stop-loss appropriately represents risk per unit. Consider using a more precise calculation:
        positionSize = riskAmount / (atr * atrMultiplierSL * syminfo.mintick)
        
        • This accounts for the minimum price movement, ensuring accurate position sizing.
    3. Prevent Overtrading:

      • Currently, the strategy can potentially enter multiple trades per candle if conditions are met repeatedly. To prevent overtrading:
        if (strategy.position_size == 0 and not na(strategy.opentrades))
            // Existing entry conditions
        
    4. Handling Multiple Time Frames:

      • If you intend to use higher time frames for indicators (e.g., daily Supertrend in an hourly chart), consider integrating multi-time frame analysis for better signal accuracy.
    5. Optimizing Volatility Check:

      • Bollinger Bands width is a good proxy for volatility, but consider combining it with other volatility measures (like the Volatility Index) for more robust filtering.
    6. Enhancing Risk Management:

      • Implement features like dynamic max drawdown adjustment based on performance.
      • Incorporate trailing take profits or scaling out of positions for better profit management.

    c. Code Enhancements:

    1. Improved Position Size Calculation:

      // Calculate position size based on risk per trade and ATR
      riskAmount = strategy.equity * (riskPerTrade / 100)
      atrValue = ta.atr(atrPeriod)
      positionSize = riskAmount / (atrValue * atrMultiplierSL)
      positionSize := math.max(positionSize, 0)
      
    2. Configurable Time Zone:

      timeZone = input.timezone("GMT", "Time Zone")
      sessionStartTime = timestamp(timeZone, tradeYear, tradeMonth, tradeDay, startHour, startMinute)
      sessionEndTime   = timestamp(timeZone, tradeYear, tradeMonth, tradeDay, endHour, endMinute)
      
    3. Preventing Multiple Entries:

      if (strategy.position_size == 0 and allowTrading and inTradeSession and highVolatility)
          if (longCondition)
              strategy.entry("Long", strategy.long, qty=positionSize)
          if (shortCondition)
              strategy.entry("Short", strategy.short, qty=positionSize)
      
    4. Enhanced Plotting for Clarity:

      • Use distinct colors and styles for different indicators to improve chart readability.
      plot(supertrend, title="Supertrend", color=(supertrendDirection == 1 ? color.green : color.red), linewidth=2, style=plot.style_line)
      plot(cci, title="CCI", color=color.blue, linewidth=1)
      plot(upperBB, title="Upper BB", color=color.orange, linewidth=1, style=plot.style_line)
      plot(lowerBB, title="Lower BB", color=color.orange, linewidth=1, style=plot.style_line)
      hline(cciUpper, title="CCI Overbought Level", color=color.red, linestyle=hline.style_dotted)
      hline(cciLower, title="CCI Oversold Level", color=color.green, linestyle=hline.style_dotted)
      bgcolor(highVolatility ? color.new(color.yellow, 90) : na, title="High Volatility Background")
      

    3. Additional Recommendations

    a. Backtesting and Optimization:

    • Historical Data Testing: Ensure you backtest your strategy over different market conditions (bullish, bearish, ranging) to validate its robustness.
    • Optimization: Fine-tune the input parameters (e.g., ATR periods, CCI lengths) using TradingView’s strategy optimizer to enhance performance.

    b. Risk Alerts:

    • Implement alerts for when the drawdown limit is reached to notify you when trading is halted.
      if (drawdown >= maxDrawdownPercent)
          alert("Max drawdown reached. Trading is halted.", alert.freq_once_per_bar_close)
      

    c. Code Documentation:

    • Adding comments and documentation within your code enhances readability and maintainability, especially if you plan to modify or share it.

    d. Consider Additional Filters:

    • Volume Filters: Incorporate volume-based indicators to confirm the strength of signals.
    • Momentum Indicators: Adding momentum indicators like RSI or MACD can provide additional confirmation for entries and exits.

    4. Final Thoughts

    Your strategy is well-structured and integrates multiple indicators effectively to manage entries, exits, and risk. Implementing the suggested improvements can enhance its performance, reliability, and adaptability to various market conditions. Always ensure thorough backtesting and forward testing with paper trading before deploying with real capital.

    If you have specific questions or need further assistance with particular parts of the script, feel free to ask!