Indicator · Pine Script v5 · On the chart

Covered Calls Optimizer

by BluEng9

The Covered Calls Optimizer indicator helps traders analyze covered call option strategies directly on price charts.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code268
Settings9inputs
LicenceMIT
Last update1 year ago6 Oct 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

268 lines of Pine Script v5 from tradingview_covered_calls.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

tradingview_covered_calls.pine
//@version=5
indicator("Covered Calls Optimizer", overlay=true, max_labels_count=500)

// ═══════════════════════════════════════════════════════════════════
// 📊 COVERED CALLS OPTIMIZER - TradingView Pine Script
// ═══════════════════════════════════════════════════════════════════
// Advanced indicator for covered calls strategy analysis
// Features:
// - Optimal strike price calculation
// - Premium yield analysis
// - Risk/reward visualization
// - Support/resistance levels
// - Volatility-based recommendations
// ═══════════════════════════════════════════════════════════════════

// ══════════ INPUT PARAMETERS ══════════

// Position Settings
positionSize = input.int(100, "Position Size (shares)", minval=100, step=100,
                         tooltip="Number of shares owned (must be multiple of 100)")
avgCost = input.float(0, "Average Cost (0 = current price)", minval=0,
                      tooltip="Your average entry price. Use 0 for current price")

// Strategy Settings
daysToExpiration = input.int(30, "Target DTE", minval=7, maxval=90,
                            tooltip="Target days to expiration")
riskLevel = input.string("Moderate", "Risk Level",
                        options=["Conservative", "Moderate", "Aggressive"],
                        tooltip="Conservative=Low risk/low premium, Aggressive=Higher risk/premium")
targetPremium = input.float(1.0, "Min Premium %", minval=0.1, step=0.1,
                           tooltip="Minimum premium percentage per month")

// Technical Settings
showSupport = input.bool(true, "Show Support/Resistance", group="Display")
showTargets = input.bool(true, "Show Strike Targets", group="Display")
showZones = input.bool(true, "Show Risk Zones", group="Display")
showTable = input.bool(true, "Show Stats Table", group="Display")

// ══════════ CALCULATIONS ══════════

// Current price
currentPrice = close
costBasis = avgCost > 0 ? avgCost : currentPrice

// Calculate ATR for volatility
atr = ta.atr(14)
atrPercent = (atr / currentPrice) * 100

// Historical Volatility (20-day)
returns = math.log(close / close[1])
hvol = ta.stdev(returns, 20) * math.sqrt(252) * 100

// Risk level multipliers
deltaTarget = riskLevel == "Conservative" ? 0.20 :
              riskLevel == "Moderate" ? 0.30 : 0.40

otmPercent = riskLevel == "Conservative" ? 5.0 :
             riskLevel == "Moderate" ? 3.0 : 2.0

// ══════════ STRIKE PRICE CALCULATIONS ══════════

// Calculate target strike based on delta approximation
// Delta ≈ 0.5 + (ln(S/K) / (σ√T)) / 2
// Simplified: Higher strike = Lower delta
strikeMultiplier = 1 + (otmPercent / 100)
targetStrike = currentPrice * strikeMultiplier

// Round to nearest $5 for stocks > $100, $2.5 for $50-$100, $1 for < $50
strikeIncrement = currentPrice > 100 ? 5.0 :
                  currentPrice > 50 ? 2.5 : 1.0
targetStrikeRounded = math.round(targetStrike / strikeIncrement) * strikeIncrement

// Alternative strikes
conservativeStrike = math.round((currentPrice * 1.07) / strikeIncrement) * strikeIncrement
moderateStrike = math.round((currentPrice * 1.04) / strikeIncrement) * strikeIncrement
aggressiveStrike = math.round((currentPrice * 1.02) / strikeIncrement) * strikeIncrement

// ══════════ PREMIUM ESTIMATION ══════════

// Rough premium estimation using volatility
// Premium ≈ Stock Price × IV × √(DTE/365) × Delta
ivEstimate = math.max(hvol, atrPercent * 2)
timeValue = math.sqrt(daysToExpiration / 365)
premiumEstimate = currentPrice * (ivEstimate / 100) * timeValue * deltaTarget

// Adjust for strike distance
strikeDistance = (targetStrikeRounded - currentPrice) / currentPrice
premiumAdjusted = premiumEstimate * (1 - strikeDistance)

// Calculate yield
contracts = math.floor(positionSize / 100)
totalPremium = premiumAdjusted * contracts * 100
premiumYieldPct = (totalPremium / (currentPrice * positionSize)) * 100
annualizedYield = premiumYieldPct * (365 / daysToExpiration)

// ══════════ RISK ZONES ══════════

// Support and Resistance levels
pivotHigh = ta.pivothigh(high, 10, 10)
pivotLow = ta.pivotlow(low, 10, 10)

var float[] resistanceLevels = array.new_float(0)
var float[] supportLevels = array.new_float(0)

// Store pivot points
if not na(pivotHigh)
    array.push(resistanceLevels, pivotHigh)
    if array.size(resistanceLevels) > 5
        array.shift(resistanceLevels)

if not na(pivotLow)
    array.push(supportLevels, pivotLow)
    if array.size(supportLevels) > 5
        array.shift(supportLevels)

// Find nearest resistance
nearestResistance = currentPrice
if array.size(resistanceLevels) > 0
    for i = 0 to array.size(resistanceLevels) - 1
        level = array.get(resistanceLevels, i)
        if level > currentPrice and (nearestResistance == currentPrice or level < nearestResistance)
            nearestResistance := level

// Find nearest support
nearestSupport = currentPrice
if array.size(supportLevels) > 0
    for i = 0 to array.size(supportLevels) - 1
        level = array.get(supportLevels, i)
        if level < currentPrice and (nearestSupport == currentPrice or level > nearestSupport)
            nearestSupport := level

// ══════════ VISUALIZATION ══════════

// Plot strike levels
plot(showTargets ? targetStrikeRounded : na, "Target Strike", color.new(color.blue, 0), 2, plot.style_line)
plot(showTargets ? conservativeStrike : na, "Conservative Strike", color.new(color.green, 50), 1, plot.style_linebr)
plot(showTargets ? aggressiveStrike : na, "Aggressive Strike", color.new(color.red, 50), 1, plot.style_linebr)

// Plot support/resistance
plot(showSupport and nearestResistance != currentPrice ? nearestResistance : na,
     "Resistance", color.new(color.red, 70), 1, plot.style_circles)
plot(showSupport and nearestSupport != currentPrice ? nearestSupport : na,
     "Support", color.new(color.green, 70), 1, plot.style_circles)

// Plot cost basis
plot(costBasis != currentPrice ? costBasis : na, "Cost Basis",
     color.new(color.orange, 30), 2, plot.style_cross)

// Background zones
assignmentRisk = close >= targetStrikeRounded * 0.98
safeZone = close < targetStrikeRounded * 0.95

bgcolor(showZones and assignmentRisk ? color.new(color.red, 90) : na, title="Assignment Risk")
bgcolor(showZones and safeZone ? color.new(color.green, 95) : na, title="Safe Zone")

// ══════════ ALERTS ══════════

// Price approaching strike
approachingStrike = ta.crossover(close, targetStrikeRounded * 0.95)
alertcondition(approachingStrike, "Approaching Strike", "Price approaching {{ticker}} strike level")

// Price above strike (assignment risk)
aboveStrike = ta.crossover(close, targetStrikeRounded)
alertcondition(aboveStrike, "Above Strike Price", "{{ticker}} above strike - assignment risk!")

// High volatility opportunity
highVolatility = hvol > hvol[1] * 1.2 and hvol > 30
alertcondition(highVolatility, "High IV Opportunity", "{{ticker}} showing high IV - good premium opportunity")

// ══════════ LABELS ══════════

// Label for target strike
if showTargets and barstate.islast
    label.new(bar_index, targetStrikeRounded,
              text="🎯 " + str.tostring(targetStrikeRounded, "#.##"),
              style=label.style_label_left,
              color=color.new(color.blue, 30),
              textcolor=color.white,
              size=size.normal)

// ══════════ STATISTICS TABLE ══════════

if showTable and barstate.islast
    var table statsTable = table.new(position.top_right, 2, 12,
                                     border_width=1,
                                     border_color=color.gray,
                                     frame_color=color.gray,
                                     frame_width=1)

    // Header
    table.cell(statsTable, 0, 0, "Covered Calls Strategy",
               bgcolor=color.new(color.blue, 70), text_color=color.white, text_size=size.normal)
    table.merge_cells(statsTable, 0, 0, 1, 0)

    // Current Position
    table.cell(statsTable, 0, 1, "Current Price", text_halign=text.align_left)
    table.cell(statsTable, 1, 1, "$" + str.tostring(currentPrice, "#.##"),
               text_halign=text.align_right, text_color=color.white)

    table.cell(statsTable, 0, 2, "Cost Basis", text_halign=text.align_left)
    pnlColor = currentPrice >= costBasis ? color.green : color.red
    pnlPct = ((currentPrice - costBasis) / costBasis) * 100
    table.cell(statsTable, 1, 2, "$" + str.tostring(costBasis, "#.##") + " (" + str.tostring(pnlPct, "+#.##") + "%)",
               text_halign=text.align_right, text_color=pnlColor)

    // Strike Recommendations
    table.cell(statsTable, 0, 3, "Target Strike", text_halign=text.align_left)
    table.cell(statsTable, 1, 3, "$" + str.tostring(targetStrikeRounded, "#.##"),
               text_halign=text.align_right, bgcolor=color.new(color.blue, 80))

    table.cell(statsTable, 0, 4, "Strike Distance", text_halign=text.align_left)
    distPct = ((targetStrikeRounded - currentPrice) / currentPrice) * 100
    table.cell(statsTable, 1, 4, str.tostring(distPct, "+#.##") + "%",
               text_halign=text.align_right)

    // Premium Analysis
    table.cell(statsTable, 0, 5, "Est. Premium", text_halign=text.align_left)
    table.cell(statsTable, 1, 5, "$" + str.tostring(premiumAdjusted, "#.##") + "/contract",
               text_halign=text.align_right, text_color=color.yellow)

    table.cell(statsTable, 0, 6, "Total Premium", text_halign=text.align_left)
    table.cell(statsTable, 1, 6, "$" + str.tostring(totalPremium, "#") + " (" + str.tostring(contracts, "#") + " contracts)",
               text_halign=text.align_right, text_color=color.yellow)

    table.cell(statsTable, 0, 7, "Premium Yield", text_halign=text.align_left)
    yieldColor = premiumYieldPct >= targetPremium ? color.green : color.orange
    table.cell(statsTable, 1, 7, str.tostring(premiumYieldPct, "#.##") + "%",
               text_halign=text.align_right, text_color=yieldColor)

    table.cell(statsTable, 0, 8, "Annualized Yield", text_halign=text.align_left)
    table.cell(statsTable, 1, 8, str.tostring(annualizedYield, "#.##") + "%",
               text_halign=text.align_right, text_color=color.green)

    // Risk Metrics
    table.cell(statsTable, 0, 9, "Volatility (HV)", text_halign=text.align_left)
    volColor = hvol > 40 ? color.red : hvol > 25 ? color.yellow : color.green
    table.cell(statsTable, 1, 9, str.tostring(hvol, "#.#") + "%",
               text_halign=text.align_right, text_color=volColor)

    table.cell(statsTable, 0, 10, "Risk Level", text_halign=text.align_left)
    riskColor = riskLevel == "Conservative" ? color.green :
                riskLevel == "Moderate" ? color.yellow : color.red
    table.cell(statsTable, 1, 10, riskLevel,
               text_halign=text.align_right, text_color=riskColor)

    // Status
    table.cell(statsTable, 0, 11, "Status", text_halign=text.align_left)
    status = assignmentRisk ? "⚠️ At Risk" : safeZone ? "✅ Safe" : "📊 Monitor"
    statusColor = assignmentRisk ? color.red : safeZone ? color.green : color.yellow
    table.cell(statsTable, 1, 11, status,
               text_halign=text.align_right, text_color=statusColor, text_size=size.normal)

// ══════════ PLOTSHAPE FOR SIGNALS ══════════

// Good entry signal (high volatility + safe zone)
goodEntry = hvol > 25 and safeZone and barstate.islast
plotshape(goodEntry, "Good Entry", shape.triangleup, location.belowbar,
          color.new(color.green, 0), size=size.small)

// Warning signal (approaching strike)
warning = close >= targetStrikeRounded * 0.95 and close < targetStrikeRounded
plotshape(warning and barstate.islast, "Warning", shape.diamond, location.abovebar,
          color.new(color.orange, 0), size=size.small)

// Assignment risk signal
riskSignal = close >= targetStrikeRounded
plotshape(riskSignal and barstate.islast, "Assignment Risk", shape.triangledown, location.abovebar,
          color.new(color.red, 0), size=size.small)

Overview

Covered Calls Optimizer calculates target strike prices and estimated yields based on stock volatility (ATR and 20-day historical volatility) and user-defined risk profiles, such as Conservative, Moderate, or Aggressive. The script overlays strike targets, support and resistance levels, and risk zones onto the main chart pane while displaying key position and strategy statistics in an optional dashboard table.

Details

Published by

BluEng9 on GitHub

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Support & resistance, Screeners & dashboards

Markets

Stocks, Crypto

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Position Size (shares)int100positionSize
Average Cost (0 = current price)float0avgCost
Target DTEint30daysToExpiration
Risk LevelstringModerateriskLevel
Min Premium %float1.0targetPremium
Show Support/ResistancebooltrueshowSupport
Show Strike TargetsbooltrueshowTargets
Show Risk ZonesbooltrueshowZones
Show Stats TablebooltrueshowTable
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

218 stars

This indicator maps market structure and supply and demand zones on the price chart. It marks validated and optional unvalidated swing highs and lows using a pivot length and extra confirmation bars. Consolidation and impulse moves are measured against ATR to

Indicator v6 SMC / ICT / price actionSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Market Structure + Supply/Demand
56 stars

This indicator marks forex trading sessions and opening ranges on the price chart. It can draw Sydney, Tokyo, Frankfurt, London, and New York session boxes or five- and fifteen-minute opening ranges, plus an optional opening channel and a day-open range. Day r

Indicator v5 Sessions & timeSupport & resistance Repaints
Updated 2 months ago · None stated GitHub repository of Day Trading Booster by DGT

ADR levels

by TamaraKGreen
46 stars

This indicator plots average daily range levels on the price chart, together with optional standard-deviation and Fibonacci levels scaled from that range. Users set the lookback in days, a scale factor, and the visibility, color, and line style of the ADR line

Indicator v5 Support & resistanceVolatility & bands
Updated 7 weeks ago · None stated GitHub repository of ADR levels
41 stars

ATR Matrix calculates Average True Range and a 50-period Simple Moving Average to display multi-tier volatility levels and risk-reward metrics. It project stop levels using negative ATR multiples from an entry price, alongside target levels from 0x to 11x ATR

Indicator v5 Volatility & bandsSupport & resistance

Zen Trading Toolkit

by Zen-Tim
29 stars

This indicator plots average bar range (ABR) measured move targets, opening range boxes, and historical key reference levels directly on the price chart. It projects bullish and bearish targets (0.5x, 1.0x, 1.5x, 2.0x ABR) from the previous session's close, al

Indicator v6 Support & resistanceVolatility & bands
Updated 2 weeks ago · MIT GitHub repository of Zen Trading Toolkit
20 stars

This indicator calculates a base moving average (EMA, SMA, WMA, or HMA) and projects multiple symmetrical envelope bands around it directly on the price chart. Users can adjust the length, source, moving average type, and initial envelope multiplier. Additiona

Indicator v5 Moving averagesVolatility & bands
Updated 1 year ago · None stated GitHub repository of Multiple Moving Average Envelope

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers